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