xref: /netbsd-src/crypto/external/bsd/openssh/dist/kex.c (revision f89f6560d453f5e37386cc7938c072d2f528b9fa)
1 /*	$NetBSD: kex.c,v 1.10 2015/04/03 23:58:19 christos Exp $	*/
2 /* $OpenBSD: kex.c,v 1.105 2015/01/30 00:22:25 djm 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.10 2015/04/03 23:58:19 christos Exp $");
29 #include <sys/param.h>	/* MAX roundup */
30 
31 #include <signal.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 "ssh2.h"
41 #include "packet.h"
42 #include "compat.h"
43 #include "cipher.h"
44 #include "sshkey.h"
45 #include "kex.h"
46 #include "log.h"
47 #include "mac.h"
48 #include "match.h"
49 #include "misc.h"
50 #include "dispatch.h"
51 #include "monitor.h"
52 #include "canohost.h"
53 #include "roaming.h"
54 
55 #include "ssherr.h"
56 #include "sshbuf.h"
57 #include "digest.h"
58 
59 /* prototype */
60 static int kex_choose_conf(struct ssh *);
61 static int kex_input_newkeys(int, u_int32_t, void *);
62 
63 struct kexalg {
64 	const char *name;
65 	u_int type;
66 	int ec_nid;
67 	int hash_alg;
68 };
69 static const struct kexalg kexalgs[] = {
70 #ifdef WITH_OPENSSL
71 	{ KEX_DH1, KEX_DH_GRP1_SHA1, 0, SSH_DIGEST_SHA1 },
72 	{ KEX_DH14, KEX_DH_GRP14_SHA1, 0, SSH_DIGEST_SHA1 },
73 	{ KEX_DHGEX_SHA1, KEX_DH_GEX_SHA1, 0, SSH_DIGEST_SHA1 },
74 	{ KEX_DHGEX_SHA256, KEX_DH_GEX_SHA256, 0, SSH_DIGEST_SHA256 },
75 	{ KEX_ECDH_SHA2_NISTP256, KEX_ECDH_SHA2,
76 	    NID_X9_62_prime256v1, SSH_DIGEST_SHA256 },
77 	{ KEX_ECDH_SHA2_NISTP384, KEX_ECDH_SHA2, NID_secp384r1,
78 	    SSH_DIGEST_SHA384 },
79 	{ KEX_ECDH_SHA2_NISTP521, KEX_ECDH_SHA2, NID_secp521r1,
80 	    SSH_DIGEST_SHA512 },
81 #endif
82 	{ KEX_CURVE25519_SHA256, KEX_C25519_SHA256, 0, SSH_DIGEST_SHA256 },
83 	{ NULL, (u_int)-1, -1, -1},
84 };
85 
86 char *
87 kex_alg_list(char sep)
88 {
89 	char *ret = NULL, *tmp;
90 	size_t nlen, rlen = 0;
91 	const struct kexalg *k;
92 
93 	for (k = kexalgs; k->name != NULL; k++) {
94 		if (ret != NULL)
95 			ret[rlen++] = sep;
96 		nlen = strlen(k->name);
97 		if ((tmp = realloc(ret, rlen + nlen + 2)) == NULL) {
98 			free(ret);
99 			return NULL;
100 		}
101 		ret = tmp;
102 		memcpy(ret + rlen, k->name, nlen + 1);
103 		rlen += nlen;
104 	}
105 	return ret;
106 }
107 
108 static const struct kexalg *
109 kex_alg_by_name(const char *name)
110 {
111 	const struct kexalg *k;
112 
113 	for (k = kexalgs; k->name != NULL; k++) {
114 		if (strcmp(k->name, name) == 0)
115 			return k;
116 	}
117 	return NULL;
118 }
119 
120 /* Validate KEX method name list */
121 int
122 kex_names_valid(const char *names)
123 {
124 	char *s, *cp, *p;
125 
126 	if (names == NULL || strcmp(names, "") == 0)
127 		return 0;
128 	if ((s = cp = strdup(names)) == NULL)
129 		return 0;
130 	for ((p = strsep(&cp, ",")); p && *p != '\0';
131 	    (p = strsep(&cp, ","))) {
132 		if (kex_alg_by_name(p) == NULL) {
133 			error("Unsupported KEX algorithm \"%.100s\"", p);
134 			free(s);
135 			return 0;
136 		}
137 	}
138 	debug3("kex names ok: [%s]", names);
139 	free(s);
140 	return 1;
141 }
142 
143 /* put algorithm proposal into buffer */
144 int
145 kex_prop2buf(struct sshbuf *b, const char *proposal[PROPOSAL_MAX])
146 {
147 	u_int i;
148 	int r;
149 
150 	sshbuf_reset(b);
151 
152 	/*
153 	 * add a dummy cookie, the cookie will be overwritten by
154 	 * kex_send_kexinit(), each time a kexinit is set
155 	 */
156 	for (i = 0; i < KEX_COOKIE_LEN; i++) {
157 		if ((r = sshbuf_put_u8(b, 0)) != 0)
158 			return r;
159 	}
160 	for (i = 0; i < PROPOSAL_MAX; i++) {
161 		if ((r = sshbuf_put_cstring(b, proposal[i])) != 0)
162 			return r;
163 	}
164 	if ((r = sshbuf_put_u8(b, 0)) != 0 ||	/* first_kex_packet_follows */
165 	    (r = sshbuf_put_u32(b, 0)) != 0)	/* uint32 reserved */
166 		return r;
167 	return 0;
168 }
169 
170 /* parse buffer and return algorithm proposal */
171 int
172 kex_buf2prop(struct sshbuf *raw, int *first_kex_follows, char ***propp)
173 {
174 	struct sshbuf *b = NULL;
175 	u_char v;
176 	u_int i;
177 	char **proposal = NULL;
178 	int r;
179 
180 	*propp = NULL;
181 	if ((proposal = calloc(PROPOSAL_MAX, sizeof(char *))) == NULL)
182 		return SSH_ERR_ALLOC_FAIL;
183 	if ((b = sshbuf_fromb(raw)) == NULL) {
184 		r = SSH_ERR_ALLOC_FAIL;
185 		goto out;
186 	}
187 	if ((r = sshbuf_consume(b, KEX_COOKIE_LEN)) != 0) /* skip cookie */
188 		goto out;
189 	/* extract kex init proposal strings */
190 	for (i = 0; i < PROPOSAL_MAX; i++) {
191 		if ((r = sshbuf_get_cstring(b, &(proposal[i]), NULL)) != 0)
192 			goto out;
193 		debug2("kex_parse_kexinit: %s", proposal[i]);
194 	}
195 	/* first kex follows / reserved */
196 	if ((r = sshbuf_get_u8(b, &v)) != 0 ||
197 	    (r = sshbuf_get_u32(b, &i)) != 0)
198 		goto out;
199 	if (first_kex_follows != NULL)
200 		*first_kex_follows = i;
201 	debug2("kex_parse_kexinit: first_kex_follows %d ", v);
202 	debug2("kex_parse_kexinit: reserved %u ", i);
203 	r = 0;
204 	*propp = proposal;
205  out:
206 	if (r != 0 && proposal != NULL)
207 		kex_prop_free(proposal);
208 	sshbuf_free(b);
209 	return r;
210 }
211 
212 void
213 kex_prop_free(char **proposal)
214 {
215 	u_int i;
216 
217 	for (i = 0; i < PROPOSAL_MAX; i++)
218 		free(proposal[i]);
219 	free(proposal);
220 }
221 
222 /* ARGSUSED */
223 static int
224 kex_protocol_error(int type, u_int32_t seq, void *ctxt)
225 {
226 	error("Hm, kex protocol error: type %d seq %u", type, seq);
227 	return 0;
228 }
229 
230 static void
231 kex_reset_dispatch(struct ssh *ssh)
232 {
233 	ssh_dispatch_range(ssh, SSH2_MSG_TRANSPORT_MIN,
234 	    SSH2_MSG_TRANSPORT_MAX, &kex_protocol_error);
235 	ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
236 }
237 
238 int
239 kex_send_newkeys(struct ssh *ssh)
240 {
241 	int r;
242 
243 	kex_reset_dispatch(ssh);
244 	if ((r = sshpkt_start(ssh, SSH2_MSG_NEWKEYS)) != 0 ||
245 	    (r = sshpkt_send(ssh)) != 0)
246 		return r;
247 	debug("SSH2_MSG_NEWKEYS sent");
248 	debug("expecting SSH2_MSG_NEWKEYS");
249 	ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_input_newkeys);
250 	return 0;
251 }
252 
253 static int
254 kex_input_newkeys(int type, u_int32_t seq, void *ctxt)
255 {
256 	struct ssh *ssh = ctxt;
257 	struct kex *kex = ssh->kex;
258 	int r;
259 
260 	debug("SSH2_MSG_NEWKEYS received");
261 	ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_protocol_error);
262 	if ((r = sshpkt_get_end(ssh)) != 0)
263 		return r;
264 	kex->done = 1;
265 	sshbuf_reset(kex->peer);
266 	/* sshbuf_reset(kex->my); */
267 	kex->flags &= ~KEX_INIT_SENT;
268 	free(kex->name);
269 	kex->name = NULL;
270 	return 0;
271 }
272 
273 int
274 kex_send_kexinit(struct ssh *ssh)
275 {
276 	u_char *cookie;
277 	struct kex *kex = ssh->kex;
278 	int r;
279 
280 	if (kex == NULL)
281 		return SSH_ERR_INTERNAL_ERROR;
282 	if (kex->flags & KEX_INIT_SENT)
283 		return 0;
284 	kex->done = 0;
285 
286 	/* generate a random cookie */
287 	if (sshbuf_len(kex->my) < KEX_COOKIE_LEN)
288 		return SSH_ERR_INVALID_FORMAT;
289 	if ((cookie = sshbuf_mutable_ptr(kex->my)) == NULL)
290 		return SSH_ERR_INTERNAL_ERROR;
291 	arc4random_buf(cookie, KEX_COOKIE_LEN);
292 
293 	if ((r = sshpkt_start(ssh, SSH2_MSG_KEXINIT)) != 0 ||
294 	    (r = sshpkt_putb(ssh, kex->my)) != 0 ||
295 	    (r = sshpkt_send(ssh)) != 0)
296 		return r;
297 	debug("SSH2_MSG_KEXINIT sent");
298 	kex->flags |= KEX_INIT_SENT;
299 	return 0;
300 }
301 
302 /* ARGSUSED */
303 int
304 kex_input_kexinit(int type, u_int32_t seq, void *ctxt)
305 {
306 	struct ssh *ssh = ctxt;
307 	struct kex *kex = ssh->kex;
308 	const u_char *ptr;
309 	u_int i;
310 	size_t dlen;
311 	int r;
312 
313 	debug("SSH2_MSG_KEXINIT received");
314 	if (kex == NULL)
315 		return SSH_ERR_INVALID_ARGUMENT;
316 
317 	ptr = sshpkt_ptr(ssh, &dlen);
318 	if ((r = sshbuf_put(kex->peer, ptr, dlen)) != 0)
319 		return r;
320 
321 	/* discard packet */
322 	for (i = 0; i < KEX_COOKIE_LEN; i++)
323 		if ((r = sshpkt_get_u8(ssh, NULL)) != 0)
324 			return r;
325 	for (i = 0; i < PROPOSAL_MAX; i++)
326 		if ((r = sshpkt_get_string(ssh, NULL, NULL)) != 0)
327 			return r;
328 	/*
329 	 * XXX RFC4253 sec 7: "each side MAY guess" - currently no supported
330 	 * KEX method has the server move first, but a server might be using
331 	 * a custom method or one that we otherwise don't support. We should
332 	 * be prepared to remember first_kex_follows here so we can eat a
333 	 * packet later.
334 	 * XXX2 - RFC4253 is kind of ambiguous on what first_kex_follows means
335 	 * for cases where the server *doesn't* go first. I guess we should
336 	 * ignore it when it is set for these cases, which is what we do now.
337 	 */
338 	if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||	/* first_kex_follows */
339 	    (r = sshpkt_get_u32(ssh, NULL)) != 0 ||	/* reserved */
340 	    (r = sshpkt_get_end(ssh)) != 0)
341 			return r;
342 
343 	if (!(kex->flags & KEX_INIT_SENT))
344 		if ((r = kex_send_kexinit(ssh)) != 0)
345 			return r;
346 	if ((r = kex_choose_conf(ssh)) != 0)
347 		return r;
348 
349 	if (kex->kex_type < KEX_MAX && kex->kex[kex->kex_type] != NULL)
350 		return (kex->kex[kex->kex_type])(ssh);
351 
352 	return SSH_ERR_INTERNAL_ERROR;
353 }
354 
355 int
356 kex_new(struct ssh *ssh, const char *proposal[PROPOSAL_MAX], struct kex **kexp)
357 {
358 	struct kex *kex;
359 	int r;
360 
361 	*kexp = NULL;
362 	if ((kex = calloc(1, sizeof(*kex))) == NULL)
363 		return SSH_ERR_ALLOC_FAIL;
364 	if ((kex->peer = sshbuf_new()) == NULL ||
365 	    (kex->my = sshbuf_new()) == NULL) {
366 		r = SSH_ERR_ALLOC_FAIL;
367 		goto out;
368 	}
369 	if ((r = kex_prop2buf(kex->my, proposal)) != 0)
370 		goto out;
371 	kex->done = 0;
372 	kex_reset_dispatch(ssh);
373 	r = 0;
374 	*kexp = kex;
375  out:
376 	if (r != 0)
377 		kex_free(kex);
378 	return r;
379 }
380 
381 void
382 kex_free_newkeys(struct newkeys *newkeys)
383 {
384 	if (newkeys == NULL)
385 		return;
386 	if (newkeys->enc.key) {
387 		explicit_bzero(newkeys->enc.key, newkeys->enc.key_len);
388 		free(newkeys->enc.key);
389 		newkeys->enc.key = NULL;
390 	}
391 	if (newkeys->enc.iv) {
392 		explicit_bzero(newkeys->enc.iv, newkeys->enc.block_size);
393 		free(newkeys->enc.iv);
394 		newkeys->enc.iv = NULL;
395 	}
396 	free(newkeys->enc.name);
397 	explicit_bzero(&newkeys->enc, sizeof(newkeys->enc));
398 	free(newkeys->comp.name);
399 	explicit_bzero(&newkeys->comp, sizeof(newkeys->comp));
400 	mac_clear(&newkeys->mac);
401 	if (newkeys->mac.key) {
402 		explicit_bzero(newkeys->mac.key, newkeys->mac.key_len);
403 		free(newkeys->mac.key);
404 		newkeys->mac.key = NULL;
405 	}
406 	free(newkeys->mac.name);
407 	explicit_bzero(&newkeys->mac, sizeof(newkeys->mac));
408 	explicit_bzero(newkeys, sizeof(*newkeys));
409 	free(newkeys);
410 }
411 
412 void
413 kex_free(struct kex *kex)
414 {
415 	u_int mode;
416 
417 #ifdef WITH_OPENSSL
418 	if (kex->dh)
419 		DH_free(kex->dh);
420 	if (kex->ec_client_key)
421 		EC_KEY_free(kex->ec_client_key);
422 #endif
423 	for (mode = 0; mode < MODE_MAX; mode++) {
424 		kex_free_newkeys(kex->newkeys[mode]);
425 		kex->newkeys[mode] = NULL;
426 	}
427 	sshbuf_free(kex->peer);
428 	sshbuf_free(kex->my);
429 	free(kex->session_id);
430 	free(kex->client_version_string);
431 	free(kex->server_version_string);
432 	free(kex);
433 }
434 
435 int
436 kex_setup(struct ssh *ssh, const char *proposal[PROPOSAL_MAX])
437 {
438 	int r;
439 
440 	if ((r = kex_new(ssh, proposal, &ssh->kex)) != 0)
441 		return r;
442 	if ((r = kex_send_kexinit(ssh)) != 0) {		/* we start */
443 		kex_free(ssh->kex);
444 		ssh->kex = NULL;
445 		return r;
446 	}
447 	return 0;
448 }
449 
450 static int
451 choose_enc(struct sshenc *enc, char *client, char *server)
452 {
453 	char *name = match_list(client, server, NULL);
454 
455 	if (name == NULL)
456 		return SSH_ERR_NO_CIPHER_ALG_MATCH;
457 	if ((enc->cipher = cipher_by_name(name)) == NULL)
458 		return SSH_ERR_INTERNAL_ERROR;
459 	enc->name = name;
460 	enc->enabled = 0;
461 	enc->iv = NULL;
462 	enc->iv_len = cipher_ivlen(enc->cipher);
463 	enc->key = NULL;
464 	enc->key_len = cipher_keylen(enc->cipher);
465 	enc->block_size = cipher_blocksize(enc->cipher);
466 	return 0;
467 }
468 
469 static int
470 choose_mac(struct ssh *ssh, struct sshmac *mac, char *client, char *server)
471 {
472 	char *name = match_list(client, server, NULL);
473 
474 	if (name == NULL)
475 		return SSH_ERR_NO_MAC_ALG_MATCH;
476 	if (mac_setup(mac, name) < 0)
477 		return SSH_ERR_INTERNAL_ERROR;
478 	/* truncate the key */
479 	if (ssh->compat & SSH_BUG_HMAC)
480 		mac->key_len = 16;
481 	mac->name = name;
482 	mac->key = NULL;
483 	mac->enabled = 0;
484 	return 0;
485 }
486 
487 static int
488 choose_comp(struct sshcomp *comp, char *client, char *server)
489 {
490 	char *name = match_list(client, server, NULL);
491 
492 	if (name == NULL)
493 		return SSH_ERR_NO_COMPRESS_ALG_MATCH;
494 	if (strcmp(name, "zlib@openssh.com") == 0) {
495 		comp->type = COMP_DELAYED;
496 	} else if (strcmp(name, "zlib") == 0) {
497 		comp->type = COMP_ZLIB;
498 	} else if (strcmp(name, "none") == 0) {
499 		comp->type = COMP_NONE;
500 	} else {
501 		return SSH_ERR_INTERNAL_ERROR;
502 	}
503 	comp->name = name;
504 	return 0;
505 }
506 
507 static int
508 choose_kex(struct kex *k, char *client, char *server)
509 {
510 	const struct kexalg *kexalg;
511 
512 	k->name = match_list(client, server, NULL);
513 
514 	if (k->name == NULL)
515 		return SSH_ERR_NO_KEX_ALG_MATCH;
516 	if ((kexalg = kex_alg_by_name(k->name)) == NULL)
517 		return SSH_ERR_INTERNAL_ERROR;
518 	k->kex_type = kexalg->type;
519 	k->hash_alg = kexalg->hash_alg;
520 	k->ec_nid = kexalg->ec_nid;
521 	return 0;
522 }
523 
524 static int
525 choose_hostkeyalg(struct kex *k, char *client, char *server)
526 {
527 	char *hostkeyalg = match_list(client, server, NULL);
528 
529 	if (hostkeyalg == NULL)
530 		return SSH_ERR_NO_HOSTKEY_ALG_MATCH;
531 	k->hostkey_type = sshkey_type_from_name(hostkeyalg);
532 	if (k->hostkey_type == KEY_UNSPEC)
533 		return SSH_ERR_INTERNAL_ERROR;
534 	k->hostkey_nid = sshkey_ecdsa_nid_from_name(hostkeyalg);
535 	free(hostkeyalg);
536 	return 0;
537 }
538 
539 static int
540 proposals_match(char *my[PROPOSAL_MAX], char *peer[PROPOSAL_MAX])
541 {
542 	static int check[] = {
543 		PROPOSAL_KEX_ALGS, PROPOSAL_SERVER_HOST_KEY_ALGS, -1
544 	};
545 	int *idx;
546 	char *p;
547 
548 	for (idx = &check[0]; *idx != -1; idx++) {
549 		if ((p = strchr(my[*idx], ',')) != NULL)
550 			*p = '\0';
551 		if ((p = strchr(peer[*idx], ',')) != NULL)
552 			*p = '\0';
553 		if (strcmp(my[*idx], peer[*idx]) != 0) {
554 			debug2("proposal mismatch: my %s peer %s",
555 			    my[*idx], peer[*idx]);
556 			return (0);
557 		}
558 	}
559 	debug2("proposals match");
560 	return (1);
561 }
562 
563 static int
564 kex_choose_conf(struct ssh *ssh)
565 {
566 	struct kex *kex = ssh->kex;
567 	struct newkeys *newkeys;
568 	char **my = NULL, **peer = NULL;
569 	char **cprop, **sprop;
570 	int nenc, nmac, ncomp;
571 	u_int mode, ctos, need, dh_need, authlen;
572 	int log_flag = 0;
573 	int r, first_kex_follows;
574 
575 	if ((r = kex_buf2prop(kex->my, NULL, &my)) != 0 ||
576 	    (r = kex_buf2prop(kex->peer, &first_kex_follows, &peer)) != 0)
577 		goto out;
578 
579 	if (kex->server) {
580 		cprop=peer;
581 		sprop=my;
582 	} else {
583 		cprop=my;
584 		sprop=peer;
585 	}
586 
587 	/* Check whether server offers roaming */
588 	if (!kex->server) {
589 		char *roaming = match_list(KEX_RESUME,
590 		    peer[PROPOSAL_KEX_ALGS], NULL);
591 
592 		if (roaming) {
593 			kex->roaming = 1;
594 			free(roaming);
595 		}
596 	}
597 
598 	/* Algorithm Negotiation */
599 	for (mode = 0; mode < MODE_MAX; mode++) {
600 		if ((newkeys = calloc(1, sizeof(*newkeys))) == NULL) {
601 			r = SSH_ERR_ALLOC_FAIL;
602 			goto out;
603 		}
604 		kex->newkeys[mode] = newkeys;
605 		ctos = (!kex->server && mode == MODE_OUT) ||
606 		    (kex->server && mode == MODE_IN);
607 		nenc  = ctos ? PROPOSAL_ENC_ALGS_CTOS  : PROPOSAL_ENC_ALGS_STOC;
608 		nmac  = ctos ? PROPOSAL_MAC_ALGS_CTOS  : PROPOSAL_MAC_ALGS_STOC;
609 		ncomp = ctos ? PROPOSAL_COMP_ALGS_CTOS : PROPOSAL_COMP_ALGS_STOC;
610 		if ((r = choose_enc(&newkeys->enc, cprop[nenc],
611 		    sprop[nenc])) != 0)
612 			goto out;
613 		authlen = cipher_authlen(newkeys->enc.cipher);
614 		/* ignore mac for authenticated encryption */
615 		if (authlen == 0 &&
616 		    (r = choose_mac(ssh, &newkeys->mac, cprop[nmac],
617 		    sprop[nmac])) != 0)
618 			goto out;
619 		if ((r = choose_comp(&newkeys->comp, cprop[ncomp],
620 		    sprop[ncomp])) != 0)
621 			goto out;
622 		debug("REQUESTED ENC.NAME is '%s'", newkeys->enc.name);
623 		if (strcmp(newkeys->enc.name, "none") == 0) {
624 			int auth_flag;
625 
626 			auth_flag = ssh_packet_authentication_state();
627 			debug("Requesting NONE. Authflag is %d", auth_flag);
628 			if (auth_flag == 1) {
629 				debug("None requested post authentication.");
630 			} else {
631 				fatal("Pre-authentication none cipher requests are not allowed.");
632 			}
633 		}
634 		debug("kex: %s %s %s %s",
635 		    ctos ? "client->server" : "server->client",
636 		    newkeys->enc.name,
637 		    authlen == 0 ? newkeys->mac.name : "<implicit>",
638 		    newkeys->comp.name);
639 		/* client starts withctos = 0 && log flag = 0 and no log*/
640 		/* 2nd client pass ctos=1 and flag = 1 so no log*/
641 		/* server starts with ctos =1 && log_flag = 0 so log */
642 		/* 2nd sever pass ctos = 1 && log flag = 1 so no log*/
643 		/* -cjr*/
644 		if (ctos && !log_flag) {
645 			logit("SSH: Server;Ltype: Kex;Remote: %s-%d;Enc: %s;MAC: %s;Comp: %s",
646 			      get_remote_ipaddr(),
647 			      get_remote_port(),
648 			      newkeys->enc.name,
649 			      newkeys->mac.name,
650 			      newkeys->comp.name);
651 		}
652 		log_flag = 1;
653 	}
654 	if ((r = choose_kex(kex, cprop[PROPOSAL_KEX_ALGS],
655 	    sprop[PROPOSAL_KEX_ALGS])) != 0 ||
656 	    (r = choose_hostkeyalg(kex, cprop[PROPOSAL_SERVER_HOST_KEY_ALGS],
657 	    sprop[PROPOSAL_SERVER_HOST_KEY_ALGS])) != 0)
658 		goto out;
659 	need = dh_need = 0;
660 	for (mode = 0; mode < MODE_MAX; mode++) {
661 		newkeys = kex->newkeys[mode];
662 		need = MAX(need, newkeys->enc.key_len);
663 		need = MAX(need, newkeys->enc.block_size);
664 		need = MAX(need, newkeys->enc.iv_len);
665 		need = MAX(need, newkeys->mac.key_len);
666 		dh_need = MAX(dh_need, cipher_seclen(newkeys->enc.cipher));
667 		dh_need = MAX(dh_need, newkeys->enc.block_size);
668 		dh_need = MAX(dh_need, newkeys->enc.iv_len);
669 		dh_need = MAX(dh_need, newkeys->mac.key_len);
670 	}
671 	/* XXX need runden? */
672 	kex->we_need = need;
673 	kex->dh_need = dh_need;
674 
675 	/* ignore the next message if the proposals do not match */
676 	if (first_kex_follows && !proposals_match(my, peer) &&
677 	    !(ssh->compat & SSH_BUG_FIRSTKEX))
678 		ssh->dispatch_skip_packets = 1;
679 	r = 0;
680  out:
681 	kex_prop_free(my);
682 	kex_prop_free(peer);
683 	return r;
684 }
685 
686 static int
687 derive_key(struct ssh *ssh, int id, u_int need, u_char *hash, u_int hashlen,
688     const struct sshbuf *shared_secret, u_char **keyp)
689 {
690 	struct kex *kex = ssh->kex;
691 	struct ssh_digest_ctx *hashctx = NULL;
692 	char c = id;
693 	u_int have;
694 	size_t mdsz;
695 	u_char *digest;
696 	int r;
697 
698 	if ((mdsz = ssh_digest_bytes(kex->hash_alg)) == 0)
699 		return SSH_ERR_INVALID_ARGUMENT;
700 	if ((digest = calloc(1, roundup(need, mdsz))) == NULL) {
701 		r = SSH_ERR_ALLOC_FAIL;
702 		goto out;
703 	}
704 
705 	/* K1 = HASH(K || H || "A" || session_id) */
706 	if ((hashctx = ssh_digest_start(kex->hash_alg)) == NULL ||
707 	    ssh_digest_update_buffer(hashctx, shared_secret) != 0 ||
708 	    ssh_digest_update(hashctx, hash, hashlen) != 0 ||
709 	    ssh_digest_update(hashctx, &c, 1) != 0 ||
710 	    ssh_digest_update(hashctx, kex->session_id,
711 	    kex->session_id_len) != 0 ||
712 	    ssh_digest_final(hashctx, digest, mdsz) != 0) {
713 		r = SSH_ERR_LIBCRYPTO_ERROR;
714 		goto out;
715 	}
716 	ssh_digest_free(hashctx);
717 	hashctx = NULL;
718 
719 	/*
720 	 * expand key:
721 	 * Kn = HASH(K || H || K1 || K2 || ... || Kn-1)
722 	 * Key = K1 || K2 || ... || Kn
723 	 */
724 	for (have = mdsz; need > have; have += mdsz) {
725 		if ((hashctx = ssh_digest_start(kex->hash_alg)) == NULL ||
726 		    ssh_digest_update_buffer(hashctx, shared_secret) != 0 ||
727 		    ssh_digest_update(hashctx, hash, hashlen) != 0 ||
728 		    ssh_digest_update(hashctx, digest, have) != 0 ||
729 		    ssh_digest_final(hashctx, digest + have, mdsz) != 0) {
730 			r = SSH_ERR_LIBCRYPTO_ERROR;
731 			goto out;
732 		}
733 		ssh_digest_free(hashctx);
734 		hashctx = NULL;
735 	}
736 #ifdef DEBUG_KEX
737 	fprintf(stderr, "key '%c'== ", c);
738 	dump_digest("key", digest, need);
739 #endif
740 	*keyp = digest;
741 	digest = NULL;
742 	r = 0;
743  out:
744 	if (digest)
745 		free(digest);
746 	ssh_digest_free(hashctx);
747 	return r;
748 }
749 
750 #define NKEYS	6
751 int
752 kex_derive_keys(struct ssh *ssh, u_char *hash, u_int hashlen,
753     const struct sshbuf *shared_secret)
754 {
755 	struct kex *kex = ssh->kex;
756 	u_char *keys[NKEYS];
757 	u_int i, j, mode, ctos;
758 	int r;
759 
760 	for (i = 0; i < NKEYS; i++) {
761 		if ((r = derive_key(ssh, 'A'+i, kex->we_need, hash, hashlen,
762 		    shared_secret, &keys[i])) != 0) {
763 			for (j = 0; j < i; j++)
764 				free(keys[j]);
765 			return r;
766 		}
767 	}
768 	for (mode = 0; mode < MODE_MAX; mode++) {
769 		ctos = (!kex->server && mode == MODE_OUT) ||
770 		    (kex->server && mode == MODE_IN);
771 		kex->newkeys[mode]->enc.iv  = keys[ctos ? 0 : 1];
772 		kex->newkeys[mode]->enc.key = keys[ctos ? 2 : 3];
773 		kex->newkeys[mode]->mac.key = keys[ctos ? 4 : 5];
774 	}
775 	return 0;
776 }
777 
778 #ifdef WITH_OPENSSL
779 int
780 kex_derive_keys_bn(struct ssh *ssh, u_char *hash, u_int hashlen,
781     const BIGNUM *secret)
782 {
783 	struct sshbuf *shared_secret;
784 	int r;
785 
786 	if ((shared_secret = sshbuf_new()) == NULL)
787 		return SSH_ERR_ALLOC_FAIL;
788 	if ((r = sshbuf_put_bignum2(shared_secret, secret)) == 0)
789 		r = kex_derive_keys(ssh, hash, hashlen, shared_secret);
790 	sshbuf_free(shared_secret);
791 	return r;
792 }
793 #endif
794 
795 #ifdef WITH_SSH1
796 int
797 derive_ssh1_session_id(BIGNUM *host_modulus, BIGNUM *server_modulus,
798     u_int8_t cookie[8], u_int8_t id[16])
799 {
800 	u_int8_t hbuf[2048], sbuf[2048], obuf[SSH_DIGEST_MAX_LENGTH];
801 	struct ssh_digest_ctx *hashctx = NULL;
802 	size_t hlen, slen;
803 	int r;
804 
805 	hlen = BN_num_bytes(host_modulus);
806 	slen = BN_num_bytes(server_modulus);
807 	if (hlen < (512 / 8) || (u_int)hlen > sizeof(hbuf) ||
808 	    slen < (512 / 8) || (u_int)slen > sizeof(sbuf))
809 		return SSH_ERR_KEY_BITS_MISMATCH;
810 	if (BN_bn2bin(host_modulus, hbuf) <= 0 ||
811 	    BN_bn2bin(server_modulus, sbuf) <= 0) {
812 		r = SSH_ERR_LIBCRYPTO_ERROR;
813 		goto out;
814 	}
815 	if ((hashctx = ssh_digest_start(SSH_DIGEST_MD5)) == NULL) {
816 		r = SSH_ERR_ALLOC_FAIL;
817 		goto out;
818 	}
819 	if (ssh_digest_update(hashctx, hbuf, hlen) != 0 ||
820 	    ssh_digest_update(hashctx, sbuf, slen) != 0 ||
821 	    ssh_digest_update(hashctx, cookie, 8) != 0 ||
822 	    ssh_digest_final(hashctx, obuf, sizeof(obuf)) != 0) {
823 		r = SSH_ERR_LIBCRYPTO_ERROR;
824 		goto out;
825 	}
826 	memcpy(id, obuf, ssh_digest_bytes(SSH_DIGEST_MD5));
827 	r = 0;
828  out:
829 	ssh_digest_free(hashctx);
830 	explicit_bzero(hbuf, sizeof(hbuf));
831 	explicit_bzero(sbuf, sizeof(sbuf));
832 	explicit_bzero(obuf, sizeof(obuf));
833 	return r;
834 }
835 #endif
836 
837 #if defined(DEBUG_KEX) || defined(DEBUG_KEXDH) || defined(DEBUG_KEXECDH)
838 void
839 dump_digest(char *msg, u_char *digest, int len)
840 {
841 	fprintf(stderr, "%s\n", msg);
842 	sshbuf_dump_data(digest, len, stderr);
843 }
844 #endif
845