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