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