xref: /openssh-portable/kex.c (revision 00865c29)
1 /* $OpenBSD: kex.c,v 1.153 2019/09/06 01:58:50 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/types.h>
29 #include <errno.h>
30 #include <signal.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <stdlib.h>
34 #include <string.h>
35 #include <unistd.h>
36 #include <poll.h>
37 
38 #ifdef WITH_OPENSSL
39 #include <openssl/crypto.h>
40 #include <openssl/dh.h>
41 #endif
42 
43 #include "ssh.h"
44 #include "ssh2.h"
45 #include "atomicio.h"
46 #include "version.h"
47 #include "packet.h"
48 #include "compat.h"
49 #include "cipher.h"
50 #include "sshkey.h"
51 #include "kex.h"
52 #include "log.h"
53 #include "mac.h"
54 #include "match.h"
55 #include "misc.h"
56 #include "dispatch.h"
57 #include "monitor.h"
58 
59 #include "ssherr.h"
60 #include "sshbuf.h"
61 #include "digest.h"
62 
63 /* prototype */
64 static int kex_choose_conf(struct ssh *);
65 static int kex_input_newkeys(int, u_int32_t, struct ssh *);
66 
67 static const char *proposal_names[PROPOSAL_MAX] = {
68 	"KEX algorithms",
69 	"host key algorithms",
70 	"ciphers ctos",
71 	"ciphers stoc",
72 	"MACs ctos",
73 	"MACs stoc",
74 	"compression ctos",
75 	"compression stoc",
76 	"languages ctos",
77 	"languages stoc",
78 };
79 
80 struct kexalg {
81 	char *name;
82 	u_int type;
83 	int ec_nid;
84 	int hash_alg;
85 };
86 static const struct kexalg kexalgs[] = {
87 #ifdef WITH_OPENSSL
88 	{ KEX_DH1, KEX_DH_GRP1_SHA1, 0, SSH_DIGEST_SHA1 },
89 	{ KEX_DH14_SHA1, KEX_DH_GRP14_SHA1, 0, SSH_DIGEST_SHA1 },
90 	{ KEX_DH14_SHA256, KEX_DH_GRP14_SHA256, 0, SSH_DIGEST_SHA256 },
91 	{ KEX_DH16_SHA512, KEX_DH_GRP16_SHA512, 0, SSH_DIGEST_SHA512 },
92 	{ KEX_DH18_SHA512, KEX_DH_GRP18_SHA512, 0, SSH_DIGEST_SHA512 },
93 	{ KEX_DHGEX_SHA1, KEX_DH_GEX_SHA1, 0, SSH_DIGEST_SHA1 },
94 #ifdef HAVE_EVP_SHA256
95 	{ KEX_DHGEX_SHA256, KEX_DH_GEX_SHA256, 0, SSH_DIGEST_SHA256 },
96 #endif /* HAVE_EVP_SHA256 */
97 #ifdef OPENSSL_HAS_ECC
98 	{ KEX_ECDH_SHA2_NISTP256, KEX_ECDH_SHA2,
99 	    NID_X9_62_prime256v1, SSH_DIGEST_SHA256 },
100 	{ KEX_ECDH_SHA2_NISTP384, KEX_ECDH_SHA2, NID_secp384r1,
101 	    SSH_DIGEST_SHA384 },
102 # ifdef OPENSSL_HAS_NISTP521
103 	{ KEX_ECDH_SHA2_NISTP521, KEX_ECDH_SHA2, NID_secp521r1,
104 	    SSH_DIGEST_SHA512 },
105 # endif /* OPENSSL_HAS_NISTP521 */
106 #endif /* OPENSSL_HAS_ECC */
107 #endif /* WITH_OPENSSL */
108 #if defined(HAVE_EVP_SHA256) || !defined(WITH_OPENSSL)
109 	{ KEX_CURVE25519_SHA256, KEX_C25519_SHA256, 0, SSH_DIGEST_SHA256 },
110 	{ KEX_CURVE25519_SHA256_OLD, KEX_C25519_SHA256, 0, SSH_DIGEST_SHA256 },
111 	{ KEX_SNTRUP4591761X25519_SHA512, KEX_KEM_SNTRUP4591761X25519_SHA512, 0,
112 	    SSH_DIGEST_SHA512 },
113 #endif /* HAVE_EVP_SHA256 || !WITH_OPENSSL */
114 	{ NULL, -1, -1, -1},
115 };
116 
117 char *
118 kex_alg_list(char sep)
119 {
120 	char *ret = NULL, *tmp;
121 	size_t nlen, rlen = 0;
122 	const struct kexalg *k;
123 
124 	for (k = kexalgs; k->name != NULL; k++) {
125 		if (ret != NULL)
126 			ret[rlen++] = sep;
127 		nlen = strlen(k->name);
128 		if ((tmp = realloc(ret, rlen + nlen + 2)) == NULL) {
129 			free(ret);
130 			return NULL;
131 		}
132 		ret = tmp;
133 		memcpy(ret + rlen, k->name, nlen + 1);
134 		rlen += nlen;
135 	}
136 	return ret;
137 }
138 
139 static const struct kexalg *
140 kex_alg_by_name(const char *name)
141 {
142 	const struct kexalg *k;
143 
144 	for (k = kexalgs; k->name != NULL; k++) {
145 		if (strcmp(k->name, name) == 0)
146 			return k;
147 	}
148 	return NULL;
149 }
150 
151 /* Validate KEX method name list */
152 int
153 kex_names_valid(const char *names)
154 {
155 	char *s, *cp, *p;
156 
157 	if (names == NULL || strcmp(names, "") == 0)
158 		return 0;
159 	if ((s = cp = strdup(names)) == NULL)
160 		return 0;
161 	for ((p = strsep(&cp, ",")); p && *p != '\0';
162 	    (p = strsep(&cp, ","))) {
163 		if (kex_alg_by_name(p) == NULL) {
164 			error("Unsupported KEX algorithm \"%.100s\"", p);
165 			free(s);
166 			return 0;
167 		}
168 	}
169 	debug3("kex names ok: [%s]", names);
170 	free(s);
171 	return 1;
172 }
173 
174 /*
175  * Concatenate algorithm names, avoiding duplicates in the process.
176  * Caller must free returned string.
177  */
178 char *
179 kex_names_cat(const char *a, const char *b)
180 {
181 	char *ret = NULL, *tmp = NULL, *cp, *p, *m;
182 	size_t len;
183 
184 	if (a == NULL || *a == '\0')
185 		return strdup(b);
186 	if (b == NULL || *b == '\0')
187 		return strdup(a);
188 	if (strlen(b) > 1024*1024)
189 		return NULL;
190 	len = strlen(a) + strlen(b) + 2;
191 	if ((tmp = cp = strdup(b)) == NULL ||
192 	    (ret = calloc(1, len)) == NULL) {
193 		free(tmp);
194 		return NULL;
195 	}
196 	strlcpy(ret, a, len);
197 	for ((p = strsep(&cp, ",")); p && *p != '\0'; (p = strsep(&cp, ","))) {
198 		if ((m = match_list(ret, p, NULL)) != NULL) {
199 			free(m);
200 			continue; /* Algorithm already present */
201 		}
202 		if (strlcat(ret, ",", len) >= len ||
203 		    strlcat(ret, p, len) >= len) {
204 			free(tmp);
205 			free(ret);
206 			return NULL; /* Shouldn't happen */
207 		}
208 	}
209 	free(tmp);
210 	return ret;
211 }
212 
213 /*
214  * Assemble a list of algorithms from a default list and a string from a
215  * configuration file. The user-provided string may begin with '+' to
216  * indicate that it should be appended to the default or '-' that the
217  * specified names should be removed.
218  */
219 int
220 kex_assemble_names(char **listp, const char *def, const char *all)
221 {
222 	char *cp, *tmp, *patterns;
223 	char *list = NULL, *ret = NULL, *matching = NULL, *opatterns = NULL;
224 	int r = SSH_ERR_INTERNAL_ERROR;
225 
226 	if (listp == NULL || def == NULL || all == NULL)
227 		return SSH_ERR_INVALID_ARGUMENT;
228 
229 	if (*listp == NULL || **listp == '\0') {
230 		if ((*listp = strdup(def)) == NULL)
231 			return SSH_ERR_ALLOC_FAIL;
232 		return 0;
233 	}
234 
235 	list = *listp;
236 	*listp = NULL;
237 	if (*list == '+') {
238 		/* Append names to default list */
239 		if ((tmp = kex_names_cat(def, list + 1)) == NULL) {
240 			r = SSH_ERR_ALLOC_FAIL;
241 			goto fail;
242 		}
243 		free(list);
244 		list = tmp;
245 	} else if (*list == '-') {
246 		/* Remove names from default list */
247 		if ((*listp = match_filter_blacklist(def, list + 1)) == NULL) {
248 			r = SSH_ERR_ALLOC_FAIL;
249 			goto fail;
250 		}
251 		free(list);
252 		/* filtering has already been done */
253 		return 0;
254 	} else {
255 		/* Explicit list, overrides default - just use "list" as is */
256 	}
257 
258 	/*
259 	 * The supplied names may be a pattern-list. For the -list case,
260 	 * the patterns are applied above. For the +list and explicit list
261 	 * cases we need to do it now.
262 	 */
263 	ret = NULL;
264 	if ((patterns = opatterns = strdup(list)) == NULL) {
265 		r = SSH_ERR_ALLOC_FAIL;
266 		goto fail;
267 	}
268 	/* Apply positive (i.e. non-negated) patterns from the list */
269 	while ((cp = strsep(&patterns, ",")) != NULL) {
270 		if (*cp == '!') {
271 			/* negated matches are not supported here */
272 			r = SSH_ERR_INVALID_ARGUMENT;
273 			goto fail;
274 		}
275 		free(matching);
276 		if ((matching = match_filter_whitelist(all, cp)) == NULL) {
277 			r = SSH_ERR_ALLOC_FAIL;
278 			goto fail;
279 		}
280 		if ((tmp = kex_names_cat(ret, matching)) == NULL) {
281 			r = SSH_ERR_ALLOC_FAIL;
282 			goto fail;
283 		}
284 		free(ret);
285 		ret = tmp;
286 	}
287 	if (ret == NULL || *ret == '\0') {
288 		/* An empty name-list is an error */
289 		/* XXX better error code? */
290 		r = SSH_ERR_INVALID_ARGUMENT;
291 		goto fail;
292 	}
293 
294 	/* success */
295 	*listp = ret;
296 	ret = NULL;
297 	r = 0;
298 
299  fail:
300 	free(matching);
301 	free(opatterns);
302 	free(list);
303 	free(ret);
304 	return r;
305 }
306 
307 /* put algorithm proposal into buffer */
308 int
309 kex_prop2buf(struct sshbuf *b, char *proposal[PROPOSAL_MAX])
310 {
311 	u_int i;
312 	int r;
313 
314 	sshbuf_reset(b);
315 
316 	/*
317 	 * add a dummy cookie, the cookie will be overwritten by
318 	 * kex_send_kexinit(), each time a kexinit is set
319 	 */
320 	for (i = 0; i < KEX_COOKIE_LEN; i++) {
321 		if ((r = sshbuf_put_u8(b, 0)) != 0)
322 			return r;
323 	}
324 	for (i = 0; i < PROPOSAL_MAX; i++) {
325 		if ((r = sshbuf_put_cstring(b, proposal[i])) != 0)
326 			return r;
327 	}
328 	if ((r = sshbuf_put_u8(b, 0)) != 0 ||	/* first_kex_packet_follows */
329 	    (r = sshbuf_put_u32(b, 0)) != 0)	/* uint32 reserved */
330 		return r;
331 	return 0;
332 }
333 
334 /* parse buffer and return algorithm proposal */
335 int
336 kex_buf2prop(struct sshbuf *raw, int *first_kex_follows, char ***propp)
337 {
338 	struct sshbuf *b = NULL;
339 	u_char v;
340 	u_int i;
341 	char **proposal = NULL;
342 	int r;
343 
344 	*propp = NULL;
345 	if ((proposal = calloc(PROPOSAL_MAX, sizeof(char *))) == NULL)
346 		return SSH_ERR_ALLOC_FAIL;
347 	if ((b = sshbuf_fromb(raw)) == NULL) {
348 		r = SSH_ERR_ALLOC_FAIL;
349 		goto out;
350 	}
351 	if ((r = sshbuf_consume(b, KEX_COOKIE_LEN)) != 0) { /* skip cookie */
352 		error("%s: consume cookie: %s", __func__, ssh_err(r));
353 		goto out;
354 	}
355 	/* extract kex init proposal strings */
356 	for (i = 0; i < PROPOSAL_MAX; i++) {
357 		if ((r = sshbuf_get_cstring(b, &(proposal[i]), NULL)) != 0) {
358 			error("%s: parse proposal %u: %s", __func__,
359 			    i, ssh_err(r));
360 			goto out;
361 		}
362 		debug2("%s: %s", proposal_names[i], proposal[i]);
363 	}
364 	/* first kex follows / reserved */
365 	if ((r = sshbuf_get_u8(b, &v)) != 0 ||	/* first_kex_follows */
366 	    (r = sshbuf_get_u32(b, &i)) != 0) {	/* reserved */
367 		error("%s: parse: %s", __func__, ssh_err(r));
368 		goto out;
369 	}
370 	if (first_kex_follows != NULL)
371 		*first_kex_follows = v;
372 	debug2("first_kex_follows %d ", v);
373 	debug2("reserved %u ", i);
374 	r = 0;
375 	*propp = proposal;
376  out:
377 	if (r != 0 && proposal != NULL)
378 		kex_prop_free(proposal);
379 	sshbuf_free(b);
380 	return r;
381 }
382 
383 void
384 kex_prop_free(char **proposal)
385 {
386 	u_int i;
387 
388 	if (proposal == NULL)
389 		return;
390 	for (i = 0; i < PROPOSAL_MAX; i++)
391 		free(proposal[i]);
392 	free(proposal);
393 }
394 
395 /* ARGSUSED */
396 static int
397 kex_protocol_error(int type, u_int32_t seq, struct ssh *ssh)
398 {
399 	int r;
400 
401 	error("kex protocol error: type %d seq %u", type, seq);
402 	if ((r = sshpkt_start(ssh, SSH2_MSG_UNIMPLEMENTED)) != 0 ||
403 	    (r = sshpkt_put_u32(ssh, seq)) != 0 ||
404 	    (r = sshpkt_send(ssh)) != 0)
405 		return r;
406 	return 0;
407 }
408 
409 static void
410 kex_reset_dispatch(struct ssh *ssh)
411 {
412 	ssh_dispatch_range(ssh, SSH2_MSG_TRANSPORT_MIN,
413 	    SSH2_MSG_TRANSPORT_MAX, &kex_protocol_error);
414 }
415 
416 static int
417 kex_send_ext_info(struct ssh *ssh)
418 {
419 	int r;
420 	char *algs;
421 
422 	debug("Sending SSH2_MSG_EXT_INFO");
423 	if ((algs = sshkey_alg_list(0, 1, 1, ',')) == NULL)
424 		return SSH_ERR_ALLOC_FAIL;
425 	/* XXX filter algs list by allowed pubkey/hostbased types */
426 	if ((r = sshpkt_start(ssh, SSH2_MSG_EXT_INFO)) != 0 ||
427 	    (r = sshpkt_put_u32(ssh, 1)) != 0 ||
428 	    (r = sshpkt_put_cstring(ssh, "server-sig-algs")) != 0 ||
429 	    (r = sshpkt_put_cstring(ssh, algs)) != 0 ||
430 	    (r = sshpkt_send(ssh)) != 0) {
431 		error("%s: compose: %s", __func__, ssh_err(r));
432 		goto out;
433 	}
434 	/* success */
435 	r = 0;
436  out:
437 	free(algs);
438 	return r;
439 }
440 
441 int
442 kex_send_newkeys(struct ssh *ssh)
443 {
444 	int r;
445 
446 	kex_reset_dispatch(ssh);
447 	if ((r = sshpkt_start(ssh, SSH2_MSG_NEWKEYS)) != 0 ||
448 	    (r = sshpkt_send(ssh)) != 0)
449 		return r;
450 	debug("SSH2_MSG_NEWKEYS sent");
451 	ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_input_newkeys);
452 	if (ssh->kex->ext_info_c && (ssh->kex->flags & KEX_INITIAL) != 0)
453 		if ((r = kex_send_ext_info(ssh)) != 0)
454 			return r;
455 	debug("expecting SSH2_MSG_NEWKEYS");
456 	return 0;
457 }
458 
459 int
460 kex_input_ext_info(int type, u_int32_t seq, struct ssh *ssh)
461 {
462 	struct kex *kex = ssh->kex;
463 	u_int32_t i, ninfo;
464 	char *name;
465 	u_char *val;
466 	size_t vlen;
467 	int r;
468 
469 	debug("SSH2_MSG_EXT_INFO received");
470 	ssh_dispatch_set(ssh, SSH2_MSG_EXT_INFO, &kex_protocol_error);
471 	if ((r = sshpkt_get_u32(ssh, &ninfo)) != 0)
472 		return r;
473 	for (i = 0; i < ninfo; i++) {
474 		if ((r = sshpkt_get_cstring(ssh, &name, NULL)) != 0)
475 			return r;
476 		if ((r = sshpkt_get_string(ssh, &val, &vlen)) != 0) {
477 			free(name);
478 			return r;
479 		}
480 		if (strcmp(name, "server-sig-algs") == 0) {
481 			/* Ensure no \0 lurking in value */
482 			if (memchr(val, '\0', vlen) != NULL) {
483 				error("%s: nul byte in %s", __func__, name);
484 				return SSH_ERR_INVALID_FORMAT;
485 			}
486 			debug("%s: %s=<%s>", __func__, name, val);
487 			kex->server_sig_algs = val;
488 			val = NULL;
489 		} else
490 			debug("%s: %s (unrecognised)", __func__, name);
491 		free(name);
492 		free(val);
493 	}
494 	return sshpkt_get_end(ssh);
495 }
496 
497 static int
498 kex_input_newkeys(int type, u_int32_t seq, struct ssh *ssh)
499 {
500 	struct kex *kex = ssh->kex;
501 	int r;
502 
503 	debug("SSH2_MSG_NEWKEYS received");
504 	ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_protocol_error);
505 	ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
506 	if ((r = sshpkt_get_end(ssh)) != 0)
507 		return r;
508 	if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0)
509 		return r;
510 	kex->done = 1;
511 	kex->flags &= ~KEX_INITIAL;
512 	sshbuf_reset(kex->peer);
513 	/* sshbuf_reset(kex->my); */
514 	kex->flags &= ~KEX_INIT_SENT;
515 	free(kex->name);
516 	kex->name = NULL;
517 	return 0;
518 }
519 
520 int
521 kex_send_kexinit(struct ssh *ssh)
522 {
523 	u_char *cookie;
524 	struct kex *kex = ssh->kex;
525 	int r;
526 
527 	if (kex == NULL) {
528 		error("%s: no hex", __func__);
529 		return SSH_ERR_INTERNAL_ERROR;
530 	}
531 	if (kex->flags & KEX_INIT_SENT)
532 		return 0;
533 	kex->done = 0;
534 
535 	/* generate a random cookie */
536 	if (sshbuf_len(kex->my) < KEX_COOKIE_LEN) {
537 		error("%s: bad kex length: %zu < %d", __func__,
538 		    sshbuf_len(kex->my), KEX_COOKIE_LEN);
539 		return SSH_ERR_INVALID_FORMAT;
540 	}
541 	if ((cookie = sshbuf_mutable_ptr(kex->my)) == NULL) {
542 		error("%s: buffer error", __func__);
543 		return SSH_ERR_INTERNAL_ERROR;
544 	}
545 	arc4random_buf(cookie, KEX_COOKIE_LEN);
546 
547 	if ((r = sshpkt_start(ssh, SSH2_MSG_KEXINIT)) != 0 ||
548 	    (r = sshpkt_putb(ssh, kex->my)) != 0 ||
549 	    (r = sshpkt_send(ssh)) != 0) {
550 		error("%s: compose reply: %s", __func__, ssh_err(r));
551 		return r;
552 	}
553 	debug("SSH2_MSG_KEXINIT sent");
554 	kex->flags |= KEX_INIT_SENT;
555 	return 0;
556 }
557 
558 /* ARGSUSED */
559 int
560 kex_input_kexinit(int type, u_int32_t seq, struct ssh *ssh)
561 {
562 	struct kex *kex = ssh->kex;
563 	const u_char *ptr;
564 	u_int i;
565 	size_t dlen;
566 	int r;
567 
568 	debug("SSH2_MSG_KEXINIT received");
569 	if (kex == NULL) {
570 		error("%s: no hex", __func__);
571 		return SSH_ERR_INTERNAL_ERROR;
572 	}
573 	ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, NULL);
574 	ptr = sshpkt_ptr(ssh, &dlen);
575 	if ((r = sshbuf_put(kex->peer, ptr, dlen)) != 0)
576 		return r;
577 
578 	/* discard packet */
579 	for (i = 0; i < KEX_COOKIE_LEN; i++) {
580 		if ((r = sshpkt_get_u8(ssh, NULL)) != 0) {
581 			error("%s: discard cookie: %s", __func__, ssh_err(r));
582 			return r;
583 		}
584 	}
585 	for (i = 0; i < PROPOSAL_MAX; i++) {
586 		if ((r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
587 			error("%s: discard proposal: %s", __func__, ssh_err(r));
588 			return r;
589 		}
590 	}
591 	/*
592 	 * XXX RFC4253 sec 7: "each side MAY guess" - currently no supported
593 	 * KEX method has the server move first, but a server might be using
594 	 * a custom method or one that we otherwise don't support. We should
595 	 * be prepared to remember first_kex_follows here so we can eat a
596 	 * packet later.
597 	 * XXX2 - RFC4253 is kind of ambiguous on what first_kex_follows means
598 	 * for cases where the server *doesn't* go first. I guess we should
599 	 * ignore it when it is set for these cases, which is what we do now.
600 	 */
601 	if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||	/* first_kex_follows */
602 	    (r = sshpkt_get_u32(ssh, NULL)) != 0 ||	/* reserved */
603 	    (r = sshpkt_get_end(ssh)) != 0)
604 			return r;
605 
606 	if (!(kex->flags & KEX_INIT_SENT))
607 		if ((r = kex_send_kexinit(ssh)) != 0)
608 			return r;
609 	if ((r = kex_choose_conf(ssh)) != 0)
610 		return r;
611 
612 	if (kex->kex_type < KEX_MAX && kex->kex[kex->kex_type] != NULL)
613 		return (kex->kex[kex->kex_type])(ssh);
614 
615 	error("%s: unknown kex type %u", __func__, kex->kex_type);
616 	return SSH_ERR_INTERNAL_ERROR;
617 }
618 
619 struct kex *
620 kex_new(void)
621 {
622 	struct kex *kex;
623 
624 	if ((kex = calloc(1, sizeof(*kex))) == NULL ||
625 	    (kex->peer = sshbuf_new()) == NULL ||
626 	    (kex->my = sshbuf_new()) == NULL ||
627 	    (kex->client_version = sshbuf_new()) == NULL ||
628 	    (kex->server_version = sshbuf_new()) == NULL) {
629 		kex_free(kex);
630 		return NULL;
631 	}
632 	return kex;
633 }
634 
635 void
636 kex_free_newkeys(struct newkeys *newkeys)
637 {
638 	if (newkeys == NULL)
639 		return;
640 	if (newkeys->enc.key) {
641 		explicit_bzero(newkeys->enc.key, newkeys->enc.key_len);
642 		free(newkeys->enc.key);
643 		newkeys->enc.key = NULL;
644 	}
645 	if (newkeys->enc.iv) {
646 		explicit_bzero(newkeys->enc.iv, newkeys->enc.iv_len);
647 		free(newkeys->enc.iv);
648 		newkeys->enc.iv = NULL;
649 	}
650 	free(newkeys->enc.name);
651 	explicit_bzero(&newkeys->enc, sizeof(newkeys->enc));
652 	free(newkeys->comp.name);
653 	explicit_bzero(&newkeys->comp, sizeof(newkeys->comp));
654 	mac_clear(&newkeys->mac);
655 	if (newkeys->mac.key) {
656 		explicit_bzero(newkeys->mac.key, newkeys->mac.key_len);
657 		free(newkeys->mac.key);
658 		newkeys->mac.key = NULL;
659 	}
660 	free(newkeys->mac.name);
661 	explicit_bzero(&newkeys->mac, sizeof(newkeys->mac));
662 	explicit_bzero(newkeys, sizeof(*newkeys));
663 	free(newkeys);
664 }
665 
666 void
667 kex_free(struct kex *kex)
668 {
669 	u_int mode;
670 
671 	if (kex == NULL)
672 		return;
673 
674 #ifdef WITH_OPENSSL
675 	DH_free(kex->dh);
676 #ifdef OPENSSL_HAS_ECC
677 	EC_KEY_free(kex->ec_client_key);
678 #endif /* OPENSSL_HAS_ECC */
679 #endif /* WITH_OPENSSL */
680 	for (mode = 0; mode < MODE_MAX; mode++) {
681 		kex_free_newkeys(kex->newkeys[mode]);
682 		kex->newkeys[mode] = NULL;
683 	}
684 	sshbuf_free(kex->peer);
685 	sshbuf_free(kex->my);
686 	sshbuf_free(kex->client_version);
687 	sshbuf_free(kex->server_version);
688 	sshbuf_free(kex->client_pub);
689 	free(kex->session_id);
690 	free(kex->failed_choice);
691 	free(kex->hostkey_alg);
692 	free(kex->name);
693 	free(kex);
694 }
695 
696 int
697 kex_ready(struct ssh *ssh, char *proposal[PROPOSAL_MAX])
698 {
699 	int r;
700 
701 	if ((r = kex_prop2buf(ssh->kex->my, proposal)) != 0)
702 		return r;
703 	ssh->kex->flags = KEX_INITIAL;
704 	kex_reset_dispatch(ssh);
705 	ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
706 	return 0;
707 }
708 
709 int
710 kex_setup(struct ssh *ssh, char *proposal[PROPOSAL_MAX])
711 {
712 	int r;
713 
714 	if ((r = kex_ready(ssh, proposal)) != 0)
715 		return r;
716 	if ((r = kex_send_kexinit(ssh)) != 0) {		/* we start */
717 		kex_free(ssh->kex);
718 		ssh->kex = NULL;
719 		return r;
720 	}
721 	return 0;
722 }
723 
724 /*
725  * Request key re-exchange, returns 0 on success or a ssherr.h error
726  * code otherwise. Must not be called if KEX is incomplete or in-progress.
727  */
728 int
729 kex_start_rekex(struct ssh *ssh)
730 {
731 	if (ssh->kex == NULL) {
732 		error("%s: no kex", __func__);
733 		return SSH_ERR_INTERNAL_ERROR;
734 	}
735 	if (ssh->kex->done == 0) {
736 		error("%s: requested twice", __func__);
737 		return SSH_ERR_INTERNAL_ERROR;
738 	}
739 	ssh->kex->done = 0;
740 	return kex_send_kexinit(ssh);
741 }
742 
743 static int
744 choose_enc(struct sshenc *enc, char *client, char *server)
745 {
746 	char *name = match_list(client, server, NULL);
747 
748 	if (name == NULL)
749 		return SSH_ERR_NO_CIPHER_ALG_MATCH;
750 	if ((enc->cipher = cipher_by_name(name)) == NULL) {
751 		error("%s: unsupported cipher %s", __func__, name);
752 		free(name);
753 		return SSH_ERR_INTERNAL_ERROR;
754 	}
755 	enc->name = name;
756 	enc->enabled = 0;
757 	enc->iv = NULL;
758 	enc->iv_len = cipher_ivlen(enc->cipher);
759 	enc->key = NULL;
760 	enc->key_len = cipher_keylen(enc->cipher);
761 	enc->block_size = cipher_blocksize(enc->cipher);
762 	return 0;
763 }
764 
765 static int
766 choose_mac(struct ssh *ssh, struct sshmac *mac, char *client, char *server)
767 {
768 	char *name = match_list(client, server, NULL);
769 
770 	if (name == NULL)
771 		return SSH_ERR_NO_MAC_ALG_MATCH;
772 	if (mac_setup(mac, name) < 0) {
773 		error("%s: unsupported MAC %s", __func__, name);
774 		free(name);
775 		return SSH_ERR_INTERNAL_ERROR;
776 	}
777 	mac->name = name;
778 	mac->key = NULL;
779 	mac->enabled = 0;
780 	return 0;
781 }
782 
783 static int
784 choose_comp(struct sshcomp *comp, char *client, char *server)
785 {
786 	char *name = match_list(client, server, NULL);
787 
788 	if (name == NULL)
789 		return SSH_ERR_NO_COMPRESS_ALG_MATCH;
790 	if (strcmp(name, "zlib@openssh.com") == 0) {
791 		comp->type = COMP_DELAYED;
792 	} else if (strcmp(name, "zlib") == 0) {
793 		comp->type = COMP_ZLIB;
794 	} else if (strcmp(name, "none") == 0) {
795 		comp->type = COMP_NONE;
796 	} else {
797 		error("%s: unsupported compression scheme %s", __func__, name);
798 		free(name);
799 		return SSH_ERR_INTERNAL_ERROR;
800 	}
801 	comp->name = name;
802 	return 0;
803 }
804 
805 static int
806 choose_kex(struct kex *k, char *client, char *server)
807 {
808 	const struct kexalg *kexalg;
809 
810 	k->name = match_list(client, server, NULL);
811 
812 	debug("kex: algorithm: %s", k->name ? k->name : "(no match)");
813 	if (k->name == NULL)
814 		return SSH_ERR_NO_KEX_ALG_MATCH;
815 	if ((kexalg = kex_alg_by_name(k->name)) == NULL) {
816 		error("%s: unsupported KEX method %s", __func__, k->name);
817 		return SSH_ERR_INTERNAL_ERROR;
818 	}
819 	k->kex_type = kexalg->type;
820 	k->hash_alg = kexalg->hash_alg;
821 	k->ec_nid = kexalg->ec_nid;
822 	return 0;
823 }
824 
825 static int
826 choose_hostkeyalg(struct kex *k, char *client, char *server)
827 {
828 	k->hostkey_alg = match_list(client, server, NULL);
829 
830 	debug("kex: host key algorithm: %s",
831 	    k->hostkey_alg ? k->hostkey_alg : "(no match)");
832 	if (k->hostkey_alg == NULL)
833 		return SSH_ERR_NO_HOSTKEY_ALG_MATCH;
834 	k->hostkey_type = sshkey_type_from_name(k->hostkey_alg);
835 	if (k->hostkey_type == KEY_UNSPEC) {
836 		error("%s: unsupported hostkey algorithm %s", __func__,
837 		    k->hostkey_alg);
838 		return SSH_ERR_INTERNAL_ERROR;
839 	}
840 	k->hostkey_nid = sshkey_ecdsa_nid_from_name(k->hostkey_alg);
841 	return 0;
842 }
843 
844 static int
845 proposals_match(char *my[PROPOSAL_MAX], char *peer[PROPOSAL_MAX])
846 {
847 	static int check[] = {
848 		PROPOSAL_KEX_ALGS, PROPOSAL_SERVER_HOST_KEY_ALGS, -1
849 	};
850 	int *idx;
851 	char *p;
852 
853 	for (idx = &check[0]; *idx != -1; idx++) {
854 		if ((p = strchr(my[*idx], ',')) != NULL)
855 			*p = '\0';
856 		if ((p = strchr(peer[*idx], ',')) != NULL)
857 			*p = '\0';
858 		if (strcmp(my[*idx], peer[*idx]) != 0) {
859 			debug2("proposal mismatch: my %s peer %s",
860 			    my[*idx], peer[*idx]);
861 			return (0);
862 		}
863 	}
864 	debug2("proposals match");
865 	return (1);
866 }
867 
868 static int
869 kex_choose_conf(struct ssh *ssh)
870 {
871 	struct kex *kex = ssh->kex;
872 	struct newkeys *newkeys;
873 	char **my = NULL, **peer = NULL;
874 	char **cprop, **sprop;
875 	int nenc, nmac, ncomp;
876 	u_int mode, ctos, need, dh_need, authlen;
877 	int r, first_kex_follows;
878 
879 	debug2("local %s KEXINIT proposal", kex->server ? "server" : "client");
880 	if ((r = kex_buf2prop(kex->my, NULL, &my)) != 0)
881 		goto out;
882 	debug2("peer %s KEXINIT proposal", kex->server ? "client" : "server");
883 	if ((r = kex_buf2prop(kex->peer, &first_kex_follows, &peer)) != 0)
884 		goto out;
885 
886 	if (kex->server) {
887 		cprop=peer;
888 		sprop=my;
889 	} else {
890 		cprop=my;
891 		sprop=peer;
892 	}
893 
894 	/* Check whether client supports ext_info_c */
895 	if (kex->server && (kex->flags & KEX_INITIAL)) {
896 		char *ext;
897 
898 		ext = match_list("ext-info-c", peer[PROPOSAL_KEX_ALGS], NULL);
899 		kex->ext_info_c = (ext != NULL);
900 		free(ext);
901 	}
902 
903 	/* Algorithm Negotiation */
904 	if ((r = choose_kex(kex, cprop[PROPOSAL_KEX_ALGS],
905 	    sprop[PROPOSAL_KEX_ALGS])) != 0) {
906 		kex->failed_choice = peer[PROPOSAL_KEX_ALGS];
907 		peer[PROPOSAL_KEX_ALGS] = NULL;
908 		goto out;
909 	}
910 	if ((r = choose_hostkeyalg(kex, cprop[PROPOSAL_SERVER_HOST_KEY_ALGS],
911 	    sprop[PROPOSAL_SERVER_HOST_KEY_ALGS])) != 0) {
912 		kex->failed_choice = peer[PROPOSAL_SERVER_HOST_KEY_ALGS];
913 		peer[PROPOSAL_SERVER_HOST_KEY_ALGS] = NULL;
914 		goto out;
915 	}
916 	for (mode = 0; mode < MODE_MAX; mode++) {
917 		if ((newkeys = calloc(1, sizeof(*newkeys))) == NULL) {
918 			r = SSH_ERR_ALLOC_FAIL;
919 			goto out;
920 		}
921 		kex->newkeys[mode] = newkeys;
922 		ctos = (!kex->server && mode == MODE_OUT) ||
923 		    (kex->server && mode == MODE_IN);
924 		nenc  = ctos ? PROPOSAL_ENC_ALGS_CTOS  : PROPOSAL_ENC_ALGS_STOC;
925 		nmac  = ctos ? PROPOSAL_MAC_ALGS_CTOS  : PROPOSAL_MAC_ALGS_STOC;
926 		ncomp = ctos ? PROPOSAL_COMP_ALGS_CTOS : PROPOSAL_COMP_ALGS_STOC;
927 		if ((r = choose_enc(&newkeys->enc, cprop[nenc],
928 		    sprop[nenc])) != 0) {
929 			kex->failed_choice = peer[nenc];
930 			peer[nenc] = NULL;
931 			goto out;
932 		}
933 		authlen = cipher_authlen(newkeys->enc.cipher);
934 		/* ignore mac for authenticated encryption */
935 		if (authlen == 0 &&
936 		    (r = choose_mac(ssh, &newkeys->mac, cprop[nmac],
937 		    sprop[nmac])) != 0) {
938 			kex->failed_choice = peer[nmac];
939 			peer[nmac] = NULL;
940 			goto out;
941 		}
942 		if ((r = choose_comp(&newkeys->comp, cprop[ncomp],
943 		    sprop[ncomp])) != 0) {
944 			kex->failed_choice = peer[ncomp];
945 			peer[ncomp] = NULL;
946 			goto out;
947 		}
948 		debug("kex: %s cipher: %s MAC: %s compression: %s",
949 		    ctos ? "client->server" : "server->client",
950 		    newkeys->enc.name,
951 		    authlen == 0 ? newkeys->mac.name : "<implicit>",
952 		    newkeys->comp.name);
953 	}
954 	need = dh_need = 0;
955 	for (mode = 0; mode < MODE_MAX; mode++) {
956 		newkeys = kex->newkeys[mode];
957 		need = MAXIMUM(need, newkeys->enc.key_len);
958 		need = MAXIMUM(need, newkeys->enc.block_size);
959 		need = MAXIMUM(need, newkeys->enc.iv_len);
960 		need = MAXIMUM(need, newkeys->mac.key_len);
961 		dh_need = MAXIMUM(dh_need, cipher_seclen(newkeys->enc.cipher));
962 		dh_need = MAXIMUM(dh_need, newkeys->enc.block_size);
963 		dh_need = MAXIMUM(dh_need, newkeys->enc.iv_len);
964 		dh_need = MAXIMUM(dh_need, newkeys->mac.key_len);
965 	}
966 	/* XXX need runden? */
967 	kex->we_need = need;
968 	kex->dh_need = dh_need;
969 
970 	/* ignore the next message if the proposals do not match */
971 	if (first_kex_follows && !proposals_match(my, peer))
972 		ssh->dispatch_skip_packets = 1;
973 	r = 0;
974  out:
975 	kex_prop_free(my);
976 	kex_prop_free(peer);
977 	return r;
978 }
979 
980 static int
981 derive_key(struct ssh *ssh, int id, u_int need, u_char *hash, u_int hashlen,
982     const struct sshbuf *shared_secret, u_char **keyp)
983 {
984 	struct kex *kex = ssh->kex;
985 	struct ssh_digest_ctx *hashctx = NULL;
986 	char c = id;
987 	u_int have;
988 	size_t mdsz;
989 	u_char *digest;
990 	int r;
991 
992 	if ((mdsz = ssh_digest_bytes(kex->hash_alg)) == 0)
993 		return SSH_ERR_INVALID_ARGUMENT;
994 	if ((digest = calloc(1, ROUNDUP(need, mdsz))) == NULL) {
995 		r = SSH_ERR_ALLOC_FAIL;
996 		goto out;
997 	}
998 
999 	/* K1 = HASH(K || H || "A" || session_id) */
1000 	if ((hashctx = ssh_digest_start(kex->hash_alg)) == NULL ||
1001 	    ssh_digest_update_buffer(hashctx, shared_secret) != 0 ||
1002 	    ssh_digest_update(hashctx, hash, hashlen) != 0 ||
1003 	    ssh_digest_update(hashctx, &c, 1) != 0 ||
1004 	    ssh_digest_update(hashctx, kex->session_id,
1005 	    kex->session_id_len) != 0 ||
1006 	    ssh_digest_final(hashctx, digest, mdsz) != 0) {
1007 		r = SSH_ERR_LIBCRYPTO_ERROR;
1008 		error("%s: KEX hash failed", __func__);
1009 		goto out;
1010 	}
1011 	ssh_digest_free(hashctx);
1012 	hashctx = NULL;
1013 
1014 	/*
1015 	 * expand key:
1016 	 * Kn = HASH(K || H || K1 || K2 || ... || Kn-1)
1017 	 * Key = K1 || K2 || ... || Kn
1018 	 */
1019 	for (have = mdsz; need > have; have += mdsz) {
1020 		if ((hashctx = ssh_digest_start(kex->hash_alg)) == NULL ||
1021 		    ssh_digest_update_buffer(hashctx, shared_secret) != 0 ||
1022 		    ssh_digest_update(hashctx, hash, hashlen) != 0 ||
1023 		    ssh_digest_update(hashctx, digest, have) != 0 ||
1024 		    ssh_digest_final(hashctx, digest + have, mdsz) != 0) {
1025 			error("%s: KDF failed", __func__);
1026 			r = SSH_ERR_LIBCRYPTO_ERROR;
1027 			goto out;
1028 		}
1029 		ssh_digest_free(hashctx);
1030 		hashctx = NULL;
1031 	}
1032 #ifdef DEBUG_KEX
1033 	fprintf(stderr, "key '%c'== ", c);
1034 	dump_digest("key", digest, need);
1035 #endif
1036 	*keyp = digest;
1037 	digest = NULL;
1038 	r = 0;
1039  out:
1040 	free(digest);
1041 	ssh_digest_free(hashctx);
1042 	return r;
1043 }
1044 
1045 #define NKEYS	6
1046 int
1047 kex_derive_keys(struct ssh *ssh, u_char *hash, u_int hashlen,
1048     const struct sshbuf *shared_secret)
1049 {
1050 	struct kex *kex = ssh->kex;
1051 	u_char *keys[NKEYS];
1052 	u_int i, j, mode, ctos;
1053 	int r;
1054 
1055 	/* save initial hash as session id */
1056 	if (kex->session_id == NULL) {
1057 		kex->session_id_len = hashlen;
1058 		kex->session_id = malloc(kex->session_id_len);
1059 		if (kex->session_id == NULL)
1060 			return SSH_ERR_ALLOC_FAIL;
1061 		memcpy(kex->session_id, hash, kex->session_id_len);
1062 	}
1063 	for (i = 0; i < NKEYS; i++) {
1064 		if ((r = derive_key(ssh, 'A'+i, kex->we_need, hash, hashlen,
1065 		    shared_secret, &keys[i])) != 0) {
1066 			for (j = 0; j < i; j++)
1067 				free(keys[j]);
1068 			return r;
1069 		}
1070 	}
1071 	for (mode = 0; mode < MODE_MAX; mode++) {
1072 		ctos = (!kex->server && mode == MODE_OUT) ||
1073 		    (kex->server && mode == MODE_IN);
1074 		kex->newkeys[mode]->enc.iv  = keys[ctos ? 0 : 1];
1075 		kex->newkeys[mode]->enc.key = keys[ctos ? 2 : 3];
1076 		kex->newkeys[mode]->mac.key = keys[ctos ? 4 : 5];
1077 	}
1078 	return 0;
1079 }
1080 
1081 int
1082 kex_load_hostkey(struct ssh *ssh, struct sshkey **prvp, struct sshkey **pubp)
1083 {
1084 	struct kex *kex = ssh->kex;
1085 
1086 	*pubp = NULL;
1087 	*prvp = NULL;
1088 	if (kex->load_host_public_key == NULL ||
1089 	    kex->load_host_private_key == NULL) {
1090 		error("%s: missing hostkey loader", __func__);
1091 		return SSH_ERR_INVALID_ARGUMENT;
1092 	}
1093 	*pubp = kex->load_host_public_key(kex->hostkey_type,
1094 	    kex->hostkey_nid, ssh);
1095 	*prvp = kex->load_host_private_key(kex->hostkey_type,
1096 	    kex->hostkey_nid, ssh);
1097 	if (*pubp == NULL)
1098 		return SSH_ERR_NO_HOSTKEY_LOADED;
1099 	return 0;
1100 }
1101 
1102 int
1103 kex_verify_host_key(struct ssh *ssh, struct sshkey *server_host_key)
1104 {
1105 	struct kex *kex = ssh->kex;
1106 
1107 	if (kex->verify_host_key == NULL) {
1108 		error("%s: missing hostkey verifier", __func__);
1109 		return SSH_ERR_INVALID_ARGUMENT;
1110 	}
1111 	if (server_host_key->type != kex->hostkey_type ||
1112 	    (kex->hostkey_type == KEY_ECDSA &&
1113 	    server_host_key->ecdsa_nid != kex->hostkey_nid))
1114 		return SSH_ERR_KEY_TYPE_MISMATCH;
1115 	if (kex->verify_host_key(server_host_key, ssh) == -1)
1116 		return  SSH_ERR_SIGNATURE_INVALID;
1117 	return 0;
1118 }
1119 
1120 #if defined(DEBUG_KEX) || defined(DEBUG_KEXDH) || defined(DEBUG_KEXECDH)
1121 void
1122 dump_digest(const char *msg, const u_char *digest, int len)
1123 {
1124 	fprintf(stderr, "%s\n", msg);
1125 	sshbuf_dump_data(digest, len, stderr);
1126 }
1127 #endif
1128 
1129 /*
1130  * Send a plaintext error message to the peer, suffixed by \r\n.
1131  * Only used during banner exchange, and there only for the server.
1132  */
1133 static void
1134 send_error(struct ssh *ssh, char *msg)
1135 {
1136 	char *crnl = "\r\n";
1137 
1138 	if (!ssh->kex->server)
1139 		return;
1140 
1141 	if (atomicio(vwrite, ssh_packet_get_connection_out(ssh),
1142 	    msg, strlen(msg)) != strlen(msg) ||
1143 	    atomicio(vwrite, ssh_packet_get_connection_out(ssh),
1144 	    crnl, strlen(crnl)) != strlen(crnl))
1145 		error("%s: write: %.100s", __func__, strerror(errno));
1146 }
1147 
1148 /*
1149  * Sends our identification string and waits for the peer's. Will block for
1150  * up to timeout_ms (or indefinitely if timeout_ms <= 0).
1151  * Returns on 0 success or a ssherr.h code on failure.
1152  */
1153 int
1154 kex_exchange_identification(struct ssh *ssh, int timeout_ms,
1155     const char *version_addendum)
1156 {
1157 	int remote_major, remote_minor, mismatch;
1158 	size_t len, i, n;
1159 	int r, expect_nl;
1160 	u_char c;
1161 	struct sshbuf *our_version = ssh->kex->server ?
1162 	    ssh->kex->server_version : ssh->kex->client_version;
1163 	struct sshbuf *peer_version = ssh->kex->server ?
1164 	    ssh->kex->client_version : ssh->kex->server_version;
1165 	char *our_version_string = NULL, *peer_version_string = NULL;
1166 	char *cp, *remote_version = NULL;
1167 
1168 	/* Prepare and send our banner */
1169 	sshbuf_reset(our_version);
1170 	if (version_addendum != NULL && *version_addendum == '\0')
1171 		version_addendum = NULL;
1172 	if ((r = sshbuf_putf(our_version, "SSH-%d.%d-%.100s%s%s\r\n",
1173 	   PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2, SSH_VERSION,
1174 	    version_addendum == NULL ? "" : " ",
1175 	    version_addendum == NULL ? "" : version_addendum)) != 0) {
1176 		error("%s: sshbuf_putf: %s", __func__, ssh_err(r));
1177 		goto out;
1178 	}
1179 
1180 	if (atomicio(vwrite, ssh_packet_get_connection_out(ssh),
1181 	    sshbuf_mutable_ptr(our_version),
1182 	    sshbuf_len(our_version)) != sshbuf_len(our_version)) {
1183 		error("%s: write: %.100s", __func__, strerror(errno));
1184 		r = SSH_ERR_SYSTEM_ERROR;
1185 		goto out;
1186 	}
1187 	if ((r = sshbuf_consume_end(our_version, 2)) != 0) { /* trim \r\n */
1188 		error("%s: sshbuf_consume_end: %s", __func__, ssh_err(r));
1189 		goto out;
1190 	}
1191 	our_version_string = sshbuf_dup_string(our_version);
1192 	if (our_version_string == NULL) {
1193 		error("%s: sshbuf_dup_string failed", __func__);
1194 		r = SSH_ERR_ALLOC_FAIL;
1195 		goto out;
1196 	}
1197 	debug("Local version string %.100s", our_version_string);
1198 
1199 	/* Read other side's version identification. */
1200 	for (n = 0; ; n++) {
1201 		if (n >= SSH_MAX_PRE_BANNER_LINES) {
1202 			send_error(ssh, "No SSH identification string "
1203 			    "received.");
1204 			error("%s: No SSH version received in first %u lines "
1205 			    "from server", __func__, SSH_MAX_PRE_BANNER_LINES);
1206 			r = SSH_ERR_INVALID_FORMAT;
1207 			goto out;
1208 		}
1209 		sshbuf_reset(peer_version);
1210 		expect_nl = 0;
1211 		for (i = 0; ; i++) {
1212 			if (timeout_ms > 0) {
1213 				r = waitrfd(ssh_packet_get_connection_in(ssh),
1214 				    &timeout_ms);
1215 				if (r == -1 && errno == ETIMEDOUT) {
1216 					send_error(ssh, "Timed out waiting "
1217 					    "for SSH identification string.");
1218 					error("Connection timed out during "
1219 					    "banner exchange");
1220 					r = SSH_ERR_CONN_TIMEOUT;
1221 					goto out;
1222 				} else if (r == -1) {
1223 					error("%s: %s",
1224 					    __func__, strerror(errno));
1225 					r = SSH_ERR_SYSTEM_ERROR;
1226 					goto out;
1227 				}
1228 			}
1229 
1230 			len = atomicio(read, ssh_packet_get_connection_in(ssh),
1231 			    &c, 1);
1232 			if (len != 1 && errno == EPIPE) {
1233 				error("%s: Connection closed by remote host",
1234 				    __func__);
1235 				r = SSH_ERR_CONN_CLOSED;
1236 				goto out;
1237 			} else if (len != 1) {
1238 				error("%s: read: %.100s",
1239 				    __func__, strerror(errno));
1240 				r = SSH_ERR_SYSTEM_ERROR;
1241 				goto out;
1242 			}
1243 			if (c == '\r') {
1244 				expect_nl = 1;
1245 				continue;
1246 			}
1247 			if (c == '\n')
1248 				break;
1249 			if (c == '\0' || expect_nl) {
1250 				error("%s: banner line contains invalid "
1251 				    "characters", __func__);
1252 				goto invalid;
1253 			}
1254 			if ((r = sshbuf_put_u8(peer_version, c)) != 0) {
1255 				error("%s: sshbuf_put: %s",
1256 				    __func__, ssh_err(r));
1257 				goto out;
1258 			}
1259 			if (sshbuf_len(peer_version) > SSH_MAX_BANNER_LEN) {
1260 				error("%s: banner line too long", __func__);
1261 				goto invalid;
1262 			}
1263 		}
1264 		/* Is this an actual protocol banner? */
1265 		if (sshbuf_len(peer_version) > 4 &&
1266 		    memcmp(sshbuf_ptr(peer_version), "SSH-", 4) == 0)
1267 			break;
1268 		/* If not, then just log the line and continue */
1269 		if ((cp = sshbuf_dup_string(peer_version)) == NULL) {
1270 			error("%s: sshbuf_dup_string failed", __func__);
1271 			r = SSH_ERR_ALLOC_FAIL;
1272 			goto out;
1273 		}
1274 		/* Do not accept lines before the SSH ident from a client */
1275 		if (ssh->kex->server) {
1276 			error("%s: client sent invalid protocol identifier "
1277 			    "\"%.256s\"", __func__, cp);
1278 			free(cp);
1279 			goto invalid;
1280 		}
1281 		debug("%s: banner line %zu: %s", __func__, n, cp);
1282 		free(cp);
1283 	}
1284 	peer_version_string = sshbuf_dup_string(peer_version);
1285 	if (peer_version_string == NULL)
1286 		error("%s: sshbuf_dup_string failed", __func__);
1287 	/* XXX must be same size for sscanf */
1288 	if ((remote_version = calloc(1, sshbuf_len(peer_version))) == NULL) {
1289 		error("%s: calloc failed", __func__);
1290 		r = SSH_ERR_ALLOC_FAIL;
1291 		goto out;
1292 	}
1293 
1294 	/*
1295 	 * Check that the versions match.  In future this might accept
1296 	 * several versions and set appropriate flags to handle them.
1297 	 */
1298 	if (sscanf(peer_version_string, "SSH-%d.%d-%[^\n]\n",
1299 	    &remote_major, &remote_minor, remote_version) != 3) {
1300 		error("Bad remote protocol version identification: '%.100s'",
1301 		    peer_version_string);
1302  invalid:
1303 		send_error(ssh, "Invalid SSH identification string.");
1304 		r = SSH_ERR_INVALID_FORMAT;
1305 		goto out;
1306 	}
1307 	debug("Remote protocol version %d.%d, remote software version %.100s",
1308 	    remote_major, remote_minor, remote_version);
1309 	ssh->compat = compat_datafellows(remote_version);
1310 
1311 	mismatch = 0;
1312 	switch (remote_major) {
1313 	case 2:
1314 		break;
1315 	case 1:
1316 		if (remote_minor != 99)
1317 			mismatch = 1;
1318 		break;
1319 	default:
1320 		mismatch = 1;
1321 		break;
1322 	}
1323 	if (mismatch) {
1324 		error("Protocol major versions differ: %d vs. %d",
1325 		    PROTOCOL_MAJOR_2, remote_major);
1326 		send_error(ssh, "Protocol major versions differ.");
1327 		r = SSH_ERR_NO_PROTOCOL_VERSION;
1328 		goto out;
1329 	}
1330 
1331 	if (ssh->kex->server && (ssh->compat & SSH_BUG_PROBE) != 0) {
1332 		logit("probed from %s port %d with %s.  Don't panic.",
1333 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1334 		    peer_version_string);
1335 		r = SSH_ERR_CONN_CLOSED; /* XXX */
1336 		goto out;
1337 	}
1338 	if (ssh->kex->server && (ssh->compat & SSH_BUG_SCANNER) != 0) {
1339 		logit("scanned from %s port %d with %s.  Don't panic.",
1340 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1341 		    peer_version_string);
1342 		r = SSH_ERR_CONN_CLOSED; /* XXX */
1343 		goto out;
1344 	}
1345 	if ((ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
1346 		logit("Remote version \"%.100s\" uses unsafe RSA signature "
1347 		    "scheme; disabling use of RSA keys", remote_version);
1348 	}
1349 	/* success */
1350 	r = 0;
1351  out:
1352 	free(our_version_string);
1353 	free(peer_version_string);
1354 	free(remote_version);
1355 	return r;
1356 }
1357 
1358