xref: /netbsd/crypto/external/bsd/openssh/dist/kex.c (revision 6550d01e)
1 /*	$NetBSD: kex.c,v 1.5 2010/11/21 18:59:04 adam Exp $	*/
2 /* $OpenBSD: kex.c,v 1.82 2009/10/24 11:13:54 andreas Exp $ */
3 /*
4  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include "includes.h"
28 __RCSID("$NetBSD: kex.c,v 1.5 2010/11/21 18:59:04 adam Exp $");
29 #include <sys/param.h>
30 
31 #include <signal.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 
36 #include <openssl/crypto.h>
37 
38 #include "xmalloc.h"
39 #include "ssh2.h"
40 #include "buffer.h"
41 #include "packet.h"
42 #include "compat.h"
43 #include "cipher.h"
44 #include "key.h"
45 #include "kex.h"
46 #include "log.h"
47 #include "mac.h"
48 #include "match.h"
49 #include "dispatch.h"
50 #include "monitor.h"
51 #include "canohost.h"
52 #include "roaming.h"
53 
54 /* prototype */
55 static void kex_kexinit_finish(Kex *);
56 static void kex_choose_conf(Kex *);
57 
58 /* put algorithm proposal into buffer */
59 /* used in sshconnect.c as well as kex.c */
60 void
61 kex_prop2buf(Buffer *b, char *proposal[PROPOSAL_MAX])
62 {
63 	u_int i;
64 
65 	buffer_clear(b);
66 	/*
67 	 * add a dummy cookie, the cookie will be overwritten by
68 	 * kex_send_kexinit(), each time a kexinit is set
69 	 */
70 	for (i = 0; i < KEX_COOKIE_LEN; i++)
71 		buffer_put_char(b, 0);
72 	for (i = 0; i < PROPOSAL_MAX; i++)
73 		buffer_put_cstring(b, proposal[i]);
74 	buffer_put_char(b, 0);			/* first_kex_packet_follows */
75 	buffer_put_int(b, 0);			/* uint32 reserved */
76 }
77 
78 /* parse buffer and return algorithm proposal */
79 static char **
80 kex_buf2prop(Buffer *raw, int *first_kex_follows)
81 {
82 	Buffer b;
83 	u_int i;
84 	char **proposal;
85 
86 	proposal = xcalloc(PROPOSAL_MAX, sizeof(char *));
87 
88 	buffer_init(&b);
89 	buffer_append(&b, buffer_ptr(raw), buffer_len(raw));
90 	/* skip cookie */
91 	for (i = 0; i < KEX_COOKIE_LEN; i++)
92 		buffer_get_char(&b);
93 	/* extract kex init proposal strings */
94 	for (i = 0; i < PROPOSAL_MAX; i++) {
95 		proposal[i] = buffer_get_string(&b,NULL);
96 		debug2("kex_parse_kexinit: %s", proposal[i]);
97 	}
98 	/* first kex follows / reserved */
99 	i = buffer_get_char(&b);
100 	if (first_kex_follows != NULL)
101 		*first_kex_follows = i;
102 	debug2("kex_parse_kexinit: first_kex_follows %d ", i);
103 	i = buffer_get_int(&b);
104 	debug2("kex_parse_kexinit: reserved %u ", i);
105 	buffer_free(&b);
106 	return proposal;
107 }
108 
109 static void
110 kex_prop_free(char **proposal)
111 {
112 	u_int i;
113 
114 	for (i = 0; i < PROPOSAL_MAX; i++)
115 		xfree(proposal[i]);
116 	xfree(proposal);
117 }
118 
119 /* ARGSUSED */
120 static void
121 kex_protocol_error(int type, u_int32_t seq, void *ctxt)
122 {
123 	error("Hm, kex protocol error: type %d seq %u", type, seq);
124 }
125 
126 static void
127 kex_reset_dispatch(void)
128 {
129 	dispatch_range(SSH2_MSG_TRANSPORT_MIN,
130 	    SSH2_MSG_TRANSPORT_MAX, &kex_protocol_error);
131 	dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
132 }
133 
134 void
135 kex_finish(Kex *kex)
136 {
137 	kex_reset_dispatch();
138 
139 	packet_start(SSH2_MSG_NEWKEYS);
140 	packet_send();
141 	/* packet_write_wait(); */
142 	debug("SSH2_MSG_NEWKEYS sent");
143 
144 	debug("expecting SSH2_MSG_NEWKEYS");
145 	packet_read_expect(SSH2_MSG_NEWKEYS);
146 	packet_check_eom();
147 	debug("SSH2_MSG_NEWKEYS received");
148 
149 	kex->done = 1;
150 	buffer_clear(&kex->peer);
151 	/* buffer_clear(&kex->my); */
152 	kex->flags &= ~KEX_INIT_SENT;
153 	xfree(kex->name);
154 	kex->name = NULL;
155 }
156 
157 void
158 kex_send_kexinit(Kex *kex)
159 {
160 	u_int32_t rnd = 0;
161 	u_char *cookie;
162 	u_int i;
163 
164 	if (kex == NULL) {
165 		error("kex_send_kexinit: no kex, cannot rekey");
166 		return;
167 	}
168 	if (kex->flags & KEX_INIT_SENT) {
169 		debug("KEX_INIT_SENT");
170 		return;
171 	}
172 	kex->done = 0;
173 
174 	/* generate a random cookie */
175 	if (buffer_len(&kex->my) < KEX_COOKIE_LEN)
176 		fatal("kex_send_kexinit: kex proposal too short");
177 	cookie = buffer_ptr(&kex->my);
178 	for (i = 0; i < KEX_COOKIE_LEN; i++) {
179 		if (i % 4 == 0)
180 			rnd = arc4random();
181 		cookie[i] = rnd;
182 		rnd >>= 8;
183 	}
184 	packet_start(SSH2_MSG_KEXINIT);
185 	packet_put_raw(buffer_ptr(&kex->my), buffer_len(&kex->my));
186 	packet_send();
187 	debug("SSH2_MSG_KEXINIT sent");
188 	kex->flags |= KEX_INIT_SENT;
189 }
190 
191 /* ARGSUSED */
192 void
193 kex_input_kexinit(int type, u_int32_t seq, void *ctxt)
194 {
195 	char *ptr;
196 	u_int i, dlen;
197 	Kex *kex = (Kex *)ctxt;
198 
199 	debug("SSH2_MSG_KEXINIT received");
200 	if (kex == NULL)
201 		fatal("kex_input_kexinit: no kex, cannot rekey");
202 
203 	ptr = packet_get_raw(&dlen);
204 	buffer_append(&kex->peer, ptr, dlen);
205 
206 	/* discard packet */
207 	for (i = 0; i < KEX_COOKIE_LEN; i++)
208 		packet_get_char();
209 	for (i = 0; i < PROPOSAL_MAX; i++)
210 		xfree(packet_get_string(NULL));
211 	(void) packet_get_char();
212 	(void) packet_get_int();
213 	packet_check_eom();
214 
215 	kex_kexinit_finish(kex);
216 }
217 
218 Kex *
219 kex_setup(char *proposal[PROPOSAL_MAX])
220 {
221 	Kex *kex;
222 
223 	kex = xcalloc(1, sizeof(*kex));
224 	buffer_init(&kex->peer);
225 	buffer_init(&kex->my);
226 	kex_prop2buf(&kex->my, proposal);
227 	kex->done = 0;
228 
229 	kex_send_kexinit(kex);					/* we start */
230 	kex_reset_dispatch();
231 
232 	return kex;
233 }
234 
235 static void
236 kex_kexinit_finish(Kex *kex)
237 {
238 	if (!(kex->flags & KEX_INIT_SENT))
239 		kex_send_kexinit(kex);
240 
241 	kex_choose_conf(kex);
242 
243 	if (kex->kex_type >= 0 && kex->kex_type < KEX_MAX &&
244 	    kex->kex[kex->kex_type] != NULL) {
245 		(kex->kex[kex->kex_type])(kex);
246 	} else {
247 		fatal("Unsupported key exchange %d", kex->kex_type);
248 	}
249 }
250 
251 static void
252 choose_enc(Enc *enc, char *client, char *server)
253 {
254 	char *name = match_list(client, server, NULL);
255 	if (name == NULL)
256 		fatal("no matching cipher found: client %s server %s",
257 		    client, server);
258 	if ((enc->cipher = cipher_by_name(name)) == NULL)
259 		fatal("matching cipher is not supported: %s", name);
260 	enc->name = name;
261 	enc->enabled = 0;
262 	enc->iv = NULL;
263 	enc->key = NULL;
264 	enc->key_len = cipher_keylen(enc->cipher);
265 	enc->block_size = cipher_blocksize(enc->cipher);
266 }
267 
268 static void
269 choose_mac(Mac *mac, char *client, char *server)
270 {
271 	char *name = match_list(client, server, NULL);
272 	if (name == NULL)
273 		fatal("no matching mac found: client %s server %s",
274 		    client, server);
275 	if (mac_setup(mac, name) < 0)
276 		fatal("unsupported mac %s", name);
277 	/* truncate the key */
278 	if (datafellows & SSH_BUG_HMAC)
279 		mac->key_len = 16;
280 	mac->name = name;
281 	mac->key = NULL;
282 	mac->enabled = 0;
283 }
284 
285 static void
286 choose_comp(Comp *comp, char *client, char *server)
287 {
288 	char *name = match_list(client, server, NULL);
289 	if (name == NULL)
290 		fatal("no matching comp found: client %s server %s", client, server);
291 	if (strcmp(name, "zlib@openssh.com") == 0) {
292 		comp->type = COMP_DELAYED;
293 	} else if (strcmp(name, "zlib") == 0) {
294 		comp->type = COMP_ZLIB;
295 	} else if (strcmp(name, "none") == 0) {
296 		comp->type = COMP_NONE;
297 	} else {
298 		fatal("unsupported comp %s", name);
299 	}
300 	comp->name = name;
301 }
302 
303 static void
304 choose_kex(Kex *k, char *client, char *server)
305 {
306 	k->name = match_list(client, server, NULL);
307 	if (k->name == NULL)
308 		fatal("Unable to negotiate a key exchange method");
309 	if (strcmp(k->name, KEX_DH1) == 0) {
310 		k->kex_type = KEX_DH_GRP1_SHA1;
311 		k->evp_md = EVP_sha1();
312 	} else if (strcmp(k->name, KEX_DH14) == 0) {
313 		k->kex_type = KEX_DH_GRP14_SHA1;
314 		k->evp_md = EVP_sha1();
315 	} else if (strcmp(k->name, KEX_DHGEX_SHA1) == 0) {
316 		k->kex_type = KEX_DH_GEX_SHA1;
317 		k->evp_md = EVP_sha1();
318 	} else if (strcmp(k->name, KEX_DHGEX_SHA256) == 0) {
319 		k->kex_type = KEX_DH_GEX_SHA256;
320 		k->evp_md = EVP_sha256();
321 	} else
322 		fatal("bad kex alg %s", k->name);
323 }
324 
325 static void
326 choose_hostkeyalg(Kex *k, char *client, char *server)
327 {
328 	char *hostkeyalg = match_list(client, server, NULL);
329 	if (hostkeyalg == NULL)
330 		fatal("no hostkey alg");
331 	k->hostkey_type = key_type_from_name(hostkeyalg);
332 	if (k->hostkey_type == KEY_UNSPEC)
333 		fatal("bad hostkey alg '%s'", hostkeyalg);
334 	xfree(hostkeyalg);
335 }
336 
337 static int
338 proposals_match(char *my[PROPOSAL_MAX], char *peer[PROPOSAL_MAX])
339 {
340 	static int check[] = {
341 		PROPOSAL_KEX_ALGS, PROPOSAL_SERVER_HOST_KEY_ALGS, -1
342 	};
343 	int *idx;
344 	char *p;
345 
346 	for (idx = &check[0]; *idx != -1; idx++) {
347 		if ((p = strchr(my[*idx], ',')) != NULL)
348 			*p = '\0';
349 		if ((p = strchr(peer[*idx], ',')) != NULL)
350 			*p = '\0';
351 		if (strcmp(my[*idx], peer[*idx]) != 0) {
352 			debug2("proposal mismatch: my %s peer %s",
353 			    my[*idx], peer[*idx]);
354 			return (0);
355 		}
356 	}
357 	debug2("proposals match");
358 	return (1);
359 }
360 
361 static void
362 kex_choose_conf(Kex *kex)
363 {
364 	Newkeys *newkeys;
365 	char **my, **peer;
366 	char **cprop, **sprop;
367 	int nenc, nmac, ncomp;
368 	u_int mode, ctos, need;
369 	int first_kex_follows, type;
370 	int log_flag = 0;
371 
372 	int auth_flag;
373 
374 	auth_flag = packet_authentication_state();
375 
376 	debug ("AUTH STATE IS %d", auth_flag);
377 
378 	my   = kex_buf2prop(&kex->my, NULL);
379 	peer = kex_buf2prop(&kex->peer, &first_kex_follows);
380 
381 	if (kex->server) {
382 		cprop=peer;
383 		sprop=my;
384 	} else {
385 		cprop=my;
386 		sprop=peer;
387 	}
388 
389 	/* Check whether server offers roaming */
390 	if (!kex->server) {
391 		char *roaming;
392 		roaming = match_list(KEX_RESUME, peer[PROPOSAL_KEX_ALGS], NULL);
393 		if (roaming) {
394 			kex->roaming = 1;
395 			xfree(roaming);
396 		}
397 	}
398 
399 	/* Algorithm Negotiation */
400 	for (mode = 0; mode < MODE_MAX; mode++) {
401 		newkeys = xcalloc(1, sizeof(*newkeys));
402 		kex->newkeys[mode] = newkeys;
403 		ctos = (!kex->server && mode == MODE_OUT) ||
404 		    (kex->server && mode == MODE_IN);
405 		nenc  = ctos ? PROPOSAL_ENC_ALGS_CTOS  : PROPOSAL_ENC_ALGS_STOC;
406 		nmac  = ctos ? PROPOSAL_MAC_ALGS_CTOS  : PROPOSAL_MAC_ALGS_STOC;
407 		ncomp = ctos ? PROPOSAL_COMP_ALGS_CTOS : PROPOSAL_COMP_ALGS_STOC;
408 		choose_enc (&newkeys->enc,  cprop[nenc],  sprop[nenc]);
409 		choose_mac (&newkeys->mac,  cprop[nmac],  sprop[nmac]);
410 		choose_comp(&newkeys->comp, cprop[ncomp], sprop[ncomp]);
411 		debug("REQUESTED ENC.NAME is '%s'", newkeys->enc.name);
412 		if (strcmp(newkeys->enc.name, "none") == 0) {
413 				debug("Requesting NONE. Authflag is %d", auth_flag);
414 			if (auth_flag == 1) {
415 				debug("None requested post authentication.");
416 			} else {
417 				fatal("Pre-authentication none cipher requests are not allowed.");
418 			}
419 		}
420 		debug("kex: %s %s %s %s",
421 		    ctos ? "client->server" : "server->client",
422 		    newkeys->enc.name,
423 		    newkeys->mac.name,
424 		    newkeys->comp.name);
425 		/* client starts withctos = 0 && log flag = 0 and no log*/
426 		/* 2nd client pass ctos=1 and flag = 1 so no log*/
427 		/* server starts with ctos =1 && log_flag = 0 so log */
428 		/* 2nd sever pass ctos = 1 && log flag = 1 so no log*/
429 		/* -cjr*/
430 		if (ctos && !log_flag) {
431 			logit("SSH: Server;Ltype: Kex;Remote: %s-%d;Enc: %s;MAC: %s;Comp: %s",
432 			      get_remote_ipaddr(),
433 			      get_remote_port(),
434 			      newkeys->enc.name,
435 			      newkeys->mac.name,
436 			      newkeys->comp.name);
437 		}
438 		log_flag = 1;
439 	}
440 	choose_kex(kex, cprop[PROPOSAL_KEX_ALGS], sprop[PROPOSAL_KEX_ALGS]);
441 	choose_hostkeyalg(kex, cprop[PROPOSAL_SERVER_HOST_KEY_ALGS],
442 	    sprop[PROPOSAL_SERVER_HOST_KEY_ALGS]);
443 	need = 0;
444 	for (mode = 0; mode < MODE_MAX; mode++) {
445 		newkeys = kex->newkeys[mode];
446 		if (need < newkeys->enc.key_len)
447 			need = newkeys->enc.key_len;
448 		if (need < newkeys->enc.block_size)
449 			need = newkeys->enc.block_size;
450 		if (need < newkeys->mac.key_len)
451 			need = newkeys->mac.key_len;
452 	}
453 	/* XXX need runden? */
454 	kex->we_need = need;
455 
456 	/* ignore the next message if the proposals do not match */
457 	if (first_kex_follows && !proposals_match(my, peer) &&
458 	    !(datafellows & SSH_BUG_FIRSTKEX)) {
459 		type = packet_read();
460 		debug2("skipping next packet (type %u)", type);
461 	}
462 
463 	kex_prop_free(my);
464 	kex_prop_free(peer);
465 }
466 
467 static u_char *
468 derive_key(Kex *kex, int id, u_int need, u_char *hash, u_int hashlen,
469     BIGNUM *shared_secret)
470 {
471 	Buffer b;
472 	EVP_MD_CTX md;
473 	char c = id;
474 	u_int have;
475 	int mdsz;
476 	u_char *digest;
477 
478 	if ((mdsz = EVP_MD_size(kex->evp_md)) <= 0)
479 		fatal("bad kex md size %d", mdsz);
480 	digest = xmalloc(roundup(need, mdsz));
481 
482 	buffer_init(&b);
483 	buffer_put_bignum2(&b, shared_secret);
484 
485 	/* K1 = HASH(K || H || "A" || session_id) */
486 	EVP_DigestInit(&md, kex->evp_md);
487 	if (!(datafellows & SSH_BUG_DERIVEKEY))
488 		EVP_DigestUpdate(&md, buffer_ptr(&b), buffer_len(&b));
489 	EVP_DigestUpdate(&md, hash, hashlen);
490 	EVP_DigestUpdate(&md, &c, 1);
491 	EVP_DigestUpdate(&md, kex->session_id, kex->session_id_len);
492 	EVP_DigestFinal(&md, digest, NULL);
493 
494 	/*
495 	 * expand key:
496 	 * Kn = HASH(K || H || K1 || K2 || ... || Kn-1)
497 	 * Key = K1 || K2 || ... || Kn
498 	 */
499 	for (have = mdsz; need > have; have += mdsz) {
500 		EVP_DigestInit(&md, kex->evp_md);
501 		if (!(datafellows & SSH_BUG_DERIVEKEY))
502 			EVP_DigestUpdate(&md, buffer_ptr(&b), buffer_len(&b));
503 		EVP_DigestUpdate(&md, hash, hashlen);
504 		EVP_DigestUpdate(&md, digest, have);
505 		EVP_DigestFinal(&md, digest + have, NULL);
506 	}
507 	buffer_free(&b);
508 #ifdef DEBUG_KEX
509 	fprintf(stderr, "key '%c'== ", c);
510 	dump_digest("key", digest, need);
511 #endif
512 	return digest;
513 }
514 
515 Newkeys *current_keys[MODE_MAX];
516 
517 #define NKEYS	6
518 void
519 kex_derive_keys(Kex *kex, u_char *hash, u_int hashlen, BIGNUM *shared_secret)
520 {
521 	u_char *keys[NKEYS];
522 	u_int i, mode, ctos;
523 
524 	for (i = 0; i < NKEYS; i++) {
525 		keys[i] = derive_key(kex, 'A'+i, kex->we_need, hash, hashlen,
526 		    shared_secret);
527 	}
528 
529 	debug2("kex_derive_keys");
530 	for (mode = 0; mode < MODE_MAX; mode++) {
531 		current_keys[mode] = kex->newkeys[mode];
532 		kex->newkeys[mode] = NULL;
533 		ctos = (!kex->server && mode == MODE_OUT) ||
534 		    (kex->server && mode == MODE_IN);
535 		current_keys[mode]->enc.iv  = keys[ctos ? 0 : 1];
536 		current_keys[mode]->enc.key = keys[ctos ? 2 : 3];
537 		current_keys[mode]->mac.key = keys[ctos ? 4 : 5];
538 	}
539 }
540 
541 Newkeys *
542 kex_get_newkeys(int mode)
543 {
544 	Newkeys *ret;
545 
546 	ret = current_keys[mode];
547 	current_keys[mode] = NULL;
548 	return ret;
549 }
550 
551 void
552 derive_ssh1_session_id(BIGNUM *host_modulus, BIGNUM *server_modulus,
553     u_int8_t cookie[8], u_int8_t id[16])
554 {
555 	const EVP_MD *evp_md = EVP_md5();
556 	EVP_MD_CTX md;
557 	u_int8_t nbuf[2048], obuf[EVP_MAX_MD_SIZE];
558 	int len;
559 
560 	EVP_DigestInit(&md, evp_md);
561 
562 	len = BN_num_bytes(host_modulus);
563 	if (len < (512 / 8) || (u_int)len > sizeof(nbuf))
564 		fatal("%s: bad host modulus (len %d)", __func__, len);
565 	BN_bn2bin(host_modulus, nbuf);
566 	EVP_DigestUpdate(&md, nbuf, len);
567 
568 	len = BN_num_bytes(server_modulus);
569 	if (len < (512 / 8) || (u_int)len > sizeof(nbuf))
570 		fatal("%s: bad server modulus (len %d)", __func__, len);
571 	BN_bn2bin(server_modulus, nbuf);
572 	EVP_DigestUpdate(&md, nbuf, len);
573 
574 	EVP_DigestUpdate(&md, cookie, 8);
575 
576 	EVP_DigestFinal(&md, obuf, NULL);
577 	memcpy(id, obuf, 16);
578 
579 	memset(nbuf, 0, sizeof(nbuf));
580 	memset(obuf, 0, sizeof(obuf));
581 	memset(&md, 0, sizeof(md));
582 }
583 
584 #if defined(DEBUG_KEX) || defined(DEBUG_KEXDH)
585 void
586 dump_digest(char *msg, u_char *digest, int len)
587 {
588 	u_int i;
589 
590 	fprintf(stderr, "%s\n", msg);
591 	for (i = 0; i < len; i++) {
592 		fprintf(stderr, "%02x", digest[i]);
593 		if (i%32 == 31)
594 			fprintf(stderr, "\n");
595 		else if (i%8 == 7)
596 			fprintf(stderr, " ");
597 	}
598 	fprintf(stderr, "\n");
599 }
600 #endif
601