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