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