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