Home | History | Annotate | Download | only in openssh
      1 /* $OpenBSD: kex.c,v 1.109 2015/07/30 00:01:34 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 *
    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 *
    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
    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 /*
    160  * Concatenate algorithm names, avoiding duplicates in the process.
    161  * Caller must free returned string.
    162  */
    163 char *
    164 kex_names_cat(const char *a, const char *b)
    165 {
    166 	char *ret = NULL, *tmp = NULL, *cp, *p;
    167 	size_t len;
    168 
    169 	if (a == NULL || *a == '\0')
    170 		return NULL;
    171 	if (b == NULL || *b == '\0')
    172 		return strdup(a);
    173 	if (strlen(b) > 1024*1024)
    174 		return NULL;
    175 	len = strlen(a) + strlen(b) + 2;
    176 	if ((tmp = cp = strdup(b)) == NULL ||
    177 	    (ret = calloc(1, len)) == NULL) {
    178 		free(tmp);
    179 		return NULL;
    180 	}
    181 	strlcpy(ret, a, len);
    182 	for ((p = strsep(&cp, ",")); p && *p != '\0'; (p = strsep(&cp, ","))) {
    183 		if (match_list(ret, p, NULL) != NULL)
    184 			continue; /* Algorithm already present */
    185 		if (strlcat(ret, ",", len) >= len ||
    186 		    strlcat(ret, p, len) >= len) {
    187 			free(tmp);
    188 			free(ret);
    189 			return NULL; /* Shouldn't happen */
    190 		}
    191 	}
    192 	free(tmp);
    193 	return ret;
    194 }
    195 
    196 /*
    197  * Assemble a list of algorithms from a default list and a string from a
    198  * configuration file. The user-provided string may begin with '+' to
    199  * indicate that it should be appended to the default.
    200  */
    201 int
    202 kex_assemble_names(const char *def, char **list)
    203 {
    204 	char *ret;
    205 
    206 	if (list == NULL || *list == NULL || **list == '\0') {
    207 		*list = strdup(def);
    208 		return 0;
    209 	}
    210 	if (**list != '+') {
    211 		return 0;
    212 	}
    213 
    214 	if ((ret = kex_names_cat(def, *list + 1)) == NULL)
    215 		return SSH_ERR_ALLOC_FAIL;
    216 	free(*list);
    217 	*list = ret;
    218 	return 0;
    219 }
    220 
    221 /* put algorithm proposal into buffer */
    222 int
    223 kex_prop2buf(struct sshbuf *b, char *proposal[PROPOSAL_MAX])
    224 {
    225 	u_int i;
    226 	int r;
    227 
    228 	sshbuf_reset(b);
    229 
    230 	/*
    231 	 * add a dummy cookie, the cookie will be overwritten by
    232 	 * kex_send_kexinit(), each time a kexinit is set
    233 	 */
    234 	for (i = 0; i < KEX_COOKIE_LEN; i++) {
    235 		if ((r = sshbuf_put_u8(b, 0)) != 0)
    236 			return r;
    237 	}
    238 	for (i = 0; i < PROPOSAL_MAX; i++) {
    239 		if ((r = sshbuf_put_cstring(b, proposal[i])) != 0)
    240 			return r;
    241 	}
    242 	if ((r = sshbuf_put_u8(b, 0)) != 0 ||	/* first_kex_packet_follows */
    243 	    (r = sshbuf_put_u32(b, 0)) != 0)	/* uint32 reserved */
    244 		return r;
    245 	return 0;
    246 }
    247 
    248 /* parse buffer and return algorithm proposal */
    249 int
    250 kex_buf2prop(struct sshbuf *raw, int *first_kex_follows, char ***propp)
    251 {
    252 	struct sshbuf *b = NULL;
    253 	u_char v;
    254 	u_int i;
    255 	char **proposal = NULL;
    256 	int r;
    257 
    258 	*propp = NULL;
    259 	if ((proposal = calloc(PROPOSAL_MAX, sizeof(char *))) == NULL)
    260 		return SSH_ERR_ALLOC_FAIL;
    261 	if ((b = sshbuf_fromb(raw)) == NULL) {
    262 		r = SSH_ERR_ALLOC_FAIL;
    263 		goto out;
    264 	}
    265 	if ((r = sshbuf_consume(b, KEX_COOKIE_LEN)) != 0) /* skip cookie */
    266 		goto out;
    267 	/* extract kex init proposal strings */
    268 	for (i = 0; i < PROPOSAL_MAX; i++) {
    269 		if ((r = sshbuf_get_cstring(b, &(proposal[i]), NULL)) != 0)
    270 			goto out;
    271 		debug2("kex_parse_kexinit: %s", proposal[i]);
    272 	}
    273 	/* first kex follows / reserved */
    274 	if ((r = sshbuf_get_u8(b, &v)) != 0 ||	/* first_kex_follows */
    275 	    (r = sshbuf_get_u32(b, &i)) != 0)	/* reserved */
    276 		goto out;
    277 	if (first_kex_follows != NULL)
    278 		*first_kex_follows = v;
    279 	debug2("first_kex_follows %d ", v);
    280 	debug2("reserved %u ", i);
    281 	r = 0;
    282 	*propp = proposal;
    283  out:
    284 	if (r != 0 && proposal != NULL)
    285 		kex_prop_free(proposal);
    286 	sshbuf_free(b);
    287 	return r;
    288 }
    289 
    290 void
    291 kex_prop_free(char **proposal)
    292 {
    293 	u_int i;
    294 
    295 	if (proposal == NULL)
    296 		return;
    297 	for (i = 0; i < PROPOSAL_MAX; i++)
    298 		free(proposal[i]);
    299 	free(proposal);
    300 }
    301 
    302 /* ARGSUSED */
    303 static int
    304 kex_protocol_error(int type, u_int32_t seq, void *ctxt)
    305 {
    306 	error("Hm, kex protocol error: type %d seq %u", type, seq);
    307 	return 0;
    308 }
    309 
    310 static void
    311 kex_reset_dispatch(struct ssh *ssh)
    312 {
    313 	ssh_dispatch_range(ssh, SSH2_MSG_TRANSPORT_MIN,
    314 	    SSH2_MSG_TRANSPORT_MAX, &kex_protocol_error);
    315 	ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
    316 }
    317 
    318 int
    319 kex_send_newkeys(struct ssh *ssh)
    320 {
    321 	int r;
    322 
    323 	kex_reset_dispatch(ssh);
    324 	if ((r = sshpkt_start(ssh, SSH2_MSG_NEWKEYS)) != 0 ||
    325 	    (r = sshpkt_send(ssh)) != 0)
    326 		return r;
    327 	debug("SSH2_MSG_NEWKEYS sent");
    328 	debug("expecting SSH2_MSG_NEWKEYS");
    329 	ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_input_newkeys);
    330 	return 0;
    331 }
    332 
    333 static int
    334 kex_input_newkeys(int type, u_int32_t seq, void *ctxt)
    335 {
    336 	struct ssh *ssh = ctxt;
    337 	struct kex *kex = ssh->kex;
    338 	int r;
    339 
    340 	debug("SSH2_MSG_NEWKEYS received");
    341 	ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_protocol_error);
    342 	if ((r = sshpkt_get_end(ssh)) != 0)
    343 		return r;
    344 	kex->done = 1;
    345 	sshbuf_reset(kex->peer);
    346 	/* sshbuf_reset(kex->my); */
    347 	kex->flags &= ~KEX_INIT_SENT;
    348 	free(kex->name);
    349 	kex->name = NULL;
    350 	return 0;
    351 }
    352 
    353 int
    354 kex_send_kexinit(struct ssh *ssh)
    355 {
    356 	u_char *cookie;
    357 	struct kex *kex = ssh->kex;
    358 	int r;
    359 
    360 	if (kex == NULL)
    361 		return SSH_ERR_INTERNAL_ERROR;
    362 	if (kex->flags & KEX_INIT_SENT)
    363 		return 0;
    364 	kex->done = 0;
    365 
    366 	/* generate a random cookie */
    367 	if (sshbuf_len(kex->my) < KEX_COOKIE_LEN)
    368 		return SSH_ERR_INVALID_FORMAT;
    369 	if ((cookie = sshbuf_mutable_ptr(kex->my)) == NULL)
    370 		return SSH_ERR_INTERNAL_ERROR;
    371 	arc4random_buf(cookie, KEX_COOKIE_LEN);
    372 
    373 	if ((r = sshpkt_start(ssh, SSH2_MSG_KEXINIT)) != 0 ||
    374 	    (r = sshpkt_putb(ssh, kex->my)) != 0 ||
    375 	    (r = sshpkt_send(ssh)) != 0)
    376 		return r;
    377 	debug("SSH2_MSG_KEXINIT sent");
    378 	kex->flags |= KEX_INIT_SENT;
    379 	return 0;
    380 }
    381 
    382 /* ARGSUSED */
    383 int
    384 kex_input_kexinit(int type, u_int32_t seq, void *ctxt)
    385 {
    386 	struct ssh *ssh = ctxt;
    387 	struct kex *kex = ssh->kex;
    388 	const u_char *ptr;
    389 	u_int i;
    390 	size_t dlen;
    391 	int r;
    392 
    393 	debug("SSH2_MSG_KEXINIT received");
    394 	if (kex == NULL)
    395 		return SSH_ERR_INVALID_ARGUMENT;
    396 
    397 	ptr = sshpkt_ptr(ssh, &dlen);
    398 	if ((r = sshbuf_put(kex->peer, ptr, dlen)) != 0)
    399 		return r;
    400 
    401 	/* discard packet */
    402 	for (i = 0; i < KEX_COOKIE_LEN; i++)
    403 		if ((r = sshpkt_get_u8(ssh, NULL)) != 0)
    404 			return r;
    405 	for (i = 0; i < PROPOSAL_MAX; i++)
    406 		if ((r = sshpkt_get_string(ssh, NULL, NULL)) != 0)
    407 			return r;
    408 	/*
    409 	 * XXX RFC4253 sec 7: "each side MAY guess" - currently no supported
    410 	 * KEX method has the server move first, but a server might be using
    411 	 * a custom method or one that we otherwise don't support. We should
    412 	 * be prepared to remember first_kex_follows here so we can eat a
    413 	 * packet later.
    414 	 * XXX2 - RFC4253 is kind of ambiguous on what first_kex_follows means
    415 	 * for cases where the server *doesn't* go first. I guess we should
    416 	 * ignore it when it is set for these cases, which is what we do now.
    417 	 */
    418 	if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||	/* first_kex_follows */
    419 	    (r = sshpkt_get_u32(ssh, NULL)) != 0 ||	/* reserved */
    420 	    (r = sshpkt_get_end(ssh)) != 0)
    421 			return r;
    422 
    423 	if (!(kex->flags & KEX_INIT_SENT))
    424 		if ((r = kex_send_kexinit(ssh)) != 0)
    425 			return r;
    426 	if ((r = kex_choose_conf(ssh)) != 0)
    427 		return r;
    428 
    429 	if (kex->kex_type < KEX_MAX && kex->kex[kex->kex_type] != NULL)
    430 		return (kex->kex[kex->kex_type])(ssh);
    431 
    432 	return SSH_ERR_INTERNAL_ERROR;
    433 }
    434 
    435 int
    436 kex_new(struct ssh *ssh, char *proposal[PROPOSAL_MAX], struct kex **kexp)
    437 {
    438 	struct kex *kex;
    439 	int r;
    440 
    441 	*kexp = NULL;
    442 	if ((kex = calloc(1, sizeof(*kex))) == NULL)
    443 		return SSH_ERR_ALLOC_FAIL;
    444 	if ((kex->peer = sshbuf_new()) == NULL ||
    445 	    (kex->my = sshbuf_new()) == NULL) {
    446 		r = SSH_ERR_ALLOC_FAIL;
    447 		goto out;
    448 	}
    449 	if ((r = kex_prop2buf(kex->my, proposal)) != 0)
    450 		goto out;
    451 	kex->done = 0;
    452 	kex_reset_dispatch(ssh);
    453 	r = 0;
    454 	*kexp = kex;
    455  out:
    456 	if (r != 0)
    457 		kex_free(kex);
    458 	return r;
    459 }
    460 
    461 void
    462 kex_free_newkeys(struct newkeys *newkeys)
    463 {
    464 	if (newkeys == NULL)
    465 		return;
    466 	if (newkeys->enc.key) {
    467 		explicit_bzero(newkeys->enc.key, newkeys->enc.key_len);
    468 		free(newkeys->enc.key);
    469 		newkeys->enc.key = NULL;
    470 	}
    471 	if (newkeys->enc.iv) {
    472 		explicit_bzero(newkeys->enc.iv, newkeys->enc.block_size);
    473 		free(newkeys->enc.iv);
    474 		newkeys->enc.iv = NULL;
    475 	}
    476 	free(newkeys->enc.name);
    477 	explicit_bzero(&newkeys->enc, sizeof(newkeys->enc));
    478 	free(newkeys->comp.name);
    479 	explicit_bzero(&newkeys->comp, sizeof(newkeys->comp));
    480 	mac_clear(&newkeys->mac);
    481 	if (newkeys->mac.key) {
    482 		explicit_bzero(newkeys->mac.key, newkeys->mac.key_len);
    483 		free(newkeys->mac.key);
    484 		newkeys->mac.key = NULL;
    485 	}
    486 	free(newkeys->mac.name);
    487 	explicit_bzero(&newkeys->mac, sizeof(newkeys->mac));
    488 	explicit_bzero(newkeys, sizeof(*newkeys));
    489 	free(newkeys);
    490 }
    491 
    492 void
    493 kex_free(struct kex *kex)
    494 {
    495 	u_int mode;
    496 
    497 #ifdef WITH_OPENSSL
    498 	if (kex->dh)
    499 		DH_free(kex->dh);
    500 #ifdef OPENSSL_HAS_ECC
    501 	if (kex->ec_client_key)
    502 		EC_KEY_free(kex->ec_client_key);
    503 #endif /* OPENSSL_HAS_ECC */
    504 #endif /* WITH_OPENSSL */
    505 	for (mode = 0; mode < MODE_MAX; mode++) {
    506 		kex_free_newkeys(kex->newkeys[mode]);
    507 		kex->newkeys[mode] = NULL;
    508 	}
    509 	sshbuf_free(kex->peer);
    510 	sshbuf_free(kex->my);
    511 	free(kex->session_id);
    512 	free(kex->client_version_string);
    513 	free(kex->server_version_string);
    514 	free(kex->failed_choice);
    515 	free(kex);
    516 }
    517 
    518 int
    519 kex_setup(struct ssh *ssh, char *proposal[PROPOSAL_MAX])
    520 {
    521 	int r;
    522 
    523 	if ((r = kex_new(ssh, proposal, &ssh->kex)) != 0)
    524 		return r;
    525 	if ((r = kex_send_kexinit(ssh)) != 0) {		/* we start */
    526 		kex_free(ssh->kex);
    527 		ssh->kex = NULL;
    528 		return r;
    529 	}
    530 	return 0;
    531 }
    532 
    533 static int
    534 choose_enc(struct sshenc *enc, char *client, char *server)
    535 {
    536 	char *name = match_list(client, server, NULL);
    537 
    538 	if (name == NULL)
    539 		return SSH_ERR_NO_CIPHER_ALG_MATCH;
    540 	if ((enc->cipher = cipher_by_name(name)) == NULL)
    541 		return SSH_ERR_INTERNAL_ERROR;
    542 	enc->name = name;
    543 	enc->enabled = 0;
    544 	enc->iv = NULL;
    545 	enc->iv_len = cipher_ivlen(enc->cipher);
    546 	enc->key = NULL;
    547 	enc->key_len = cipher_keylen(enc->cipher);
    548 	enc->block_size = cipher_blocksize(enc->cipher);
    549 	return 0;
    550 }
    551 
    552 static int
    553 choose_mac(struct ssh *ssh, struct sshmac *mac, char *client, char *server)
    554 {
    555 	char *name = match_list(client, server, NULL);
    556 
    557 	if (name == NULL)
    558 		return SSH_ERR_NO_MAC_ALG_MATCH;
    559 	if (mac_setup(mac, name) < 0)
    560 		return SSH_ERR_INTERNAL_ERROR;
    561 	/* truncate the key */
    562 	if (ssh->compat & SSH_BUG_HMAC)
    563 		mac->key_len = 16;
    564 	mac->name = name;
    565 	mac->key = NULL;
    566 	mac->enabled = 0;
    567 	return 0;
    568 }
    569 
    570 static int
    571 choose_comp(struct sshcomp *comp, char *client, char *server)
    572 {
    573 	char *name = match_list(client, server, NULL);
    574 
    575 	if (name == NULL)
    576 		return SSH_ERR_NO_COMPRESS_ALG_MATCH;
    577 	if (strcmp(name, "zlib (at) openssh.com") == 0) {
    578 		comp->type = COMP_DELAYED;
    579 	} else if (strcmp(name, "zlib") == 0) {
    580 		comp->type = COMP_ZLIB;
    581 	} else if (strcmp(name, "none") == 0) {
    582 		comp->type = COMP_NONE;
    583 	} else {
    584 		return SSH_ERR_INTERNAL_ERROR;
    585 	}
    586 	comp->name = name;
    587 	return 0;
    588 }
    589 
    590 static int
    591 choose_kex(struct kex *k, char *client, char *server)
    592 {
    593 	const struct kexalg *kexalg;
    594 
    595 	k->name = match_list(client, server, NULL);
    596 
    597 	if (k->name == NULL)
    598 		return SSH_ERR_NO_KEX_ALG_MATCH;
    599 	if ((kexalg = kex_alg_by_name(k->name)) == NULL)
    600 		return SSH_ERR_INTERNAL_ERROR;
    601 	k->kex_type = kexalg->type;
    602 	k->hash_alg = kexalg->hash_alg;
    603 	k->ec_nid = kexalg->ec_nid;
    604 	return 0;
    605 }
    606 
    607 static int
    608 choose_hostkeyalg(struct kex *k, char *client, char *server)
    609 {
    610 	char *hostkeyalg = match_list(client, server, NULL);
    611 
    612 	if (hostkeyalg == NULL)
    613 		return SSH_ERR_NO_HOSTKEY_ALG_MATCH;
    614 	k->hostkey_type = sshkey_type_from_name(hostkeyalg);
    615 	if (k->hostkey_type == KEY_UNSPEC)
    616 		return SSH_ERR_INTERNAL_ERROR;
    617 	k->hostkey_nid = sshkey_ecdsa_nid_from_name(hostkeyalg);
    618 	free(hostkeyalg);
    619 	return 0;
    620 }
    621 
    622 static int
    623 proposals_match(char *my[PROPOSAL_MAX], char *peer[PROPOSAL_MAX])
    624 {
    625 	static int check[] = {
    626 		PROPOSAL_KEX_ALGS, PROPOSAL_SERVER_HOST_KEY_ALGS, -1
    627 	};
    628 	int *idx;
    629 	char *p;
    630 
    631 	for (idx = &check[0]; *idx != -1; idx++) {
    632 		if ((p = strchr(my[*idx], ',')) != NULL)
    633 			*p = '\0';
    634 		if ((p = strchr(peer[*idx], ',')) != NULL)
    635 			*p = '\0';
    636 		if (strcmp(my[*idx], peer[*idx]) != 0) {
    637 			debug2("proposal mismatch: my %s peer %s",
    638 			    my[*idx], peer[*idx]);
    639 			return (0);
    640 		}
    641 	}
    642 	debug2("proposals match");
    643 	return (1);
    644 }
    645 
    646 static int
    647 kex_choose_conf(struct ssh *ssh)
    648 {
    649 	struct kex *kex = ssh->kex;
    650 	struct newkeys *newkeys;
    651 	char **my = NULL, **peer = NULL;
    652 	char **cprop, **sprop;
    653 	int nenc, nmac, ncomp;
    654 	u_int mode, ctos, need, dh_need, authlen;
    655 	int r, first_kex_follows;
    656 
    657 	if ((r = kex_buf2prop(kex->my, NULL, &my)) != 0 ||
    658 	    (r = kex_buf2prop(kex->peer, &first_kex_follows, &peer)) != 0)
    659 		goto out;
    660 
    661 	if (kex->server) {
    662 		cprop=peer;
    663 		sprop=my;
    664 	} else {
    665 		cprop=my;
    666 		sprop=peer;
    667 	}
    668 
    669 	/* Check whether server offers roaming */
    670 	if (!kex->server) {
    671 		char *roaming = match_list(KEX_RESUME,
    672 		    peer[PROPOSAL_KEX_ALGS], NULL);
    673 
    674 		if (roaming) {
    675 			kex->roaming = 1;
    676 			free(roaming);
    677 		}
    678 	}
    679 
    680 	/* Algorithm Negotiation */
    681 	for (mode = 0; mode < MODE_MAX; mode++) {
    682 		if ((newkeys = calloc(1, sizeof(*newkeys))) == NULL) {
    683 			r = SSH_ERR_ALLOC_FAIL;
    684 			goto out;
    685 		}
    686 		kex->newkeys[mode] = newkeys;
    687 		ctos = (!kex->server && mode == MODE_OUT) ||
    688 		    (kex->server && mode == MODE_IN);
    689 		nenc  = ctos ? PROPOSAL_ENC_ALGS_CTOS  : PROPOSAL_ENC_ALGS_STOC;
    690 		nmac  = ctos ? PROPOSAL_MAC_ALGS_CTOS  : PROPOSAL_MAC_ALGS_STOC;
    691 		ncomp = ctos ? PROPOSAL_COMP_ALGS_CTOS : PROPOSAL_COMP_ALGS_STOC;
    692 		if ((r = choose_enc(&newkeys->enc, cprop[nenc],
    693 		    sprop[nenc])) != 0) {
    694 			kex->failed_choice = peer[nenc];
    695 			peer[nenc] = NULL;
    696 			goto out;
    697 		}
    698 		authlen = cipher_authlen(newkeys->enc.cipher);
    699 		/* ignore mac for authenticated encryption */
    700 		if (authlen == 0 &&
    701 		    (r = choose_mac(ssh, &newkeys->mac, cprop[nmac],
    702 		    sprop[nmac])) != 0) {
    703 			kex->failed_choice = peer[nmac];
    704 			peer[nmac] = NULL;
    705 			goto out;
    706 		}
    707 		if ((r = choose_comp(&newkeys->comp, cprop[ncomp],
    708 		    sprop[ncomp])) != 0) {
    709 			kex->failed_choice = peer[ncomp];
    710 			peer[ncomp] = NULL;
    711 			goto out;
    712 		}
    713 		debug("kex: %s %s %s %s",
    714 		    ctos ? "client->server" : "server->client",
    715 		    newkeys->enc.name,
    716 		    authlen == 0 ? newkeys->mac.name : "<implicit>",
    717 		    newkeys->comp.name);
    718 	}
    719 	if ((r = choose_kex(kex, cprop[PROPOSAL_KEX_ALGS],
    720 	    sprop[PROPOSAL_KEX_ALGS])) != 0) {
    721 		kex->failed_choice = peer[PROPOSAL_KEX_ALGS];
    722 		peer[PROPOSAL_KEX_ALGS] = NULL;
    723 		goto out;
    724 	}
    725 	if ((r = choose_hostkeyalg(kex, cprop[PROPOSAL_SERVER_HOST_KEY_ALGS],
    726 	    sprop[PROPOSAL_SERVER_HOST_KEY_ALGS])) != 0) {
    727 		kex->failed_choice = peer[PROPOSAL_SERVER_HOST_KEY_ALGS];
    728 		peer[PROPOSAL_SERVER_HOST_KEY_ALGS] = NULL;
    729 		goto out;
    730 	}
    731 	need = dh_need = 0;
    732 	for (mode = 0; mode < MODE_MAX; mode++) {
    733 		newkeys = kex->newkeys[mode];
    734 		need = MAX(need, newkeys->enc.key_len);
    735 		need = MAX(need, newkeys->enc.block_size);
    736 		need = MAX(need, newkeys->enc.iv_len);
    737 		need = MAX(need, newkeys->mac.key_len);
    738 		dh_need = MAX(dh_need, cipher_seclen(newkeys->enc.cipher));
    739 		dh_need = MAX(dh_need, newkeys->enc.block_size);
    740 		dh_need = MAX(dh_need, newkeys->enc.iv_len);
    741 		dh_need = MAX(dh_need, newkeys->mac.key_len);
    742 	}
    743 	/* XXX need runden? */
    744 	kex->we_need = need;
    745 	kex->dh_need = dh_need;
    746 
    747 	/* ignore the next message if the proposals do not match */
    748 	if (first_kex_follows && !proposals_match(my, peer) &&
    749 	    !(ssh->compat & SSH_BUG_FIRSTKEX))
    750 		ssh->dispatch_skip_packets = 1;
    751 	r = 0;
    752  out:
    753 	kex_prop_free(my);
    754 	kex_prop_free(peer);
    755 	return r;
    756 }
    757 
    758 static int
    759 derive_key(struct ssh *ssh, int id, u_int need, u_char *hash, u_int hashlen,
    760     const struct sshbuf *shared_secret, u_char **keyp)
    761 {
    762 	struct kex *kex = ssh->kex;
    763 	struct ssh_digest_ctx *hashctx = NULL;
    764 	char c = id;
    765 	u_int have;
    766 	size_t mdsz;
    767 	u_char *digest;
    768 	int r;
    769 
    770 	if ((mdsz = ssh_digest_bytes(kex->hash_alg)) == 0)
    771 		return SSH_ERR_INVALID_ARGUMENT;
    772 	if ((digest = calloc(1, roundup(need, mdsz))) == NULL) {
    773 		r = SSH_ERR_ALLOC_FAIL;
    774 		goto out;
    775 	}
    776 
    777 	/* K1 = HASH(K || H || "A" || session_id) */
    778 	if ((hashctx = ssh_digest_start(kex->hash_alg)) == NULL ||
    779 	    ssh_digest_update_buffer(hashctx, shared_secret) != 0 ||
    780 	    ssh_digest_update(hashctx, hash, hashlen) != 0 ||
    781 	    ssh_digest_update(hashctx, &c, 1) != 0 ||
    782 	    ssh_digest_update(hashctx, kex->session_id,
    783 	    kex->session_id_len) != 0 ||
    784 	    ssh_digest_final(hashctx, digest, mdsz) != 0) {
    785 		r = SSH_ERR_LIBCRYPTO_ERROR;
    786 		goto out;
    787 	}
    788 	ssh_digest_free(hashctx);
    789 	hashctx = NULL;
    790 
    791 	/*
    792 	 * expand key:
    793 	 * Kn = HASH(K || H || K1 || K2 || ... || Kn-1)
    794 	 * Key = K1 || K2 || ... || Kn
    795 	 */
    796 	for (have = mdsz; need > have; have += mdsz) {
    797 		if ((hashctx = ssh_digest_start(kex->hash_alg)) == NULL ||
    798 		    ssh_digest_update_buffer(hashctx, shared_secret) != 0 ||
    799 		    ssh_digest_update(hashctx, hash, hashlen) != 0 ||
    800 		    ssh_digest_update(hashctx, digest, have) != 0 ||
    801 		    ssh_digest_final(hashctx, digest + have, mdsz) != 0) {
    802 			r = SSH_ERR_LIBCRYPTO_ERROR;
    803 			goto out;
    804 		}
    805 		ssh_digest_free(hashctx);
    806 		hashctx = NULL;
    807 	}
    808 #ifdef DEBUG_KEX
    809 	fprintf(stderr, "key '%c'== ", c);
    810 	dump_digest("key", digest, need);
    811 #endif
    812 	*keyp = digest;
    813 	digest = NULL;
    814 	r = 0;
    815  out:
    816 	if (digest)
    817 		free(digest);
    818 	ssh_digest_free(hashctx);
    819 	return r;
    820 }
    821 
    822 #define NKEYS	6
    823 int
    824 kex_derive_keys(struct ssh *ssh, u_char *hash, u_int hashlen,
    825     const struct sshbuf *shared_secret)
    826 {
    827 	struct kex *kex = ssh->kex;
    828 	u_char *keys[NKEYS];
    829 	u_int i, j, mode, ctos;
    830 	int r;
    831 
    832 	for (i = 0; i < NKEYS; i++) {
    833 		if ((r = derive_key(ssh, 'A'+i, kex->we_need, hash, hashlen,
    834 		    shared_secret, &keys[i])) != 0) {
    835 			for (j = 0; j < i; j++)
    836 				free(keys[j]);
    837 			return r;
    838 		}
    839 	}
    840 	for (mode = 0; mode < MODE_MAX; mode++) {
    841 		ctos = (!kex->server && mode == MODE_OUT) ||
    842 		    (kex->server && mode == MODE_IN);
    843 		kex->newkeys[mode]->enc.iv  = keys[ctos ? 0 : 1];
    844 		kex->newkeys[mode]->enc.key = keys[ctos ? 2 : 3];
    845 		kex->newkeys[mode]->mac.key = keys[ctos ? 4 : 5];
    846 	}
    847 	return 0;
    848 }
    849 
    850 #ifdef WITH_OPENSSL
    851 int
    852 kex_derive_keys_bn(struct ssh *ssh, u_char *hash, u_int hashlen,
    853     const BIGNUM *secret)
    854 {
    855 	struct sshbuf *shared_secret;
    856 	int r;
    857 
    858 	if ((shared_secret = sshbuf_new()) == NULL)
    859 		return SSH_ERR_ALLOC_FAIL;
    860 	if ((r = sshbuf_put_bignum2(shared_secret, secret)) == 0)
    861 		r = kex_derive_keys(ssh, hash, hashlen, shared_secret);
    862 	sshbuf_free(shared_secret);
    863 	return r;
    864 }
    865 #endif
    866 
    867 #ifdef WITH_SSH1
    868 int
    869 derive_ssh1_session_id(BIGNUM *host_modulus, BIGNUM *server_modulus,
    870     u_int8_t cookie[8], u_int8_t id[16])
    871 {
    872 	u_int8_t hbuf[2048], sbuf[2048], obuf[SSH_DIGEST_MAX_LENGTH];
    873 	struct ssh_digest_ctx *hashctx = NULL;
    874 	size_t hlen, slen;
    875 	int r;
    876 
    877 	hlen = BN_num_bytes(host_modulus);
    878 	slen = BN_num_bytes(server_modulus);
    879 	if (hlen < (512 / 8) || (u_int)hlen > sizeof(hbuf) ||
    880 	    slen < (512 / 8) || (u_int)slen > sizeof(sbuf))
    881 		return SSH_ERR_KEY_BITS_MISMATCH;
    882 	if (BN_bn2bin(host_modulus, hbuf) <= 0 ||
    883 	    BN_bn2bin(server_modulus, sbuf) <= 0) {
    884 		r = SSH_ERR_LIBCRYPTO_ERROR;
    885 		goto out;
    886 	}
    887 	if ((hashctx = ssh_digest_start(SSH_DIGEST_MD5)) == NULL) {
    888 		r = SSH_ERR_ALLOC_FAIL;
    889 		goto out;
    890 	}
    891 	if (ssh_digest_update(hashctx, hbuf, hlen) != 0 ||
    892 	    ssh_digest_update(hashctx, sbuf, slen) != 0 ||
    893 	    ssh_digest_update(hashctx, cookie, 8) != 0 ||
    894 	    ssh_digest_final(hashctx, obuf, sizeof(obuf)) != 0) {
    895 		r = SSH_ERR_LIBCRYPTO_ERROR;
    896 		goto out;
    897 	}
    898 	memcpy(id, obuf, ssh_digest_bytes(SSH_DIGEST_MD5));
    899 	r = 0;
    900  out:
    901 	ssh_digest_free(hashctx);
    902 	explicit_bzero(hbuf, sizeof(hbuf));
    903 	explicit_bzero(sbuf, sizeof(sbuf));
    904 	explicit_bzero(obuf, sizeof(obuf));
    905 	return r;
    906 }
    907 #endif
    908 
    909 #if defined(DEBUG_KEX) || defined(DEBUG_KEXDH) || defined(DEBUG_KEXECDH)
    910 void
    911 dump_digest(char *msg, u_char *digest, int len)
    912 {
    913 	fprintf(stderr, "%s\n", msg);
    914 	sshbuf_dump_data(digest, len, stderr);
    915 }
    916 #endif
    917