xref: /freebsd/crypto/openssh/kex.c (revision 6ae1554a5d9b318f8ad53ccc39fa5a961403da73)
1 /* $OpenBSD: kex.c,v 1.98 2014/02/02 03:44:31 djm Exp $ */
2 /* $FreeBSD$ */
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("$FreeBSD$");
29 
30 #include <sys/param.h>
31 
32 #include <signal.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 
38 #include <openssl/crypto.h>
39 
40 #include "xmalloc.h"
41 #include "ssh2.h"
42 #include "buffer.h"
43 #include "packet.h"
44 #include "compat.h"
45 #include "cipher.h"
46 #include "key.h"
47 #include "kex.h"
48 #include "log.h"
49 #include "mac.h"
50 #include "match.h"
51 #include "dispatch.h"
52 #include "monitor.h"
53 #include "roaming.h"
54 #include "digest.h"
55 
56 #if OPENSSL_VERSION_NUMBER >= 0x00907000L
57 # if defined(HAVE_EVP_SHA256)
58 # define evp_ssh_sha256 EVP_sha256
59 # else
60 extern const EVP_MD *evp_ssh_sha256(void);
61 # endif
62 #endif
63 
64 /* prototype */
65 static void kex_kexinit_finish(Kex *);
66 static void kex_choose_conf(Kex *);
67 
68 struct kexalg {
69 	char *name;
70 	int type;
71 	int ec_nid;
72 	int hash_alg;
73 };
74 static const struct kexalg kexalgs[] = {
75 	{ KEX_DH1, KEX_DH_GRP1_SHA1, 0, SSH_DIGEST_SHA1 },
76 	{ KEX_DH14, KEX_DH_GRP14_SHA1, 0, SSH_DIGEST_SHA1 },
77 	{ KEX_DHGEX_SHA1, KEX_DH_GEX_SHA1, 0, SSH_DIGEST_SHA1 },
78 #ifdef HAVE_EVP_SHA256
79 	{ KEX_DHGEX_SHA256, KEX_DH_GEX_SHA256, 0, SSH_DIGEST_SHA256 },
80 #endif
81 #ifdef OPENSSL_HAS_ECC
82 	{ KEX_ECDH_SHA2_NISTP256, KEX_ECDH_SHA2,
83 	    NID_X9_62_prime256v1, SSH_DIGEST_SHA256 },
84 	{ KEX_ECDH_SHA2_NISTP384, KEX_ECDH_SHA2, NID_secp384r1,
85 	    SSH_DIGEST_SHA384 },
86 # ifdef OPENSSL_HAS_NISTP521
87 	{ KEX_ECDH_SHA2_NISTP521, KEX_ECDH_SHA2, NID_secp521r1,
88 	    SSH_DIGEST_SHA512 },
89 # endif
90 #endif
91 	{ KEX_DH1, KEX_DH_GRP1_SHA1, 0, SSH_DIGEST_SHA1 },
92 #ifdef HAVE_EVP_SHA256
93 	{ KEX_CURVE25519_SHA256, KEX_C25519_SHA256, 0, SSH_DIGEST_SHA256 },
94 #endif
95 	{ NULL, -1, -1, -1},
96 };
97 
98 char *
99 kex_alg_list(char sep)
100 {
101 	char *ret = NULL;
102 	size_t nlen, rlen = 0;
103 	const struct kexalg *k;
104 
105 	for (k = kexalgs; k->name != NULL; k++) {
106 		if (ret != NULL)
107 			ret[rlen++] = sep;
108 		nlen = strlen(k->name);
109 		ret = xrealloc(ret, 1, rlen + nlen + 2);
110 		memcpy(ret + rlen, k->name, nlen + 1);
111 		rlen += nlen;
112 	}
113 	return ret;
114 }
115 
116 static const struct kexalg *
117 kex_alg_by_name(const char *name)
118 {
119 	const struct kexalg *k;
120 
121 	for (k = kexalgs; k->name != NULL; k++) {
122 		if (strcmp(k->name, name) == 0)
123 			return k;
124 	}
125 	return NULL;
126 }
127 
128 /* Validate KEX method name list */
129 int
130 kex_names_valid(const char *names)
131 {
132 	char *s, *cp, *p;
133 
134 	if (names == NULL || strcmp(names, "") == 0)
135 		return 0;
136 	s = cp = xstrdup(names);
137 	for ((p = strsep(&cp, ",")); p && *p != '\0';
138 	    (p = strsep(&cp, ","))) {
139 		if (kex_alg_by_name(p) == NULL) {
140 			error("Unsupported KEX algorithm \"%.100s\"", p);
141 			free(s);
142 			return 0;
143 		}
144 	}
145 	debug3("kex names ok: [%s]", names);
146 	free(s);
147 	return 1;
148 }
149 
150 /* put algorithm proposal into buffer. */
151 #ifndef NONE_CIPHER_ENABLED
152 static void
153 #else
154 /* Also used in sshconnect2.c. */
155 void
156 #endif
157 kex_prop2buf(Buffer *b, char *proposal[PROPOSAL_MAX])
158 {
159 	u_int i;
160 
161 	buffer_clear(b);
162 	/*
163 	 * add a dummy cookie, the cookie will be overwritten by
164 	 * kex_send_kexinit(), each time a kexinit is set
165 	 */
166 	for (i = 0; i < KEX_COOKIE_LEN; i++)
167 		buffer_put_char(b, 0);
168 	for (i = 0; i < PROPOSAL_MAX; i++)
169 		buffer_put_cstring(b, proposal[i]);
170 	buffer_put_char(b, 0);			/* first_kex_packet_follows */
171 	buffer_put_int(b, 0);			/* uint32 reserved */
172 }
173 
174 /* parse buffer and return algorithm proposal */
175 static char **
176 kex_buf2prop(Buffer *raw, int *first_kex_follows)
177 {
178 	Buffer b;
179 	u_int i;
180 	char **proposal;
181 
182 	proposal = xcalloc(PROPOSAL_MAX, sizeof(char *));
183 
184 	buffer_init(&b);
185 	buffer_append(&b, buffer_ptr(raw), buffer_len(raw));
186 	/* skip cookie */
187 	for (i = 0; i < KEX_COOKIE_LEN; i++)
188 		buffer_get_char(&b);
189 	/* extract kex init proposal strings */
190 	for (i = 0; i < PROPOSAL_MAX; i++) {
191 		proposal[i] = buffer_get_cstring(&b,NULL);
192 		debug2("kex_parse_kexinit: %s", proposal[i]);
193 	}
194 	/* first kex follows / reserved */
195 	i = buffer_get_char(&b);
196 	if (first_kex_follows != NULL)
197 		*first_kex_follows = i;
198 	debug2("kex_parse_kexinit: first_kex_follows %d ", i);
199 	i = buffer_get_int(&b);
200 	debug2("kex_parse_kexinit: reserved %u ", i);
201 	buffer_free(&b);
202 	return proposal;
203 }
204 
205 static void
206 kex_prop_free(char **proposal)
207 {
208 	u_int i;
209 
210 	for (i = 0; i < PROPOSAL_MAX; i++)
211 		free(proposal[i]);
212 	free(proposal);
213 }
214 
215 /* ARGSUSED */
216 static void
217 kex_protocol_error(int type, u_int32_t seq, void *ctxt)
218 {
219 	error("Hm, kex protocol error: type %d seq %u", type, seq);
220 }
221 
222 static void
223 kex_reset_dispatch(void)
224 {
225 	dispatch_range(SSH2_MSG_TRANSPORT_MIN,
226 	    SSH2_MSG_TRANSPORT_MAX, &kex_protocol_error);
227 	dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
228 }
229 
230 void
231 kex_finish(Kex *kex)
232 {
233 	kex_reset_dispatch();
234 
235 	packet_start(SSH2_MSG_NEWKEYS);
236 	packet_send();
237 	/* packet_write_wait(); */
238 	debug("SSH2_MSG_NEWKEYS sent");
239 
240 	debug("expecting SSH2_MSG_NEWKEYS");
241 	packet_read_expect(SSH2_MSG_NEWKEYS);
242 	packet_check_eom();
243 	debug("SSH2_MSG_NEWKEYS received");
244 
245 	kex->done = 1;
246 	buffer_clear(&kex->peer);
247 	/* buffer_clear(&kex->my); */
248 	kex->flags &= ~KEX_INIT_SENT;
249 	free(kex->name);
250 	kex->name = NULL;
251 }
252 
253 void
254 kex_send_kexinit(Kex *kex)
255 {
256 	u_int32_t rnd = 0;
257 	u_char *cookie;
258 	u_int i;
259 
260 	if (kex == NULL) {
261 		error("kex_send_kexinit: no kex, cannot rekey");
262 		return;
263 	}
264 	if (kex->flags & KEX_INIT_SENT) {
265 		debug("KEX_INIT_SENT");
266 		return;
267 	}
268 	kex->done = 0;
269 
270 	/* generate a random cookie */
271 	if (buffer_len(&kex->my) < KEX_COOKIE_LEN)
272 		fatal("kex_send_kexinit: kex proposal too short");
273 	cookie = buffer_ptr(&kex->my);
274 	for (i = 0; i < KEX_COOKIE_LEN; i++) {
275 		if (i % 4 == 0)
276 			rnd = arc4random();
277 		cookie[i] = rnd;
278 		rnd >>= 8;
279 	}
280 	packet_start(SSH2_MSG_KEXINIT);
281 	packet_put_raw(buffer_ptr(&kex->my), buffer_len(&kex->my));
282 	packet_send();
283 	debug("SSH2_MSG_KEXINIT sent");
284 	kex->flags |= KEX_INIT_SENT;
285 }
286 
287 /* ARGSUSED */
288 void
289 kex_input_kexinit(int type, u_int32_t seq, void *ctxt)
290 {
291 	char *ptr;
292 	u_int i, dlen;
293 	Kex *kex = (Kex *)ctxt;
294 
295 	debug("SSH2_MSG_KEXINIT received");
296 	if (kex == NULL)
297 		fatal("kex_input_kexinit: no kex, cannot rekey");
298 
299 	ptr = packet_get_raw(&dlen);
300 	buffer_append(&kex->peer, ptr, dlen);
301 
302 	/* discard packet */
303 	for (i = 0; i < KEX_COOKIE_LEN; i++)
304 		packet_get_char();
305 	for (i = 0; i < PROPOSAL_MAX; i++)
306 		free(packet_get_string(NULL));
307 	/*
308 	 * XXX RFC4253 sec 7: "each side MAY guess" - currently no supported
309 	 * KEX method has the server move first, but a server might be using
310 	 * a custom method or one that we otherwise don't support. We should
311 	 * be prepared to remember first_kex_follows here so we can eat a
312 	 * packet later.
313 	 * XXX2 - RFC4253 is kind of ambiguous on what first_kex_follows means
314 	 * for cases where the server *doesn't* go first. I guess we should
315 	 * ignore it when it is set for these cases, which is what we do now.
316 	 */
317 	(void) packet_get_char();	/* first_kex_follows */
318 	(void) packet_get_int();	/* reserved */
319 	packet_check_eom();
320 
321 	kex_kexinit_finish(kex);
322 }
323 
324 Kex *
325 kex_setup(char *proposal[PROPOSAL_MAX])
326 {
327 	Kex *kex;
328 
329 	kex = xcalloc(1, sizeof(*kex));
330 	buffer_init(&kex->peer);
331 	buffer_init(&kex->my);
332 	kex_prop2buf(&kex->my, proposal);
333 	kex->done = 0;
334 
335 	kex_send_kexinit(kex);					/* we start */
336 	kex_reset_dispatch();
337 
338 	return kex;
339 }
340 
341 static void
342 kex_kexinit_finish(Kex *kex)
343 {
344 	if (!(kex->flags & KEX_INIT_SENT))
345 		kex_send_kexinit(kex);
346 
347 	kex_choose_conf(kex);
348 
349 	if (kex->kex_type >= 0 && kex->kex_type < KEX_MAX &&
350 	    kex->kex[kex->kex_type] != NULL) {
351 		(kex->kex[kex->kex_type])(kex);
352 	} else {
353 		fatal("Unsupported key exchange %d", kex->kex_type);
354 	}
355 }
356 
357 static void
358 choose_enc(Enc *enc, char *client, char *server)
359 {
360 	char *name = match_list(client, server, NULL);
361 	if (name == NULL)
362 		fatal("no matching cipher found: client %s server %s",
363 		    client, server);
364 	if ((enc->cipher = cipher_by_name(name)) == NULL)
365 		fatal("matching cipher is not supported: %s", name);
366 	enc->name = name;
367 	enc->enabled = 0;
368 	enc->iv = NULL;
369 	enc->iv_len = cipher_ivlen(enc->cipher);
370 	enc->key = NULL;
371 	enc->key_len = cipher_keylen(enc->cipher);
372 	enc->block_size = cipher_blocksize(enc->cipher);
373 }
374 
375 static void
376 choose_mac(Mac *mac, char *client, char *server)
377 {
378 	char *name = match_list(client, server, NULL);
379 	if (name == NULL)
380 		fatal("no matching mac found: client %s server %s",
381 		    client, server);
382 	if (mac_setup(mac, name) < 0)
383 		fatal("unsupported mac %s", name);
384 	/* truncate the key */
385 	if (datafellows & SSH_BUG_HMAC)
386 		mac->key_len = 16;
387 	mac->name = name;
388 	mac->key = NULL;
389 	mac->enabled = 0;
390 }
391 
392 static void
393 choose_comp(Comp *comp, char *client, char *server)
394 {
395 	char *name = match_list(client, server, NULL);
396 	if (name == NULL)
397 		fatal("no matching comp found: client %s server %s", client, server);
398 	if (strcmp(name, "zlib@openssh.com") == 0) {
399 		comp->type = COMP_DELAYED;
400 	} else if (strcmp(name, "zlib") == 0) {
401 		comp->type = COMP_ZLIB;
402 	} else if (strcmp(name, "none") == 0) {
403 		comp->type = COMP_NONE;
404 	} else {
405 		fatal("unsupported comp %s", name);
406 	}
407 	comp->name = name;
408 }
409 
410 static void
411 choose_kex(Kex *k, char *client, char *server)
412 {
413 	const struct kexalg *kexalg;
414 
415 	k->name = match_list(client, server, NULL);
416 	if (k->name == NULL)
417 		fatal("Unable to negotiate a key exchange method");
418 	if ((kexalg = kex_alg_by_name(k->name)) == NULL)
419 		fatal("unsupported kex alg %s", k->name);
420 	k->kex_type = kexalg->type;
421 	k->hash_alg = kexalg->hash_alg;
422 	k->ec_nid = kexalg->ec_nid;
423 }
424 
425 static void
426 choose_hostkeyalg(Kex *k, char *client, char *server)
427 {
428 	char *hostkeyalg = match_list(client, server, NULL);
429 	if (hostkeyalg == NULL)
430 		fatal("no hostkey alg");
431 	k->hostkey_type = key_type_from_name(hostkeyalg);
432 	if (k->hostkey_type == KEY_UNSPEC)
433 		fatal("bad hostkey alg '%s'", hostkeyalg);
434 	free(hostkeyalg);
435 }
436 
437 static int
438 proposals_match(char *my[PROPOSAL_MAX], char *peer[PROPOSAL_MAX])
439 {
440 	static int check[] = {
441 		PROPOSAL_KEX_ALGS, PROPOSAL_SERVER_HOST_KEY_ALGS, -1
442 	};
443 	int *idx;
444 	char *p;
445 
446 	for (idx = &check[0]; *idx != -1; idx++) {
447 		if ((p = strchr(my[*idx], ',')) != NULL)
448 			*p = '\0';
449 		if ((p = strchr(peer[*idx], ',')) != NULL)
450 			*p = '\0';
451 		if (strcmp(my[*idx], peer[*idx]) != 0) {
452 			debug2("proposal mismatch: my %s peer %s",
453 			    my[*idx], peer[*idx]);
454 			return (0);
455 		}
456 	}
457 	debug2("proposals match");
458 	return (1);
459 }
460 
461 static void
462 kex_choose_conf(Kex *kex)
463 {
464 	Newkeys *newkeys;
465 	char **my, **peer;
466 	char **cprop, **sprop;
467 	int nenc, nmac, ncomp;
468 	u_int mode, ctos, need, dh_need, authlen;
469 	int first_kex_follows, type;
470 #ifdef	NONE_CIPHER_ENABLED
471 	int auth_flag;
472 #endif
473 
474 	my   = kex_buf2prop(&kex->my, NULL);
475 	peer = kex_buf2prop(&kex->peer, &first_kex_follows);
476 
477 	if (kex->server) {
478 		cprop=peer;
479 		sprop=my;
480 	} else {
481 		cprop=my;
482 		sprop=peer;
483 	}
484 
485 	/* Check whether server offers roaming */
486 	if (!kex->server) {
487 		char *roaming;
488 		roaming = match_list(KEX_RESUME, peer[PROPOSAL_KEX_ALGS], NULL);
489 		if (roaming) {
490 			kex->roaming = 1;
491 			free(roaming);
492 		}
493 	}
494 
495 	/* Algorithm Negotiation */
496 #ifdef	NONE_CIPHER_ENABLED
497 	auth_flag = packet_get_authentication_state();
498 	debug ("AUTH STATE is %d", auth_flag);
499 #endif
500 	for (mode = 0; mode < MODE_MAX; mode++) {
501 		newkeys = xcalloc(1, sizeof(*newkeys));
502 		kex->newkeys[mode] = newkeys;
503 		ctos = (!kex->server && mode == MODE_OUT) ||
504 		    (kex->server && mode == MODE_IN);
505 		nenc  = ctos ? PROPOSAL_ENC_ALGS_CTOS  : PROPOSAL_ENC_ALGS_STOC;
506 		nmac  = ctos ? PROPOSAL_MAC_ALGS_CTOS  : PROPOSAL_MAC_ALGS_STOC;
507 		ncomp = ctos ? PROPOSAL_COMP_ALGS_CTOS : PROPOSAL_COMP_ALGS_STOC;
508 		choose_enc(&newkeys->enc, cprop[nenc], sprop[nenc]);
509 		/* ignore mac for authenticated encryption */
510 		authlen = cipher_authlen(newkeys->enc.cipher);
511 		if (authlen == 0)
512 			choose_mac(&newkeys->mac, cprop[nmac], sprop[nmac]);
513 		choose_comp(&newkeys->comp, cprop[ncomp], sprop[ncomp]);
514 #ifdef	NONE_CIPHER_ENABLED
515 		debug("REQUESTED ENC.NAME is '%s'", newkeys->enc.name);
516 		if (strcmp(newkeys->enc.name, "none") == 0) {
517 			debug("Requesting NONE. Authflag is %d", auth_flag);
518 			if (auth_flag == 1)
519 				debug("None requested post authentication.");
520 			else
521 				fatal("Pre-authentication none cipher requests "
522 				    "are not allowed.");
523 		}
524 #endif
525 		debug("kex: %s %s %s %s",
526 		    ctos ? "client->server" : "server->client",
527 		    newkeys->enc.name,
528 		    authlen == 0 ? newkeys->mac.name : "<implicit>",
529 		    newkeys->comp.name);
530 	}
531 	choose_kex(kex, cprop[PROPOSAL_KEX_ALGS], sprop[PROPOSAL_KEX_ALGS]);
532 	choose_hostkeyalg(kex, cprop[PROPOSAL_SERVER_HOST_KEY_ALGS],
533 	    sprop[PROPOSAL_SERVER_HOST_KEY_ALGS]);
534 	need = dh_need = 0;
535 	for (mode = 0; mode < MODE_MAX; mode++) {
536 		newkeys = kex->newkeys[mode];
537 		need = MAX(need, newkeys->enc.key_len);
538 		need = MAX(need, newkeys->enc.block_size);
539 		need = MAX(need, newkeys->enc.iv_len);
540 		need = MAX(need, newkeys->mac.key_len);
541 		dh_need = MAX(dh_need, cipher_seclen(newkeys->enc.cipher));
542 		dh_need = MAX(dh_need, newkeys->enc.block_size);
543 		dh_need = MAX(dh_need, newkeys->enc.iv_len);
544 		dh_need = MAX(dh_need, newkeys->mac.key_len);
545 	}
546 	/* XXX need runden? */
547 	kex->we_need = need;
548 	kex->dh_need = dh_need;
549 
550 	/* ignore the next message if the proposals do not match */
551 	if (first_kex_follows && !proposals_match(my, peer) &&
552 	    !(datafellows & SSH_BUG_FIRSTKEX)) {
553 		type = packet_read();
554 		debug2("skipping next packet (type %u)", type);
555 	}
556 
557 	kex_prop_free(my);
558 	kex_prop_free(peer);
559 }
560 
561 static u_char *
562 derive_key(Kex *kex, int id, u_int need, u_char *hash, u_int hashlen,
563     const u_char *shared_secret, u_int slen)
564 {
565 	Buffer b;
566 	struct ssh_digest_ctx *hashctx;
567 	char c = id;
568 	u_int have;
569 	size_t mdsz;
570 	u_char *digest;
571 
572 	if ((mdsz = ssh_digest_bytes(kex->hash_alg)) == 0)
573 		fatal("bad kex md size %zu", mdsz);
574 	digest = xmalloc(roundup(need, mdsz));
575 
576 	buffer_init(&b);
577 	buffer_append(&b, shared_secret, slen);
578 
579 	/* K1 = HASH(K || H || "A" || session_id) */
580 	if ((hashctx = ssh_digest_start(kex->hash_alg)) == NULL)
581 		fatal("%s: ssh_digest_start failed", __func__);
582 	if (ssh_digest_update_buffer(hashctx, &b) != 0 ||
583 	    ssh_digest_update(hashctx, hash, hashlen) != 0 ||
584 	    ssh_digest_update(hashctx, &c, 1) != 0 ||
585 	    ssh_digest_update(hashctx, kex->session_id,
586 	    kex->session_id_len) != 0)
587 		fatal("%s: ssh_digest_update failed", __func__);
588 	if (ssh_digest_final(hashctx, digest, mdsz) != 0)
589 		fatal("%s: ssh_digest_final failed", __func__);
590 	ssh_digest_free(hashctx);
591 
592 	/*
593 	 * expand key:
594 	 * Kn = HASH(K || H || K1 || K2 || ... || Kn-1)
595 	 * Key = K1 || K2 || ... || Kn
596 	 */
597 	for (have = mdsz; need > have; have += mdsz) {
598 		if ((hashctx = ssh_digest_start(kex->hash_alg)) == NULL)
599 			fatal("%s: ssh_digest_start failed", __func__);
600 		if (ssh_digest_update_buffer(hashctx, &b) != 0 ||
601 		    ssh_digest_update(hashctx, hash, hashlen) != 0 ||
602 		    ssh_digest_update(hashctx, digest, have) != 0)
603 			fatal("%s: ssh_digest_update failed", __func__);
604 		if (ssh_digest_final(hashctx, digest + have, mdsz) != 0)
605 			fatal("%s: ssh_digest_final failed", __func__);
606 		ssh_digest_free(hashctx);
607 	}
608 	buffer_free(&b);
609 #ifdef DEBUG_KEX
610 	fprintf(stderr, "key '%c'== ", c);
611 	dump_digest("key", digest, need);
612 #endif
613 	return digest;
614 }
615 
616 Newkeys *current_keys[MODE_MAX];
617 
618 #define NKEYS	6
619 void
620 kex_derive_keys(Kex *kex, u_char *hash, u_int hashlen,
621     const u_char *shared_secret, u_int slen)
622 {
623 	u_char *keys[NKEYS];
624 	u_int i, mode, ctos;
625 
626 	for (i = 0; i < NKEYS; i++) {
627 		keys[i] = derive_key(kex, 'A'+i, kex->we_need, hash, hashlen,
628 		    shared_secret, slen);
629 	}
630 
631 	debug2("kex_derive_keys");
632 	for (mode = 0; mode < MODE_MAX; mode++) {
633 		current_keys[mode] = kex->newkeys[mode];
634 		kex->newkeys[mode] = NULL;
635 		ctos = (!kex->server && mode == MODE_OUT) ||
636 		    (kex->server && mode == MODE_IN);
637 		current_keys[mode]->enc.iv  = keys[ctos ? 0 : 1];
638 		current_keys[mode]->enc.key = keys[ctos ? 2 : 3];
639 		current_keys[mode]->mac.key = keys[ctos ? 4 : 5];
640 	}
641 }
642 
643 void
644 kex_derive_keys_bn(Kex *kex, u_char *hash, u_int hashlen, const BIGNUM *secret)
645 {
646 	Buffer shared_secret;
647 
648 	buffer_init(&shared_secret);
649 	buffer_put_bignum2(&shared_secret, secret);
650 	kex_derive_keys(kex, hash, hashlen,
651 	    buffer_ptr(&shared_secret), buffer_len(&shared_secret));
652 	buffer_free(&shared_secret);
653 }
654 
655 Newkeys *
656 kex_get_newkeys(int mode)
657 {
658 	Newkeys *ret;
659 
660 	ret = current_keys[mode];
661 	current_keys[mode] = NULL;
662 	return ret;
663 }
664 
665 void
666 derive_ssh1_session_id(BIGNUM *host_modulus, BIGNUM *server_modulus,
667     u_int8_t cookie[8], u_int8_t id[16])
668 {
669 	u_int8_t nbuf[2048], obuf[SSH_DIGEST_MAX_LENGTH];
670 	int len;
671 	struct ssh_digest_ctx *hashctx;
672 
673 	if ((hashctx = ssh_digest_start(SSH_DIGEST_MD5)) == NULL)
674 		fatal("%s: ssh_digest_start", __func__);
675 
676 	len = BN_num_bytes(host_modulus);
677 	if (len < (512 / 8) || (u_int)len > sizeof(nbuf))
678 		fatal("%s: bad host modulus (len %d)", __func__, len);
679 	BN_bn2bin(host_modulus, nbuf);
680 	if (ssh_digest_update(hashctx, nbuf, len) != 0)
681 		fatal("%s: ssh_digest_update failed", __func__);
682 
683 	len = BN_num_bytes(server_modulus);
684 	if (len < (512 / 8) || (u_int)len > sizeof(nbuf))
685 		fatal("%s: bad server modulus (len %d)", __func__, len);
686 	BN_bn2bin(server_modulus, nbuf);
687 	if (ssh_digest_update(hashctx, nbuf, len) != 0 ||
688 	    ssh_digest_update(hashctx, cookie, 8) != 0)
689 		fatal("%s: ssh_digest_update failed", __func__);
690 	if (ssh_digest_final(hashctx, obuf, sizeof(obuf)) != 0)
691 		fatal("%s: ssh_digest_final failed", __func__);
692 	memcpy(id, obuf, ssh_digest_bytes(SSH_DIGEST_MD5));
693 
694 	explicit_bzero(nbuf, sizeof(nbuf));
695 	explicit_bzero(obuf, sizeof(obuf));
696 }
697 
698 #if defined(DEBUG_KEX) || defined(DEBUG_KEXDH) || defined(DEBUG_KEXECDH)
699 void
700 dump_digest(char *msg, u_char *digest, int len)
701 {
702 	int i;
703 
704 	fprintf(stderr, "%s\n", msg);
705 	for (i = 0; i < len; i++) {
706 		fprintf(stderr, "%02x", digest[i]);
707 		if (i%32 == 31)
708 			fprintf(stderr, "\n");
709 		else if (i%8 == 7)
710 			fprintf(stderr, " ");
711 	}
712 	fprintf(stderr, "\n");
713 }
714 #endif
715