xref: /titanic_41/usr/src/cmd/ssh/libssh/common/kex.c (revision 0f1702c5201310f0529cd5abb77652e5e9b241b6)
1 /*
2  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
14  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
15  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
16  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
17  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
18  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
19  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
20  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
21  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
22  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23  *
24  * Copyright 2008 Sun Microsystems, Inc.  All rights reserved.
25  * Use is subject to license terms.
26  */
27 
28 #include "includes.h"
29 RCSID("$OpenBSD: kex.c,v 1.51 2002/06/24 14:55:38 markus Exp $");
30 
31 #include <locale.h>
32 
33 #include <openssl/crypto.h>
34 
35 #include "ssh2.h"
36 #include "xmalloc.h"
37 #include "buffer.h"
38 #include "bufaux.h"
39 #include "packet.h"
40 #include "compat.h"
41 #include "cipher.h"
42 #include "kex.h"
43 #include "key.h"
44 #include "log.h"
45 #include "mac.h"
46 #include "match.h"
47 #include "dispatch.h"
48 #include "g11n.h"
49 
50 #ifdef GSSAPI
51 #include "ssh-gss.h"
52 #endif
53 
54 #define KEX_COOKIE_LEN	16
55 
56 char *session_lang = NULL;
57 
58 
59 /* prototype */
60 static void kex_do_hook(Kex *kex);
61 static void kex_kexinit_finish(Kex *);
62 static void kex_choose_conf(Kex *);
63 
64 /* put algorithm proposal into buffer */
65 static
66 void
67 kex_prop2buf(Buffer *b, char *proposal[PROPOSAL_MAX])
68 {
69 	int i;
70 
71 	buffer_clear(b);
72 	/*
73 	 * add a dummy cookie, the cookie will be overwritten by
74 	 * kex_send_kexinit(), each time a kexinit is set
75 	 */
76 	for (i = 0; i < KEX_COOKIE_LEN; i++)
77 		buffer_put_char(b, 0);
78 	for (i = 0; i < PROPOSAL_MAX; i++)
79 		buffer_put_cstring(b, proposal[i]);
80 	buffer_put_char(b, 0);			/* first_kex_packet_follows */
81 	buffer_put_int(b, 0);			/* uint32 reserved */
82 }
83 
84 /* parse buffer and return algorithm proposal */
85 static
86 char **
87 kex_buf2prop(Buffer *raw, int *first_kex_follows)
88 {
89 	Buffer b;
90 	int i;
91 	char **proposal;
92 
93 	proposal = xmalloc(PROPOSAL_MAX * sizeof(char *));
94 
95 	buffer_init(&b);
96 	buffer_append(&b, buffer_ptr(raw), buffer_len(raw));
97 	/* skip cookie */
98 	for (i = 0; i < KEX_COOKIE_LEN; i++)
99 		buffer_get_char(&b);
100 	/* extract kex init proposal strings */
101 	for (i = 0; i < PROPOSAL_MAX; i++) {
102 		proposal[i] = buffer_get_string(&b,NULL);
103 		debug2("kex_parse_kexinit: %s", proposal[i]);
104 	}
105 	/* first kex follows / reserved */
106 	i = buffer_get_char(&b);
107 	if (first_kex_follows != NULL)
108 		*first_kex_follows = i;
109 	debug2("kex_parse_kexinit: first_kex_follows %d ", i);
110 	i = buffer_get_int(&b);
111 	debug2("kex_parse_kexinit: reserved %d ", i);
112 	buffer_free(&b);
113 	return proposal;
114 }
115 
116 static
117 void
118 kex_prop_free(char **proposal)
119 {
120 	int i;
121 
122 	for (i = 0; i < PROPOSAL_MAX; i++)
123 		xfree(proposal[i]);
124 	xfree(proposal);
125 }
126 
127 static void
128 kex_protocol_error(int type, u_int32_t seq, void *ctxt)
129 {
130 	error("Hm, kex protocol error: type %d seq %u", type, seq);
131 }
132 
133 static void
134 kex_reset_dispatch(void)
135 {
136 #ifdef ALTPRIVSEP
137 	/* unprivileged sshd has a kex packet handler that must not be reset */
138 	debug3("kex_reset_dispatch -- should we dispatch_set(KEXINIT) here? %d && !%d",
139 		packet_is_server(), packet_is_monitor());
140 	if (packet_is_server() && !packet_is_monitor()) {
141 		debug3("kex_reset_dispatch -- skipping dispatch_set(KEXINIT) in unpriv proc");
142 		return;
143 	}
144 #endif /* ALTPRIVSEP */
145 
146 	dispatch_range(SSH2_MSG_TRANSPORT_MIN,
147 	    SSH2_MSG_TRANSPORT_MAX, &kex_protocol_error);
148 	dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
149 }
150 
151 void
152 kex_finish(Kex *kex)
153 {
154 	kex_reset_dispatch();
155 
156 	packet_start(SSH2_MSG_NEWKEYS);
157 	packet_send();
158 	/* packet_write_wait(); */
159 	debug("SSH2_MSG_NEWKEYS sent");
160 
161 #ifdef ALTPRIVSEP
162 	if (packet_is_monitor())
163 		goto skip_newkeys;
164 #endif /* ALTPRIVSEP */
165 	debug("expecting SSH2_MSG_NEWKEYS");
166 	packet_read_expect(SSH2_MSG_NEWKEYS);
167 	packet_check_eom();
168 	debug("SSH2_MSG_NEWKEYS received");
169 #ifdef ALTPRIVSEP
170 skip_newkeys:
171 #endif /* ALTPRIVSEP */
172 
173 	kex->done = 1;
174 	kex->initial_kex_done = 1; /* never to be cleared once set */
175 	buffer_clear(&kex->peer);
176 	/* buffer_clear(&kex->my); */
177 	kex->flags &= ~KEX_INIT_SENT;
178 	xfree(kex->name);
179 	kex->name = NULL;
180 }
181 
182 void
183 kex_send_kexinit(Kex *kex)
184 {
185 	u_int32_t rand = 0;
186 	u_char *cookie;
187 	int i;
188 
189 	if (kex == NULL) {
190 		error("kex_send_kexinit: no kex, cannot rekey");
191 		return;
192 	}
193 	if (kex->flags & KEX_INIT_SENT) {
194 		debug("KEX_INIT_SENT");
195 		return;
196 	}
197 	kex->done = 0;
198 
199 	/* update my proposal -- e.g., add/remove GSS kexalgs */
200 	kex_do_hook(kex);
201 
202 	/* generate a random cookie */
203 	if (buffer_len(&kex->my) < KEX_COOKIE_LEN)
204 		fatal("kex_send_kexinit: kex proposal too short");
205 	cookie = buffer_ptr(&kex->my);
206 	for (i = 0; i < KEX_COOKIE_LEN; i++) {
207 		if (i % 4 == 0)
208 			rand = arc4random();
209 		cookie[i] = rand;
210 		rand >>= 8;
211 	}
212 	packet_start(SSH2_MSG_KEXINIT);
213 	packet_put_raw(buffer_ptr(&kex->my), buffer_len(&kex->my));
214 	packet_send();
215 	debug("SSH2_MSG_KEXINIT sent");
216 	kex->flags |= KEX_INIT_SENT;
217 }
218 
219 void
220 kex_input_kexinit(int type, u_int32_t seq, void *ctxt)
221 {
222 	char *ptr;
223 	u_int dlen;
224 	int i;
225 	Kex *kex = (Kex *)ctxt;
226 
227 	debug("SSH2_MSG_KEXINIT received");
228 	if (kex == NULL)
229 		fatal("kex_input_kexinit: no kex, cannot rekey");
230 
231 	ptr = packet_get_raw(&dlen);
232 	buffer_append(&kex->peer, ptr, dlen);
233 
234 	/* discard packet */
235 	for (i = 0; i < KEX_COOKIE_LEN; i++)
236 		packet_get_char();
237 	for (i = 0; i < PROPOSAL_MAX; i++)
238 		xfree(packet_get_string(NULL));
239 	(void) packet_get_char();
240 	(void) packet_get_int();
241 	packet_check_eom();
242 
243 	kex_kexinit_finish(kex);
244 }
245 
246 /*
247  * This is for GSS keyex, where actual KEX offer can change at rekey
248  * time due to credential expiration/renewal...
249  */
250 static
251 void
252 kex_do_hook(Kex *kex)
253 {
254 	char    **prop;
255 
256 	if (kex->kex_hook == NULL)
257 		return;
258 
259 	/* Unmarshall my proposal, let the hook modify it, remarshall it */
260 	prop = kex_buf2prop(&kex->my, NULL);
261 	buffer_clear(&kex->my);
262 	(kex->kex_hook)(kex, prop);
263 	kex_prop2buf(&kex->my, prop);
264 	kex_prop_free(prop);
265 }
266 
267 /* Initiate the key exchange by sending the SSH2_MSG_KEXINIT message. */
268 void
269 kex_start(Kex *kex)
270 {
271 	kex_send_kexinit(kex);
272 	kex_reset_dispatch();
273 }
274 
275 /*
276  * Allocate a key exchange structure and populate it with a proposal we are
277  * going to use. This function does not start the actual key exchange.
278  */
279 Kex *
280 kex_setup(const char *host, char *proposal[PROPOSAL_MAX], Kex_hook_func hook)
281 {
282 	Kex	*kex;
283 
284 	kex = xmalloc(sizeof(*kex));
285 	memset(kex, 0, sizeof(*kex));
286 	buffer_init(&kex->peer);
287 	buffer_init(&kex->my);
288 
289 	kex->kex_hook = hook; /* called by kex_send_kexinit() */
290 
291 	if (host != NULL && *host != '\0')
292 		kex->serverhost = xstrdup(host);
293 	else
294 		kex->server = 1;
295 
296 	kex_prop2buf(&kex->my, proposal);
297 
298 	return kex;
299 }
300 
301 static void
302 kex_kexinit_finish(Kex *kex)
303 {
304 	if (!(kex->flags & KEX_INIT_SENT))
305 		kex_send_kexinit(kex);
306 
307 	kex_choose_conf(kex);
308 
309 	if (kex->kex_type >= 0 && kex->kex_type < KEX_MAX &&
310 	    kex->kex[kex->kex_type] != NULL)
311 		(kex->kex[kex->kex_type])(kex);
312 	else
313 		fatal("Unsupported key exchange %d", kex->kex_type);
314 }
315 
316 static void
317 choose_lang(char **lang, char *client, char *server)
318 {
319 	if (datafellows & SSH_BUG_LOCALES_NOT_LANGTAGS)
320 		*lang = match_list(client, server, NULL);
321 	else
322 		*lang = g11n_srvr_locale_negotiate(client, NULL);
323 }
324 static void
325 choose_enc(Enc *enc, char *client, char *server)
326 {
327 	char *name = match_list(client, server, NULL);
328 	if (name == NULL)
329 		fatal("no matching cipher found: client %s server %s", client, server);
330 	if ((enc->cipher = cipher_by_name(name)) == NULL)
331 		fatal("matching cipher is not supported: %s", name);
332 	enc->name = name;
333 	enc->enabled = 0;
334 	enc->iv = NULL;
335 	enc->key = NULL;
336 	enc->key_len = cipher_keylen(enc->cipher);
337 	enc->block_size = cipher_blocksize(enc->cipher);
338 }
339 static void
340 choose_mac(Mac *mac, char *client, char *server)
341 {
342 	char *name = match_list(client, server, NULL);
343 	if (name == NULL)
344 		fatal("no matching mac found: client %s server %s", client, server);
345 	if (mac_init(mac, name) < 0)
346 		fatal("unsupported mac %s", name);
347 	/* truncate the key */
348 	if (datafellows & SSH_BUG_HMAC)
349 		mac->key_len = 16;
350 	mac->name = name;
351 	mac->key = NULL;
352 	mac->enabled = 0;
353 }
354 static void
355 choose_comp(Comp *comp, char *client, char *server)
356 {
357 	char *name = match_list(client, server, NULL);
358 	if (name == NULL)
359 		fatal("no matching comp found: client %s server %s", client, server);
360 	if (strcmp(name, "zlib") == 0) {
361 		comp->type = 1;
362 	} else if (strcmp(name, "none") == 0) {
363 		comp->type = 0;
364 	} else {
365 		fatal("unsupported comp %s", name);
366 	}
367 	comp->name = name;
368 }
369 static void
370 choose_kex(Kex *k, char *client, char *server)
371 {
372 	k->name = match_list(client, server, NULL);
373 	if (k->name == NULL)
374 		fatal("no common kex alg: client '%s', server '%s'", client,
375 		    server);
376 	/* XXX Finish 3.6/7 merge of kex stuff -- choose_kex() done */
377 	if (strcmp(k->name, KEX_DH1) == 0) {
378 		k->kex_type = KEX_DH_GRP1_SHA1;
379 	} else if (strcmp(k->name, KEX_DHGEX) == 0) {
380 		k->kex_type = KEX_DH_GEX_SHA1;
381 #ifdef GSSAPI
382 	} else if (strncmp(k->name, KEX_GSS_SHA1, sizeof(KEX_GSS_SHA1)-1) == 0) {
383 		k->kex_type = KEX_GSS_GRP1_SHA1;
384 #endif
385 	} else
386 		fatal("bad kex alg %s", k->name);
387 }
388 static void
389 choose_hostkeyalg(Kex *k, char *client, char *server)
390 {
391 	char *hostkeyalg = match_list(client, server, NULL);
392 	if (hostkeyalg == NULL)
393 		fatal("no hostkey alg");
394 	k->hostkey_type = key_type_from_name(hostkeyalg);
395 	if (k->hostkey_type == KEY_UNSPEC)
396 		fatal("bad hostkey alg '%s'", hostkeyalg);
397 	xfree(hostkeyalg);
398 }
399 
400 static int
401 proposals_match(char *my[PROPOSAL_MAX], char *peer[PROPOSAL_MAX])
402 {
403 	static int check[] = {
404 		PROPOSAL_KEX_ALGS, PROPOSAL_SERVER_HOST_KEY_ALGS, -1
405 	};
406 	int *idx;
407 	char *p;
408 
409 	for (idx = &check[0]; *idx != -1; idx++) {
410 		if ((p = strchr(my[*idx], ',')) != NULL)
411 			*p = '\0';
412 		if ((p = strchr(peer[*idx], ',')) != NULL)
413 			*p = '\0';
414 		if (strcmp(my[*idx], peer[*idx]) != 0) {
415 			debug2("proposal mismatch: my %s peer %s",
416 			    my[*idx], peer[*idx]);
417 			return (0);
418 		}
419 	}
420 	debug2("proposals match");
421 	return (1);
422 }
423 
424 static void
425 kex_choose_conf(Kex *kex)
426 {
427 	Newkeys *newkeys;
428 	char **my, **peer;
429 	char **cprop, **sprop;
430 	char *p_langs_c2s, *p_langs_s2c; /* peer's langs */
431 	char *plangs = NULL;		 /* peer's langs*/
432 	char *mlangs = NULL;		 /* my langs */
433 	int nenc, nmac, ncomp;
434 	int mode;
435 	int ctos;				/* direction: if true client-to-server */
436 	int need;
437 	int first_kex_follows, type;
438 
439 	my   = kex_buf2prop(&kex->my, NULL);
440 	peer = kex_buf2prop(&kex->peer, &first_kex_follows);
441 
442 	if (kex->server) {
443 		cprop=peer;
444 		sprop=my;
445 	} else {
446 		cprop=my;
447 		sprop=peer;
448 	}
449 
450 	/* Algorithm Negotiation */
451 	for (mode = 0; mode < MODE_MAX; mode++) {
452 		newkeys = xmalloc(sizeof(*newkeys));
453 		memset(newkeys, 0, sizeof(*newkeys));
454 		kex->newkeys[mode] = newkeys;
455 		ctos = (!kex->server && mode == MODE_OUT) || (kex->server && mode == MODE_IN);
456 		nenc  = ctos ? PROPOSAL_ENC_ALGS_CTOS  : PROPOSAL_ENC_ALGS_STOC;
457 		nmac  = ctos ? PROPOSAL_MAC_ALGS_CTOS  : PROPOSAL_MAC_ALGS_STOC;
458 		ncomp = ctos ? PROPOSAL_COMP_ALGS_CTOS : PROPOSAL_COMP_ALGS_STOC;
459 		choose_enc (&newkeys->enc,  cprop[nenc],  sprop[nenc]);
460 		choose_mac (&newkeys->mac,  cprop[nmac],  sprop[nmac]);
461 		choose_comp(&newkeys->comp, cprop[ncomp], sprop[ncomp]);
462 		debug("kex: %s %s %s %s",
463 		    ctos ? "client->server" : "server->client",
464 		    newkeys->enc.name,
465 		    newkeys->mac.name,
466 		    newkeys->comp.name);
467 	}
468 	choose_kex(kex, cprop[PROPOSAL_KEX_ALGS], sprop[PROPOSAL_KEX_ALGS]);
469 	choose_hostkeyalg(kex, cprop[PROPOSAL_SERVER_HOST_KEY_ALGS],
470 	    sprop[PROPOSAL_SERVER_HOST_KEY_ALGS]);
471 	need = 0;
472 	for (mode = 0; mode < MODE_MAX; mode++) {
473 		newkeys = kex->newkeys[mode];
474 		if (need < newkeys->enc.key_len)
475 			need = newkeys->enc.key_len;
476 		if (need < newkeys->enc.block_size)
477 			need = newkeys->enc.block_size;
478 		if (need < newkeys->mac.key_len)
479 			need = newkeys->mac.key_len;
480 	}
481 	/* XXX need runden? */
482 	kex->we_need = need;
483 
484 	/* ignore the next message if the proposals do not match */
485 	if (first_kex_follows && !proposals_match(my, peer) &&
486 	    !(datafellows & SSH_BUG_FIRSTKEX)) {
487 		type = packet_read();
488 		debug2("skipping next packet (type %u)", type);
489 	}
490 
491 	/* Language/locale negotiation -- not worth doing on re-key */
492 
493 	if (!kex->initial_kex_done) {
494 		p_langs_c2s = peer[PROPOSAL_LANG_CTOS];
495 		p_langs_s2c = peer[PROPOSAL_LANG_STOC];
496 		debug("Peer sent proposed langtags, ctos: %s", p_langs_c2s);
497 		debug("Peer sent proposed langtags, stoc: %s", p_langs_s2c);
498 		plangs = NULL;
499 
500 		/* We propose the same langs for each protocol direction */
501 		mlangs = my[PROPOSAL_LANG_STOC];
502 		debug("We proposed langtags, ctos: %s", my[PROPOSAL_LANG_CTOS]);
503 		debug("We proposed langtags, stoc: %s", mlangs);
504 
505 		/*
506 		 * Why oh why did they bother with negotiating langs for
507 		 * each protocol direction?!
508 		 *
509 		 * The semantics of this are vaguely specified, but one can
510 		 * imagine using one language (locale) for the whole session and
511 		 * a different one for message localization (e.g., 'en_US.UTF-8'
512 		 * overall and 'fr' for messages).  Weird?  Maybe.  But lang
513 		 * tags don't include codeset info, like locales do...
514 		 *
515 		 * So, server-side we want:
516 		 *  - setlocale(LC_ALL, c2s_locale);
517 		 *  and
518 		 *  - setlocale(LC_MESSAGES, s2c_locale);
519 		 *
520 		 * Client-side we don't really care.  But we could do:
521 		 *
522 		 *  - when very verbose, tell the use what lang the server's
523 		 *    messages are in, if left out in the protocol
524 		 *  - when sending messages to the server, and if applicable, we
525 		 *    can localize them according to the language negotiated for
526 		 *    that direction.
527 		 *
528 		 * But for now we do nothing on the client side.
529 		 */
530 		if ((p_langs_c2s && *p_langs_c2s) && !(p_langs_s2c && *p_langs_s2c))
531 			plangs = p_langs_c2s;
532 		else if ((p_langs_s2c && *p_langs_s2c) && !(p_langs_c2s && *p_langs_c2s))
533 			plangs = p_langs_s2c;
534 		else
535 			plangs = p_langs_c2s;
536 
537 		if (kex->server) {
538 			if (plangs && mlangs && *plangs && *mlangs) {
539 				char *locale;
540 
541 				choose_lang(&locale, plangs, mlangs);
542 				if (locale) {
543 					g11n_setlocale(LC_ALL, locale);
544 					debug("Negotiated main locale: %s", locale);
545 					packet_send_debug("Negotiated main locale: %s", locale);
546 					xfree(locale);
547 				}
548 				if (plangs != p_langs_s2c &&
549 				    p_langs_s2c && *p_langs_s2c) {
550 					choose_lang(&locale, p_langs_s2c, mlangs);
551 					if (locale) {
552 						g11n_setlocale(LC_MESSAGES, locale);
553 						debug("Negotiated messages locale: %s", locale);
554 						packet_send_debug("Negotiated "
555 						    "messages locale: %s", locale);
556 						xfree(locale);
557 					}
558 				}
559 			}
560 		}
561 		else {
562 			if (plangs && mlangs && *plangs && *mlangs &&
563 			    !(datafellows & SSH_BUG_LOCALES_NOT_LANGTAGS)) {
564 				char *lang;
565 				lang = g11n_clnt_langtag_negotiate(mlangs, plangs);
566 				if (lang) {
567 					session_lang = lang;
568 					debug("Negotiated lang: %s", lang);
569 				}
570 			}
571 		}
572 	}
573 
574 	kex_prop_free(my);
575 	kex_prop_free(peer);
576 }
577 
578 static u_char *
579 derive_key(Kex *kex, int id, int need, u_char *hash, BIGNUM *shared_secret)
580 {
581 	Buffer b;
582 	const EVP_MD *evp_md = EVP_sha1();
583 	EVP_MD_CTX md;
584 	char c = id;
585 	int have;
586 	int mdsz = EVP_MD_size(evp_md);
587 	u_char *digest = xmalloc(roundup(need, mdsz));
588 
589 	buffer_init(&b);
590 	buffer_put_bignum2(&b, shared_secret);
591 
592 	/* K1 = HASH(K || H || "A" || session_id) */
593 	EVP_DigestInit(&md, evp_md);
594 	if (!(datafellows & SSH_BUG_DERIVEKEY))
595 		EVP_DigestUpdate(&md, buffer_ptr(&b), buffer_len(&b));
596 	EVP_DigestUpdate(&md, hash, mdsz);
597 	EVP_DigestUpdate(&md, &c, 1);
598 	EVP_DigestUpdate(&md, kex->session_id, kex->session_id_len);
599 	EVP_DigestFinal(&md, digest, NULL);
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 		EVP_DigestInit(&md, evp_md);
608 		if (!(datafellows & SSH_BUG_DERIVEKEY))
609 			EVP_DigestUpdate(&md, buffer_ptr(&b), buffer_len(&b));
610 		EVP_DigestUpdate(&md, hash, mdsz);
611 		EVP_DigestUpdate(&md, digest, have);
612 		EVP_DigestFinal(&md, digest + have, NULL);
613 	}
614 	buffer_free(&b);
615 #ifdef DEBUG_KEX
616 	fprintf(stderr, "key '%c'== ", c);
617 	dump_digest("key", digest, need);
618 #endif
619 	return digest;
620 }
621 
622 Newkeys *current_keys[MODE_MAX];
623 
624 #define NKEYS	6
625 void
626 kex_derive_keys(Kex *kex, u_char *hash, BIGNUM *shared_secret)
627 {
628 	u_char *keys[NKEYS];
629 	int i, mode, ctos;
630 
631 	for (i = 0; i < NKEYS; i++)
632 		keys[i] = derive_key(kex, 'A'+i, kex->we_need, hash, shared_secret);
633 
634 	debug2("kex_derive_keys");
635 	for (mode = 0; mode < MODE_MAX; mode++) {
636 		current_keys[mode] = kex->newkeys[mode];
637 		kex->newkeys[mode] = NULL;
638 		ctos = (!kex->server && mode == MODE_OUT) || (kex->server && mode == MODE_IN);
639 		current_keys[mode]->enc.iv  = keys[ctos ? 0 : 1];
640 		current_keys[mode]->enc.key = keys[ctos ? 2 : 3];
641 		current_keys[mode]->mac.key = keys[ctos ? 4 : 5];
642 	}
643 }
644 
645 Newkeys *
646 kex_get_newkeys(int mode)
647 {
648 	Newkeys *ret;
649 
650 	ret = current_keys[mode];
651 	current_keys[mode] = NULL;
652 	return ret;
653 }
654 
655 #if defined(DEBUG_KEX) || defined(DEBUG_KEXDH)
656 void
657 dump_digest(char *msg, u_char *digest, int len)
658 {
659 	int i;
660 
661 	fprintf(stderr, "%s\n", msg);
662 	for (i = 0; i< len; i++) {
663 		fprintf(stderr, "%02x", digest[i]);
664 		if (i%32 == 31)
665 			fprintf(stderr, "\n");
666 		else if (i%8 == 7)
667 			fprintf(stderr, " ");
668 	}
669 	fprintf(stderr, "\n");
670 }
671 #endif
672