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