kex.c revision 240075
1/* $OpenBSD: kex.c,v 1.86 2010/09/22 05:01:29 djm Exp $ */
2/* $FreeBSD: head/crypto/openssh/kex.c 240075 2012-09-03 16:51:41Z des $ */
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
29#include <sys/param.h>
30
31#include <signal.h>
32#include <stdarg.h>
33#include <stdio.h>
34#include <stdlib.h>
35#include <string.h>
36
37#include <openssl/crypto.h>
38
39#include "xmalloc.h"
40#include "ssh2.h"
41#include "buffer.h"
42#include "packet.h"
43#include "compat.h"
44#include "cipher.h"
45#include "key.h"
46#include "kex.h"
47#include "log.h"
48#include "mac.h"
49#include "match.h"
50#include "dispatch.h"
51#include "monitor.h"
52#include "roaming.h"
53
54#if OPENSSL_VERSION_NUMBER >= 0x00907000L
55# if defined(HAVE_EVP_SHA256)
56# define evp_ssh_sha256 EVP_sha256
57# else
58extern const EVP_MD *evp_ssh_sha256(void);
59# endif
60#endif
61
62/* prototype */
63static void kex_kexinit_finish(Kex *);
64static void kex_choose_conf(Kex *);
65
66/* Validate KEX method name list */
67int
68kex_names_valid(const char *names)
69{
70	char *s, *cp, *p;
71
72	if (names == NULL || strcmp(names, "") == 0)
73		return 0;
74	s = cp = xstrdup(names);
75	for ((p = strsep(&cp, ",")); p && *p != '\0';
76	    (p = strsep(&cp, ","))) {
77	    	if (strcmp(p, KEX_DHGEX_SHA256) != 0 &&
78		    strcmp(p, KEX_DHGEX_SHA1) != 0 &&
79		    strcmp(p, KEX_DH14) != 0 &&
80		    strcmp(p, KEX_DH1) != 0 &&
81		    (strncmp(p, KEX_ECDH_SHA2_STEM,
82		    sizeof(KEX_ECDH_SHA2_STEM) - 1) != 0 ||
83		    kex_ecdh_name_to_nid(p) == -1)) {
84			error("Unsupported KEX algorithm \"%.100s\"", p);
85			xfree(s);
86			return 0;
87		}
88	}
89	debug3("kex names ok: [%s]", names);
90	xfree(s);
91	return 1;
92}
93
94/* put algorithm proposal into buffer. */
95#ifndef NONE_CIPHER_ENABLED
96static void
97#else
98/* Also used in sshconnect2.c. */
99void
100#endif
101kex_prop2buf(Buffer *b, char *proposal[PROPOSAL_MAX])
102{
103	u_int i;
104
105	buffer_clear(b);
106	/*
107	 * add a dummy cookie, the cookie will be overwritten by
108	 * kex_send_kexinit(), each time a kexinit is set
109	 */
110	for (i = 0; i < KEX_COOKIE_LEN; i++)
111		buffer_put_char(b, 0);
112	for (i = 0; i < PROPOSAL_MAX; i++)
113		buffer_put_cstring(b, proposal[i]);
114	buffer_put_char(b, 0);			/* first_kex_packet_follows */
115	buffer_put_int(b, 0);			/* uint32 reserved */
116}
117
118/* parse buffer and return algorithm proposal */
119static char **
120kex_buf2prop(Buffer *raw, int *first_kex_follows)
121{
122	Buffer b;
123	u_int i;
124	char **proposal;
125
126	proposal = xcalloc(PROPOSAL_MAX, sizeof(char *));
127
128	buffer_init(&b);
129	buffer_append(&b, buffer_ptr(raw), buffer_len(raw));
130	/* skip cookie */
131	for (i = 0; i < KEX_COOKIE_LEN; i++)
132		buffer_get_char(&b);
133	/* extract kex init proposal strings */
134	for (i = 0; i < PROPOSAL_MAX; i++) {
135		proposal[i] = buffer_get_cstring(&b,NULL);
136		debug2("kex_parse_kexinit: %s", proposal[i]);
137	}
138	/* first kex follows / reserved */
139	i = buffer_get_char(&b);
140	if (first_kex_follows != NULL)
141		*first_kex_follows = i;
142	debug2("kex_parse_kexinit: first_kex_follows %d ", i);
143	i = buffer_get_int(&b);
144	debug2("kex_parse_kexinit: reserved %u ", i);
145	buffer_free(&b);
146	return proposal;
147}
148
149static void
150kex_prop_free(char **proposal)
151{
152	u_int i;
153
154	for (i = 0; i < PROPOSAL_MAX; i++)
155		xfree(proposal[i]);
156	xfree(proposal);
157}
158
159/* ARGSUSED */
160static void
161kex_protocol_error(int type, u_int32_t seq, void *ctxt)
162{
163	error("Hm, kex protocol error: type %d seq %u", type, seq);
164}
165
166static void
167kex_reset_dispatch(void)
168{
169	dispatch_range(SSH2_MSG_TRANSPORT_MIN,
170	    SSH2_MSG_TRANSPORT_MAX, &kex_protocol_error);
171	dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
172}
173
174void
175kex_finish(Kex *kex)
176{
177	kex_reset_dispatch();
178
179	packet_start(SSH2_MSG_NEWKEYS);
180	packet_send();
181	/* packet_write_wait(); */
182	debug("SSH2_MSG_NEWKEYS sent");
183
184	debug("expecting SSH2_MSG_NEWKEYS");
185	packet_read_expect(SSH2_MSG_NEWKEYS);
186	packet_check_eom();
187	debug("SSH2_MSG_NEWKEYS received");
188
189	kex->done = 1;
190	buffer_clear(&kex->peer);
191	/* buffer_clear(&kex->my); */
192	kex->flags &= ~KEX_INIT_SENT;
193	xfree(kex->name);
194	kex->name = NULL;
195}
196
197void
198kex_send_kexinit(Kex *kex)
199{
200	u_int32_t rnd = 0;
201	u_char *cookie;
202	u_int i;
203
204	if (kex == NULL) {
205		error("kex_send_kexinit: no kex, cannot rekey");
206		return;
207	}
208	if (kex->flags & KEX_INIT_SENT) {
209		debug("KEX_INIT_SENT");
210		return;
211	}
212	kex->done = 0;
213
214	/* generate a random cookie */
215	if (buffer_len(&kex->my) < KEX_COOKIE_LEN)
216		fatal("kex_send_kexinit: kex proposal too short");
217	cookie = buffer_ptr(&kex->my);
218	for (i = 0; i < KEX_COOKIE_LEN; i++) {
219		if (i % 4 == 0)
220			rnd = arc4random();
221		cookie[i] = rnd;
222		rnd >>= 8;
223	}
224	packet_start(SSH2_MSG_KEXINIT);
225	packet_put_raw(buffer_ptr(&kex->my), buffer_len(&kex->my));
226	packet_send();
227	debug("SSH2_MSG_KEXINIT sent");
228	kex->flags |= KEX_INIT_SENT;
229}
230
231/* ARGSUSED */
232void
233kex_input_kexinit(int type, u_int32_t seq, void *ctxt)
234{
235	char *ptr;
236	u_int i, dlen;
237	Kex *kex = (Kex *)ctxt;
238
239	debug("SSH2_MSG_KEXINIT received");
240	if (kex == NULL)
241		fatal("kex_input_kexinit: no kex, cannot rekey");
242
243	ptr = packet_get_raw(&dlen);
244	buffer_append(&kex->peer, ptr, dlen);
245
246	/* discard packet */
247	for (i = 0; i < KEX_COOKIE_LEN; i++)
248		packet_get_char();
249	for (i = 0; i < PROPOSAL_MAX; i++)
250		xfree(packet_get_string(NULL));
251	(void) packet_get_char();
252	(void) packet_get_int();
253	packet_check_eom();
254
255	kex_kexinit_finish(kex);
256}
257
258Kex *
259kex_setup(char *proposal[PROPOSAL_MAX])
260{
261	Kex *kex;
262
263	kex = xcalloc(1, sizeof(*kex));
264	buffer_init(&kex->peer);
265	buffer_init(&kex->my);
266	kex_prop2buf(&kex->my, proposal);
267	kex->done = 0;
268
269	kex_send_kexinit(kex);					/* we start */
270	kex_reset_dispatch();
271
272	return kex;
273}
274
275static void
276kex_kexinit_finish(Kex *kex)
277{
278	if (!(kex->flags & KEX_INIT_SENT))
279		kex_send_kexinit(kex);
280
281	kex_choose_conf(kex);
282
283	if (kex->kex_type >= 0 && kex->kex_type < KEX_MAX &&
284	    kex->kex[kex->kex_type] != NULL) {
285		(kex->kex[kex->kex_type])(kex);
286	} else {
287		fatal("Unsupported key exchange %d", kex->kex_type);
288	}
289}
290
291static void
292choose_enc(Enc *enc, char *client, char *server)
293{
294	char *name = match_list(client, server, NULL);
295	if (name == NULL)
296		fatal("no matching cipher found: client %s server %s",
297		    client, server);
298	if ((enc->cipher = cipher_by_name(name)) == NULL)
299		fatal("matching cipher is not supported: %s", name);
300	enc->name = name;
301	enc->enabled = 0;
302	enc->iv = NULL;
303	enc->key = NULL;
304	enc->key_len = cipher_keylen(enc->cipher);
305	enc->block_size = cipher_blocksize(enc->cipher);
306}
307
308static void
309choose_mac(Mac *mac, char *client, char *server)
310{
311	char *name = match_list(client, server, NULL);
312	if (name == NULL)
313		fatal("no matching mac found: client %s server %s",
314		    client, server);
315	if (mac_setup(mac, name) < 0)
316		fatal("unsupported mac %s", name);
317	/* truncate the key */
318	if (datafellows & SSH_BUG_HMAC)
319		mac->key_len = 16;
320	mac->name = name;
321	mac->key = NULL;
322	mac->enabled = 0;
323}
324
325static void
326choose_comp(Comp *comp, char *client, char *server)
327{
328	char *name = match_list(client, server, NULL);
329	if (name == NULL)
330		fatal("no matching comp found: client %s server %s", client, server);
331	if (strcmp(name, "zlib@openssh.com") == 0) {
332		comp->type = COMP_DELAYED;
333	} else if (strcmp(name, "zlib") == 0) {
334		comp->type = COMP_ZLIB;
335	} else if (strcmp(name, "none") == 0) {
336		comp->type = COMP_NONE;
337	} else {
338		fatal("unsupported comp %s", name);
339	}
340	comp->name = name;
341}
342
343static void
344choose_kex(Kex *k, char *client, char *server)
345{
346	k->name = match_list(client, server, NULL);
347	if (k->name == NULL)
348		fatal("Unable to negotiate a key exchange method");
349	if (strcmp(k->name, KEX_DH1) == 0) {
350		k->kex_type = KEX_DH_GRP1_SHA1;
351		k->evp_md = EVP_sha1();
352	} else if (strcmp(k->name, KEX_DH14) == 0) {
353		k->kex_type = KEX_DH_GRP14_SHA1;
354		k->evp_md = EVP_sha1();
355	} else if (strcmp(k->name, KEX_DHGEX_SHA1) == 0) {
356		k->kex_type = KEX_DH_GEX_SHA1;
357		k->evp_md = EVP_sha1();
358#if OPENSSL_VERSION_NUMBER >= 0x00907000L
359	} else if (strcmp(k->name, KEX_DHGEX_SHA256) == 0) {
360		k->kex_type = KEX_DH_GEX_SHA256;
361		k->evp_md = evp_ssh_sha256();
362	} else if (strncmp(k->name, KEX_ECDH_SHA2_STEM,
363	    sizeof(KEX_ECDH_SHA2_STEM) - 1) == 0) {
364 		k->kex_type = KEX_ECDH_SHA2;
365		k->evp_md = kex_ecdh_name_to_evpmd(k->name);
366#endif
367	} else
368		fatal("bad kex alg %s", k->name);
369}
370
371static void
372choose_hostkeyalg(Kex *k, char *client, char *server)
373{
374	char *hostkeyalg = match_list(client, server, NULL);
375	if (hostkeyalg == NULL)
376		fatal("no hostkey alg");
377	k->hostkey_type = key_type_from_name(hostkeyalg);
378	if (k->hostkey_type == KEY_UNSPEC)
379		fatal("bad hostkey alg '%s'", hostkeyalg);
380	xfree(hostkeyalg);
381}
382
383static int
384proposals_match(char *my[PROPOSAL_MAX], char *peer[PROPOSAL_MAX])
385{
386	static int check[] = {
387		PROPOSAL_KEX_ALGS, PROPOSAL_SERVER_HOST_KEY_ALGS, -1
388	};
389	int *idx;
390	char *p;
391
392	for (idx = &check[0]; *idx != -1; idx++) {
393		if ((p = strchr(my[*idx], ',')) != NULL)
394			*p = '\0';
395		if ((p = strchr(peer[*idx], ',')) != NULL)
396			*p = '\0';
397		if (strcmp(my[*idx], peer[*idx]) != 0) {
398			debug2("proposal mismatch: my %s peer %s",
399			    my[*idx], peer[*idx]);
400			return (0);
401		}
402	}
403	debug2("proposals match");
404	return (1);
405}
406
407static void
408kex_choose_conf(Kex *kex)
409{
410	Newkeys *newkeys;
411	char **my, **peer;
412	char **cprop, **sprop;
413	int nenc, nmac, ncomp;
414	u_int mode, ctos, need;
415	int first_kex_follows, type;
416#ifdef	NONE_CIPHER_ENABLED
417	int auth_flag;
418#endif
419
420	my   = kex_buf2prop(&kex->my, NULL);
421	peer = kex_buf2prop(&kex->peer, &first_kex_follows);
422
423	if (kex->server) {
424		cprop=peer;
425		sprop=my;
426	} else {
427		cprop=my;
428		sprop=peer;
429	}
430
431	/* Check whether server offers roaming */
432	if (!kex->server) {
433		char *roaming;
434		roaming = match_list(KEX_RESUME, peer[PROPOSAL_KEX_ALGS], NULL);
435		if (roaming) {
436			kex->roaming = 1;
437			xfree(roaming);
438		}
439	}
440
441	/* Algorithm Negotiation */
442#ifdef	NONE_CIPHER_ENABLED
443	auth_flag = packet_get_authentication_state();
444	debug ("AUTH STATE is %d", auth_flag);
445#endif
446	for (mode = 0; mode < MODE_MAX; mode++) {
447		newkeys = xcalloc(1, sizeof(*newkeys));
448		kex->newkeys[mode] = newkeys;
449		ctos = (!kex->server && mode == MODE_OUT) ||
450		    (kex->server && mode == MODE_IN);
451		nenc  = ctos ? PROPOSAL_ENC_ALGS_CTOS  : PROPOSAL_ENC_ALGS_STOC;
452		nmac  = ctos ? PROPOSAL_MAC_ALGS_CTOS  : PROPOSAL_MAC_ALGS_STOC;
453		ncomp = ctos ? PROPOSAL_COMP_ALGS_CTOS : PROPOSAL_COMP_ALGS_STOC;
454		choose_enc (&newkeys->enc,  cprop[nenc],  sprop[nenc]);
455		choose_mac (&newkeys->mac,  cprop[nmac],  sprop[nmac]);
456		choose_comp(&newkeys->comp, cprop[ncomp], sprop[ncomp]);
457#ifdef	NONE_CIPHER_ENABLED
458		debug("REQUESTED ENC.NAME is '%s'", newkeys->enc.name);
459		if (strcmp(newkeys->enc.name, "none") == 0) {
460			debug("Requesting NONE. Authflag is %d", auth_flag);
461			if (auth_flag == 1)
462				debug("None requested post authentication.");
463			else
464				fatal("Pre-authentication none cipher requests "
465				    "are not allowed.");
466		}
467#endif
468		debug("kex: %s %s %s %s",
469		    ctos ? "client->server" : "server->client",
470		    newkeys->enc.name,
471		    newkeys->mac.name,
472		    newkeys->comp.name);
473	}
474	choose_kex(kex, cprop[PROPOSAL_KEX_ALGS], sprop[PROPOSAL_KEX_ALGS]);
475	choose_hostkeyalg(kex, cprop[PROPOSAL_SERVER_HOST_KEY_ALGS],
476	    sprop[PROPOSAL_SERVER_HOST_KEY_ALGS]);
477	need = 0;
478	for (mode = 0; mode < MODE_MAX; mode++) {
479		newkeys = kex->newkeys[mode];
480		if (need < newkeys->enc.key_len)
481			need = newkeys->enc.key_len;
482		if (need < newkeys->enc.block_size)
483			need = newkeys->enc.block_size;
484		if (need < newkeys->mac.key_len)
485			need = newkeys->mac.key_len;
486	}
487	/* XXX need runden? */
488	kex->we_need = need;
489
490	/* ignore the next message if the proposals do not match */
491	if (first_kex_follows && !proposals_match(my, peer) &&
492	    !(datafellows & SSH_BUG_FIRSTKEX)) {
493		type = packet_read();
494		debug2("skipping next packet (type %u)", type);
495	}
496
497	kex_prop_free(my);
498	kex_prop_free(peer);
499}
500
501static u_char *
502derive_key(Kex *kex, int id, u_int need, u_char *hash, u_int hashlen,
503    BIGNUM *shared_secret)
504{
505	Buffer b;
506	EVP_MD_CTX md;
507	char c = id;
508	u_int have;
509	int mdsz;
510	u_char *digest;
511
512	if ((mdsz = EVP_MD_size(kex->evp_md)) <= 0)
513		fatal("bad kex md size %d", mdsz);
514	digest = xmalloc(roundup(need, mdsz));
515
516	buffer_init(&b);
517	buffer_put_bignum2(&b, shared_secret);
518
519	/* K1 = HASH(K || H || "A" || session_id) */
520	EVP_DigestInit(&md, kex->evp_md);
521	if (!(datafellows & SSH_BUG_DERIVEKEY))
522		EVP_DigestUpdate(&md, buffer_ptr(&b), buffer_len(&b));
523	EVP_DigestUpdate(&md, hash, hashlen);
524	EVP_DigestUpdate(&md, &c, 1);
525	EVP_DigestUpdate(&md, kex->session_id, kex->session_id_len);
526	EVP_DigestFinal(&md, digest, NULL);
527
528	/*
529	 * expand key:
530	 * Kn = HASH(K || H || K1 || K2 || ... || Kn-1)
531	 * Key = K1 || K2 || ... || Kn
532	 */
533	for (have = mdsz; need > have; have += mdsz) {
534		EVP_DigestInit(&md, kex->evp_md);
535		if (!(datafellows & SSH_BUG_DERIVEKEY))
536			EVP_DigestUpdate(&md, buffer_ptr(&b), buffer_len(&b));
537		EVP_DigestUpdate(&md, hash, hashlen);
538		EVP_DigestUpdate(&md, digest, have);
539		EVP_DigestFinal(&md, digest + have, NULL);
540	}
541	buffer_free(&b);
542#ifdef DEBUG_KEX
543	fprintf(stderr, "key '%c'== ", c);
544	dump_digest("key", digest, need);
545#endif
546	return digest;
547}
548
549Newkeys *current_keys[MODE_MAX];
550
551#define NKEYS	6
552void
553kex_derive_keys(Kex *kex, u_char *hash, u_int hashlen, BIGNUM *shared_secret)
554{
555	u_char *keys[NKEYS];
556	u_int i, mode, ctos;
557
558	for (i = 0; i < NKEYS; i++) {
559		keys[i] = derive_key(kex, 'A'+i, kex->we_need, hash, hashlen,
560		    shared_secret);
561	}
562
563	debug2("kex_derive_keys");
564	for (mode = 0; mode < MODE_MAX; mode++) {
565		current_keys[mode] = kex->newkeys[mode];
566		kex->newkeys[mode] = NULL;
567		ctos = (!kex->server && mode == MODE_OUT) ||
568		    (kex->server && mode == MODE_IN);
569		current_keys[mode]->enc.iv  = keys[ctos ? 0 : 1];
570		current_keys[mode]->enc.key = keys[ctos ? 2 : 3];
571		current_keys[mode]->mac.key = keys[ctos ? 4 : 5];
572	}
573}
574
575Newkeys *
576kex_get_newkeys(int mode)
577{
578	Newkeys *ret;
579
580	ret = current_keys[mode];
581	current_keys[mode] = NULL;
582	return ret;
583}
584
585void
586derive_ssh1_session_id(BIGNUM *host_modulus, BIGNUM *server_modulus,
587    u_int8_t cookie[8], u_int8_t id[16])
588{
589	const EVP_MD *evp_md = EVP_md5();
590	EVP_MD_CTX md;
591	u_int8_t nbuf[2048], obuf[EVP_MAX_MD_SIZE];
592	int len;
593
594	EVP_DigestInit(&md, evp_md);
595
596	len = BN_num_bytes(host_modulus);
597	if (len < (512 / 8) || (u_int)len > sizeof(nbuf))
598		fatal("%s: bad host modulus (len %d)", __func__, len);
599	BN_bn2bin(host_modulus, nbuf);
600	EVP_DigestUpdate(&md, nbuf, len);
601
602	len = BN_num_bytes(server_modulus);
603	if (len < (512 / 8) || (u_int)len > sizeof(nbuf))
604		fatal("%s: bad server modulus (len %d)", __func__, len);
605	BN_bn2bin(server_modulus, nbuf);
606	EVP_DigestUpdate(&md, nbuf, len);
607
608	EVP_DigestUpdate(&md, cookie, 8);
609
610	EVP_DigestFinal(&md, obuf, NULL);
611	memcpy(id, obuf, 16);
612
613	memset(nbuf, 0, sizeof(nbuf));
614	memset(obuf, 0, sizeof(obuf));
615	memset(&md, 0, sizeof(md));
616}
617
618#if defined(DEBUG_KEX) || defined(DEBUG_KEXDH) || defined(DEBUG_KEXECDH)
619void
620dump_digest(char *msg, u_char *digest, int len)
621{
622	int i;
623
624	fprintf(stderr, "%s\n", msg);
625	for (i = 0; i < len; i++) {
626		fprintf(stderr, "%02x", digest[i]);
627		if (i%32 == 31)
628			fprintf(stderr, "\n");
629		else if (i%8 == 7)
630			fprintf(stderr, " ");
631	}
632	fprintf(stderr, "\n");
633}
634#endif
635