kex.c revision 1.93
1/* $OpenBSD: kex.c,v 1.93 2013/11/07 11:58:27 dtucker Exp $ */
2/*
3 * Copyright (c) 2000, 2001 Markus Friedl.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 *
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
18 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26#include <sys/param.h>
27
28#include <signal.h>
29#include <stdio.h>
30#include <stdlib.h>
31#include <string.h>
32
33#include <openssl/crypto.h>
34
35#include "xmalloc.h"
36#include "ssh2.h"
37#include "buffer.h"
38#include "packet.h"
39#include "compat.h"
40#include "cipher.h"
41#include "key.h"
42#include "kex.h"
43#include "log.h"
44#include "mac.h"
45#include "match.h"
46#include "dispatch.h"
47#include "monitor.h"
48#include "roaming.h"
49
50/* prototype */
51static void kex_kexinit_finish(Kex *);
52static void kex_choose_conf(Kex *);
53
54struct kexalg {
55	char *name;
56	int type;
57	int ec_nid;
58	const EVP_MD *(*mdfunc)(void);
59};
60static const struct kexalg kexalgs[] = {
61	{ KEX_DH1, KEX_DH_GRP1_SHA1, 0, EVP_sha1 },
62	{ KEX_DH14, KEX_DH_GRP14_SHA1, 0, EVP_sha1 },
63	{ KEX_DHGEX_SHA1, KEX_DH_GEX_SHA1, 0, EVP_sha1 },
64	{ KEX_DHGEX_SHA256, KEX_DH_GEX_SHA256, 0, EVP_sha256 },
65	{ KEX_ECDH_SHA2_NISTP256, KEX_ECDH_SHA2, NID_X9_62_prime256v1, EVP_sha256 },
66	{ KEX_ECDH_SHA2_NISTP384, KEX_ECDH_SHA2, NID_secp384r1, EVP_sha384 },
67	{ KEX_ECDH_SHA2_NISTP521, KEX_ECDH_SHA2, NID_secp521r1, EVP_sha512 },
68	{ KEX_CURVE25519_SHA256, KEX_C25519_SHA256, 0, EVP_sha256 },
69	{ NULL, -1, -1, NULL},
70};
71
72char *
73kex_alg_list(char sep)
74{
75	char *ret = NULL;
76	size_t nlen, rlen = 0;
77	const struct kexalg *k;
78
79	for (k = kexalgs; k->name != NULL; k++) {
80		if (ret != NULL)
81			ret[rlen++] = sep;
82		nlen = strlen(k->name);
83		ret = xrealloc(ret, 1, rlen + nlen + 2);
84		memcpy(ret + rlen, k->name, nlen + 1);
85		rlen += nlen;
86	}
87	return ret;
88}
89
90static const struct kexalg *
91kex_alg_by_name(const char *name)
92{
93	const struct kexalg *k;
94
95	for (k = kexalgs; k->name != NULL; k++) {
96		if (strcmp(k->name, name) == 0)
97			return k;
98	}
99	return NULL;
100}
101
102/* Validate KEX method name list */
103int
104kex_names_valid(const char *names)
105{
106	char *s, *cp, *p;
107
108	if (names == NULL || strcmp(names, "") == 0)
109		return 0;
110	s = cp = xstrdup(names);
111	for ((p = strsep(&cp, ",")); p && *p != '\0';
112	    (p = strsep(&cp, ","))) {
113		if (kex_alg_by_name(p) == NULL) {
114			error("Unsupported KEX algorithm \"%.100s\"", p);
115			free(s);
116			return 0;
117		}
118	}
119	debug3("kex names ok: [%s]", names);
120	free(s);
121	return 1;
122}
123
124/* put algorithm proposal into buffer */
125static void
126kex_prop2buf(Buffer *b, char *proposal[PROPOSAL_MAX])
127{
128	u_int i;
129
130	buffer_clear(b);
131	/*
132	 * add a dummy cookie, the cookie will be overwritten by
133	 * kex_send_kexinit(), each time a kexinit is set
134	 */
135	for (i = 0; i < KEX_COOKIE_LEN; i++)
136		buffer_put_char(b, 0);
137	for (i = 0; i < PROPOSAL_MAX; i++)
138		buffer_put_cstring(b, proposal[i]);
139	buffer_put_char(b, 0);			/* first_kex_packet_follows */
140	buffer_put_int(b, 0);			/* uint32 reserved */
141}
142
143/* parse buffer and return algorithm proposal */
144static char **
145kex_buf2prop(Buffer *raw, int *first_kex_follows)
146{
147	Buffer b;
148	u_int i;
149	char **proposal;
150
151	proposal = xcalloc(PROPOSAL_MAX, sizeof(char *));
152
153	buffer_init(&b);
154	buffer_append(&b, buffer_ptr(raw), buffer_len(raw));
155	/* skip cookie */
156	for (i = 0; i < KEX_COOKIE_LEN; i++)
157		buffer_get_char(&b);
158	/* extract kex init proposal strings */
159	for (i = 0; i < PROPOSAL_MAX; i++) {
160		proposal[i] = buffer_get_cstring(&b,NULL);
161		debug2("kex_parse_kexinit: %s", proposal[i]);
162	}
163	/* first kex follows / reserved */
164	i = buffer_get_char(&b);
165	if (first_kex_follows != NULL)
166		*first_kex_follows = i;
167	debug2("kex_parse_kexinit: first_kex_follows %d ", i);
168	i = buffer_get_int(&b);
169	debug2("kex_parse_kexinit: reserved %u ", i);
170	buffer_free(&b);
171	return proposal;
172}
173
174static void
175kex_prop_free(char **proposal)
176{
177	u_int i;
178
179	for (i = 0; i < PROPOSAL_MAX; i++)
180		free(proposal[i]);
181	free(proposal);
182}
183
184/* ARGSUSED */
185static void
186kex_protocol_error(int type, u_int32_t seq, void *ctxt)
187{
188	error("Hm, kex protocol error: type %d seq %u", type, seq);
189}
190
191static void
192kex_reset_dispatch(void)
193{
194	dispatch_range(SSH2_MSG_TRANSPORT_MIN,
195	    SSH2_MSG_TRANSPORT_MAX, &kex_protocol_error);
196	dispatch_set(SSH2_MSG_KEXINIT, &kex_input_kexinit);
197}
198
199void
200kex_finish(Kex *kex)
201{
202	kex_reset_dispatch();
203
204	packet_start(SSH2_MSG_NEWKEYS);
205	packet_send();
206	/* packet_write_wait(); */
207	debug("SSH2_MSG_NEWKEYS sent");
208
209	debug("expecting SSH2_MSG_NEWKEYS");
210	packet_read_expect(SSH2_MSG_NEWKEYS);
211	packet_check_eom();
212	debug("SSH2_MSG_NEWKEYS received");
213
214	kex->done = 1;
215	buffer_clear(&kex->peer);
216	/* buffer_clear(&kex->my); */
217	kex->flags &= ~KEX_INIT_SENT;
218	free(kex->name);
219	kex->name = NULL;
220}
221
222void
223kex_send_kexinit(Kex *kex)
224{
225	u_int32_t rnd = 0;
226	u_char *cookie;
227	u_int i;
228
229	if (kex == NULL) {
230		error("kex_send_kexinit: no kex, cannot rekey");
231		return;
232	}
233	if (kex->flags & KEX_INIT_SENT) {
234		debug("KEX_INIT_SENT");
235		return;
236	}
237	kex->done = 0;
238
239	/* generate a random cookie */
240	if (buffer_len(&kex->my) < KEX_COOKIE_LEN)
241		fatal("kex_send_kexinit: kex proposal too short");
242	cookie = buffer_ptr(&kex->my);
243	for (i = 0; i < KEX_COOKIE_LEN; i++) {
244		if (i % 4 == 0)
245			rnd = arc4random();
246		cookie[i] = rnd;
247		rnd >>= 8;
248	}
249	packet_start(SSH2_MSG_KEXINIT);
250	packet_put_raw(buffer_ptr(&kex->my), buffer_len(&kex->my));
251	packet_send();
252	debug("SSH2_MSG_KEXINIT sent");
253	kex->flags |= KEX_INIT_SENT;
254}
255
256/* ARGSUSED */
257void
258kex_input_kexinit(int type, u_int32_t seq, void *ctxt)
259{
260	char *ptr;
261	u_int i, dlen;
262	Kex *kex = (Kex *)ctxt;
263
264	debug("SSH2_MSG_KEXINIT received");
265	if (kex == NULL)
266		fatal("kex_input_kexinit: no kex, cannot rekey");
267
268	ptr = packet_get_raw(&dlen);
269	buffer_append(&kex->peer, ptr, dlen);
270
271	/* discard packet */
272	for (i = 0; i < KEX_COOKIE_LEN; i++)
273		packet_get_char();
274	for (i = 0; i < PROPOSAL_MAX; i++)
275		free(packet_get_string(NULL));
276	/*
277	 * XXX RFC4253 sec 7: "each side MAY guess" - currently no supported
278	 * KEX method has the server move first, but a server might be using
279	 * a custom method or one that we otherwise don't support. We should
280	 * be prepared to remember first_kex_follows here so we can eat a
281	 * packet later.
282	 * XXX2 - RFC4253 is kind of ambiguous on what first_kex_follows means
283	 * for cases where the server *doesn't* go first. I guess we should
284	 * ignore it when it is set for these cases, which is what we do now.
285	 */
286	(void) packet_get_char();	/* first_kex_follows */
287	(void) packet_get_int();	/* reserved */
288	packet_check_eom();
289
290	kex_kexinit_finish(kex);
291}
292
293Kex *
294kex_setup(char *proposal[PROPOSAL_MAX])
295{
296	Kex *kex;
297
298	kex = xcalloc(1, sizeof(*kex));
299	buffer_init(&kex->peer);
300	buffer_init(&kex->my);
301	kex_prop2buf(&kex->my, proposal);
302	kex->done = 0;
303
304	kex_send_kexinit(kex);					/* we start */
305	kex_reset_dispatch();
306
307	return kex;
308}
309
310static void
311kex_kexinit_finish(Kex *kex)
312{
313	if (!(kex->flags & KEX_INIT_SENT))
314		kex_send_kexinit(kex);
315
316	kex_choose_conf(kex);
317
318	if (kex->kex_type >= 0 && kex->kex_type < KEX_MAX &&
319	    kex->kex[kex->kex_type] != NULL) {
320		(kex->kex[kex->kex_type])(kex);
321	} else {
322		fatal("Unsupported key exchange %d", kex->kex_type);
323	}
324}
325
326static void
327choose_enc(Enc *enc, char *client, char *server)
328{
329	char *name = match_list(client, server, NULL);
330	if (name == NULL)
331		fatal("no matching cipher found: client %s server %s",
332		    client, server);
333	if ((enc->cipher = cipher_by_name(name)) == NULL)
334		fatal("matching cipher is not supported: %s", name);
335	enc->name = name;
336	enc->enabled = 0;
337	enc->iv = NULL;
338	enc->iv_len = cipher_ivlen(enc->cipher);
339	enc->key = NULL;
340	enc->key_len = cipher_keylen(enc->cipher);
341	enc->block_size = cipher_blocksize(enc->cipher);
342}
343
344static void
345choose_mac(Mac *mac, char *client, char *server)
346{
347	char *name = match_list(client, server, NULL);
348	if (name == NULL)
349		fatal("no matching mac found: client %s server %s",
350		    client, server);
351	if (mac_setup(mac, name) < 0)
352		fatal("unsupported mac %s", name);
353	/* truncate the key */
354	if (datafellows & SSH_BUG_HMAC)
355		mac->key_len = 16;
356	mac->name = name;
357	mac->key = NULL;
358	mac->enabled = 0;
359}
360
361static void
362choose_comp(Comp *comp, char *client, char *server)
363{
364	char *name = match_list(client, server, NULL);
365	if (name == NULL)
366		fatal("no matching comp found: client %s server %s", client, server);
367	if (strcmp(name, "zlib@openssh.com") == 0) {
368		comp->type = COMP_DELAYED;
369	} else if (strcmp(name, "zlib") == 0) {
370		comp->type = COMP_ZLIB;
371	} else if (strcmp(name, "none") == 0) {
372		comp->type = COMP_NONE;
373	} else {
374		fatal("unsupported comp %s", name);
375	}
376	comp->name = name;
377}
378
379static void
380choose_kex(Kex *k, char *client, char *server)
381{
382	const struct kexalg *kexalg;
383
384	k->name = match_list(client, server, NULL);
385	if (k->name == NULL)
386		fatal("Unable to negotiate a key exchange method");
387	if ((kexalg = kex_alg_by_name(k->name)) == NULL)
388		fatal("unsupported kex alg %s", k->name);
389	k->kex_type = kexalg->type;
390	k->evp_md = kexalg->mdfunc();
391	k->ec_nid = kexalg->ec_nid;
392}
393
394static void
395choose_hostkeyalg(Kex *k, char *client, char *server)
396{
397	char *hostkeyalg = match_list(client, server, NULL);
398	if (hostkeyalg == NULL)
399		fatal("no hostkey alg");
400	k->hostkey_type = key_type_from_name(hostkeyalg);
401	if (k->hostkey_type == KEY_UNSPEC)
402		fatal("bad hostkey alg '%s'", hostkeyalg);
403	free(hostkeyalg);
404}
405
406static int
407proposals_match(char *my[PROPOSAL_MAX], char *peer[PROPOSAL_MAX])
408{
409	static int check[] = {
410		PROPOSAL_KEX_ALGS, PROPOSAL_SERVER_HOST_KEY_ALGS, -1
411	};
412	int *idx;
413	char *p;
414
415	for (idx = &check[0]; *idx != -1; idx++) {
416		if ((p = strchr(my[*idx], ',')) != NULL)
417			*p = '\0';
418		if ((p = strchr(peer[*idx], ',')) != NULL)
419			*p = '\0';
420		if (strcmp(my[*idx], peer[*idx]) != 0) {
421			debug2("proposal mismatch: my %s peer %s",
422			    my[*idx], peer[*idx]);
423			return (0);
424		}
425	}
426	debug2("proposals match");
427	return (1);
428}
429
430static void
431kex_choose_conf(Kex *kex)
432{
433	Newkeys *newkeys;
434	char **my, **peer;
435	char **cprop, **sprop;
436	int nenc, nmac, ncomp;
437	u_int mode, ctos, need, authlen;
438	int first_kex_follows, type;
439
440	my   = kex_buf2prop(&kex->my, NULL);
441	peer = kex_buf2prop(&kex->peer, &first_kex_follows);
442
443	if (kex->server) {
444		cprop=peer;
445		sprop=my;
446	} else {
447		cprop=my;
448		sprop=peer;
449	}
450
451	/* Check whether server offers roaming */
452	if (!kex->server) {
453		char *roaming;
454		roaming = match_list(KEX_RESUME, peer[PROPOSAL_KEX_ALGS], NULL);
455		if (roaming) {
456			kex->roaming = 1;
457			free(roaming);
458		}
459	}
460
461	/* Algorithm Negotiation */
462	for (mode = 0; mode < MODE_MAX; mode++) {
463		newkeys = xcalloc(1, sizeof(*newkeys));
464		kex->newkeys[mode] = newkeys;
465		ctos = (!kex->server && mode == MODE_OUT) ||
466		    (kex->server && mode == MODE_IN);
467		nenc  = ctos ? PROPOSAL_ENC_ALGS_CTOS  : PROPOSAL_ENC_ALGS_STOC;
468		nmac  = ctos ? PROPOSAL_MAC_ALGS_CTOS  : PROPOSAL_MAC_ALGS_STOC;
469		ncomp = ctos ? PROPOSAL_COMP_ALGS_CTOS : PROPOSAL_COMP_ALGS_STOC;
470		choose_enc(&newkeys->enc, cprop[nenc], sprop[nenc]);
471		/* ignore mac for authenticated encryption */
472		authlen = cipher_authlen(newkeys->enc.cipher);
473		if (authlen == 0)
474			choose_mac(&newkeys->mac, cprop[nmac], sprop[nmac]);
475		choose_comp(&newkeys->comp, cprop[ncomp], sprop[ncomp]);
476		debug("kex: %s %s %s %s",
477		    ctos ? "client->server" : "server->client",
478		    newkeys->enc.name,
479		    authlen == 0 ? newkeys->mac.name : "<implicit>",
480		    newkeys->comp.name);
481	}
482	choose_kex(kex, cprop[PROPOSAL_KEX_ALGS], sprop[PROPOSAL_KEX_ALGS]);
483	choose_hostkeyalg(kex, cprop[PROPOSAL_SERVER_HOST_KEY_ALGS],
484	    sprop[PROPOSAL_SERVER_HOST_KEY_ALGS]);
485	need = 0;
486	for (mode = 0; mode < MODE_MAX; mode++) {
487		newkeys = kex->newkeys[mode];
488		if (need < newkeys->enc.key_len)
489			need = newkeys->enc.key_len;
490		if (need < newkeys->enc.block_size)
491			need = newkeys->enc.block_size;
492		if (need < newkeys->enc.iv_len)
493			need = newkeys->enc.iv_len;
494		if (need < newkeys->mac.key_len)
495			need = newkeys->mac.key_len;
496	}
497	/* XXX need runden? */
498	kex->we_need = need;
499
500	/* ignore the next message if the proposals do not match */
501	if (first_kex_follows && !proposals_match(my, peer) &&
502	    !(datafellows & SSH_BUG_FIRSTKEX)) {
503		type = packet_read();
504		debug2("skipping next packet (type %u)", type);
505	}
506
507	kex_prop_free(my);
508	kex_prop_free(peer);
509}
510
511static u_char *
512derive_key(Kex *kex, int id, u_int need, u_char *hash, u_int hashlen,
513    BIGNUM *shared_secret)
514{
515	Buffer b;
516	EVP_MD_CTX md;
517	char c = id;
518	u_int have;
519	int mdsz;
520	u_char *digest;
521
522	if ((mdsz = EVP_MD_size(kex->evp_md)) <= 0)
523		fatal("bad kex md size %d", mdsz);
524	digest = xmalloc(roundup(need, mdsz));
525
526	buffer_init(&b);
527	buffer_put_bignum2(&b, shared_secret);
528
529	/* K1 = HASH(K || H || "A" || session_id) */
530	EVP_DigestInit(&md, kex->evp_md);
531	if (!(datafellows & SSH_BUG_DERIVEKEY))
532		EVP_DigestUpdate(&md, buffer_ptr(&b), buffer_len(&b));
533	EVP_DigestUpdate(&md, hash, hashlen);
534	EVP_DigestUpdate(&md, &c, 1);
535	EVP_DigestUpdate(&md, kex->session_id, kex->session_id_len);
536	EVP_DigestFinal(&md, digest, NULL);
537
538	/*
539	 * expand key:
540	 * Kn = HASH(K || H || K1 || K2 || ... || Kn-1)
541	 * Key = K1 || K2 || ... || Kn
542	 */
543	for (have = mdsz; need > have; have += mdsz) {
544		EVP_DigestInit(&md, kex->evp_md);
545		if (!(datafellows & SSH_BUG_DERIVEKEY))
546			EVP_DigestUpdate(&md, buffer_ptr(&b), buffer_len(&b));
547		EVP_DigestUpdate(&md, hash, hashlen);
548		EVP_DigestUpdate(&md, digest, have);
549		EVP_DigestFinal(&md, digest + have, NULL);
550	}
551	buffer_free(&b);
552#ifdef DEBUG_KEX
553	fprintf(stderr, "key '%c'== ", c);
554	dump_digest("key", digest, need);
555#endif
556	return digest;
557}
558
559Newkeys *current_keys[MODE_MAX];
560
561#define NKEYS	6
562void
563kex_derive_keys(Kex *kex, u_char *hash, u_int hashlen, BIGNUM *shared_secret)
564{
565	u_char *keys[NKEYS];
566	u_int i, mode, ctos;
567
568	for (i = 0; i < NKEYS; i++) {
569		keys[i] = derive_key(kex, 'A'+i, kex->we_need, hash, hashlen,
570		    shared_secret);
571	}
572
573	debug2("kex_derive_keys");
574	for (mode = 0; mode < MODE_MAX; mode++) {
575		current_keys[mode] = kex->newkeys[mode];
576		kex->newkeys[mode] = NULL;
577		ctos = (!kex->server && mode == MODE_OUT) ||
578		    (kex->server && mode == MODE_IN);
579		current_keys[mode]->enc.iv  = keys[ctos ? 0 : 1];
580		current_keys[mode]->enc.key = keys[ctos ? 2 : 3];
581		current_keys[mode]->mac.key = keys[ctos ? 4 : 5];
582	}
583}
584
585Newkeys *
586kex_get_newkeys(int mode)
587{
588	Newkeys *ret;
589
590	ret = current_keys[mode];
591	current_keys[mode] = NULL;
592	return ret;
593}
594
595void
596derive_ssh1_session_id(BIGNUM *host_modulus, BIGNUM *server_modulus,
597    u_int8_t cookie[8], u_int8_t id[16])
598{
599	const EVP_MD *evp_md = EVP_md5();
600	EVP_MD_CTX md;
601	u_int8_t nbuf[2048], obuf[EVP_MAX_MD_SIZE];
602	int len;
603
604	EVP_DigestInit(&md, evp_md);
605
606	len = BN_num_bytes(host_modulus);
607	if (len < (512 / 8) || (u_int)len > sizeof(nbuf))
608		fatal("%s: bad host modulus (len %d)", __func__, len);
609	BN_bn2bin(host_modulus, nbuf);
610	EVP_DigestUpdate(&md, nbuf, len);
611
612	len = BN_num_bytes(server_modulus);
613	if (len < (512 / 8) || (u_int)len > sizeof(nbuf))
614		fatal("%s: bad server modulus (len %d)", __func__, len);
615	BN_bn2bin(server_modulus, nbuf);
616	EVP_DigestUpdate(&md, nbuf, len);
617
618	EVP_DigestUpdate(&md, cookie, 8);
619
620	EVP_DigestFinal(&md, obuf, NULL);
621	memcpy(id, obuf, 16);
622
623	memset(nbuf, 0, sizeof(nbuf));
624	memset(obuf, 0, sizeof(obuf));
625	memset(&md, 0, sizeof(md));
626}
627
628#if defined(DEBUG_KEX) || defined(DEBUG_KEXDH) || defined(DEBUG_KEXECDH)
629void
630dump_digest(char *msg, u_char *digest, int len)
631{
632	int i;
633
634	fprintf(stderr, "%s\n", msg);
635	for (i = 0; i < len; i++) {
636		fprintf(stderr, "%02x", digest[i]);
637		if (i%32 == 31)
638			fprintf(stderr, "\n");
639		else if (i%8 == 7)
640			fprintf(stderr, " ");
641	}
642	fprintf(stderr, "\n");
643}
644#endif
645