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