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