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