xref: /openbsd-src/usr.bin/ssh/kex.c (revision daf88648c0e349d5c02e1504293082072c981640)
1 /* $OpenBSD: kex.c,v 1.77 2007/01/21 01:41:54 stevesk 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 
49 #define KEX_COOKIE_LEN	16
50 
51 extern const EVP_MD *evp_ssh_sha256(void);
52 
53 /* prototype */
54 static void kex_kexinit_finish(Kex *);
55 static void kex_choose_conf(Kex *);
56 
57 /* put algorithm proposal into buffer */
58 static void
59 kex_prop2buf(Buffer *b, char *proposal[PROPOSAL_MAX])
60 {
61 	u_int i;
62 
63 	buffer_clear(b);
64 	/*
65 	 * add a dummy cookie, the cookie will be overwritten by
66 	 * kex_send_kexinit(), each time a kexinit is set
67 	 */
68 	for (i = 0; i < KEX_COOKIE_LEN; i++)
69 		buffer_put_char(b, 0);
70 	for (i = 0; i < PROPOSAL_MAX; i++)
71 		buffer_put_cstring(b, proposal[i]);
72 	buffer_put_char(b, 0);			/* first_kex_packet_follows */
73 	buffer_put_int(b, 0);			/* uint32 reserved */
74 }
75 
76 /* parse buffer and return algorithm proposal */
77 static char **
78 kex_buf2prop(Buffer *raw, int *first_kex_follows)
79 {
80 	Buffer b;
81 	int i;
82 	char **proposal;
83 
84 	proposal = xcalloc(PROPOSAL_MAX, sizeof(char *));
85 
86 	buffer_init(&b);
87 	buffer_append(&b, buffer_ptr(raw), buffer_len(raw));
88 	/* skip cookie */
89 	for (i = 0; i < KEX_COOKIE_LEN; i++)
90 		buffer_get_char(&b);
91 	/* extract kex init proposal strings */
92 	for (i = 0; i < PROPOSAL_MAX; i++) {
93 		proposal[i] = buffer_get_string(&b,NULL);
94 		debug2("kex_parse_kexinit: %s", proposal[i]);
95 	}
96 	/* first kex follows / reserved */
97 	i = buffer_get_char(&b);
98 	if (first_kex_follows != NULL)
99 		*first_kex_follows = i;
100 	debug2("kex_parse_kexinit: first_kex_follows %d ", i);
101 	i = buffer_get_int(&b);
102 	debug2("kex_parse_kexinit: reserved %d ", i);
103 	buffer_free(&b);
104 	return proposal;
105 }
106 
107 static void
108 kex_prop_free(char **proposal)
109 {
110 	u_int i;
111 
112 	for (i = 0; i < PROPOSAL_MAX; i++)
113 		xfree(proposal[i]);
114 	xfree(proposal);
115 }
116 
117 static void
118 kex_protocol_error(int type, u_int32_t seq, void *ctxt)
119 {
120 	error("Hm, kex protocol error: type %d seq %u", type, seq);
121 }
122 
123 static void
124 kex_reset_dispatch(void)
125 {
126 	dispatch_range(SSH2_MSG_TRANSPORT_MIN,
127 	    SSH2_MSG_TRANSPORT_MAX, &kex_protocol_error);
128 	dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
129 }
130 
131 void
132 kex_finish(Kex *kex)
133 {
134 	kex_reset_dispatch();
135 
136 	packet_start(SSH2_MSG_NEWKEYS);
137 	packet_send();
138 	/* packet_write_wait(); */
139 	debug("SSH2_MSG_NEWKEYS sent");
140 
141 	debug("expecting SSH2_MSG_NEWKEYS");
142 	packet_read_expect(SSH2_MSG_NEWKEYS);
143 	packet_check_eom();
144 	debug("SSH2_MSG_NEWKEYS received");
145 
146 	kex->done = 1;
147 	buffer_clear(&kex->peer);
148 	/* buffer_clear(&kex->my); */
149 	kex->flags &= ~KEX_INIT_SENT;
150 	xfree(kex->name);
151 	kex->name = NULL;
152 }
153 
154 void
155 kex_send_kexinit(Kex *kex)
156 {
157 	u_int32_t rnd = 0;
158 	u_char *cookie;
159 	u_int i;
160 
161 	if (kex == NULL) {
162 		error("kex_send_kexinit: no kex, cannot rekey");
163 		return;
164 	}
165 	if (kex->flags & KEX_INIT_SENT) {
166 		debug("KEX_INIT_SENT");
167 		return;
168 	}
169 	kex->done = 0;
170 
171 	/* generate a random cookie */
172 	if (buffer_len(&kex->my) < KEX_COOKIE_LEN)
173 		fatal("kex_send_kexinit: kex proposal too short");
174 	cookie = buffer_ptr(&kex->my);
175 	for (i = 0; i < KEX_COOKIE_LEN; i++) {
176 		if (i % 4 == 0)
177 			rnd = arc4random();
178 		cookie[i] = rnd;
179 		rnd >>= 8;
180 	}
181 	packet_start(SSH2_MSG_KEXINIT);
182 	packet_put_raw(buffer_ptr(&kex->my), buffer_len(&kex->my));
183 	packet_send();
184 	debug("SSH2_MSG_KEXINIT sent");
185 	kex->flags |= KEX_INIT_SENT;
186 }
187 
188 void
189 kex_input_kexinit(int type, u_int32_t seq, void *ctxt)
190 {
191 	char *ptr;
192 	u_int i, dlen;
193 	Kex *kex = (Kex *)ctxt;
194 
195 	debug("SSH2_MSG_KEXINIT received");
196 	if (kex == NULL)
197 		fatal("kex_input_kexinit: no kex, cannot rekey");
198 
199 	ptr = packet_get_raw(&dlen);
200 	buffer_append(&kex->peer, ptr, dlen);
201 
202 	/* discard packet */
203 	for (i = 0; i < KEX_COOKIE_LEN; i++)
204 		packet_get_char();
205 	for (i = 0; i < PROPOSAL_MAX; i++)
206 		xfree(packet_get_string(NULL));
207 	(void) packet_get_char();
208 	(void) packet_get_int();
209 	packet_check_eom();
210 
211 	kex_kexinit_finish(kex);
212 }
213 
214 Kex *
215 kex_setup(char *proposal[PROPOSAL_MAX])
216 {
217 	Kex *kex;
218 
219 	kex = xcalloc(1, sizeof(*kex));
220 	buffer_init(&kex->peer);
221 	buffer_init(&kex->my);
222 	kex_prop2buf(&kex->my, proposal);
223 	kex->done = 0;
224 
225 	kex_send_kexinit(kex);					/* we start */
226 	kex_reset_dispatch();
227 
228 	return kex;
229 }
230 
231 static void
232 kex_kexinit_finish(Kex *kex)
233 {
234 	if (!(kex->flags & KEX_INIT_SENT))
235 		kex_send_kexinit(kex);
236 
237 	kex_choose_conf(kex);
238 
239 	if (kex->kex_type >= 0 && kex->kex_type < KEX_MAX &&
240 	    kex->kex[kex->kex_type] != NULL) {
241 		(kex->kex[kex->kex_type])(kex);
242 	} else {
243 		fatal("Unsupported key exchange %d", kex->kex_type);
244 	}
245 }
246 
247 static void
248 choose_enc(Enc *enc, char *client, char *server)
249 {
250 	char *name = match_list(client, server, NULL);
251 	if (name == NULL)
252 		fatal("no matching cipher found: client %s server %s", client, server);
253 	if ((enc->cipher = cipher_by_name(name)) == NULL)
254 		fatal("matching cipher is not supported: %s", name);
255 	enc->name = name;
256 	enc->enabled = 0;
257 	enc->iv = NULL;
258 	enc->key = NULL;
259 	enc->key_len = cipher_keylen(enc->cipher);
260 	enc->block_size = cipher_blocksize(enc->cipher);
261 }
262 
263 static void
264 choose_mac(Mac *mac, char *client, char *server)
265 {
266 	char *name = match_list(client, server, NULL);
267 	if (name == NULL)
268 		fatal("no matching mac found: client %s server %s", client, server);
269 	if (mac_init(mac, name) < 0)
270 		fatal("unsupported mac %s", name);
271 	/* truncate the key */
272 	if (datafellows & SSH_BUG_HMAC)
273 		mac->key_len = 16;
274 	mac->name = name;
275 	mac->key = NULL;
276 	mac->enabled = 0;
277 }
278 
279 static void
280 choose_comp(Comp *comp, char *client, char *server)
281 {
282 	char *name = match_list(client, server, NULL);
283 	if (name == NULL)
284 		fatal("no matching comp found: client %s server %s", client, server);
285 	if (strcmp(name, "zlib@openssh.com") == 0) {
286 		comp->type = COMP_DELAYED;
287 	} else if (strcmp(name, "zlib") == 0) {
288 		comp->type = COMP_ZLIB;
289 	} else if (strcmp(name, "none") == 0) {
290 		comp->type = COMP_NONE;
291 	} else {
292 		fatal("unsupported comp %s", name);
293 	}
294 	comp->name = name;
295 }
296 
297 static void
298 choose_kex(Kex *k, char *client, char *server)
299 {
300 	k->name = match_list(client, server, NULL);
301 	if (k->name == NULL)
302 		fatal("no kex alg");
303 	if (strcmp(k->name, KEX_DH1) == 0) {
304 		k->kex_type = KEX_DH_GRP1_SHA1;
305 		k->evp_md = EVP_sha1();
306 	} else if (strcmp(k->name, KEX_DH14) == 0) {
307 		k->kex_type = KEX_DH_GRP14_SHA1;
308 		k->evp_md = EVP_sha1();
309 	} else if (strcmp(k->name, KEX_DHGEX_SHA1) == 0) {
310 		k->kex_type = KEX_DH_GEX_SHA1;
311 		k->evp_md = EVP_sha1();
312 	} else if (strcmp(k->name, KEX_DHGEX_SHA256) == 0) {
313 		k->kex_type = KEX_DH_GEX_SHA256;
314 		k->evp_md = evp_ssh_sha256();
315 	} else
316 		fatal("bad kex alg %s", k->name);
317 }
318 
319 static void
320 choose_hostkeyalg(Kex *k, char *client, char *server)
321 {
322 	char *hostkeyalg = match_list(client, server, NULL);
323 	if (hostkeyalg == NULL)
324 		fatal("no hostkey alg");
325 	k->hostkey_type = key_type_from_name(hostkeyalg);
326 	if (k->hostkey_type == KEY_UNSPEC)
327 		fatal("bad hostkey alg '%s'", hostkeyalg);
328 	xfree(hostkeyalg);
329 }
330 
331 static int
332 proposals_match(char *my[PROPOSAL_MAX], char *peer[PROPOSAL_MAX])
333 {
334 	static int check[] = {
335 		PROPOSAL_KEX_ALGS, PROPOSAL_SERVER_HOST_KEY_ALGS, -1
336 	};
337 	int *idx;
338 	char *p;
339 
340 	for (idx = &check[0]; *idx != -1; idx++) {
341 		if ((p = strchr(my[*idx], ',')) != NULL)
342 			*p = '\0';
343 		if ((p = strchr(peer[*idx], ',')) != NULL)
344 			*p = '\0';
345 		if (strcmp(my[*idx], peer[*idx]) != 0) {
346 			debug2("proposal mismatch: my %s peer %s",
347 			    my[*idx], peer[*idx]);
348 			return (0);
349 		}
350 	}
351 	debug2("proposals match");
352 	return (1);
353 }
354 
355 static void
356 kex_choose_conf(Kex *kex)
357 {
358 	Newkeys *newkeys;
359 	char **my, **peer;
360 	char **cprop, **sprop;
361 	int nenc, nmac, ncomp;
362 	u_int mode, ctos, need;
363 	int first_kex_follows, type;
364 
365 	my   = kex_buf2prop(&kex->my, NULL);
366 	peer = kex_buf2prop(&kex->peer, &first_kex_follows);
367 
368 	if (kex->server) {
369 		cprop=peer;
370 		sprop=my;
371 	} else {
372 		cprop=my;
373 		sprop=peer;
374 	}
375 
376 	/* Algorithm Negotiation */
377 	for (mode = 0; mode < MODE_MAX; mode++) {
378 		newkeys = xcalloc(1, sizeof(*newkeys));
379 		kex->newkeys[mode] = newkeys;
380 		ctos = (!kex->server && mode == MODE_OUT) || (kex->server && mode == MODE_IN);
381 		nenc  = ctos ? PROPOSAL_ENC_ALGS_CTOS  : PROPOSAL_ENC_ALGS_STOC;
382 		nmac  = ctos ? PROPOSAL_MAC_ALGS_CTOS  : PROPOSAL_MAC_ALGS_STOC;
383 		ncomp = ctos ? PROPOSAL_COMP_ALGS_CTOS : PROPOSAL_COMP_ALGS_STOC;
384 		choose_enc (&newkeys->enc,  cprop[nenc],  sprop[nenc]);
385 		choose_mac (&newkeys->mac,  cprop[nmac],  sprop[nmac]);
386 		choose_comp(&newkeys->comp, cprop[ncomp], sprop[ncomp]);
387 		debug("kex: %s %s %s %s",
388 		    ctos ? "client->server" : "server->client",
389 		    newkeys->enc.name,
390 		    newkeys->mac.name,
391 		    newkeys->comp.name);
392 	}
393 	choose_kex(kex, cprop[PROPOSAL_KEX_ALGS], sprop[PROPOSAL_KEX_ALGS]);
394 	choose_hostkeyalg(kex, cprop[PROPOSAL_SERVER_HOST_KEY_ALGS],
395 	    sprop[PROPOSAL_SERVER_HOST_KEY_ALGS]);
396 	need = 0;
397 	for (mode = 0; mode < MODE_MAX; mode++) {
398 		newkeys = kex->newkeys[mode];
399 		if (need < newkeys->enc.key_len)
400 			need = newkeys->enc.key_len;
401 		if (need < newkeys->enc.block_size)
402 			need = newkeys->enc.block_size;
403 		if (need < newkeys->mac.key_len)
404 			need = newkeys->mac.key_len;
405 	}
406 	/* XXX need runden? */
407 	kex->we_need = need;
408 
409 	/* ignore the next message if the proposals do not match */
410 	if (first_kex_follows && !proposals_match(my, peer) &&
411 	    !(datafellows & SSH_BUG_FIRSTKEX)) {
412 		type = packet_read();
413 		debug2("skipping next packet (type %u)", type);
414 	}
415 
416 	kex_prop_free(my);
417 	kex_prop_free(peer);
418 }
419 
420 static u_char *
421 derive_key(Kex *kex, int id, u_int need, u_char *hash, u_int hashlen,
422     BIGNUM *shared_secret)
423 {
424 	Buffer b;
425 	EVP_MD_CTX md;
426 	char c = id;
427 	u_int have;
428 	int mdsz;
429 	u_char *digest;
430 
431 	if ((mdsz = EVP_MD_size(kex->evp_md)) <= 0)
432 		fatal("bad kex md size %d", mdsz);
433 	digest = xmalloc(roundup(need, mdsz));
434 
435 	buffer_init(&b);
436 	buffer_put_bignum2(&b, shared_secret);
437 
438 	/* K1 = HASH(K || H || "A" || session_id) */
439 	EVP_DigestInit(&md, kex->evp_md);
440 	if (!(datafellows & SSH_BUG_DERIVEKEY))
441 		EVP_DigestUpdate(&md, buffer_ptr(&b), buffer_len(&b));
442 	EVP_DigestUpdate(&md, hash, hashlen);
443 	EVP_DigestUpdate(&md, &c, 1);
444 	EVP_DigestUpdate(&md, kex->session_id, kex->session_id_len);
445 	EVP_DigestFinal(&md, digest, NULL);
446 
447 	/*
448 	 * expand key:
449 	 * Kn = HASH(K || H || K1 || K2 || ... || Kn-1)
450 	 * Key = K1 || K2 || ... || Kn
451 	 */
452 	for (have = mdsz; need > have; have += mdsz) {
453 		EVP_DigestInit(&md, kex->evp_md);
454 		if (!(datafellows & SSH_BUG_DERIVEKEY))
455 			EVP_DigestUpdate(&md, buffer_ptr(&b), buffer_len(&b));
456 		EVP_DigestUpdate(&md, hash, hashlen);
457 		EVP_DigestUpdate(&md, digest, have);
458 		EVP_DigestFinal(&md, digest + have, NULL);
459 	}
460 	buffer_free(&b);
461 #ifdef DEBUG_KEX
462 	fprintf(stderr, "key '%c'== ", c);
463 	dump_digest("key", digest, need);
464 #endif
465 	return digest;
466 }
467 
468 Newkeys *current_keys[MODE_MAX];
469 
470 #define NKEYS	6
471 void
472 kex_derive_keys(Kex *kex, u_char *hash, u_int hashlen, BIGNUM *shared_secret)
473 {
474 	u_char *keys[NKEYS];
475 	u_int i, mode, ctos;
476 
477 	for (i = 0; i < NKEYS; i++) {
478 		keys[i] = derive_key(kex, 'A'+i, kex->we_need, hash, hashlen,
479 		    shared_secret);
480 	}
481 
482 	debug2("kex_derive_keys");
483 	for (mode = 0; mode < MODE_MAX; mode++) {
484 		current_keys[mode] = kex->newkeys[mode];
485 		kex->newkeys[mode] = NULL;
486 		ctos = (!kex->server && mode == MODE_OUT) ||
487 		    (kex->server && mode == MODE_IN);
488 		current_keys[mode]->enc.iv  = keys[ctos ? 0 : 1];
489 		current_keys[mode]->enc.key = keys[ctos ? 2 : 3];
490 		current_keys[mode]->mac.key = keys[ctos ? 4 : 5];
491 	}
492 }
493 
494 Newkeys *
495 kex_get_newkeys(int mode)
496 {
497 	Newkeys *ret;
498 
499 	ret = current_keys[mode];
500 	current_keys[mode] = NULL;
501 	return ret;
502 }
503 
504 void
505 derive_ssh1_session_id(BIGNUM *host_modulus, BIGNUM *server_modulus,
506     u_int8_t cookie[8], u_int8_t id[16])
507 {
508 	const EVP_MD *evp_md = EVP_md5();
509 	EVP_MD_CTX md;
510 	u_int8_t nbuf[2048], obuf[EVP_MAX_MD_SIZE];
511 	int len;
512 
513 	EVP_DigestInit(&md, evp_md);
514 
515 	len = BN_num_bytes(host_modulus);
516 	if (len < (512 / 8) || (u_int)len > sizeof(nbuf))
517 		fatal("%s: bad host modulus (len %d)", __func__, len);
518 	BN_bn2bin(host_modulus, nbuf);
519 	EVP_DigestUpdate(&md, nbuf, len);
520 
521 	len = BN_num_bytes(server_modulus);
522 	if (len < (512 / 8) || (u_int)len > sizeof(nbuf))
523 		fatal("%s: bad server modulus (len %d)", __func__, len);
524 	BN_bn2bin(server_modulus, nbuf);
525 	EVP_DigestUpdate(&md, nbuf, len);
526 
527 	EVP_DigestUpdate(&md, cookie, 8);
528 
529 	EVP_DigestFinal(&md, obuf, NULL);
530 	memcpy(id, obuf, 16);
531 
532 	memset(nbuf, 0, sizeof(nbuf));
533 	memset(obuf, 0, sizeof(obuf));
534 	memset(&md, 0, sizeof(md));
535 }
536 
537 #if defined(DEBUG_KEX) || defined(DEBUG_KEXDH)
538 void
539 dump_digest(char *msg, u_char *digest, int len)
540 {
541 	u_int i;
542 
543 	fprintf(stderr, "%s\n", msg);
544 	for (i = 0; i < len; i++) {
545 		fprintf(stderr, "%02x", digest[i]);
546 		if (i%32 == 31)
547 			fprintf(stderr, "\n");
548 		else if (i%8 == 7)
549 			fprintf(stderr, " ");
550 	}
551 	fprintf(stderr, "\n");
552 }
553 #endif
554