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