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