xref: /titanic_44/usr/src/cmd/ssh/libssh/common/kex.c (revision 18c2aff776a775d34a4c9893a4c72e0434d68e36)
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 2004 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 #pragma ident	"%Z%%M%	%I%	%E% SMI"
32 
33 #include <locale.h>
34 
35 #include <openssl/crypto.h>
36 
37 #include "ssh2.h"
38 #include "xmalloc.h"
39 #include "buffer.h"
40 #include "bufaux.h"
41 #include "packet.h"
42 #include "compat.h"
43 #include "cipher.h"
44 #include "kex.h"
45 #include "key.h"
46 #include "log.h"
47 #include "mac.h"
48 #include "match.h"
49 #include "dispatch.h"
50 #include "monitor.h"
51 #include "g11n.h"
52 
53 #ifdef GSSAPI
54 #include "ssh-gss.h"
55 #endif
56 
57 #define KEX_COOKIE_LEN	16
58 
59 /* Use privilege separation for sshd */
60 int use_privsep;
61 struct monitor *pmonitor;
62 
63 char *session_lang = NULL;
64 
65 
66 /* prototype */
67 static void kex_do_hook(Kex *kex);
68 static void kex_kexinit_finish(Kex *);
69 static void kex_choose_conf(Kex *);
70 
71 /* put algorithm proposal into buffer */
72 static
73 void
74 kex_prop2buf(Buffer *b, char *proposal[PROPOSAL_MAX])
75 {
76 	int i;
77 
78 	buffer_clear(b);
79 	/*
80 	 * add a dummy cookie, the cookie will be overwritten by
81 	 * kex_send_kexinit(), each time a kexinit is set
82 	 */
83 	for (i = 0; i < KEX_COOKIE_LEN; i++)
84 		buffer_put_char(b, 0);
85 	for (i = 0; i < PROPOSAL_MAX; i++)
86 		buffer_put_cstring(b, proposal[i]);
87 	buffer_put_char(b, 0);			/* first_kex_packet_follows */
88 	buffer_put_int(b, 0);			/* uint32 reserved */
89 }
90 
91 /* parse buffer and return algorithm proposal */
92 static
93 char **
94 kex_buf2prop(Buffer *raw, int *first_kex_follows)
95 {
96 	Buffer b;
97 	int i;
98 	char **proposal;
99 
100 	proposal = xmalloc(PROPOSAL_MAX * sizeof(char *));
101 
102 	buffer_init(&b);
103 	buffer_append(&b, buffer_ptr(raw), buffer_len(raw));
104 	/* skip cookie */
105 	for (i = 0; i < KEX_COOKIE_LEN; i++)
106 		buffer_get_char(&b);
107 	/* extract kex init proposal strings */
108 	for (i = 0; i < PROPOSAL_MAX; i++) {
109 		proposal[i] = buffer_get_string(&b,NULL);
110 		debug2("kex_parse_kexinit: %s", proposal[i]);
111 	}
112 	/* first kex follows / reserved */
113 	i = buffer_get_char(&b);
114 	if (first_kex_follows != NULL)
115 		*first_kex_follows = i;
116 	debug2("kex_parse_kexinit: first_kex_follows %d ", i);
117 	i = buffer_get_int(&b);
118 	debug2("kex_parse_kexinit: reserved %d ", i);
119 	buffer_free(&b);
120 	return proposal;
121 }
122 
123 static
124 void
125 kex_prop_free(char **proposal)
126 {
127 	int i;
128 
129 	for (i = 0; i < PROPOSAL_MAX; i++)
130 		xfree(proposal[i]);
131 	xfree(proposal);
132 }
133 
134 static void
135 kex_protocol_error(int type, u_int32_t seq, void *ctxt)
136 {
137 	error("Hm, kex protocol error: type %d seq %u", type, seq);
138 }
139 
140 static void
141 kex_reset_dispatch(void)
142 {
143 #ifdef ALTPRIVSEP
144 	/* unprivileged sshd has a kex packet handler that must not be reset */
145 	debug3("kex_reset_dispatch -- should we dispatch_set(KEXINIT) here? %d && !%d",
146 		packet_is_server(), packet_is_monitor());
147 	if (packet_is_server() && !packet_is_monitor()) {
148 		debug3("kex_reset_dispatch -- skipping dispatch_set(KEXINIT) in unpriv proc");
149 		return;
150 	}
151 #endif /* ALTPRIVSEP */
152 
153 	dispatch_range(SSH2_MSG_TRANSPORT_MIN,
154 	    SSH2_MSG_TRANSPORT_MAX, &kex_protocol_error);
155 	dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
156 }
157 
158 void
159 kex_finish(Kex *kex)
160 {
161 	kex_reset_dispatch();
162 
163 	packet_start(SSH2_MSG_NEWKEYS);
164 	packet_send();
165 	/* packet_write_wait(); */
166 	debug("SSH2_MSG_NEWKEYS sent");
167 
168 #ifdef ALTPRIVSEP
169 	if (packet_is_monitor())
170 		goto skip_newkeys;
171 #endif /* ALTPRIVSEP */
172 	debug("expecting SSH2_MSG_NEWKEYS");
173 	packet_read_expect(SSH2_MSG_NEWKEYS);
174 	packet_check_eom();
175 	debug("SSH2_MSG_NEWKEYS received");
176 #ifdef ALTPRIVSEP
177 skip_newkeys:
178 #endif /* ALTPRIVSEP */
179 
180 	kex->done = 1;
181 	kex->initial_kex_done = 1; /* never to be cleared once set */
182 	buffer_clear(&kex->peer);
183 	/* buffer_clear(&kex->my); */
184 	kex->flags &= ~KEX_INIT_SENT;
185 #if 0
186 	/* Must have this name for use in sshd (audit_save_kex())... */
187 	xfree(kex->name);
188 	kex->name = NULL;
189 #endif
190 }
191 
192 void
193 kex_send_kexinit(Kex *kex)
194 {
195 	u_int32_t rand = 0;
196 	u_char *cookie;
197 	int i;
198 
199 	if (kex == NULL) {
200 		error("kex_send_kexinit: no kex, cannot rekey");
201 		return;
202 	}
203 	if (kex->flags & KEX_INIT_SENT) {
204 		debug("KEX_INIT_SENT");
205 		return;
206 	}
207 	kex->done = 0;
208 
209 	/* update my proposal -- e.g., add/remove GSS kexalgs */
210 	kex_do_hook(kex);
211 
212 	/* generate a random cookie */
213 	if (buffer_len(&kex->my) < KEX_COOKIE_LEN)
214 		fatal("kex_send_kexinit: kex proposal too short");
215 	cookie = buffer_ptr(&kex->my);
216 	for (i = 0; i < KEX_COOKIE_LEN; i++) {
217 		if (i % 4 == 0)
218 			rand = arc4random();
219 		cookie[i] = rand;
220 		rand >>= 8;
221 	}
222 	packet_start(SSH2_MSG_KEXINIT);
223 	packet_put_raw(buffer_ptr(&kex->my), buffer_len(&kex->my));
224 	packet_send();
225 	debug("SSH2_MSG_KEXINIT sent");
226 	kex->flags |= KEX_INIT_SENT;
227 }
228 
229 void
230 kex_input_kexinit(int type, u_int32_t seq, void *ctxt)
231 {
232 	char *ptr;
233 	u_int dlen;
234 	int i;
235 	Kex *kex = (Kex *)ctxt;
236 
237 	debug("SSH2_MSG_KEXINIT received");
238 	if (kex == NULL)
239 		fatal("kex_input_kexinit: no kex, cannot rekey");
240 
241 	ptr = packet_get_raw(&dlen);
242 	buffer_append(&kex->peer, ptr, dlen);
243 
244 	/* discard packet */
245 	for (i = 0; i < KEX_COOKIE_LEN; i++)
246 		packet_get_char();
247 	for (i = 0; i < PROPOSAL_MAX; i++)
248 		xfree(packet_get_string(NULL));
249 	(void) packet_get_char();
250 	(void) packet_get_int();
251 	packet_check_eom();
252 
253 	kex_kexinit_finish(kex);
254 }
255 
256 /*
257  * This is for GSS keyex, where actual KEX offer can change at rekey
258  * time due to credential expiration/renewal...
259  */
260 static
261 void
262 kex_do_hook(Kex *kex)
263 {
264 	char    **prop;
265 
266 	if (kex->kex_hook == NULL)
267 		return;
268 
269 	/* Unmarshall my proposal, let the hook modify it, remarshall it */
270 	prop = kex_buf2prop(&kex->my, NULL);
271 	buffer_clear(&kex->my);
272 	(kex->kex_hook)(kex, prop);
273 	kex_prop2buf(&kex->my, prop);
274 	kex_prop_free(prop);
275 }
276 
277 Kex *
278 kex_setup(const char *host, char *proposal[PROPOSAL_MAX], Kex_hook_func hook)
279 {
280 	Kex	*kex;
281 
282 	kex = xmalloc(sizeof(*kex));
283 	memset(kex, 0, sizeof(*kex));
284 	buffer_init(&kex->peer);
285 	buffer_init(&kex->my);
286 
287 	kex->kex_hook = hook; /* called by kex_send_kexinit() */
288 
289 	if (host != NULL && *host != '\0')
290 		kex->serverhost = xstrdup(host);
291 	else
292 		kex->server = 1;
293 
294 	kex_prop2buf(&kex->my, proposal);
295 
296 	kex_send_kexinit(kex);
297 	kex_reset_dispatch();
298 
299 	return kex;
300 }
301 
302 static void
303 kex_kexinit_finish(Kex *kex)
304 {
305 	if (!(kex->flags & KEX_INIT_SENT))
306 		kex_send_kexinit(kex);
307 
308 	kex_choose_conf(kex);
309 
310 	if (kex->kex_type >= 0 && kex->kex_type < KEX_MAX &&
311 	    kex->kex[kex->kex_type] != NULL)
312 		(kex->kex[kex->kex_type])(kex);
313 	else
314 		fatal("Unsupported key exchange %d", kex->kex_type);
315 }
316 
317 static void
318 choose_lang(char **lang, char *client, char *server)
319 {
320 	if (datafellows & SSH_BUG_LOCALES_NOT_LANGTAGS)
321 		*lang = match_list(client, server, NULL);
322 	else
323 		*lang = g11n_srvr_locale_negotiate(client, NULL);
324 }
325 static void
326 choose_enc(Enc *enc, char *client, char *server)
327 {
328 	char *name = match_list(client, server, NULL);
329 	if (name == NULL)
330 		fatal("no matching cipher found: client %s server %s", client, server);
331 	if ((enc->cipher = cipher_by_name(name)) == NULL)
332 		fatal("matching cipher is not supported: %s", name);
333 	enc->name = name;
334 	enc->enabled = 0;
335 	enc->iv = NULL;
336 	enc->key = NULL;
337 	enc->key_len = cipher_keylen(enc->cipher);
338 	enc->block_size = cipher_blocksize(enc->cipher);
339 }
340 static void
341 choose_mac(Mac *mac, char *client, char *server)
342 {
343 	char *name = match_list(client, server, NULL);
344 	if (name == NULL)
345 		fatal("no matching mac found: client %s server %s", client, server);
346 	if (mac_init(mac, name) < 0)
347 		fatal("unsupported mac %s", name);
348 	/* truncate the key */
349 	if (datafellows & SSH_BUG_HMAC)
350 		mac->key_len = 16;
351 	mac->name = name;
352 	mac->key = NULL;
353 	mac->enabled = 0;
354 }
355 static void
356 choose_comp(Comp *comp, char *client, char *server)
357 {
358 	char *name = match_list(client, server, NULL);
359 	if (name == NULL)
360 		fatal("no matching comp found: client %s server %s", client, server);
361 	if (strcmp(name, "zlib") == 0) {
362 		comp->type = 1;
363 	} else if (strcmp(name, "none") == 0) {
364 		comp->type = 0;
365 	} else {
366 		fatal("unsupported comp %s", name);
367 	}
368 	comp->name = name;
369 }
370 static void
371 choose_kex(Kex *k, char *client, char *server)
372 {
373 	k->name = match_list(client, server, NULL);
374 	if (k->name == NULL)
375 		fatal("no kex alg");
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 				}
547 				if (plangs != p_langs_s2c &&
548 				    p_langs_s2c && *p_langs_s2c) {
549 					choose_lang(&locale, p_langs_s2c, mlangs);
550 					if (locale) {
551 						g11n_setlocale(LC_MESSAGES, locale);
552 						debug("Negotiated messages locale: %s", locale);
553 						packet_send_debug("Negotiated messages locale: %s", locale);
554 					}
555 				}
556 				/*
557 				 * Should we free locale? Or does setlocale
558 				 * retain a reference?
559 				 */
560 				/*xfree(locale);*/
561 			}
562 		}
563 		else {
564 			if (plangs && mlangs && *plangs && *mlangs &&
565 			    !(datafellows & SSH_BUG_LOCALES_NOT_LANGTAGS)) {
566 				char *lang;
567 				lang = g11n_clnt_langtag_negotiate(mlangs, plangs);
568 				if (lang) {
569 					session_lang = lang;
570 					debug("Negotiated lang: %s", lang);
571 				}
572 			}
573 		}
574 	}
575 
576 	kex_prop_free(my);
577 	kex_prop_free(peer);
578 }
579 
580 static u_char *
581 derive_key(Kex *kex, int id, int need, u_char *hash, BIGNUM *shared_secret)
582 {
583 	Buffer b;
584 	const EVP_MD *evp_md = EVP_sha1();
585 	EVP_MD_CTX md;
586 	char c = id;
587 	int have;
588 	int mdsz = EVP_MD_size(evp_md);
589 	u_char *digest = xmalloc(roundup(need, mdsz));
590 
591 	buffer_init(&b);
592 	buffer_put_bignum2(&b, shared_secret);
593 
594 	/* K1 = HASH(K || H || "A" || session_id) */
595 	EVP_DigestInit(&md, evp_md);
596 	if (!(datafellows & SSH_BUG_DERIVEKEY))
597 		EVP_DigestUpdate(&md, buffer_ptr(&b), buffer_len(&b));
598 	EVP_DigestUpdate(&md, hash, mdsz);
599 	EVP_DigestUpdate(&md, &c, 1);
600 	EVP_DigestUpdate(&md, kex->session_id, kex->session_id_len);
601 	EVP_DigestFinal(&md, digest, NULL);
602 
603 	/*
604 	 * expand key:
605 	 * Kn = HASH(K || H || K1 || K2 || ... || Kn-1)
606 	 * Key = K1 || K2 || ... || Kn
607 	 */
608 	for (have = mdsz; need > have; have += mdsz) {
609 		EVP_DigestInit(&md, evp_md);
610 		if (!(datafellows & SSH_BUG_DERIVEKEY))
611 			EVP_DigestUpdate(&md, buffer_ptr(&b), buffer_len(&b));
612 		EVP_DigestUpdate(&md, hash, mdsz);
613 		EVP_DigestUpdate(&md, digest, have);
614 		EVP_DigestFinal(&md, digest + have, NULL);
615 	}
616 	buffer_free(&b);
617 #ifdef DEBUG_KEX
618 	fprintf(stderr, "key '%c'== ", c);
619 	dump_digest("key", digest, need);
620 #endif
621 	return digest;
622 }
623 
624 Newkeys *current_keys[MODE_MAX];
625 
626 #define NKEYS	6
627 void
628 kex_derive_keys(Kex *kex, u_char *hash, BIGNUM *shared_secret)
629 {
630 	u_char *keys[NKEYS];
631 	int i, mode, ctos;
632 
633 	for (i = 0; i < NKEYS; i++)
634 		keys[i] = derive_key(kex, 'A'+i, kex->we_need, hash, shared_secret);
635 
636 	debug2("kex_derive_keys");
637 	for (mode = 0; mode < MODE_MAX; mode++) {
638 		current_keys[mode] = kex->newkeys[mode];
639 		kex->newkeys[mode] = NULL;
640 		ctos = (!kex->server && mode == MODE_OUT) || (kex->server && mode == MODE_IN);
641 		current_keys[mode]->enc.iv  = keys[ctos ? 0 : 1];
642 		current_keys[mode]->enc.key = keys[ctos ? 2 : 3];
643 		current_keys[mode]->mac.key = keys[ctos ? 4 : 5];
644 	}
645 }
646 
647 Newkeys *
648 kex_get_newkeys(int mode)
649 {
650 	Newkeys *ret;
651 
652 	ret = current_keys[mode];
653 	current_keys[mode] = NULL;
654 	return ret;
655 }
656 
657 #if defined(DEBUG_KEX) || defined(DEBUG_KEXDH)
658 void
659 dump_digest(char *msg, u_char *digest, int len)
660 {
661 	int i;
662 
663 	fprintf(stderr, "%s\n", msg);
664 	for (i = 0; i< len; i++) {
665 		fprintf(stderr, "%02x", digest[i]);
666 		if (i%32 == 31)
667 			fprintf(stderr, "\n");
668 		else if (i%8 == 7)
669 			fprintf(stderr, " ");
670 	}
671 	fprintf(stderr, "\n");
672 }
673 #endif
674