xref: /titanic_50/usr/src/cmd/ssh/libssh/common/kex.c (revision 50981ffc7e4c5048d14890df805afee6ec113991)
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 2009 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 
325 /*
326  * Make the message clear enough so that if this happens the user can figure out
327  * the workaround of changing the Ciphers option.
328  */
329 #define	CLIENT_ERR_MSG							       \
330   "Client and server could not agree on a common cipher:\n"		       \
331   "  client: %s\n"							       \
332   "  server: %s\n"							       \
333   "\n"									       \
334   "The client cipher list can be controlled using the \"Ciphers\" option, \n"  \
335   "see ssh_config(4) for more information. The \"-o Ciphers=<cipher-list>\"\n" \
336   "option may be used to temporarily override the ciphers the client\n"	       \
337   "offers."
338 
339 /*
340  * The server side message goes to syslogd and we do not want to send multiline
341  * messages there. What's more, the server side notification may be shorter
342  * since we expect that an administrator will deal with that, not the user.
343  */
344 #define	SERVER_ERR_MSG							       \
345   "Client and server could not agree on a common cipher: client \"%s\", "      \
346   "server \"%s\". The server cipher list can be controlled using the "	       \
347   "\"Ciphers\" option, see sshd_config(4) for more information."
348 
349 static void
350 choose_enc(int is_server, Enc *enc, char *client, char *server)
351 {
352 	char *name = match_list(client, server, NULL);
353 
354 	if (name == NULL) {
355 		if (is_server == 1)
356 			fatal(SERVER_ERR_MSG, client, server);
357 		else
358 			fatal(CLIENT_ERR_MSG, client, server);
359 	}
360 
361 	if ((enc->cipher = cipher_by_name(name)) == NULL)
362 		fatal("matching cipher is not supported: %s", name);
363 
364 	enc->name = name;
365 	enc->enabled = 0;
366 	enc->iv = NULL;
367 	enc->key = NULL;
368 	enc->key_len = cipher_keylen(enc->cipher);
369 	enc->block_size = cipher_blocksize(enc->cipher);
370 }
371 
372 static void
373 choose_mac(Mac *mac, char *client, char *server)
374 {
375 	char *name = match_list(client, server, NULL);
376 	if (name == NULL)
377 		fatal("no matching mac found: client %s server %s", client, server);
378 	if (mac_init(mac, name) < 0)
379 		fatal("unsupported mac %s", name);
380 	/* truncate the key */
381 	if (datafellows & SSH_BUG_HMAC)
382 		mac->key_len = 16;
383 	mac->name = name;
384 	mac->key = NULL;
385 	mac->enabled = 0;
386 }
387 static void
388 choose_comp(Comp *comp, char *client, char *server)
389 {
390 	char *name = match_list(client, server, NULL);
391 	if (name == NULL)
392 		fatal("no matching comp found: client %s server %s", client, server);
393 	if (strcmp(name, "zlib") == 0) {
394 		comp->type = 1;
395 	} else if (strcmp(name, "none") == 0) {
396 		comp->type = 0;
397 	} else {
398 		fatal("unsupported comp %s", name);
399 	}
400 	comp->name = name;
401 }
402 static void
403 choose_kex(Kex *k, char *client, char *server)
404 {
405 	k->name = match_list(client, server, NULL);
406 	if (k->name == NULL)
407 		fatal("no common kex alg: client '%s', server '%s'", client,
408 		    server);
409 	/* XXX Finish 3.6/7 merge of kex stuff -- choose_kex() done */
410 	if (strcmp(k->name, KEX_DH1) == 0) {
411 		k->kex_type = KEX_DH_GRP1_SHA1;
412 	} else if (strcmp(k->name, KEX_DHGEX) == 0) {
413 		k->kex_type = KEX_DH_GEX_SHA1;
414 #ifdef GSSAPI
415 	} else if (strncmp(k->name, KEX_GSS_SHA1, sizeof(KEX_GSS_SHA1)-1) == 0) {
416 		k->kex_type = KEX_GSS_GRP1_SHA1;
417 #endif
418 	} else
419 		fatal("bad kex alg %s", k->name);
420 }
421 static void
422 choose_hostkeyalg(Kex *k, char *client, char *server)
423 {
424 	char *hostkeyalg = match_list(client, server, NULL);
425 	if (hostkeyalg == NULL)
426 		fatal("no hostkey alg");
427 	k->hostkey_type = key_type_from_name(hostkeyalg);
428 	if (k->hostkey_type == KEY_UNSPEC)
429 		fatal("bad hostkey alg '%s'", hostkeyalg);
430 	xfree(hostkeyalg);
431 }
432 
433 static int
434 proposals_match(char *my[PROPOSAL_MAX], char *peer[PROPOSAL_MAX])
435 {
436 	static int check[] = {
437 		PROPOSAL_KEX_ALGS, PROPOSAL_SERVER_HOST_KEY_ALGS, -1
438 	};
439 	int *idx;
440 	char *p;
441 
442 	for (idx = &check[0]; *idx != -1; idx++) {
443 		if ((p = strchr(my[*idx], ',')) != NULL)
444 			*p = '\0';
445 		if ((p = strchr(peer[*idx], ',')) != NULL)
446 			*p = '\0';
447 		if (strcmp(my[*idx], peer[*idx]) != 0) {
448 			debug2("proposal mismatch: my %s peer %s",
449 			    my[*idx], peer[*idx]);
450 			return (0);
451 		}
452 	}
453 	debug2("proposals match");
454 	return (1);
455 }
456 
457 static void
458 kex_choose_conf(Kex *kex)
459 {
460 	Newkeys *newkeys;
461 	char **my, **peer;
462 	char **cprop, **sprop;
463 	char *p_langs_c2s, *p_langs_s2c; /* peer's langs */
464 	char *plangs = NULL;		 /* peer's langs*/
465 	char *mlangs = NULL;		 /* my langs */
466 	int nenc, nmac, ncomp;
467 	int mode;
468 	int ctos;				/* direction: if true client-to-server */
469 	int need;
470 	int first_kex_follows, type;
471 
472 	my   = kex_buf2prop(&kex->my, NULL);
473 	peer = kex_buf2prop(&kex->peer, &first_kex_follows);
474 
475 	if (kex->server) {
476 		cprop=peer;
477 		sprop=my;
478 	} else {
479 		cprop=my;
480 		sprop=peer;
481 	}
482 
483 	/* Algorithm Negotiation */
484 	for (mode = 0; mode < MODE_MAX; mode++) {
485 		newkeys = xmalloc(sizeof(*newkeys));
486 		memset(newkeys, 0, sizeof(*newkeys));
487 		kex->newkeys[mode] = newkeys;
488 		ctos = (!kex->server && mode == MODE_OUT) || (kex->server && mode == MODE_IN);
489 		nenc  = ctos ? PROPOSAL_ENC_ALGS_CTOS  : PROPOSAL_ENC_ALGS_STOC;
490 		nmac  = ctos ? PROPOSAL_MAC_ALGS_CTOS  : PROPOSAL_MAC_ALGS_STOC;
491 		ncomp = ctos ? PROPOSAL_COMP_ALGS_CTOS : PROPOSAL_COMP_ALGS_STOC;
492 		choose_enc(kex->server, &newkeys->enc,  cprop[nenc],  sprop[nenc]);
493 		choose_mac(&newkeys->mac,  cprop[nmac],  sprop[nmac]);
494 		choose_comp(&newkeys->comp, cprop[ncomp], sprop[ncomp]);
495 		debug("kex: %s %s %s %s",
496 		    ctos ? "client->server" : "server->client",
497 		    newkeys->enc.name,
498 		    newkeys->mac.name,
499 		    newkeys->comp.name);
500 	}
501 	choose_kex(kex, cprop[PROPOSAL_KEX_ALGS], sprop[PROPOSAL_KEX_ALGS]);
502 	choose_hostkeyalg(kex, cprop[PROPOSAL_SERVER_HOST_KEY_ALGS],
503 	    sprop[PROPOSAL_SERVER_HOST_KEY_ALGS]);
504 	need = 0;
505 	for (mode = 0; mode < MODE_MAX; mode++) {
506 		newkeys = kex->newkeys[mode];
507 		if (need < newkeys->enc.key_len)
508 			need = newkeys->enc.key_len;
509 		if (need < newkeys->enc.block_size)
510 			need = newkeys->enc.block_size;
511 		if (need < newkeys->mac.key_len)
512 			need = newkeys->mac.key_len;
513 	}
514 	/* XXX need runden? */
515 	kex->we_need = need;
516 
517 	/* ignore the next message if the proposals do not match */
518 	if (first_kex_follows && !proposals_match(my, peer) &&
519 	    !(datafellows & SSH_BUG_FIRSTKEX)) {
520 		type = packet_read();
521 		debug2("skipping next packet (type %u)", type);
522 	}
523 
524 	/* Language/locale negotiation -- not worth doing on re-key */
525 
526 	if (!kex->initial_kex_done) {
527 		p_langs_c2s = peer[PROPOSAL_LANG_CTOS];
528 		p_langs_s2c = peer[PROPOSAL_LANG_STOC];
529 		debug("Peer sent proposed langtags, ctos: %s", p_langs_c2s);
530 		debug("Peer sent proposed langtags, stoc: %s", p_langs_s2c);
531 		plangs = NULL;
532 
533 		/* We propose the same langs for each protocol direction */
534 		mlangs = my[PROPOSAL_LANG_STOC];
535 		debug("We proposed langtags, ctos: %s", my[PROPOSAL_LANG_CTOS]);
536 		debug("We proposed langtags, stoc: %s", mlangs);
537 
538 		/*
539 		 * Why oh why did they bother with negotiating langs for
540 		 * each protocol direction?!
541 		 *
542 		 * The semantics of this are vaguely specified, but one can
543 		 * imagine using one language (locale) for the whole session and
544 		 * a different one for message localization (e.g., 'en_US.UTF-8'
545 		 * overall and 'fr' for messages).  Weird?  Maybe.  But lang
546 		 * tags don't include codeset info, like locales do...
547 		 *
548 		 * So, server-side we want:
549 		 *  - setlocale(LC_ALL, c2s_locale);
550 		 *  and
551 		 *  - setlocale(LC_MESSAGES, s2c_locale);
552 		 *
553 		 * Client-side we don't really care.  But we could do:
554 		 *
555 		 *  - when very verbose, tell the use what lang the server's
556 		 *    messages are in, if left out in the protocol
557 		 *  - when sending messages to the server, and if applicable, we
558 		 *    can localize them according to the language negotiated for
559 		 *    that direction.
560 		 *
561 		 * But for now we do nothing on the client side.
562 		 */
563 		if ((p_langs_c2s && *p_langs_c2s) && !(p_langs_s2c && *p_langs_s2c))
564 			plangs = p_langs_c2s;
565 		else if ((p_langs_s2c && *p_langs_s2c) && !(p_langs_c2s && *p_langs_c2s))
566 			plangs = p_langs_s2c;
567 		else
568 			plangs = p_langs_c2s;
569 
570 		if (kex->server) {
571 			if (plangs && mlangs && *plangs && *mlangs) {
572 				char *locale;
573 
574 				choose_lang(&locale, plangs, mlangs);
575 				if (locale) {
576 					g11n_setlocale(LC_ALL, locale);
577 					debug("Negotiated main locale: %s", locale);
578 					packet_send_debug("Negotiated main locale: %s", locale);
579 					xfree(locale);
580 				}
581 				if (plangs != p_langs_s2c &&
582 				    p_langs_s2c && *p_langs_s2c) {
583 					choose_lang(&locale, p_langs_s2c, mlangs);
584 					if (locale) {
585 						g11n_setlocale(LC_MESSAGES, locale);
586 						debug("Negotiated messages locale: %s", locale);
587 						packet_send_debug("Negotiated "
588 						    "messages locale: %s", locale);
589 						xfree(locale);
590 					}
591 				}
592 			}
593 		}
594 		else {
595 			if (plangs && mlangs && *plangs && *mlangs &&
596 			    !(datafellows & SSH_BUG_LOCALES_NOT_LANGTAGS)) {
597 				char *lang;
598 				lang = g11n_clnt_langtag_negotiate(mlangs, plangs);
599 				if (lang) {
600 					session_lang = lang;
601 					debug("Negotiated lang: %s", lang);
602 				}
603 			}
604 		}
605 	}
606 
607 	kex_prop_free(my);
608 	kex_prop_free(peer);
609 }
610 
611 static u_char *
612 derive_key(Kex *kex, int id, int need, u_char *hash, BIGNUM *shared_secret)
613 {
614 	Buffer b;
615 	const EVP_MD *evp_md = EVP_sha1();
616 	EVP_MD_CTX md;
617 	char c = id;
618 	int have;
619 	int mdsz = EVP_MD_size(evp_md);
620 	u_char *digest = xmalloc(roundup(need, mdsz));
621 
622 	buffer_init(&b);
623 	buffer_put_bignum2(&b, shared_secret);
624 
625 	/* K1 = HASH(K || H || "A" || session_id) */
626 	EVP_DigestInit(&md, evp_md);
627 	if (!(datafellows & SSH_BUG_DERIVEKEY))
628 		EVP_DigestUpdate(&md, buffer_ptr(&b), buffer_len(&b));
629 	EVP_DigestUpdate(&md, hash, mdsz);
630 	EVP_DigestUpdate(&md, &c, 1);
631 	EVP_DigestUpdate(&md, kex->session_id, kex->session_id_len);
632 	EVP_DigestFinal(&md, digest, NULL);
633 
634 	/*
635 	 * expand key:
636 	 * Kn = HASH(K || H || K1 || K2 || ... || Kn-1)
637 	 * Key = K1 || K2 || ... || Kn
638 	 */
639 	for (have = mdsz; need > have; have += mdsz) {
640 		EVP_DigestInit(&md, evp_md);
641 		if (!(datafellows & SSH_BUG_DERIVEKEY))
642 			EVP_DigestUpdate(&md, buffer_ptr(&b), buffer_len(&b));
643 		EVP_DigestUpdate(&md, hash, mdsz);
644 		EVP_DigestUpdate(&md, digest, have);
645 		EVP_DigestFinal(&md, digest + have, NULL);
646 	}
647 	buffer_free(&b);
648 #ifdef DEBUG_KEX
649 	fprintf(stderr, "key '%c'== ", c);
650 	dump_digest("key", digest, need);
651 #endif
652 	return digest;
653 }
654 
655 Newkeys *current_keys[MODE_MAX];
656 
657 #define NKEYS	6
658 void
659 kex_derive_keys(Kex *kex, u_char *hash, BIGNUM *shared_secret)
660 {
661 	u_char *keys[NKEYS];
662 	int i, mode, ctos;
663 
664 	for (i = 0; i < NKEYS; i++)
665 		keys[i] = derive_key(kex, 'A'+i, kex->we_need, hash, shared_secret);
666 
667 	debug2("kex_derive_keys");
668 	for (mode = 0; mode < MODE_MAX; mode++) {
669 		current_keys[mode] = kex->newkeys[mode];
670 		kex->newkeys[mode] = NULL;
671 		ctos = (!kex->server && mode == MODE_OUT) || (kex->server && mode == MODE_IN);
672 		current_keys[mode]->enc.iv  = keys[ctos ? 0 : 1];
673 		current_keys[mode]->enc.key = keys[ctos ? 2 : 3];
674 		current_keys[mode]->mac.key = keys[ctos ? 4 : 5];
675 	}
676 }
677 
678 Newkeys *
679 kex_get_newkeys(int mode)
680 {
681 	Newkeys *ret;
682 
683 	ret = current_keys[mode];
684 	current_keys[mode] = NULL;
685 	return ret;
686 }
687 
688 #if defined(DEBUG_KEX) || defined(DEBUG_KEXDH)
689 void
690 dump_digest(char *msg, u_char *digest, int len)
691 {
692 	int i;
693 
694 	fprintf(stderr, "%s\n", msg);
695 	for (i = 0; i< len; i++) {
696 		fprintf(stderr, "%02x", digest[i]);
697 		if (i%32 == 31)
698 			fprintf(stderr, "\n");
699 		else if (i%8 == 7)
700 			fprintf(stderr, " ");
701 	}
702 	fprintf(stderr, "\n");
703 }
704 #endif
705