xref: /netbsd-src/crypto/external/bsd/openssh/dist/kex.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: kex.c,v 1.21 2018/04/06 18:59:00 christos Exp $	*/
2 /* $OpenBSD: kex.c,v 1.136 2018/02/07 02:06:50 jsing 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.21 2018/04/06 18:59:00 christos Exp $");
29 
30 #include <sys/param.h>	/* MAX roundup */
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 #include <openssl/dh.h>
39 #endif
40 
41 #include "ssh2.h"
42 #include "packet.h"
43 #include "compat.h"
44 #include "cipher.h"
45 #include "sshkey.h"
46 #include "kex.h"
47 #include "log.h"
48 #include "mac.h"
49 #include "match.h"
50 #include "misc.h"
51 #include "dispatch.h"
52 #include "packet.h"
53 #include "monitor.h"
54 #include "canohost.h"
55 
56 #include "ssherr.h"
57 #include "sshbuf.h"
58 #include "digest.h"
59 
60 /* prototype */
61 static int kex_choose_conf(struct ssh *);
62 static int kex_input_newkeys(int, u_int32_t, struct ssh *);
63 
64 static const char *proposal_names[PROPOSAL_MAX] = {
65 	"KEX algorithms",
66 	"host key algorithms",
67 	"ciphers ctos",
68 	"ciphers stoc",
69 	"MACs ctos",
70 	"MACs stoc",
71 	"compression ctos",
72 	"compression stoc",
73 	"languages ctos",
74 	"languages stoc",
75 };
76 
77 struct kexalg {
78 	const char *name;
79 	u_int type;
80 	int ec_nid;
81 	int hash_alg;
82 };
83 static const struct kexalg kexalgs[] = {
84 #ifdef WITH_OPENSSL
85 	{ KEX_DH1, KEX_DH_GRP1_SHA1, 0, SSH_DIGEST_SHA1 },
86 	{ KEX_DH14_SHA1, KEX_DH_GRP14_SHA1, 0, SSH_DIGEST_SHA1 },
87 	{ KEX_DH14_SHA256, KEX_DH_GRP14_SHA256, 0, SSH_DIGEST_SHA256 },
88 	{ KEX_DH16_SHA512, KEX_DH_GRP16_SHA512, 0, SSH_DIGEST_SHA512 },
89 	{ KEX_DH18_SHA512, KEX_DH_GRP18_SHA512, 0, SSH_DIGEST_SHA512 },
90 	{ KEX_DHGEX_SHA1, KEX_DH_GEX_SHA1, 0, SSH_DIGEST_SHA1 },
91 	{ KEX_DHGEX_SHA256, KEX_DH_GEX_SHA256, 0, SSH_DIGEST_SHA256 },
92 	{ KEX_ECDH_SHA2_NISTP256, KEX_ECDH_SHA2,
93 	    NID_X9_62_prime256v1, SSH_DIGEST_SHA256 },
94 	{ KEX_ECDH_SHA2_NISTP384, KEX_ECDH_SHA2, NID_secp384r1,
95 	    SSH_DIGEST_SHA384 },
96 	{ KEX_ECDH_SHA2_NISTP521, KEX_ECDH_SHA2, NID_secp521r1,
97 	    SSH_DIGEST_SHA512 },
98 #endif
99 	{ KEX_CURVE25519_SHA256, KEX_C25519_SHA256, 0, SSH_DIGEST_SHA256 },
100 	{ KEX_CURVE25519_SHA256_OLD, KEX_C25519_SHA256, 0, SSH_DIGEST_SHA256 },
101 	{ NULL, (u_int)-1, -1, -1},
102 };
103 
104 char *
105 kex_alg_list(char sep)
106 {
107 	char *ret = NULL, *tmp;
108 	size_t nlen, rlen = 0;
109 	const struct kexalg *k;
110 
111 	for (k = kexalgs; k->name != NULL; k++) {
112 		if (ret != NULL)
113 			ret[rlen++] = sep;
114 		nlen = strlen(k->name);
115 		if ((tmp = realloc(ret, rlen + nlen + 2)) == NULL) {
116 			free(ret);
117 			return NULL;
118 		}
119 		ret = tmp;
120 		memcpy(ret + rlen, k->name, nlen + 1);
121 		rlen += nlen;
122 	}
123 	return ret;
124 }
125 
126 static const struct kexalg *
127 kex_alg_by_name(const char *name)
128 {
129 	const struct kexalg *k;
130 
131 	for (k = kexalgs; k->name != NULL; k++) {
132 		if (strcmp(k->name, name) == 0)
133 			return k;
134 	}
135 	return NULL;
136 }
137 
138 /* Validate KEX method name list */
139 int
140 kex_names_valid(const char *names)
141 {
142 	char *s, *cp, *p;
143 
144 	if (names == NULL || strcmp(names, "") == 0)
145 		return 0;
146 	if ((s = cp = strdup(names)) == NULL)
147 		return 0;
148 	for ((p = strsep(&cp, ",")); p && *p != '\0';
149 	    (p = strsep(&cp, ","))) {
150 		if (kex_alg_by_name(p) == NULL) {
151 			error("Unsupported KEX algorithm \"%.100s\"", p);
152 			free(s);
153 			return 0;
154 		}
155 	}
156 	debug3("kex names ok: [%s]", names);
157 	free(s);
158 	return 1;
159 }
160 
161 /*
162  * Concatenate algorithm names, avoiding duplicates in the process.
163  * Caller must free returned string.
164  */
165 char *
166 kex_names_cat(const char *a, const char *b)
167 {
168 	char *ret = NULL, *tmp = NULL, *cp, *p, *m;
169 	size_t len;
170 
171 	if (a == NULL || *a == '\0')
172 		return NULL;
173 	if (b == NULL || *b == '\0')
174 		return strdup(a);
175 	if (strlen(b) > 1024*1024)
176 		return NULL;
177 	len = strlen(a) + strlen(b) + 2;
178 	if ((tmp = cp = strdup(b)) == NULL ||
179 	    (ret = calloc(1, len)) == NULL) {
180 		free(tmp);
181 		return NULL;
182 	}
183 	strlcpy(ret, a, len);
184 	for ((p = strsep(&cp, ",")); p && *p != '\0'; (p = strsep(&cp, ","))) {
185 		if ((m = match_list(ret, p, NULL)) != NULL) {
186 			free(m);
187 			continue; /* Algorithm already present */
188 		}
189 		if (strlcat(ret, ",", len) >= len ||
190 		    strlcat(ret, p, len) >= len) {
191 			free(tmp);
192 			free(ret);
193 			return NULL; /* Shouldn't happen */
194 		}
195 	}
196 	free(tmp);
197 	return ret;
198 }
199 
200 /*
201  * Assemble a list of algorithms from a default list and a string from a
202  * configuration file. The user-provided string may begin with '+' to
203  * indicate that it should be appended to the default or '-' that the
204  * specified names should be removed.
205  */
206 int
207 kex_assemble_names(const char *def, char **list)
208 {
209 	char *ret;
210 
211 	if (list == NULL || *list == NULL || **list == '\0') {
212 		*list = strdup(def);
213 		return 0;
214 	}
215 	if (**list == '+') {
216 		if ((ret = kex_names_cat(def, *list + 1)) == NULL)
217 			return SSH_ERR_ALLOC_FAIL;
218 		free(*list);
219 		*list = ret;
220 	} else if (**list == '-') {
221 		if ((ret = match_filter_list(def, *list + 1)) == NULL)
222 			return SSH_ERR_ALLOC_FAIL;
223 		free(*list);
224 		*list = ret;
225 	}
226 
227 	return 0;
228 }
229 
230 /* put algorithm proposal into buffer */
231 int
232 kex_prop2buf(struct sshbuf *b, const char *proposal[PROPOSAL_MAX])
233 {
234 	u_int i;
235 	int r;
236 
237 	sshbuf_reset(b);
238 
239 	/*
240 	 * add a dummy cookie, the cookie will be overwritten by
241 	 * kex_send_kexinit(), each time a kexinit is set
242 	 */
243 	for (i = 0; i < KEX_COOKIE_LEN; i++) {
244 		if ((r = sshbuf_put_u8(b, 0)) != 0)
245 			return r;
246 	}
247 	for (i = 0; i < PROPOSAL_MAX; i++) {
248 		if ((r = sshbuf_put_cstring(b, proposal[i])) != 0)
249 			return r;
250 	}
251 	if ((r = sshbuf_put_u8(b, 0)) != 0 ||	/* first_kex_packet_follows */
252 	    (r = sshbuf_put_u32(b, 0)) != 0)	/* uint32 reserved */
253 		return r;
254 	return 0;
255 }
256 
257 /* parse buffer and return algorithm proposal */
258 int
259 kex_buf2prop(struct sshbuf *raw, int *first_kex_follows, char ***propp)
260 {
261 	struct sshbuf *b = NULL;
262 	u_char v;
263 	u_int i;
264 	char **proposal = NULL;
265 	int r;
266 
267 	*propp = NULL;
268 	if ((proposal = calloc(PROPOSAL_MAX, sizeof(char *))) == NULL)
269 		return SSH_ERR_ALLOC_FAIL;
270 	if ((b = sshbuf_fromb(raw)) == NULL) {
271 		r = SSH_ERR_ALLOC_FAIL;
272 		goto out;
273 	}
274 	if ((r = sshbuf_consume(b, KEX_COOKIE_LEN)) != 0) /* skip cookie */
275 		goto out;
276 	/* extract kex init proposal strings */
277 	for (i = 0; i < PROPOSAL_MAX; i++) {
278 		if ((r = sshbuf_get_cstring(b, &(proposal[i]), NULL)) != 0)
279 			goto out;
280 		debug2("%s: %s", proposal_names[i], proposal[i]);
281 	}
282 	/* first kex follows / reserved */
283 	if ((r = sshbuf_get_u8(b, &v)) != 0 ||	/* first_kex_follows */
284 	    (r = sshbuf_get_u32(b, &i)) != 0)	/* reserved */
285 		goto out;
286 	if (first_kex_follows != NULL)
287 		*first_kex_follows = v;
288 	debug2("first_kex_follows %d ", v);
289 	debug2("reserved %u ", i);
290 	r = 0;
291 	*propp = proposal;
292  out:
293 	if (r != 0 && proposal != NULL)
294 		kex_prop_free(proposal);
295 	sshbuf_free(b);
296 	return r;
297 }
298 
299 void
300 kex_prop_free(char **proposal)
301 {
302 	u_int i;
303 
304 	if (proposal == NULL)
305 		return;
306 	for (i = 0; i < PROPOSAL_MAX; i++)
307 		free(proposal[i]);
308 	free(proposal);
309 }
310 
311 /* ARGSUSED */
312 static int
313 kex_protocol_error(int type, u_int32_t seq, struct ssh *ssh)
314 {
315 	int r;
316 
317 	error("kex protocol error: type %d seq %u", type, seq);
318 	if ((r = sshpkt_start(ssh, SSH2_MSG_UNIMPLEMENTED)) != 0 ||
319 	    (r = sshpkt_put_u32(ssh, seq)) != 0 ||
320 	    (r = sshpkt_send(ssh)) != 0)
321 		return r;
322 	return 0;
323 }
324 
325 static void
326 kex_reset_dispatch(struct ssh *ssh)
327 {
328 	ssh_dispatch_range(ssh, SSH2_MSG_TRANSPORT_MIN,
329 	    SSH2_MSG_TRANSPORT_MAX, &kex_protocol_error);
330 }
331 
332 static int
333 kex_send_ext_info(struct ssh *ssh)
334 {
335 	int r;
336 	char *algs;
337 
338 	if ((algs = sshkey_alg_list(0, 1, 1, ',')) == NULL)
339 		return SSH_ERR_ALLOC_FAIL;
340 	if ((r = sshpkt_start(ssh, SSH2_MSG_EXT_INFO)) != 0 ||
341 	    (r = sshpkt_put_u32(ssh, 1)) != 0 ||
342 	    (r = sshpkt_put_cstring(ssh, "server-sig-algs")) != 0 ||
343 	    (r = sshpkt_put_cstring(ssh, algs)) != 0 ||
344 	    (r = sshpkt_send(ssh)) != 0)
345 		goto out;
346 	/* success */
347 	r = 0;
348  out:
349 	free(algs);
350 	return r;
351 }
352 
353 int
354 kex_send_newkeys(struct ssh *ssh)
355 {
356 	int r;
357 
358 	kex_reset_dispatch(ssh);
359 	if ((r = sshpkt_start(ssh, SSH2_MSG_NEWKEYS)) != 0 ||
360 	    (r = sshpkt_send(ssh)) != 0)
361 		return r;
362 	debug("SSH2_MSG_NEWKEYS sent");
363 	debug("expecting SSH2_MSG_NEWKEYS");
364 	ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_input_newkeys);
365 	if (ssh->kex->ext_info_c)
366 		if ((r = kex_send_ext_info(ssh)) != 0)
367 			return r;
368 	return 0;
369 }
370 
371 int
372 kex_input_ext_info(int type, u_int32_t seq, struct ssh *ssh)
373 {
374 	struct kex *kex = ssh->kex;
375 	u_int32_t i, ninfo;
376 	char *name, *found;
377 	u_char *val;
378 	size_t vlen;
379 	int r;
380 
381 	debug("SSH2_MSG_EXT_INFO received");
382 	ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &kex_protocol_error);
383 	if ((r = sshpkt_get_u32(ssh, &ninfo)) != 0)
384 		return r;
385 	if (ninfo > 1024) {
386 		fatal("%s: too many %u fields", __func__, ninfo);
387 		return SSH_ERR_INTERNAL_ERROR;
388 	}
389 	for (i = 0; i < ninfo; i++) {
390 		if ((r = sshpkt_get_cstring(ssh, &name, NULL)) != 0)
391 			return r;
392 		if ((r = sshpkt_get_string(ssh, &val, &vlen)) != 0) {
393 			free(name);
394 			return r;
395 		}
396 		if (strcmp(name, "server-sig-algs") == 0) {
397 			char *cval = (void *)val;
398 			/* Ensure no \0 lurking in value */
399 			if (memchr(val, '\0', vlen) != NULL) {
400 				error("%s: nul byte in %s", __func__, name);
401 				return SSH_ERR_INVALID_FORMAT;
402 			}
403 			debug("%s: %s=<%s>", __func__, name, val);
404 			found = match_list("rsa-sha2-256", cval, NULL);
405 			if (found) {
406 				kex->rsa_sha2 = 256;
407 				free(found);
408 			}
409 			found = match_list("rsa-sha2-512", cval, NULL);
410 			if (found) {
411 				kex->rsa_sha2 = 512;
412 				free(found);
413 			}
414 		} else
415 			debug("%s: %s (unrecognised)", __func__, name);
416 		free(name);
417 		free(val);
418 	}
419 	return sshpkt_get_end(ssh);
420 }
421 
422 static int
423 kex_input_newkeys(int type, u_int32_t seq, struct ssh *ssh)
424 {
425 	struct kex *kex = ssh->kex;
426 	int r;
427 
428 	debug("SSH2_MSG_NEWKEYS received");
429 	ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_protocol_error);
430 	ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
431 	if ((r = sshpkt_get_end(ssh)) != 0)
432 		return r;
433 	if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0)
434 		return r;
435 	kex->done = 1;
436 	sshbuf_reset(kex->peer);
437 	/* sshbuf_reset(kex->my); */
438 	kex->flags &= ~KEX_INIT_SENT;
439 	free(kex->name);
440 	kex->name = NULL;
441 	return 0;
442 }
443 
444 int
445 kex_send_kexinit(struct ssh *ssh)
446 {
447 	u_char *cookie;
448 	struct kex *kex = ssh->kex;
449 	int r;
450 
451 	if (kex == NULL)
452 		return SSH_ERR_INTERNAL_ERROR;
453 	if (kex->flags & KEX_INIT_SENT)
454 		return 0;
455 	kex->done = 0;
456 
457 	/* generate a random cookie */
458 	if (sshbuf_len(kex->my) < KEX_COOKIE_LEN)
459 		return SSH_ERR_INVALID_FORMAT;
460 	if ((cookie = sshbuf_mutable_ptr(kex->my)) == NULL)
461 		return SSH_ERR_INTERNAL_ERROR;
462 	arc4random_buf(cookie, KEX_COOKIE_LEN);
463 
464 	if ((r = sshpkt_start(ssh, SSH2_MSG_KEXINIT)) != 0 ||
465 	    (r = sshpkt_putb(ssh, kex->my)) != 0 ||
466 	    (r = sshpkt_send(ssh)) != 0)
467 		return r;
468 	debug("SSH2_MSG_KEXINIT sent");
469 	kex->flags |= KEX_INIT_SENT;
470 	return 0;
471 }
472 
473 /* ARGSUSED */
474 int
475 kex_input_kexinit(int type, u_int32_t seq, struct ssh *ssh)
476 {
477 	struct kex *kex = ssh->kex;
478 	const u_char *ptr;
479 	u_int i;
480 	size_t dlen;
481 	int r;
482 
483 	debug("SSH2_MSG_KEXINIT received");
484 	if (kex == NULL)
485 		return SSH_ERR_INVALID_ARGUMENT;
486 
487 	ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, NULL);
488 	ptr = sshpkt_ptr(ssh, &dlen);
489 	if ((r = sshbuf_put(kex->peer, ptr, dlen)) != 0)
490 		return r;
491 
492 	/* discard packet */
493 	for (i = 0; i < KEX_COOKIE_LEN; i++)
494 		if ((r = sshpkt_get_u8(ssh, NULL)) != 0)
495 			return r;
496 	for (i = 0; i < PROPOSAL_MAX; i++)
497 		if ((r = sshpkt_get_string(ssh, NULL, NULL)) != 0)
498 			return r;
499 	/*
500 	 * XXX RFC4253 sec 7: "each side MAY guess" - currently no supported
501 	 * KEX method has the server move first, but a server might be using
502 	 * a custom method or one that we otherwise don't support. We should
503 	 * be prepared to remember first_kex_follows here so we can eat a
504 	 * packet later.
505 	 * XXX2 - RFC4253 is kind of ambiguous on what first_kex_follows means
506 	 * for cases where the server *doesn't* go first. I guess we should
507 	 * ignore it when it is set for these cases, which is what we do now.
508 	 */
509 	if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||	/* first_kex_follows */
510 	    (r = sshpkt_get_u32(ssh, NULL)) != 0 ||	/* reserved */
511 	    (r = sshpkt_get_end(ssh)) != 0)
512 			return r;
513 
514 	if (!(kex->flags & KEX_INIT_SENT))
515 		if ((r = kex_send_kexinit(ssh)) != 0)
516 			return r;
517 	if ((r = kex_choose_conf(ssh)) != 0)
518 		return r;
519 
520 	if (kex->kex_type < KEX_MAX && kex->kex[kex->kex_type] != NULL)
521 		return (kex->kex[kex->kex_type])(ssh);
522 
523 	return SSH_ERR_INTERNAL_ERROR;
524 }
525 
526 int
527 kex_new(struct ssh *ssh, const char *proposal[PROPOSAL_MAX], struct kex **kexp)
528 {
529 	struct kex *kex;
530 	int r;
531 
532 	*kexp = NULL;
533 	if ((kex = calloc(1, sizeof(*kex))) == NULL)
534 		return SSH_ERR_ALLOC_FAIL;
535 	if ((kex->peer = sshbuf_new()) == NULL ||
536 	    (kex->my = sshbuf_new()) == NULL) {
537 		r = SSH_ERR_ALLOC_FAIL;
538 		goto out;
539 	}
540 	if ((r = kex_prop2buf(kex->my, proposal)) != 0)
541 		goto out;
542 	kex->done = 0;
543 	kex_reset_dispatch(ssh);
544 	ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
545 	r = 0;
546 	*kexp = kex;
547  out:
548 	if (r != 0)
549 		kex_free(kex);
550 	return r;
551 }
552 
553 void
554 kex_free_newkeys(struct newkeys *newkeys)
555 {
556 	if (newkeys == NULL)
557 		return;
558 	if (newkeys->enc.key) {
559 		explicit_bzero(newkeys->enc.key, newkeys->enc.key_len);
560 		free(newkeys->enc.key);
561 		newkeys->enc.key = NULL;
562 	}
563 	if (newkeys->enc.iv) {
564 		explicit_bzero(newkeys->enc.iv, newkeys->enc.iv_len);
565 		free(newkeys->enc.iv);
566 		newkeys->enc.iv = NULL;
567 	}
568 	free(newkeys->enc.name);
569 	explicit_bzero(&newkeys->enc, sizeof(newkeys->enc));
570 	free(newkeys->comp.name);
571 	explicit_bzero(&newkeys->comp, sizeof(newkeys->comp));
572 	mac_clear(&newkeys->mac);
573 	if (newkeys->mac.key) {
574 		explicit_bzero(newkeys->mac.key, newkeys->mac.key_len);
575 		free(newkeys->mac.key);
576 		newkeys->mac.key = NULL;
577 	}
578 	free(newkeys->mac.name);
579 	explicit_bzero(&newkeys->mac, sizeof(newkeys->mac));
580 	explicit_bzero(newkeys, sizeof(*newkeys));
581 	free(newkeys);
582 }
583 
584 void
585 kex_free(struct kex *kex)
586 {
587 	u_int mode;
588 
589 #ifdef WITH_OPENSSL
590 	DH_free(kex->dh);
591 	EC_KEY_free(kex->ec_client_key);
592 #endif
593 	for (mode = 0; mode < MODE_MAX; mode++) {
594 		kex_free_newkeys(kex->newkeys[mode]);
595 		kex->newkeys[mode] = NULL;
596 	}
597 	sshbuf_free(kex->peer);
598 	sshbuf_free(kex->my);
599 	free(kex->session_id);
600 	free(kex->client_version_string);
601 	free(kex->server_version_string);
602 	free(kex->failed_choice);
603 	free(kex->hostkey_alg);
604 	free(kex->name);
605 	free(kex);
606 }
607 
608 int
609 kex_setup(struct ssh *ssh, const char *proposal[PROPOSAL_MAX])
610 {
611 	int r;
612 
613 	if ((r = kex_new(ssh, proposal, &ssh->kex)) != 0)
614 		return r;
615 	if ((r = kex_send_kexinit(ssh)) != 0) {		/* we start */
616 		kex_free(ssh->kex);
617 		ssh->kex = NULL;
618 		return r;
619 	}
620 	return 0;
621 }
622 
623 /*
624  * Request key re-exchange, returns 0 on success or a ssherr.h error
625  * code otherwise. Must not be called if KEX is incomplete or in-progress.
626  */
627 int
628 kex_start_rekex(struct ssh *ssh)
629 {
630 	if (ssh->kex == NULL) {
631 		error("%s: no kex", __func__);
632 		return SSH_ERR_INTERNAL_ERROR;
633 	}
634 	if (ssh->kex->done == 0) {
635 		error("%s: requested twice", __func__);
636 		return SSH_ERR_INTERNAL_ERROR;
637 	}
638 	ssh->kex->done = 0;
639 	return kex_send_kexinit(ssh);
640 }
641 
642 static int
643 choose_enc(struct sshenc *enc, char *client, char *server)
644 {
645 	char *name = match_list(client, server, NULL);
646 
647 	if (name == NULL)
648 		return SSH_ERR_NO_CIPHER_ALG_MATCH;
649 	if ((enc->cipher = cipher_by_name(name)) == NULL) {
650 		free(name);
651 		return SSH_ERR_INTERNAL_ERROR;
652 	}
653 	enc->name = name;
654 	enc->enabled = 0;
655 	enc->iv = NULL;
656 	enc->iv_len = cipher_ivlen(enc->cipher);
657 	enc->key = NULL;
658 	enc->key_len = cipher_keylen(enc->cipher);
659 	enc->block_size = cipher_blocksize(enc->cipher);
660 	return 0;
661 }
662 
663 static int
664 choose_mac(struct ssh *ssh, struct sshmac *mac, char *client, char *server)
665 {
666 	char *name = match_list(client, server, NULL);
667 
668 	if (name == NULL)
669 		return SSH_ERR_NO_MAC_ALG_MATCH;
670 	if (mac_setup(mac, name) < 0) {
671 		free(name);
672 		return SSH_ERR_INTERNAL_ERROR;
673 	}
674 	mac->name = name;
675 	mac->key = NULL;
676 	mac->enabled = 0;
677 	return 0;
678 }
679 
680 static int
681 choose_comp(struct sshcomp *comp, char *client, char *server)
682 {
683 	char *name = match_list(client, server, NULL);
684 
685 	if (name == NULL)
686 		return SSH_ERR_NO_COMPRESS_ALG_MATCH;
687 	if (strcmp(name, "zlib@openssh.com") == 0) {
688 		comp->type = COMP_DELAYED;
689 	} else if (strcmp(name, "zlib") == 0) {
690 		comp->type = COMP_ZLIB;
691 	} else if (strcmp(name, "none") == 0) {
692 		comp->type = COMP_NONE;
693 	} else {
694 		free(name);
695 		return SSH_ERR_INTERNAL_ERROR;
696 	}
697 	comp->name = name;
698 	return 0;
699 }
700 
701 static int
702 choose_kex(struct kex *k, char *client, char *server)
703 {
704 	const struct kexalg *kexalg;
705 
706 	k->name = match_list(client, server, NULL);
707 
708 	debug("kex: algorithm: %s", k->name ? k->name : "(no match)");
709 	if (k->name == NULL)
710 		return SSH_ERR_NO_KEX_ALG_MATCH;
711 	if ((kexalg = kex_alg_by_name(k->name)) == NULL)
712 		return SSH_ERR_INTERNAL_ERROR;
713 	k->kex_type = kexalg->type;
714 	k->hash_alg = kexalg->hash_alg;
715 	k->ec_nid = kexalg->ec_nid;
716 	return 0;
717 }
718 
719 static int
720 choose_hostkeyalg(struct kex *k, char *client, char *server)
721 {
722 	k->hostkey_alg = match_list(client, server, NULL);
723 
724 	debug("kex: host key algorithm: %s",
725 	    k->hostkey_alg ? k->hostkey_alg : "(no match)");
726 	if (k->hostkey_alg == NULL)
727 		return SSH_ERR_NO_HOSTKEY_ALG_MATCH;
728 	k->hostkey_type = sshkey_type_from_name(k->hostkey_alg);
729 	if (k->hostkey_type == KEY_UNSPEC)
730 		return SSH_ERR_INTERNAL_ERROR;
731 	k->hostkey_nid = sshkey_ecdsa_nid_from_name(k->hostkey_alg);
732 	return 0;
733 }
734 
735 static int
736 proposals_match(char *my[PROPOSAL_MAX], char *peer[PROPOSAL_MAX])
737 {
738 	static int check[] = {
739 		PROPOSAL_KEX_ALGS, PROPOSAL_SERVER_HOST_KEY_ALGS, -1
740 	};
741 	int *idx;
742 	char *p;
743 
744 	for (idx = &check[0]; *idx != -1; idx++) {
745 		if ((p = strchr(my[*idx], ',')) != NULL)
746 			*p = '\0';
747 		if ((p = strchr(peer[*idx], ',')) != NULL)
748 			*p = '\0';
749 		if (strcmp(my[*idx], peer[*idx]) != 0) {
750 			debug2("proposal mismatch: my %s peer %s",
751 			    my[*idx], peer[*idx]);
752 			return (0);
753 		}
754 	}
755 	debug2("proposals match");
756 	return (1);
757 }
758 
759 static int
760 kex_choose_conf(struct ssh *ssh)
761 {
762 	struct kex *kex = ssh->kex;
763 	struct newkeys *newkeys;
764 	char **my = NULL, **peer = NULL;
765 	char **cprop, **sprop;
766 	int nenc, nmac, ncomp;
767 	u_int mode, ctos, need, dh_need, authlen;
768 	int log_flag = 0;
769 	int r, first_kex_follows;
770 
771 	debug2("local %s KEXINIT proposal", kex->server ? "server" : "client");
772 	if ((r = kex_buf2prop(kex->my, NULL, &my)) != 0)
773 		goto out;
774 	debug2("peer %s KEXINIT proposal", kex->server ? "client" : "server");
775 	if ((r = kex_buf2prop(kex->peer, &first_kex_follows, &peer)) != 0)
776 		goto out;
777 
778 	if (kex->server) {
779 		cprop=peer;
780 		sprop=my;
781 	} else {
782 		cprop=my;
783 		sprop=peer;
784 	}
785 
786 	/* Check whether client supports ext_info_c */
787 	if (kex->server) {
788 		char *ext;
789 
790 		ext = match_list("ext-info-c", peer[PROPOSAL_KEX_ALGS], NULL);
791 		kex->ext_info_c = (ext != NULL);
792 		free(ext);
793 	}
794 
795 	/* Algorithm Negotiation */
796 	if ((r = choose_kex(kex, cprop[PROPOSAL_KEX_ALGS],
797 	    sprop[PROPOSAL_KEX_ALGS])) != 0) {
798 		kex->failed_choice = peer[PROPOSAL_KEX_ALGS];
799 		peer[PROPOSAL_KEX_ALGS] = NULL;
800 		goto out;
801 	}
802 	if ((r = choose_hostkeyalg(kex, cprop[PROPOSAL_SERVER_HOST_KEY_ALGS],
803 	    sprop[PROPOSAL_SERVER_HOST_KEY_ALGS])) != 0) {
804 		kex->failed_choice = peer[PROPOSAL_SERVER_HOST_KEY_ALGS];
805 		peer[PROPOSAL_SERVER_HOST_KEY_ALGS] = NULL;
806 		goto out;
807 	}
808 	for (mode = 0; mode < MODE_MAX; mode++) {
809 		if ((newkeys = calloc(1, sizeof(*newkeys))) == NULL) {
810 			r = SSH_ERR_ALLOC_FAIL;
811 			goto out;
812 		}
813 		kex->newkeys[mode] = newkeys;
814 		ctos = (!kex->server && mode == MODE_OUT) ||
815 		    (kex->server && mode == MODE_IN);
816 		nenc  = ctos ? PROPOSAL_ENC_ALGS_CTOS  : PROPOSAL_ENC_ALGS_STOC;
817 		nmac  = ctos ? PROPOSAL_MAC_ALGS_CTOS  : PROPOSAL_MAC_ALGS_STOC;
818 		ncomp = ctos ? PROPOSAL_COMP_ALGS_CTOS : PROPOSAL_COMP_ALGS_STOC;
819 		if ((r = choose_enc(&newkeys->enc, cprop[nenc],
820 		    sprop[nenc])) != 0) {
821 			kex->failed_choice = peer[nenc];
822 			peer[nenc] = NULL;
823 			goto out;
824 		}
825 		authlen = cipher_authlen(newkeys->enc.cipher);
826 		/* ignore mac for authenticated encryption */
827 		if (authlen == 0 &&
828 		    (r = choose_mac(ssh, &newkeys->mac, cprop[nmac],
829 		    sprop[nmac])) != 0) {
830 			kex->failed_choice = peer[nmac];
831 			peer[nmac] = NULL;
832 			goto out;
833 		}
834 		if ((r = choose_comp(&newkeys->comp, cprop[ncomp],
835 		    sprop[ncomp])) != 0) {
836 			kex->failed_choice = peer[ncomp];
837 			peer[ncomp] = NULL;
838 			goto out;
839 		}
840 		debug("REQUESTED ENC.NAME is '%s'", newkeys->enc.name);
841 		if (strcmp(newkeys->enc.name, "none") == 0) {
842 			int auth_flag;
843 
844 			auth_flag = ssh_packet_authentication_state();
845 			debug("Requesting NONE. Authflag is %d", auth_flag);
846 			if (auth_flag == 1) {
847 				debug("None requested post authentication.");
848 			} else {
849 				fatal("Pre-authentication none cipher requests are not allowed.");
850 			}
851 		}
852 		debug("kex: %s cipher: %s MAC: %s compression: %s",
853 		    ctos ? "client->server" : "server->client",
854 		    newkeys->enc.name,
855 		    authlen == 0 ? newkeys->mac.name : "<implicit>",
856 		    newkeys->comp.name);
857 		/* client starts withctos = 0 && log flag = 0 and no log*/
858 		/* 2nd client pass ctos=1 and flag = 1 so no log*/
859 		/* server starts with ctos =1 && log_flag = 0 so log */
860 		/* 2nd sever pass ctos = 1 && log flag = 1 so no log*/
861 		/* -cjr*/
862 		if (ctos && !log_flag) {
863 			logit("SSH: Server;Ltype: Kex;Remote: %s-%d;Enc: %s;MAC: %s;Comp: %s",
864 			      ssh_remote_ipaddr(ssh),
865 			      ssh_remote_port(ssh),
866 			      newkeys->enc.name,
867 			      newkeys->mac.name,
868 			      newkeys->comp.name);
869 		}
870 		log_flag = 1;
871 	}
872 	need = dh_need = 0;
873 	for (mode = 0; mode < MODE_MAX; mode++) {
874 		newkeys = kex->newkeys[mode];
875 		need = MAXIMUM(need, newkeys->enc.key_len);
876 		need = MAXIMUM(need, newkeys->enc.block_size);
877 		need = MAXIMUM(need, newkeys->enc.iv_len);
878 		need = MAXIMUM(need, newkeys->mac.key_len);
879 		dh_need = MAXIMUM(dh_need, cipher_seclen(newkeys->enc.cipher));
880 		dh_need = MAXIMUM(dh_need, newkeys->enc.block_size);
881 		dh_need = MAXIMUM(dh_need, newkeys->enc.iv_len);
882 		dh_need = MAXIMUM(dh_need, newkeys->mac.key_len);
883 	}
884 	/* XXX need runden? */
885 	kex->we_need = need;
886 	kex->dh_need = dh_need;
887 
888 	/* ignore the next message if the proposals do not match */
889 	if (first_kex_follows && !proposals_match(my, peer))
890 		ssh->dispatch_skip_packets = 1;
891 	r = 0;
892  out:
893 	kex_prop_free(my);
894 	kex_prop_free(peer);
895 	return r;
896 }
897 
898 static int
899 derive_key(struct ssh *ssh, int id, u_int need, u_char *hash, u_int hashlen,
900     const struct sshbuf *shared_secret, u_char **keyp)
901 {
902 	struct kex *kex = ssh->kex;
903 	struct ssh_digest_ctx *hashctx = NULL;
904 	char c = id;
905 	u_int have;
906 	size_t mdsz;
907 	u_char *digest;
908 	int r;
909 
910 	if ((mdsz = ssh_digest_bytes(kex->hash_alg)) == 0)
911 		return SSH_ERR_INVALID_ARGUMENT;
912 	if ((digest = calloc(1, ROUNDUP(need, mdsz))) == NULL) {
913 		r = SSH_ERR_ALLOC_FAIL;
914 		goto out;
915 	}
916 
917 	/* K1 = HASH(K || H || "A" || session_id) */
918 	if ((hashctx = ssh_digest_start(kex->hash_alg)) == NULL ||
919 	    ssh_digest_update_buffer(hashctx, shared_secret) != 0 ||
920 	    ssh_digest_update(hashctx, hash, hashlen) != 0 ||
921 	    ssh_digest_update(hashctx, &c, 1) != 0 ||
922 	    ssh_digest_update(hashctx, kex->session_id,
923 	    kex->session_id_len) != 0 ||
924 	    ssh_digest_final(hashctx, digest, mdsz) != 0) {
925 		r = SSH_ERR_LIBCRYPTO_ERROR;
926 		goto out;
927 	}
928 	ssh_digest_free(hashctx);
929 	hashctx = NULL;
930 
931 	/*
932 	 * expand key:
933 	 * Kn = HASH(K || H || K1 || K2 || ... || Kn-1)
934 	 * Key = K1 || K2 || ... || Kn
935 	 */
936 	for (have = mdsz; need > have; have += mdsz) {
937 		if ((hashctx = ssh_digest_start(kex->hash_alg)) == NULL ||
938 		    ssh_digest_update_buffer(hashctx, shared_secret) != 0 ||
939 		    ssh_digest_update(hashctx, hash, hashlen) != 0 ||
940 		    ssh_digest_update(hashctx, digest, have) != 0 ||
941 		    ssh_digest_final(hashctx, digest + have, mdsz) != 0) {
942 			r = SSH_ERR_LIBCRYPTO_ERROR;
943 			goto out;
944 		}
945 		ssh_digest_free(hashctx);
946 		hashctx = NULL;
947 	}
948 #ifdef DEBUG_KEX
949 	fprintf(stderr, "key '%c'== ", c);
950 	dump_digest("key", digest, need);
951 #endif
952 	*keyp = digest;
953 	digest = NULL;
954 	r = 0;
955  out:
956 	free(digest);
957 	ssh_digest_free(hashctx);
958 	return r;
959 }
960 
961 #define NKEYS	6
962 int
963 kex_derive_keys(struct ssh *ssh, u_char *hash, u_int hashlen,
964     const struct sshbuf *shared_secret)
965 {
966 	struct kex *kex = ssh->kex;
967 	u_char *keys[NKEYS];
968 	u_int i, j, mode, ctos;
969 	int r;
970 
971 	for (i = 0; i < NKEYS; i++) {
972 		if ((r = derive_key(ssh, 'A'+i, kex->we_need, hash, hashlen,
973 		    shared_secret, &keys[i])) != 0) {
974 			for (j = 0; j < i; j++)
975 				free(keys[j]);
976 			return r;
977 		}
978 	}
979 	for (mode = 0; mode < MODE_MAX; mode++) {
980 		ctos = (!kex->server && mode == MODE_OUT) ||
981 		    (kex->server && mode == MODE_IN);
982 		kex->newkeys[mode]->enc.iv  = keys[ctos ? 0 : 1];
983 		kex->newkeys[mode]->enc.key = keys[ctos ? 2 : 3];
984 		kex->newkeys[mode]->mac.key = keys[ctos ? 4 : 5];
985 	}
986 	return 0;
987 }
988 
989 #ifdef WITH_OPENSSL
990 int
991 kex_derive_keys_bn(struct ssh *ssh, u_char *hash, u_int hashlen,
992     const BIGNUM *secret)
993 {
994 	struct sshbuf *shared_secret;
995 	int r;
996 
997 	if ((shared_secret = sshbuf_new()) == NULL)
998 		return SSH_ERR_ALLOC_FAIL;
999 	if ((r = sshbuf_put_bignum2(shared_secret, secret)) == 0)
1000 		r = kex_derive_keys(ssh, hash, hashlen, shared_secret);
1001 	sshbuf_free(shared_secret);
1002 	return r;
1003 }
1004 #endif
1005 
1006 
1007 #if defined(DEBUG_KEX) || defined(DEBUG_KEXDH) || defined(DEBUG_KEXECDH)
1008 void
1009 dump_digest(char *msg, u_char *digest, int len)
1010 {
1011 	fprintf(stderr, "%s\n", msg);
1012 	sshbuf_dump_data(digest, len, stderr);
1013 }
1014 #endif
1015