xref: /netbsd-src/crypto/external/bsd/openssh/dist/kex.c (revision cef8759bd76c1b621f8eab8faa6f208faabc2e15)
1 /*	$NetBSD: kex.c,v 1.27 2020/05/28 17:05:49 christos Exp $	*/
2 /* $OpenBSD: kex.c,v 1.158 2020/03/13 04:01:56 djm Exp $ */
3 /*
4  * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include "includes.h"
28 __RCSID("$NetBSD: kex.c,v 1.27 2020/05/28 17:05:49 christos Exp $");
29 
30 #include <sys/param.h>	/* MAX roundup */
31 #include <sys/types.h>
32 #include <errno.h>
33 #include <signal.h>
34 #include <stdio.h>
35 #include <stdlib.h>
36 #include <string.h>
37 #include <unistd.h>
38 #include <poll.h>
39 
40 #ifdef WITH_OPENSSL
41 #include <openssl/crypto.h>
42 #include <openssl/dh.h>
43 #endif
44 
45 #include "ssh.h"
46 #include "ssh2.h"
47 #include "atomicio.h"
48 #include "version.h"
49 #include "packet.h"
50 #include "compat.h"
51 #include "cipher.h"
52 #include "sshkey.h"
53 #include "kex.h"
54 #include "log.h"
55 #include "mac.h"
56 #include "match.h"
57 #include "misc.h"
58 #include "dispatch.h"
59 #include "packet.h"
60 #include "monitor.h"
61 #include "canohost.h"
62 
63 #include "ssherr.h"
64 #include "sshbuf.h"
65 #include "digest.h"
66 
67 /* prototype */
68 static int kex_choose_conf(struct ssh *);
69 static int kex_input_newkeys(int, u_int32_t, struct ssh *);
70 
71 static const char *proposal_names[PROPOSAL_MAX] = {
72 	"KEX algorithms",
73 	"host key algorithms",
74 	"ciphers ctos",
75 	"ciphers stoc",
76 	"MACs ctos",
77 	"MACs stoc",
78 	"compression ctos",
79 	"compression stoc",
80 	"languages ctos",
81 	"languages stoc",
82 };
83 
84 struct kexalg {
85 	const char *name;
86 	u_int type;
87 	int ec_nid;
88 	int hash_alg;
89 };
90 static const struct kexalg kexalgs[] = {
91 #ifdef WITH_OPENSSL
92 	{ KEX_DH1, KEX_DH_GRP1_SHA1, 0, SSH_DIGEST_SHA1 },
93 	{ KEX_DH14_SHA1, KEX_DH_GRP14_SHA1, 0, SSH_DIGEST_SHA1 },
94 	{ KEX_DH14_SHA256, KEX_DH_GRP14_SHA256, 0, SSH_DIGEST_SHA256 },
95 	{ KEX_DH16_SHA512, KEX_DH_GRP16_SHA512, 0, SSH_DIGEST_SHA512 },
96 	{ KEX_DH18_SHA512, KEX_DH_GRP18_SHA512, 0, SSH_DIGEST_SHA512 },
97 	{ KEX_DHGEX_SHA1, KEX_DH_GEX_SHA1, 0, SSH_DIGEST_SHA1 },
98 	{ KEX_DHGEX_SHA256, KEX_DH_GEX_SHA256, 0, SSH_DIGEST_SHA256 },
99 	{ KEX_ECDH_SHA2_NISTP256, KEX_ECDH_SHA2,
100 	    NID_X9_62_prime256v1, SSH_DIGEST_SHA256 },
101 	{ KEX_ECDH_SHA2_NISTP384, KEX_ECDH_SHA2, NID_secp384r1,
102 	    SSH_DIGEST_SHA384 },
103 	{ KEX_ECDH_SHA2_NISTP521, KEX_ECDH_SHA2, NID_secp521r1,
104 	    SSH_DIGEST_SHA512 },
105 #endif
106 	{ KEX_CURVE25519_SHA256, KEX_C25519_SHA256, 0, SSH_DIGEST_SHA256 },
107 	{ KEX_CURVE25519_SHA256_OLD, KEX_C25519_SHA256, 0, SSH_DIGEST_SHA256 },
108 	{ KEX_SNTRUP4591761X25519_SHA512, KEX_KEM_SNTRUP4591761X25519_SHA512, 0,
109 	    SSH_DIGEST_SHA512 },
110 	{ NULL, 0, -1, -1},
111 };
112 
113 char *
114 kex_alg_list(char sep)
115 {
116 	char *ret = NULL, *tmp;
117 	size_t nlen, rlen = 0;
118 	const struct kexalg *k;
119 
120 	for (k = kexalgs; k->name != NULL; k++) {
121 		if (ret != NULL)
122 			ret[rlen++] = sep;
123 		nlen = strlen(k->name);
124 		if ((tmp = realloc(ret, rlen + nlen + 2)) == NULL) {
125 			free(ret);
126 			return NULL;
127 		}
128 		ret = tmp;
129 		memcpy(ret + rlen, k->name, nlen + 1);
130 		rlen += nlen;
131 	}
132 	return ret;
133 }
134 
135 static const struct kexalg *
136 kex_alg_by_name(const char *name)
137 {
138 	const struct kexalg *k;
139 
140 	for (k = kexalgs; k->name != NULL; k++) {
141 		if (strcmp(k->name, name) == 0)
142 			return k;
143 	}
144 	return NULL;
145 }
146 
147 /* Validate KEX method name list */
148 int
149 kex_names_valid(const char *names)
150 {
151 	char *s, *cp, *p;
152 
153 	if (names == NULL || strcmp(names, "") == 0)
154 		return 0;
155 	if ((s = cp = strdup(names)) == NULL)
156 		return 0;
157 	for ((p = strsep(&cp, ",")); p && *p != '\0';
158 	    (p = strsep(&cp, ","))) {
159 		if (kex_alg_by_name(p) == NULL) {
160 			error("Unsupported KEX algorithm \"%.100s\"", p);
161 			free(s);
162 			return 0;
163 		}
164 	}
165 	debug3("kex names ok: [%s]", names);
166 	free(s);
167 	return 1;
168 }
169 
170 /*
171  * Concatenate algorithm names, avoiding duplicates in the process.
172  * Caller must free returned string.
173  */
174 char *
175 kex_names_cat(const char *a, const char *b)
176 {
177 	char *ret = NULL, *tmp = NULL, *cp, *p, *m;
178 	size_t len;
179 
180 	if (a == NULL || *a == '\0')
181 		return strdup(b);
182 	if (b == NULL || *b == '\0')
183 		return strdup(a);
184 	if (strlen(b) > 1024*1024)
185 		return NULL;
186 	len = strlen(a) + strlen(b) + 2;
187 	if ((tmp = cp = strdup(b)) == NULL ||
188 	    (ret = calloc(1, len)) == NULL) {
189 		free(tmp);
190 		return NULL;
191 	}
192 	strlcpy(ret, a, len);
193 	for ((p = strsep(&cp, ",")); p && *p != '\0'; (p = strsep(&cp, ","))) {
194 		if ((m = match_list(ret, p, NULL)) != NULL) {
195 			free(m);
196 			continue; /* Algorithm already present */
197 		}
198 		if (strlcat(ret, ",", len) >= len ||
199 		    strlcat(ret, p, len) >= len) {
200 			free(tmp);
201 			free(ret);
202 			return NULL; /* Shouldn't happen */
203 		}
204 	}
205 	free(tmp);
206 	return ret;
207 }
208 
209 /*
210  * Assemble a list of algorithms from a default list and a string from a
211  * configuration file. The user-provided string may begin with '+' to
212  * indicate that it should be appended to the default, '-' that the
213  * specified names should be removed, or '^' that they should be placed
214  * at the head.
215  */
216 int
217 kex_assemble_names(char **listp, const char *def, const char *all)
218 {
219 	char *cp, *tmp, *patterns;
220 	char *list = NULL, *ret = NULL, *matching = NULL, *opatterns = NULL;
221 	int r = SSH_ERR_INTERNAL_ERROR;
222 
223 	if (listp == NULL || def == NULL || all == NULL)
224 		return SSH_ERR_INVALID_ARGUMENT;
225 
226 	if (*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 if (*list == '^') {
252 		/* Place names at head of default list */
253 		if ((tmp = kex_names_cat(list + 1, def)) == NULL) {
254 			r = SSH_ERR_ALLOC_FAIL;
255 			goto fail;
256 		}
257 		free(list);
258 		list = tmp;
259 	} else {
260 		/* Explicit list, overrides default - just use "list" as is */
261 	}
262 
263 	/*
264 	 * The supplied names may be a pattern-list. For the -list case,
265 	 * the patterns are applied above. For the +list and explicit list
266 	 * cases we need to do it now.
267 	 */
268 	ret = NULL;
269 	if ((patterns = opatterns = strdup(list)) == NULL) {
270 		r = SSH_ERR_ALLOC_FAIL;
271 		goto fail;
272 	}
273 	/* Apply positive (i.e. non-negated) patterns from the list */
274 	while ((cp = strsep(&patterns, ",")) != NULL) {
275 		if (*cp == '!') {
276 			/* negated matches are not supported here */
277 			r = SSH_ERR_INVALID_ARGUMENT;
278 			goto fail;
279 		}
280 		free(matching);
281 		if ((matching = match_filter_whitelist(all, cp)) == NULL) {
282 			r = SSH_ERR_ALLOC_FAIL;
283 			goto fail;
284 		}
285 		if ((tmp = kex_names_cat(ret, matching)) == NULL) {
286 			r = SSH_ERR_ALLOC_FAIL;
287 			goto fail;
288 		}
289 		free(ret);
290 		ret = tmp;
291 	}
292 	if (ret == NULL || *ret == '\0') {
293 		/* An empty name-list is an error */
294 		/* XXX better error code? */
295 		r = SSH_ERR_INVALID_ARGUMENT;
296 		goto fail;
297 	}
298 
299 	/* success */
300 	*listp = ret;
301 	ret = NULL;
302 	r = 0;
303 
304  fail:
305 	free(matching);
306 	free(opatterns);
307 	free(list);
308 	free(ret);
309 	return r;
310 }
311 
312 /* put algorithm proposal into buffer */
313 int
314 kex_prop2buf(struct sshbuf *b, const char *proposal[PROPOSAL_MAX])
315 {
316 	u_int i;
317 	int r;
318 
319 	sshbuf_reset(b);
320 
321 	/*
322 	 * add a dummy cookie, the cookie will be overwritten by
323 	 * kex_send_kexinit(), each time a kexinit is set
324 	 */
325 	for (i = 0; i < KEX_COOKIE_LEN; i++) {
326 		if ((r = sshbuf_put_u8(b, 0)) != 0)
327 			return r;
328 	}
329 	for (i = 0; i < PROPOSAL_MAX; i++) {
330 		if ((r = sshbuf_put_cstring(b, proposal[i])) != 0)
331 			return r;
332 	}
333 	if ((r = sshbuf_put_u8(b, 0)) != 0 ||	/* first_kex_packet_follows */
334 	    (r = sshbuf_put_u32(b, 0)) != 0)	/* uint32 reserved */
335 		return r;
336 	return 0;
337 }
338 
339 /* parse buffer and return algorithm proposal */
340 int
341 kex_buf2prop(struct sshbuf *raw, int *first_kex_follows, char ***propp)
342 {
343 	struct sshbuf *b = NULL;
344 	u_char v;
345 	u_int i;
346 	char **proposal = NULL;
347 	int r;
348 
349 	*propp = NULL;
350 	if ((proposal = calloc(PROPOSAL_MAX, sizeof(char *))) == NULL)
351 		return SSH_ERR_ALLOC_FAIL;
352 	if ((b = sshbuf_fromb(raw)) == NULL) {
353 		r = SSH_ERR_ALLOC_FAIL;
354 		goto out;
355 	}
356 	if ((r = sshbuf_consume(b, KEX_COOKIE_LEN)) != 0) { /* skip cookie */
357 		error("%s: consume cookie: %s", __func__, ssh_err(r));
358 		goto out;
359 	}
360 	/* extract kex init proposal strings */
361 	for (i = 0; i < PROPOSAL_MAX; i++) {
362 		if ((r = sshbuf_get_cstring(b, &(proposal[i]), NULL)) != 0) {
363 			error("%s: parse proposal %u: %s", __func__,
364 			    i, ssh_err(r));
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("%s: parse: %s", __func__, ssh_err(r));
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 static 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("%s: compose: %s", __func__, ssh_err(r));
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 			char *cval = (void *)val;
491 			/* Ensure no \0 lurking in value */
492 			if (memchr(val, '\0', vlen) != NULL) {
493 				error("%s: nul byte in %s", __func__, name);
494 				return SSH_ERR_INVALID_FORMAT;
495 			}
496 			debug("%s: %s=<%s>", __func__, name, cval);
497 			kex->server_sig_algs = cval;
498 			val = NULL;
499 		} else
500 			debug("%s: %s (unrecognised)", __func__, name);
501 		free(name);
502 		free(val);
503 	}
504 	return sshpkt_get_end(ssh);
505 }
506 
507 static int
508 kex_input_newkeys(int type, u_int32_t seq, struct ssh *ssh)
509 {
510 	struct kex *kex = ssh->kex;
511 	int r;
512 
513 	debug("SSH2_MSG_NEWKEYS received");
514 	ssh_dispatch_set(ssh, SSH2_MSG_NEWKEYS, &kex_protocol_error);
515 	ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, &kex_input_kexinit);
516 	if ((r = sshpkt_get_end(ssh)) != 0)
517 		return r;
518 	if ((r = ssh_set_newkeys(ssh, MODE_IN)) != 0)
519 		return r;
520 	kex->done = 1;
521 	kex->flags &= ~KEX_INITIAL;
522 	sshbuf_reset(kex->peer);
523 	/* sshbuf_reset(kex->my); */
524 	kex->flags &= ~KEX_INIT_SENT;
525 	free(kex->name);
526 	kex->name = NULL;
527 	return 0;
528 }
529 
530 int
531 kex_send_kexinit(struct ssh *ssh)
532 {
533 	u_char *cookie;
534 	struct kex *kex = ssh->kex;
535 	int r;
536 
537 	if (kex == NULL) {
538 		error("%s: no hex", __func__);
539 		return SSH_ERR_INTERNAL_ERROR;
540 	}
541 	if (kex->flags & KEX_INIT_SENT)
542 		return 0;
543 	kex->done = 0;
544 
545 	/* generate a random cookie */
546 	if (sshbuf_len(kex->my) < KEX_COOKIE_LEN) {
547 		error("%s: bad kex length: %zu < %d", __func__,
548 		    sshbuf_len(kex->my), KEX_COOKIE_LEN);
549 		return SSH_ERR_INVALID_FORMAT;
550 	}
551 	if ((cookie = sshbuf_mutable_ptr(kex->my)) == NULL) {
552 		error("%s: buffer error", __func__);
553 		return SSH_ERR_INTERNAL_ERROR;
554 	}
555 	arc4random_buf(cookie, KEX_COOKIE_LEN);
556 
557 	if ((r = sshpkt_start(ssh, SSH2_MSG_KEXINIT)) != 0 ||
558 	    (r = sshpkt_putb(ssh, kex->my)) != 0 ||
559 	    (r = sshpkt_send(ssh)) != 0) {
560 		error("%s: compose reply: %s", __func__, ssh_err(r));
561 		return r;
562 	}
563 	debug("SSH2_MSG_KEXINIT sent");
564 	kex->flags |= KEX_INIT_SENT;
565 	return 0;
566 }
567 
568 /* ARGSUSED */
569 int
570 kex_input_kexinit(int type, u_int32_t seq, struct ssh *ssh)
571 {
572 	struct kex *kex = ssh->kex;
573 	const u_char *ptr;
574 	u_int i;
575 	size_t dlen;
576 	int r;
577 
578 	debug("SSH2_MSG_KEXINIT received");
579 	if (kex == NULL) {
580 		error("%s: no hex", __func__);
581 		return SSH_ERR_INTERNAL_ERROR;
582 	}
583 	ssh_dispatch_set(ssh, SSH2_MSG_KEXINIT, NULL);
584 	ptr = sshpkt_ptr(ssh, &dlen);
585 	if ((r = sshbuf_put(kex->peer, ptr, dlen)) != 0)
586 		return r;
587 
588 	/* discard packet */
589 	for (i = 0; i < KEX_COOKIE_LEN; i++) {
590 		if ((r = sshpkt_get_u8(ssh, NULL)) != 0) {
591 			error("%s: discard cookie: %s", __func__, ssh_err(r));
592 			return r;
593 		}
594 	}
595 	for (i = 0; i < PROPOSAL_MAX; i++) {
596 		if ((r = sshpkt_get_string(ssh, NULL, NULL)) != 0) {
597 			error("%s: discard proposal: %s", __func__, ssh_err(r));
598 			return r;
599 		}
600 	}
601 	/*
602 	 * XXX RFC4253 sec 7: "each side MAY guess" - currently no supported
603 	 * KEX method has the server move first, but a server might be using
604 	 * a custom method or one that we otherwise don't support. We should
605 	 * be prepared to remember first_kex_follows here so we can eat a
606 	 * packet later.
607 	 * XXX2 - RFC4253 is kind of ambiguous on what first_kex_follows means
608 	 * for cases where the server *doesn't* go first. I guess we should
609 	 * ignore it when it is set for these cases, which is what we do now.
610 	 */
611 	if ((r = sshpkt_get_u8(ssh, NULL)) != 0 ||	/* first_kex_follows */
612 	    (r = sshpkt_get_u32(ssh, NULL)) != 0 ||	/* reserved */
613 	    (r = sshpkt_get_end(ssh)) != 0)
614 			return r;
615 
616 	if (!(kex->flags & KEX_INIT_SENT))
617 		if ((r = kex_send_kexinit(ssh)) != 0)
618 			return r;
619 	if ((r = kex_choose_conf(ssh)) != 0)
620 		return r;
621 
622 	if (kex->kex_type < KEX_MAX && kex->kex[kex->kex_type] != NULL)
623 		return (kex->kex[kex->kex_type])(ssh);
624 
625 	error("%s: unknown kex type %u", __func__, kex->kex_type);
626 	return SSH_ERR_INTERNAL_ERROR;
627 }
628 
629 struct kex *
630 kex_new(void)
631 {
632 	struct kex *kex;
633 
634 	if ((kex = calloc(1, sizeof(*kex))) == NULL ||
635 	    (kex->peer = sshbuf_new()) == NULL ||
636 	    (kex->my = sshbuf_new()) == NULL ||
637 	    (kex->client_version = sshbuf_new()) == NULL ||
638 	    (kex->server_version = 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 	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("%s: no kex", __func__);
740 		return SSH_ERR_INTERNAL_ERROR;
741 	}
742 	if (ssh->kex->done == 0) {
743 		error("%s: requested twice", __func__);
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("%s: unsupported cipher %s", __func__, 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("%s: unsupported MAC %s", __func__, 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("%s: unsupported compression scheme %s", __func__, 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("%s: unsupported KEX method %s", __func__, 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 	k->hostkey_alg = match_list(client, server, NULL);
839 
840 	debug("kex: host key algorithm: %s",
841 	    k->hostkey_alg ? k->hostkey_alg : "(no match)");
842 	if (k->hostkey_alg == NULL)
843 		return SSH_ERR_NO_HOSTKEY_ALG_MATCH;
844 	k->hostkey_type = sshkey_type_from_name(k->hostkey_alg);
845 	if (k->hostkey_type == KEY_UNSPEC) {
846 		error("%s: unsupported hostkey algorithm %s", __func__,
847 		    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(hashctx, kex->session_id,
1042 	    kex->session_id_len) != 0 ||
1043 	    ssh_digest_final(hashctx, digest, mdsz) != 0) {
1044 		r = SSH_ERR_LIBCRYPTO_ERROR;
1045 		error("%s: KEX hash failed", __func__);
1046 		goto out;
1047 	}
1048 	ssh_digest_free(hashctx);
1049 	hashctx = NULL;
1050 
1051 	/*
1052 	 * expand key:
1053 	 * Kn = HASH(K || H || K1 || K2 || ... || Kn-1)
1054 	 * Key = K1 || K2 || ... || Kn
1055 	 */
1056 	for (have = mdsz; need > have; have += mdsz) {
1057 		if ((hashctx = ssh_digest_start(kex->hash_alg)) == NULL ||
1058 		    ssh_digest_update_buffer(hashctx, shared_secret) != 0 ||
1059 		    ssh_digest_update(hashctx, hash, hashlen) != 0 ||
1060 		    ssh_digest_update(hashctx, digest, have) != 0 ||
1061 		    ssh_digest_final(hashctx, digest + have, mdsz) != 0) {
1062 			error("%s: KDF failed", __func__);
1063 			r = SSH_ERR_LIBCRYPTO_ERROR;
1064 			goto out;
1065 		}
1066 		ssh_digest_free(hashctx);
1067 		hashctx = NULL;
1068 	}
1069 #ifdef DEBUG_KEX
1070 	fprintf(stderr, "key '%c'== ", c);
1071 	dump_digest("key", digest, need);
1072 #endif
1073 	*keyp = digest;
1074 	digest = NULL;
1075 	r = 0;
1076  out:
1077 	free(digest);
1078 	ssh_digest_free(hashctx);
1079 	return r;
1080 }
1081 
1082 #define NKEYS	6
1083 int
1084 kex_derive_keys(struct ssh *ssh, u_char *hash, u_int hashlen,
1085     const struct sshbuf *shared_secret)
1086 {
1087 	struct kex *kex = ssh->kex;
1088 	u_char *keys[NKEYS];
1089 	u_int i, j, mode, ctos;
1090 	int r;
1091 
1092 	/* save initial hash as session id */
1093 	if (kex->session_id == NULL) {
1094 		kex->session_id_len = hashlen;
1095 		kex->session_id = malloc(kex->session_id_len);
1096 		if (kex->session_id == NULL)
1097 			return SSH_ERR_ALLOC_FAIL;
1098 		memcpy(kex->session_id, hash, kex->session_id_len);
1099 	}
1100 	for (i = 0; i < NKEYS; i++) {
1101 		if ((r = derive_key(ssh, 'A'+i, kex->we_need, hash, hashlen,
1102 		    shared_secret, &keys[i])) != 0) {
1103 			for (j = 0; j < i; j++)
1104 				free(keys[j]);
1105 			return r;
1106 		}
1107 	}
1108 	for (mode = 0; mode < MODE_MAX; mode++) {
1109 		ctos = (!kex->server && mode == MODE_OUT) ||
1110 		    (kex->server && mode == MODE_IN);
1111 		kex->newkeys[mode]->enc.iv  = keys[ctos ? 0 : 1];
1112 		kex->newkeys[mode]->enc.key = keys[ctos ? 2 : 3];
1113 		kex->newkeys[mode]->mac.key = keys[ctos ? 4 : 5];
1114 	}
1115 	return 0;
1116 }
1117 
1118 int
1119 kex_load_hostkey(struct ssh *ssh, struct sshkey **prvp, struct sshkey **pubp)
1120 {
1121 	struct kex *kex = ssh->kex;
1122 
1123 	*pubp = NULL;
1124 	*prvp = NULL;
1125 	if (kex->load_host_public_key == NULL ||
1126 	    kex->load_host_private_key == NULL) {
1127 		error("%s: missing hostkey loader", __func__);
1128 		return SSH_ERR_INVALID_ARGUMENT;
1129 	}
1130 	*pubp = kex->load_host_public_key(kex->hostkey_type,
1131 	    kex->hostkey_nid, ssh);
1132 	*prvp = kex->load_host_private_key(kex->hostkey_type,
1133 	    kex->hostkey_nid, ssh);
1134 	if (*pubp == NULL)
1135 		return SSH_ERR_NO_HOSTKEY_LOADED;
1136 	return 0;
1137 }
1138 
1139 int
1140 kex_verify_host_key(struct ssh *ssh, struct sshkey *server_host_key)
1141 {
1142 	struct kex *kex = ssh->kex;
1143 
1144 	if (kex->verify_host_key == NULL) {
1145 		error("%s: missing hostkey verifier", __func__);
1146 		return SSH_ERR_INVALID_ARGUMENT;
1147 	}
1148 	if (server_host_key->type != kex->hostkey_type ||
1149 	    (kex->hostkey_type == KEY_ECDSA &&
1150 	    server_host_key->ecdsa_nid != kex->hostkey_nid))
1151 		return SSH_ERR_KEY_TYPE_MISMATCH;
1152 	if (kex->verify_host_key(server_host_key, ssh) == -1)
1153 		return  SSH_ERR_SIGNATURE_INVALID;
1154 	return 0;
1155 }
1156 
1157 #if defined(DEBUG_KEX) || defined(DEBUG_KEXDH) || defined(DEBUG_KEXECDH)
1158 void
1159 dump_digest(const char *msg, const u_char *digest, int len)
1160 {
1161 	fprintf(stderr, "%s\n", msg);
1162 	sshbuf_dump_data(digest, len, stderr);
1163 }
1164 #endif
1165 
1166 /*
1167  * Send a plaintext error message to the peer, suffixed by \r\n.
1168  * Only used during banner exchange, and there only for the server.
1169  */
1170 static void
1171 send_error(struct ssh *ssh, const char *msg)
1172 {
1173 	const char *crnl = "\r\n";
1174 
1175 	if (!ssh->kex->server)
1176 		return;
1177 
1178 	if (atomicio(vwrite, ssh_packet_get_connection_out(ssh),
1179 	    __UNCONST(msg), strlen(msg)) != strlen(msg) ||
1180 	    atomicio(vwrite, ssh_packet_get_connection_out(ssh),
1181 	    __UNCONST(crnl), strlen(crnl)) != strlen(crnl))
1182 		error("%s: write: %.100s", __func__, strerror(errno));
1183 }
1184 
1185 /*
1186  * Sends our identification string and waits for the peer's. Will block for
1187  * up to timeout_ms (or indefinitely if timeout_ms <= 0).
1188  * Returns on 0 success or a ssherr.h code on failure.
1189  */
1190 int
1191 kex_exchange_identification(struct ssh *ssh, int timeout_ms,
1192     const char *version_addendum)
1193 {
1194 	int remote_major, remote_minor, mismatch, oerrno = 0;
1195 	size_t len, i, n;
1196 	int r, expect_nl;
1197 	u_char c;
1198 	struct sshbuf *our_version = ssh->kex->server ?
1199 	    ssh->kex->server_version : ssh->kex->client_version;
1200 	struct sshbuf *peer_version = ssh->kex->server ?
1201 	    ssh->kex->client_version : ssh->kex->server_version;
1202 	char *our_version_string = NULL, *peer_version_string = NULL;
1203 	char *cp, *remote_version = NULL;
1204 
1205 	/* Prepare and send our banner */
1206 	sshbuf_reset(our_version);
1207 	if (version_addendum != NULL && *version_addendum == '\0')
1208 		version_addendum = NULL;
1209 	if ((r = sshbuf_putf(our_version, "SSH-%d.%d-%.100s%s%s\r\n",
1210 	   PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2, SSH_VERSION,
1211 	    version_addendum == NULL ? "" : " ",
1212 	    version_addendum == NULL ? "" : version_addendum)) != 0) {
1213 		oerrno = errno;
1214 		error("%s: sshbuf_putf: %s", __func__, ssh_err(r));
1215 		goto out;
1216 	}
1217 
1218 	if (atomicio(vwrite, ssh_packet_get_connection_out(ssh),
1219 	    sshbuf_mutable_ptr(our_version),
1220 	    sshbuf_len(our_version)) != sshbuf_len(our_version)) {
1221 		oerrno = errno;
1222 		debug("%s: write: %.100s", __func__, strerror(errno));
1223 		r = SSH_ERR_SYSTEM_ERROR;
1224 		goto out;
1225 	}
1226 	if ((r = sshbuf_consume_end(our_version, 2)) != 0) { /* trim \r\n */
1227 		oerrno = errno;
1228 		error("%s: sshbuf_consume_end: %s", __func__, ssh_err(r));
1229 		goto out;
1230 	}
1231 	our_version_string = sshbuf_dup_string(our_version);
1232 	if (our_version_string == NULL) {
1233 		error("%s: sshbuf_dup_string failed", __func__);
1234 		r = SSH_ERR_ALLOC_FAIL;
1235 		goto out;
1236 	}
1237 	debug("Local version string %.100s", our_version_string);
1238 
1239 	/* Read other side's version identification. */
1240 	for (n = 0; ; n++) {
1241 		if (n >= SSH_MAX_PRE_BANNER_LINES) {
1242 			send_error(ssh, "No SSH identification string "
1243 			    "received.");
1244 			error("%s: No SSH version received in first %u lines "
1245 			    "from server", __func__, SSH_MAX_PRE_BANNER_LINES);
1246 			r = SSH_ERR_INVALID_FORMAT;
1247 			goto out;
1248 		}
1249 		sshbuf_reset(peer_version);
1250 		expect_nl = 0;
1251 		for (i = 0; ; i++) {
1252 			if (timeout_ms > 0) {
1253 				r = waitrfd(ssh_packet_get_connection_in(ssh),
1254 				    &timeout_ms);
1255 				if (r == -1 && errno == ETIMEDOUT) {
1256 					send_error(ssh, "Timed out waiting "
1257 					    "for SSH identification string.");
1258 					error("Connection timed out during "
1259 					    "banner exchange");
1260 					r = SSH_ERR_CONN_TIMEOUT;
1261 					goto out;
1262 				} else if (r == -1) {
1263 					oerrno = errno;
1264 					error("%s: %s",
1265 					    __func__, strerror(errno));
1266 					r = SSH_ERR_SYSTEM_ERROR;
1267 					goto out;
1268 				}
1269 			}
1270 
1271 			len = atomicio(read, ssh_packet_get_connection_in(ssh),
1272 			    &c, 1);
1273 			if (len != 1 && errno == EPIPE) {
1274 				error("%s: Connection closed by remote host",
1275 				    __func__);
1276 				r = SSH_ERR_CONN_CLOSED;
1277 				goto out;
1278 			} else if (len != 1) {
1279 				oerrno = errno;
1280 				error("%s: read: %.100s",
1281 				    __func__, 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("%s: banner line contains invalid "
1293 				    "characters", __func__);
1294 				goto invalid;
1295 			}
1296 			if ((r = sshbuf_put_u8(peer_version, c)) != 0) {
1297 				oerrno = errno;
1298 				error("%s: sshbuf_put: %s",
1299 				    __func__, ssh_err(r));
1300 				goto out;
1301 			}
1302 			if (sshbuf_len(peer_version) > SSH_MAX_BANNER_LEN) {
1303 				error("%s: banner line too long", __func__);
1304 				goto invalid;
1305 			}
1306 		}
1307 		/* Is this an actual protocol banner? */
1308 		if (sshbuf_len(peer_version) > 4 &&
1309 		    memcmp(sshbuf_ptr(peer_version), "SSH-", 4) == 0)
1310 			break;
1311 		/* If not, then just log the line and continue */
1312 		if ((cp = sshbuf_dup_string(peer_version)) == NULL) {
1313 			error("%s: sshbuf_dup_string failed", __func__);
1314 			r = SSH_ERR_ALLOC_FAIL;
1315 			goto out;
1316 		}
1317 		/* Do not accept lines before the SSH ident from a client */
1318 		if (ssh->kex->server) {
1319 			error("%s: client sent invalid protocol identifier "
1320 			    "\"%.256s\"", __func__, cp);
1321 			free(cp);
1322 			goto invalid;
1323 		}
1324 		debug("%s: banner line %zu: %s", __func__, n, cp);
1325 		free(cp);
1326 	}
1327 	peer_version_string = sshbuf_dup_string(peer_version);
1328 	if (peer_version_string == NULL)
1329 		error("%s: sshbuf_dup_string failed", __func__);
1330 	/* XXX must be same size for sscanf */
1331 	if ((remote_version = calloc(1, sshbuf_len(peer_version))) == NULL) {
1332 		error("%s: calloc failed", __func__);
1333 		r = SSH_ERR_ALLOC_FAIL;
1334 		goto out;
1335 	}
1336 
1337 	/*
1338 	 * Check that the versions match.  In future this might accept
1339 	 * several versions and set appropriate flags to handle them.
1340 	 */
1341 	if (sscanf(peer_version_string, "SSH-%d.%d-%[^\n]\n",
1342 	    &remote_major, &remote_minor, remote_version) != 3) {
1343 		error("Bad remote protocol version identification: '%.100s'",
1344 		    peer_version_string);
1345  invalid:
1346 		send_error(ssh, "Invalid SSH identification string.");
1347 		r = SSH_ERR_INVALID_FORMAT;
1348 		goto out;
1349 	}
1350 	debug("Remote protocol version %d.%d, remote software version %.100s",
1351 	    remote_major, remote_minor, remote_version);
1352 	ssh->compat = compat_datafellows(remote_version);
1353 
1354 	mismatch = 0;
1355 	switch (remote_major) {
1356 	case 2:
1357 		break;
1358 	case 1:
1359 		if (remote_minor != 99)
1360 			mismatch = 1;
1361 		break;
1362 	default:
1363 		mismatch = 1;
1364 		break;
1365 	}
1366 	if (mismatch) {
1367 		error("Protocol major versions differ: %d vs. %d",
1368 		    PROTOCOL_MAJOR_2, remote_major);
1369 		send_error(ssh, "Protocol major versions differ.");
1370 		r = SSH_ERR_NO_PROTOCOL_VERSION;
1371 		goto out;
1372 	}
1373 
1374 	if (ssh->kex->server && (ssh->compat & SSH_BUG_PROBE) != 0) {
1375 		logit("probed from %s port %d with %s.  Don't panic.",
1376 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1377 		    peer_version_string);
1378 		r = SSH_ERR_CONN_CLOSED; /* XXX */
1379 		goto out;
1380 	}
1381 	if (ssh->kex->server && (ssh->compat & SSH_BUG_SCANNER) != 0) {
1382 		logit("scanned from %s port %d with %s.  Don't panic.",
1383 		    ssh_remote_ipaddr(ssh), ssh_remote_port(ssh),
1384 		    peer_version_string);
1385 		r = SSH_ERR_CONN_CLOSED; /* XXX */
1386 		goto out;
1387 	}
1388 	if ((ssh->compat & SSH_BUG_RSASIGMD5) != 0) {
1389 		logit("Remote version \"%.100s\" uses unsafe RSA signature "
1390 		    "scheme; disabling use of RSA keys", remote_version);
1391 	}
1392 	/* success */
1393 	r = 0;
1394  out:
1395 	free(our_version_string);
1396 	free(peer_version_string);
1397 	free(remote_version);
1398 	if (r == SSH_ERR_SYSTEM_ERROR)
1399 		errno = oerrno;
1400 	return r;
1401 }
1402 
1403