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