kex.c revision 263691
1230557Sjimharris/* $OpenBSD: kex.c,v 1.97 2014/01/25 20:35:37 markus Exp $ */
2230557Sjimharris/* $FreeBSD: head/crypto/openssh/kex.c 263691 2014-03-24 19:15:13Z des $ */
3230557Sjimharris/*
4230557Sjimharris * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
5230557Sjimharris *
6230557Sjimharris * Redistribution and use in source and binary forms, with or without
7230557Sjimharris * modification, are permitted provided that the following conditions
8230557Sjimharris * are met:
9230557Sjimharris * 1. Redistributions of source code must retain the above copyright
10230557Sjimharris *    notice, this list of conditions and the following disclaimer.
11230557Sjimharris * 2. Redistributions in binary form must reproduce the above copyright
12230557Sjimharris *    notice, this list of conditions and the following disclaimer in the
13230557Sjimharris *    documentation and/or other materials provided with the distribution.
14230557Sjimharris *
15230557Sjimharris * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16230557Sjimharris * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17230557Sjimharris * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18230557Sjimharris * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19230557Sjimharris * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20230557Sjimharris * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21230557Sjimharris * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22230557Sjimharris * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23230557Sjimharris * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24230557Sjimharris * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25230557Sjimharris */
26230557Sjimharris
27230557Sjimharris#include "includes.h"
28230557Sjimharris__RCSID("$FreeBSD: head/crypto/openssh/kex.c 263691 2014-03-24 19:15:13Z des $");
29230557Sjimharris
30230557Sjimharris#include <sys/param.h>
31230557Sjimharris
32230557Sjimharris#include <signal.h>
33230557Sjimharris#include <stdarg.h>
34230557Sjimharris#include <stdio.h>
35230557Sjimharris#include <stdlib.h>
36230557Sjimharris#include <string.h>
37230557Sjimharris
38230557Sjimharris#include <openssl/crypto.h>
39230557Sjimharris
40230557Sjimharris#include "xmalloc.h"
41230557Sjimharris#include "ssh2.h"
42230557Sjimharris#include "buffer.h"
43230557Sjimharris#include "packet.h"
44230557Sjimharris#include "compat.h"
45230557Sjimharris#include "cipher.h"
46230557Sjimharris#include "key.h"
47230557Sjimharris#include "kex.h"
48230557Sjimharris#include "log.h"
49230557Sjimharris#include "mac.h"
50230557Sjimharris#include "match.h"
51230557Sjimharris#include "dispatch.h"
52230557Sjimharris#include "monitor.h"
53230557Sjimharris#include "roaming.h"
54230557Sjimharris#include "digest.h"
55230557Sjimharris
56230557Sjimharris#if OPENSSL_VERSION_NUMBER >= 0x00907000L
57230557Sjimharris# if defined(HAVE_EVP_SHA256)
58230557Sjimharris# define evp_ssh_sha256 EVP_sha256
59230557Sjimharris# else
60230557Sjimharrisextern const EVP_MD *evp_ssh_sha256(void);
61230557Sjimharris# endif
62230557Sjimharris#endif
63230557Sjimharris
64230557Sjimharris/* prototype */
65230557Sjimharrisstatic void kex_kexinit_finish(Kex *);
66230557Sjimharrisstatic void kex_choose_conf(Kex *);
67230557Sjimharris
68230557Sjimharrisstruct kexalg {
69230557Sjimharris	char *name;
70230557Sjimharris	int type;
71230557Sjimharris	int ec_nid;
72230557Sjimharris	int hash_alg;
73230557Sjimharris};
74230557Sjimharrisstatic const struct kexalg kexalgs[] = {
75230557Sjimharris	{ KEX_DH1, KEX_DH_GRP1_SHA1, 0, SSH_DIGEST_SHA1 },
76230557Sjimharris	{ KEX_DH14, KEX_DH_GRP14_SHA1, 0, SSH_DIGEST_SHA1 },
77230557Sjimharris	{ KEX_DHGEX_SHA1, KEX_DH_GEX_SHA1, 0, SSH_DIGEST_SHA1 },
78230557Sjimharris#ifdef HAVE_EVP_SHA256
79230557Sjimharris	{ KEX_DHGEX_SHA256, KEX_DH_GEX_SHA256, 0, SSH_DIGEST_SHA256 },
80230557Sjimharris#endif
81230557Sjimharris#ifdef OPENSSL_HAS_ECC
82230557Sjimharris	{ KEX_ECDH_SHA2_NISTP256, KEX_ECDH_SHA2,
83230557Sjimharris	    NID_X9_62_prime256v1, SSH_DIGEST_SHA256 },
84230557Sjimharris	{ KEX_ECDH_SHA2_NISTP384, KEX_ECDH_SHA2, NID_secp384r1,
85230557Sjimharris	    SSH_DIGEST_SHA384 },
86230557Sjimharris# ifdef OPENSSL_HAS_NISTP521
87230557Sjimharris	{ KEX_ECDH_SHA2_NISTP521, KEX_ECDH_SHA2, NID_secp521r1,
88230557Sjimharris	    SSH_DIGEST_SHA512 },
89230557Sjimharris# endif
90230557Sjimharris#endif
91230557Sjimharris	{ KEX_DH1, KEX_DH_GRP1_SHA1, 0, SSH_DIGEST_SHA1 },
92230557Sjimharris#ifdef HAVE_EVP_SHA256
93230557Sjimharris	{ KEX_CURVE25519_SHA256, KEX_C25519_SHA256, 0, SSH_DIGEST_SHA256 },
94230557Sjimharris#endif
95230557Sjimharris	{ NULL, -1, -1, -1},
96230557Sjimharris};
97230557Sjimharris
98230557Sjimharrischar *
99230557Sjimharriskex_alg_list(char sep)
100230557Sjimharris{
101230557Sjimharris	char *ret = NULL;
102230557Sjimharris	size_t nlen, rlen = 0;
103230557Sjimharris	const struct kexalg *k;
104230557Sjimharris
105230557Sjimharris	for (k = kexalgs; k->name != NULL; k++) {
106230557Sjimharris		if (ret != NULL)
107230557Sjimharris			ret[rlen++] = sep;
108230557Sjimharris		nlen = strlen(k->name);
109230557Sjimharris		ret = xrealloc(ret, 1, rlen + nlen + 2);
110230557Sjimharris		memcpy(ret + rlen, k->name, nlen + 1);
111230557Sjimharris		rlen += nlen;
112230557Sjimharris	}
113230557Sjimharris	return ret;
114230557Sjimharris}
115230557Sjimharris
116230557Sjimharrisstatic const struct kexalg *
117230557Sjimharriskex_alg_by_name(const char *name)
118230557Sjimharris{
119230557Sjimharris	const struct kexalg *k;
120230557Sjimharris
121230557Sjimharris	for (k = kexalgs; k->name != NULL; k++) {
122230557Sjimharris		if (strcmp(k->name, name) == 0)
123230557Sjimharris			return k;
124230557Sjimharris	}
125230557Sjimharris	return NULL;
126230557Sjimharris}
127230557Sjimharris
128230557Sjimharris/* Validate KEX method name list */
129230557Sjimharrisint
130230557Sjimharriskex_names_valid(const char *names)
131230557Sjimharris{
132230557Sjimharris	char *s, *cp, *p;
133230557Sjimharris
134230557Sjimharris	if (names == NULL || strcmp(names, "") == 0)
135230557Sjimharris		return 0;
136230557Sjimharris	s = cp = xstrdup(names);
137230557Sjimharris	for ((p = strsep(&cp, ",")); p && *p != '\0';
138230557Sjimharris	    (p = strsep(&cp, ","))) {
139230557Sjimharris		if (kex_alg_by_name(p) == NULL) {
140230557Sjimharris			error("Unsupported KEX algorithm \"%.100s\"", p);
141230557Sjimharris			free(s);
142230557Sjimharris			return 0;
143230557Sjimharris		}
144230557Sjimharris	}
145230557Sjimharris	debug3("kex names ok: [%s]", names);
146230557Sjimharris	free(s);
147230557Sjimharris	return 1;
148230557Sjimharris}
149230557Sjimharris
150230557Sjimharris/* put algorithm proposal into buffer. */
151230557Sjimharris#ifndef NONE_CIPHER_ENABLED
152230557Sjimharrisstatic void
153230557Sjimharris#else
154230557Sjimharris/* Also used in sshconnect2.c. */
155230557Sjimharrisvoid
156230557Sjimharris#endif
157230557Sjimharriskex_prop2buf(Buffer *b, char *proposal[PROPOSAL_MAX])
158230557Sjimharris{
159230557Sjimharris	u_int i;
160230557Sjimharris
161230557Sjimharris	buffer_clear(b);
162230557Sjimharris	/*
163230557Sjimharris	 * add a dummy cookie, the cookie will be overwritten by
164230557Sjimharris	 * kex_send_kexinit(), each time a kexinit is set
165230557Sjimharris	 */
166230557Sjimharris	for (i = 0; i < KEX_COOKIE_LEN; i++)
167230557Sjimharris		buffer_put_char(b, 0);
168230557Sjimharris	for (i = 0; i < PROPOSAL_MAX; i++)
169230557Sjimharris		buffer_put_cstring(b, proposal[i]);
170230557Sjimharris	buffer_put_char(b, 0);			/* first_kex_packet_follows */
171230557Sjimharris	buffer_put_int(b, 0);			/* uint32 reserved */
172230557Sjimharris}
173230557Sjimharris
174230557Sjimharris/* parse buffer and return algorithm proposal */
175230557Sjimharrisstatic char **
176230557Sjimharriskex_buf2prop(Buffer *raw, int *first_kex_follows)
177230557Sjimharris{
178230557Sjimharris	Buffer b;
179230557Sjimharris	u_int i;
180230557Sjimharris	char **proposal;
181230557Sjimharris
182230557Sjimharris	proposal = xcalloc(PROPOSAL_MAX, sizeof(char *));
183230557Sjimharris
184230557Sjimharris	buffer_init(&b);
185230557Sjimharris	buffer_append(&b, buffer_ptr(raw), buffer_len(raw));
186230557Sjimharris	/* skip cookie */
187230557Sjimharris	for (i = 0; i < KEX_COOKIE_LEN; i++)
188230557Sjimharris		buffer_get_char(&b);
189230557Sjimharris	/* extract kex init proposal strings */
190230557Sjimharris	for (i = 0; i < PROPOSAL_MAX; i++) {
191230557Sjimharris		proposal[i] = buffer_get_cstring(&b,NULL);
192230557Sjimharris		debug2("kex_parse_kexinit: %s", proposal[i]);
193230557Sjimharris	}
194230557Sjimharris	/* first kex follows / reserved */
195230557Sjimharris	i = buffer_get_char(&b);
196230557Sjimharris	if (first_kex_follows != NULL)
197230557Sjimharris		*first_kex_follows = i;
198230557Sjimharris	debug2("kex_parse_kexinit: first_kex_follows %d ", i);
199230557Sjimharris	i = buffer_get_int(&b);
200230557Sjimharris	debug2("kex_parse_kexinit: reserved %u ", i);
201230557Sjimharris	buffer_free(&b);
202230557Sjimharris	return proposal;
203230557Sjimharris}
204230557Sjimharris
205230557Sjimharrisstatic void
206230557Sjimharriskex_prop_free(char **proposal)
207230557Sjimharris{
208230557Sjimharris	u_int i;
209230557Sjimharris
210230557Sjimharris	for (i = 0; i < PROPOSAL_MAX; i++)
211230557Sjimharris		free(proposal[i]);
212230557Sjimharris	free(proposal);
213230557Sjimharris}
214230557Sjimharris
215230557Sjimharris/* ARGSUSED */
216230557Sjimharrisstatic void
217230557Sjimharriskex_protocol_error(int type, u_int32_t seq, void *ctxt)
218230557Sjimharris{
219230557Sjimharris	error("Hm, kex protocol error: type %d seq %u", type, seq);
220230557Sjimharris}
221230557Sjimharris
222230557Sjimharrisstatic void
223230557Sjimharriskex_reset_dispatch(void)
224230557Sjimharris{
225230557Sjimharris	dispatch_range(SSH2_MSG_TRANSPORT_MIN,
226230557Sjimharris	    SSH2_MSG_TRANSPORT_MAX, &kex_protocol_error);
227230557Sjimharris	dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
228230557Sjimharris}
229230557Sjimharris
230230557Sjimharrisvoid
231230557Sjimharriskex_finish(Kex *kex)
232230557Sjimharris{
233230557Sjimharris	kex_reset_dispatch();
234230557Sjimharris
235230557Sjimharris	packet_start(SSH2_MSG_NEWKEYS);
236230557Sjimharris	packet_send();
237230557Sjimharris	/* packet_write_wait(); */
238230557Sjimharris	debug("SSH2_MSG_NEWKEYS sent");
239230557Sjimharris
240230557Sjimharris	debug("expecting SSH2_MSG_NEWKEYS");
241230557Sjimharris	packet_read_expect(SSH2_MSG_NEWKEYS);
242230557Sjimharris	packet_check_eom();
243230557Sjimharris	debug("SSH2_MSG_NEWKEYS received");
244230557Sjimharris
245230557Sjimharris	kex->done = 1;
246230557Sjimharris	buffer_clear(&kex->peer);
247230557Sjimharris	/* buffer_clear(&kex->my); */
248230557Sjimharris	kex->flags &= ~KEX_INIT_SENT;
249230557Sjimharris	free(kex->name);
250230557Sjimharris	kex->name = NULL;
251230557Sjimharris}
252230557Sjimharris
253230557Sjimharrisvoid
254230557Sjimharriskex_send_kexinit(Kex *kex)
255230557Sjimharris{
256230557Sjimharris	u_int32_t rnd = 0;
257230557Sjimharris	u_char *cookie;
258230557Sjimharris	u_int i;
259230557Sjimharris
260230557Sjimharris	if (kex == NULL) {
261230557Sjimharris		error("kex_send_kexinit: no kex, cannot rekey");
262230557Sjimharris		return;
263230557Sjimharris	}
264230557Sjimharris	if (kex->flags & KEX_INIT_SENT) {
265230557Sjimharris		debug("KEX_INIT_SENT");
266230557Sjimharris		return;
267230557Sjimharris	}
268230557Sjimharris	kex->done = 0;
269230557Sjimharris
270230557Sjimharris	/* generate a random cookie */
271230557Sjimharris	if (buffer_len(&kex->my) < KEX_COOKIE_LEN)
272230557Sjimharris		fatal("kex_send_kexinit: kex proposal too short");
273230557Sjimharris	cookie = buffer_ptr(&kex->my);
274230557Sjimharris	for (i = 0; i < KEX_COOKIE_LEN; i++) {
275230557Sjimharris		if (i % 4 == 0)
276230557Sjimharris			rnd = arc4random();
277230557Sjimharris		cookie[i] = rnd;
278230557Sjimharris		rnd >>= 8;
279230557Sjimharris	}
280230557Sjimharris	packet_start(SSH2_MSG_KEXINIT);
281230557Sjimharris	packet_put_raw(buffer_ptr(&kex->my), buffer_len(&kex->my));
282230557Sjimharris	packet_send();
283230557Sjimharris	debug("SSH2_MSG_KEXINIT sent");
284230557Sjimharris	kex->flags |= KEX_INIT_SENT;
285230557Sjimharris}
286230557Sjimharris
287230557Sjimharris/* ARGSUSED */
288230557Sjimharrisvoid
289230557Sjimharriskex_input_kexinit(int type, u_int32_t seq, void *ctxt)
290230557Sjimharris{
291230557Sjimharris	char *ptr;
292230557Sjimharris	u_int i, dlen;
293230557Sjimharris	Kex *kex = (Kex *)ctxt;
294230557Sjimharris
295230557Sjimharris	debug("SSH2_MSG_KEXINIT received");
296230557Sjimharris	if (kex == NULL)
297230557Sjimharris		fatal("kex_input_kexinit: no kex, cannot rekey");
298230557Sjimharris
299230557Sjimharris	ptr = packet_get_raw(&dlen);
300230557Sjimharris	buffer_append(&kex->peer, ptr, dlen);
301230557Sjimharris
302230557Sjimharris	/* discard packet */
303230557Sjimharris	for (i = 0; i < KEX_COOKIE_LEN; i++)
304230557Sjimharris		packet_get_char();
305230557Sjimharris	for (i = 0; i < PROPOSAL_MAX; i++)
306		free(packet_get_string(NULL));
307	/*
308	 * XXX RFC4253 sec 7: "each side MAY guess" - currently no supported
309	 * KEX method has the server move first, but a server might be using
310	 * a custom method or one that we otherwise don't support. We should
311	 * be prepared to remember first_kex_follows here so we can eat a
312	 * packet later.
313	 * XXX2 - RFC4253 is kind of ambiguous on what first_kex_follows means
314	 * for cases where the server *doesn't* go first. I guess we should
315	 * ignore it when it is set for these cases, which is what we do now.
316	 */
317	(void) packet_get_char();	/* first_kex_follows */
318	(void) packet_get_int();	/* reserved */
319	packet_check_eom();
320
321	kex_kexinit_finish(kex);
322}
323
324Kex *
325kex_setup(char *proposal[PROPOSAL_MAX])
326{
327	Kex *kex;
328
329	kex = xcalloc(1, sizeof(*kex));
330	buffer_init(&kex->peer);
331	buffer_init(&kex->my);
332	kex_prop2buf(&kex->my, proposal);
333	kex->done = 0;
334
335	kex_send_kexinit(kex);					/* we start */
336	kex_reset_dispatch();
337
338	return kex;
339}
340
341static void
342kex_kexinit_finish(Kex *kex)
343{
344	if (!(kex->flags & KEX_INIT_SENT))
345		kex_send_kexinit(kex);
346
347	kex_choose_conf(kex);
348
349	if (kex->kex_type >= 0 && kex->kex_type < KEX_MAX &&
350	    kex->kex[kex->kex_type] != NULL) {
351		(kex->kex[kex->kex_type])(kex);
352	} else {
353		fatal("Unsupported key exchange %d", kex->kex_type);
354	}
355}
356
357static void
358choose_enc(Enc *enc, char *client, char *server)
359{
360	char *name = match_list(client, server, NULL);
361	if (name == NULL)
362		fatal("no matching cipher found: client %s server %s",
363		    client, server);
364	if ((enc->cipher = cipher_by_name(name)) == NULL)
365		fatal("matching cipher is not supported: %s", name);
366	enc->name = name;
367	enc->enabled = 0;
368	enc->iv = NULL;
369	enc->iv_len = cipher_ivlen(enc->cipher);
370	enc->key = NULL;
371	enc->key_len = cipher_keylen(enc->cipher);
372	enc->block_size = cipher_blocksize(enc->cipher);
373}
374
375static void
376choose_mac(Mac *mac, char *client, char *server)
377{
378	char *name = match_list(client, server, NULL);
379	if (name == NULL)
380		fatal("no matching mac found: client %s server %s",
381		    client, server);
382	if (mac_setup(mac, name) < 0)
383		fatal("unsupported mac %s", name);
384	/* truncate the key */
385	if (datafellows & SSH_BUG_HMAC)
386		mac->key_len = 16;
387	mac->name = name;
388	mac->key = NULL;
389	mac->enabled = 0;
390}
391
392static void
393choose_comp(Comp *comp, char *client, char *server)
394{
395	char *name = match_list(client, server, NULL);
396	if (name == NULL)
397		fatal("no matching comp found: client %s server %s", client, server);
398	if (strcmp(name, "zlib@openssh.com") == 0) {
399		comp->type = COMP_DELAYED;
400	} else if (strcmp(name, "zlib") == 0) {
401		comp->type = COMP_ZLIB;
402	} else if (strcmp(name, "none") == 0) {
403		comp->type = COMP_NONE;
404	} else {
405		fatal("unsupported comp %s", name);
406	}
407	comp->name = name;
408}
409
410static void
411choose_kex(Kex *k, char *client, char *server)
412{
413	const struct kexalg *kexalg;
414
415	k->name = match_list(client, server, NULL);
416	if (k->name == NULL)
417		fatal("Unable to negotiate a key exchange method");
418	if ((kexalg = kex_alg_by_name(k->name)) == NULL)
419		fatal("unsupported kex alg %s", k->name);
420	k->kex_type = kexalg->type;
421	k->hash_alg = kexalg->hash_alg;
422	k->ec_nid = kexalg->ec_nid;
423}
424
425static void
426choose_hostkeyalg(Kex *k, char *client, char *server)
427{
428	char *hostkeyalg = match_list(client, server, NULL);
429	if (hostkeyalg == NULL)
430		fatal("no hostkey alg");
431	k->hostkey_type = key_type_from_name(hostkeyalg);
432	if (k->hostkey_type == KEY_UNSPEC)
433		fatal("bad hostkey alg '%s'", hostkeyalg);
434	free(hostkeyalg);
435}
436
437static int
438proposals_match(char *my[PROPOSAL_MAX], char *peer[PROPOSAL_MAX])
439{
440	static int check[] = {
441		PROPOSAL_KEX_ALGS, PROPOSAL_SERVER_HOST_KEY_ALGS, -1
442	};
443	int *idx;
444	char *p;
445
446	for (idx = &check[0]; *idx != -1; idx++) {
447		if ((p = strchr(my[*idx], ',')) != NULL)
448			*p = '\0';
449		if ((p = strchr(peer[*idx], ',')) != NULL)
450			*p = '\0';
451		if (strcmp(my[*idx], peer[*idx]) != 0) {
452			debug2("proposal mismatch: my %s peer %s",
453			    my[*idx], peer[*idx]);
454			return (0);
455		}
456	}
457	debug2("proposals match");
458	return (1);
459}
460
461static void
462kex_choose_conf(Kex *kex)
463{
464	Newkeys *newkeys;
465	char **my, **peer;
466	char **cprop, **sprop;
467	int nenc, nmac, ncomp;
468	u_int mode, ctos, need, dh_need, authlen;
469	int first_kex_follows, type;
470#ifdef	NONE_CIPHER_ENABLED
471	int auth_flag;
472#endif
473
474	my   = kex_buf2prop(&kex->my, NULL);
475	peer = kex_buf2prop(&kex->peer, &first_kex_follows);
476
477	if (kex->server) {
478		cprop=peer;
479		sprop=my;
480	} else {
481		cprop=my;
482		sprop=peer;
483	}
484
485	/* Check whether server offers roaming */
486	if (!kex->server) {
487		char *roaming;
488		roaming = match_list(KEX_RESUME, peer[PROPOSAL_KEX_ALGS], NULL);
489		if (roaming) {
490			kex->roaming = 1;
491			free(roaming);
492		}
493	}
494
495	/* Algorithm Negotiation */
496#ifdef	NONE_CIPHER_ENABLED
497	auth_flag = packet_get_authentication_state();
498	debug ("AUTH STATE is %d", auth_flag);
499#endif
500	for (mode = 0; mode < MODE_MAX; mode++) {
501		newkeys = xcalloc(1, sizeof(*newkeys));
502		kex->newkeys[mode] = newkeys;
503		ctos = (!kex->server && mode == MODE_OUT) ||
504		    (kex->server && mode == MODE_IN);
505		nenc  = ctos ? PROPOSAL_ENC_ALGS_CTOS  : PROPOSAL_ENC_ALGS_STOC;
506		nmac  = ctos ? PROPOSAL_MAC_ALGS_CTOS  : PROPOSAL_MAC_ALGS_STOC;
507		ncomp = ctos ? PROPOSAL_COMP_ALGS_CTOS : PROPOSAL_COMP_ALGS_STOC;
508		choose_enc(&newkeys->enc, cprop[nenc], sprop[nenc]);
509		/* ignore mac for authenticated encryption */
510		authlen = cipher_authlen(newkeys->enc.cipher);
511		if (authlen == 0)
512			choose_mac(&newkeys->mac, cprop[nmac], sprop[nmac]);
513		choose_comp(&newkeys->comp, cprop[ncomp], sprop[ncomp]);
514#ifdef	NONE_CIPHER_ENABLED
515		debug("REQUESTED ENC.NAME is '%s'", newkeys->enc.name);
516		if (strcmp(newkeys->enc.name, "none") == 0) {
517			debug("Requesting NONE. Authflag is %d", auth_flag);
518			if (auth_flag == 1)
519				debug("None requested post authentication.");
520			else
521				fatal("Pre-authentication none cipher requests "
522				    "are not allowed.");
523		}
524#endif
525		debug("kex: %s %s %s %s",
526		    ctos ? "client->server" : "server->client",
527		    newkeys->enc.name,
528		    authlen == 0 ? newkeys->mac.name : "<implicit>",
529		    newkeys->comp.name);
530	}
531	choose_kex(kex, cprop[PROPOSAL_KEX_ALGS], sprop[PROPOSAL_KEX_ALGS]);
532	choose_hostkeyalg(kex, cprop[PROPOSAL_SERVER_HOST_KEY_ALGS],
533	    sprop[PROPOSAL_SERVER_HOST_KEY_ALGS]);
534	need = dh_need = 0;
535	for (mode = 0; mode < MODE_MAX; mode++) {
536		newkeys = kex->newkeys[mode];
537		need = MAX(need, newkeys->enc.key_len);
538		need = MAX(need, newkeys->enc.block_size);
539		need = MAX(need, newkeys->enc.iv_len);
540		need = MAX(need, newkeys->mac.key_len);
541		dh_need = MAX(dh_need, cipher_seclen(newkeys->enc.cipher));
542		dh_need = MAX(dh_need, newkeys->enc.block_size);
543		dh_need = MAX(dh_need, newkeys->enc.iv_len);
544		dh_need = MAX(dh_need, newkeys->mac.key_len);
545	}
546	/* XXX need runden? */
547	kex->we_need = need;
548	kex->dh_need = dh_need;
549
550	/* ignore the next message if the proposals do not match */
551	if (first_kex_follows && !proposals_match(my, peer) &&
552	    !(datafellows & SSH_BUG_FIRSTKEX)) {
553		type = packet_read();
554		debug2("skipping next packet (type %u)", type);
555	}
556
557	kex_prop_free(my);
558	kex_prop_free(peer);
559}
560
561static u_char *
562derive_key(Kex *kex, int id, u_int need, u_char *hash, u_int hashlen,
563    const u_char *shared_secret, u_int slen)
564{
565	Buffer b;
566	struct ssh_digest_ctx *hashctx;
567	char c = id;
568	u_int have;
569	size_t mdsz;
570	u_char *digest;
571
572	if ((mdsz = ssh_digest_bytes(kex->hash_alg)) == 0)
573		fatal("bad kex md size %zu", mdsz);
574	digest = xmalloc(roundup(need, mdsz));
575
576	buffer_init(&b);
577	buffer_append(&b, shared_secret, slen);
578
579	/* K1 = HASH(K || H || "A" || session_id) */
580	if ((hashctx = ssh_digest_start(kex->hash_alg)) == NULL)
581		fatal("%s: ssh_digest_start failed", __func__);
582	if (ssh_digest_update_buffer(hashctx, &b) != 0 ||
583	    ssh_digest_update(hashctx, hash, hashlen) != 0 ||
584	    ssh_digest_update(hashctx, &c, 1) != 0 ||
585	    ssh_digest_update(hashctx, kex->session_id,
586	    kex->session_id_len) != 0)
587		fatal("%s: ssh_digest_update failed", __func__);
588	if (ssh_digest_final(hashctx, digest, mdsz) != 0)
589		fatal("%s: ssh_digest_final failed", __func__);
590	ssh_digest_free(hashctx);
591
592	/*
593	 * expand key:
594	 * Kn = HASH(K || H || K1 || K2 || ... || Kn-1)
595	 * Key = K1 || K2 || ... || Kn
596	 */
597	for (have = mdsz; need > have; have += mdsz) {
598		if ((hashctx = ssh_digest_start(kex->hash_alg)) == NULL)
599			fatal("%s: ssh_digest_start failed", __func__);
600		if (ssh_digest_update_buffer(hashctx, &b) != 0 ||
601		    ssh_digest_update(hashctx, hash, hashlen) != 0 ||
602		    ssh_digest_update(hashctx, digest, have) != 0)
603			fatal("%s: ssh_digest_update failed", __func__);
604		if (ssh_digest_final(hashctx, digest + have, mdsz) != 0)
605			fatal("%s: ssh_digest_final failed", __func__);
606		ssh_digest_free(hashctx);
607	}
608	buffer_free(&b);
609#ifdef DEBUG_KEX
610	fprintf(stderr, "key '%c'== ", c);
611	dump_digest("key", digest, need);
612#endif
613	return digest;
614}
615
616Newkeys *current_keys[MODE_MAX];
617
618#define NKEYS	6
619void
620kex_derive_keys(Kex *kex, u_char *hash, u_int hashlen,
621    const u_char *shared_secret, u_int slen)
622{
623	u_char *keys[NKEYS];
624	u_int i, mode, ctos;
625
626	for (i = 0; i < NKEYS; i++) {
627		keys[i] = derive_key(kex, 'A'+i, kex->we_need, hash, hashlen,
628		    shared_secret, slen);
629	}
630
631	debug2("kex_derive_keys");
632	for (mode = 0; mode < MODE_MAX; mode++) {
633		current_keys[mode] = kex->newkeys[mode];
634		kex->newkeys[mode] = NULL;
635		ctos = (!kex->server && mode == MODE_OUT) ||
636		    (kex->server && mode == MODE_IN);
637		current_keys[mode]->enc.iv  = keys[ctos ? 0 : 1];
638		current_keys[mode]->enc.key = keys[ctos ? 2 : 3];
639		current_keys[mode]->mac.key = keys[ctos ? 4 : 5];
640	}
641}
642
643void
644kex_derive_keys_bn(Kex *kex, u_char *hash, u_int hashlen, const BIGNUM *secret)
645{
646	Buffer shared_secret;
647
648	buffer_init(&shared_secret);
649	buffer_put_bignum2(&shared_secret, secret);
650	kex_derive_keys(kex, hash, hashlen,
651	    buffer_ptr(&shared_secret), buffer_len(&shared_secret));
652	buffer_free(&shared_secret);
653}
654
655Newkeys *
656kex_get_newkeys(int mode)
657{
658	Newkeys *ret;
659
660	ret = current_keys[mode];
661	current_keys[mode] = NULL;
662	return ret;
663}
664
665void
666derive_ssh1_session_id(BIGNUM *host_modulus, BIGNUM *server_modulus,
667    u_int8_t cookie[8], u_int8_t id[16])
668{
669	u_int8_t nbuf[2048], obuf[SSH_DIGEST_MAX_LENGTH];
670	int len;
671	struct ssh_digest_ctx *hashctx;
672
673	if ((hashctx = ssh_digest_start(SSH_DIGEST_MD5)) == NULL)
674		fatal("%s: ssh_digest_start", __func__);
675
676	len = BN_num_bytes(host_modulus);
677	if (len < (512 / 8) || (u_int)len > sizeof(nbuf))
678		fatal("%s: bad host modulus (len %d)", __func__, len);
679	BN_bn2bin(host_modulus, nbuf);
680	if (ssh_digest_update(hashctx, nbuf, len) != 0)
681		fatal("%s: ssh_digest_update failed", __func__);
682
683	len = BN_num_bytes(server_modulus);
684	if (len < (512 / 8) || (u_int)len > sizeof(nbuf))
685		fatal("%s: bad server modulus (len %d)", __func__, len);
686	BN_bn2bin(server_modulus, nbuf);
687	if (ssh_digest_update(hashctx, nbuf, len) != 0 ||
688	    ssh_digest_update(hashctx, cookie, 8) != 0)
689		fatal("%s: ssh_digest_update failed", __func__);
690	if (ssh_digest_final(hashctx, obuf, sizeof(obuf)) != 0)
691		fatal("%s: ssh_digest_final failed", __func__);
692	memcpy(id, obuf, ssh_digest_bytes(SSH_DIGEST_MD5));
693
694	memset(nbuf, 0, sizeof(nbuf));
695	memset(obuf, 0, sizeof(obuf));
696}
697
698#if defined(DEBUG_KEX) || defined(DEBUG_KEXDH) || defined(DEBUG_KEXECDH)
699void
700dump_digest(char *msg, u_char *digest, int len)
701{
702	int i;
703
704	fprintf(stderr, "%s\n", msg);
705	for (i = 0; i < len; i++) {
706		fprintf(stderr, "%02x", digest[i]);
707		if (i%32 == 31)
708			fprintf(stderr, "\n");
709		else if (i%8 == 7)
710			fprintf(stderr, " ");
711	}
712	fprintf(stderr, "\n");
713}
714#endif
715