1/* 	$OpenBSD: kexfuzz.c,v 1.3 2016/10/11 21:49:54 djm Exp $ */
2/*
3 * Fuzz harness for KEX code
4 *
5 * Placed in the public domain
6 */
7
8#include "includes.h"
9
10#include <sys/types.h>
11#include <sys/param.h>
12#include <stdio.h>
13#ifdef HAVE_STDINT_H
14# include <stdint.h>
15#endif
16#include <stdlib.h>
17#include <string.h>
18#include <unistd.h>
19#include <fcntl.h>
20#ifdef HAVE_ERR_H
21# include <err.h>
22#endif
23
24#include "ssherr.h"
25#include "ssh_api.h"
26#include "sshbuf.h"
27#include "packet.h"
28#include "myproposal.h"
29#include "authfile.h"
30#include "log.h"
31
32struct ssh *active_state = NULL; /* XXX - needed for linking */
33
34void kex_tests(void);
35static int do_debug = 0;
36
37enum direction { S2C, C2S };
38
39struct hook_ctx {
40	struct ssh *client, *server, *server2;
41	int *c2s, *s2c;
42	int trigger_direction, packet_index;
43	const char *dump_path;
44	struct sshbuf *replace_data;
45};
46
47static int
48packet_hook(struct ssh *ssh, struct sshbuf *packet, u_char *typep, void *_ctx)
49{
50	struct hook_ctx *ctx = (struct hook_ctx *)_ctx;
51	int mydirection = ssh == ctx->client ? S2C : C2S;
52	int *packet_count = mydirection == S2C ? ctx->s2c : ctx->c2s;
53	FILE *dumpfile;
54	int r;
55
56	if (do_debug) {
57		printf("%s packet %d type %u:\n",
58		    mydirection == S2C ? "s2c" : "c2s",
59		    *packet_count, *typep);
60		sshbuf_dump(packet, stdout);
61	}
62	if (mydirection == ctx->trigger_direction &&
63	    ctx->packet_index == *packet_count) {
64		if (ctx->replace_data != NULL) {
65			sshbuf_reset(packet);
66			/* Type is first byte of packet */
67			if ((r = sshbuf_get_u8(ctx->replace_data,
68			    typep)) != 0 ||
69			    (r = sshbuf_putb(packet, ctx->replace_data)) != 0)
70				return r;
71			if (do_debug) {
72				printf("***** replaced packet type %u\n",
73				    *typep);
74				sshbuf_dump(packet, stdout);
75			}
76		} else if (ctx->dump_path != NULL) {
77			if ((dumpfile = fopen(ctx->dump_path, "w+")) == NULL)
78				err(1, "fopen %s", ctx->dump_path);
79			/* Write { type, packet } */
80			if (fwrite(typep, 1, 1, dumpfile) != 1)
81				err(1, "fwrite type %s", ctx->dump_path);
82			if (sshbuf_len(packet) != 0 &&
83			    fwrite(sshbuf_ptr(packet), sshbuf_len(packet),
84			    1, dumpfile) != 1)
85				err(1, "fwrite body %s", ctx->dump_path);
86			if (do_debug) {
87				printf("***** dumped packet type %u len %zu\n",
88				    *typep, sshbuf_len(packet));
89			}
90			fclose(dumpfile);
91			/* No point in continuing */
92			exit(0);
93		}
94	}
95	(*packet_count)++;
96	return 0;
97}
98
99static int
100do_send_and_receive(struct ssh *from, struct ssh *to)
101{
102	u_char type;
103	size_t len;
104	const u_char *buf;
105	int r;
106
107	for (;;) {
108		if ((r = ssh_packet_next(from, &type)) != 0) {
109			fprintf(stderr, "ssh_packet_next: %s\n", ssh_err(r));
110			return r;
111		}
112
113		if (type != 0)
114			return 0;
115		buf = ssh_output_ptr(from, &len);
116		if (len == 0)
117			return 0;
118		if ((r = ssh_input_append(to, buf, len)) != 0) {
119			debug("ssh_input_append: %s", ssh_err(r));
120			return r;
121		}
122		if ((r = ssh_output_consume(from, len)) != 0) {
123			debug("ssh_output_consume: %s", ssh_err(r));
124			return r;
125		}
126	}
127}
128
129/* Minimal test_helper.c scaffholding to make this standalone */
130const char *in_test = NULL;
131#define TEST_START(a)	\
132	do { \
133		in_test = (a); \
134		if (do_debug) \
135			fprintf(stderr, "test %s starting\n", in_test); \
136	} while (0)
137#define TEST_DONE()	\
138	do { \
139		if (do_debug) \
140			fprintf(stderr, "test %s done\n", \
141			    in_test ? in_test : "???"); \
142		in_test = NULL; \
143	} while(0)
144#define ASSERT_INT_EQ(a, b) \
145	do { \
146		if ((int)(a) != (int)(b)) { \
147			fprintf(stderr, "%s %s:%d " \
148			    "%s (%d) != expected %s (%d)\n", \
149			    in_test ? in_test : "(none)", \
150			    __func__, __LINE__, #a, (int)(a), #b, (int)(b)); \
151			exit(2); \
152		} \
153	} while (0)
154#define ASSERT_INT_GE(a, b) \
155	do { \
156		if ((int)(a) < (int)(b)) { \
157			fprintf(stderr, "%s %s:%d " \
158			    "%s (%d) < expected %s (%d)\n", \
159			    in_test ? in_test : "(none)", \
160			    __func__, __LINE__, #a, (int)(a), #b, (int)(b)); \
161			exit(2); \
162		} \
163	} while (0)
164#define ASSERT_PTR_NE(a, b) \
165	do { \
166		if ((a) == (b)) { \
167			fprintf(stderr, "%s %s:%d " \
168			    "%s (%p) != expected %s (%p)\n", \
169			    in_test ? in_test : "(none)", \
170			    __func__, __LINE__, #a, (a), #b, (b)); \
171			exit(2); \
172		} \
173	} while (0)
174
175
176static void
177run_kex(struct ssh *client, struct ssh *server)
178{
179	int r = 0;
180
181	while (!server->kex->done || !client->kex->done) {
182		if ((r = do_send_and_receive(server, client)) != 0) {
183			debug("do_send_and_receive S2C: %s", ssh_err(r));
184			break;
185		}
186		if ((r = do_send_and_receive(client, server)) != 0) {
187			debug("do_send_and_receive C2S: %s", ssh_err(r));
188			break;
189		}
190	}
191	if (do_debug)
192		printf("done: %s\n", ssh_err(r));
193	ASSERT_INT_EQ(r, 0);
194	ASSERT_INT_EQ(server->kex->done, 1);
195	ASSERT_INT_EQ(client->kex->done, 1);
196}
197
198static void
199do_kex_with_key(const char *kex, struct sshkey *prvkey, int *c2s, int *s2c,
200    int direction, int packet_index,
201    const char *dump_path, struct sshbuf *replace_data)
202{
203	struct ssh *client = NULL, *server = NULL, *server2 = NULL;
204	struct sshkey *pubkey = NULL;
205	struct sshbuf *state;
206	struct kex_params kex_params;
207	char *myproposal[PROPOSAL_MAX] = { KEX_CLIENT };
208	char *keyname = NULL;
209	struct hook_ctx hook_ctx;
210
211	TEST_START("sshkey_from_private");
212	ASSERT_INT_EQ(sshkey_from_private(prvkey, &pubkey), 0);
213	TEST_DONE();
214
215	TEST_START("ssh_init");
216	memcpy(kex_params.proposal, myproposal, sizeof(myproposal));
217	if (kex != NULL)
218		kex_params.proposal[PROPOSAL_KEX_ALGS] = strdup(kex);
219	keyname = strdup(sshkey_ssh_name(prvkey));
220	ASSERT_PTR_NE(keyname, NULL);
221	kex_params.proposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = keyname;
222	ASSERT_INT_EQ(ssh_init(&client, 0, &kex_params), 0);
223	ASSERT_INT_EQ(ssh_init(&server, 1, &kex_params), 0);
224	ASSERT_INT_EQ(ssh_init(&server2, 1, NULL), 0);
225	ASSERT_PTR_NE(client, NULL);
226	ASSERT_PTR_NE(server, NULL);
227	ASSERT_PTR_NE(server2, NULL);
228	TEST_DONE();
229
230	hook_ctx.c2s = c2s;
231	hook_ctx.s2c = s2c;
232	hook_ctx.trigger_direction = direction;
233	hook_ctx.packet_index = packet_index;
234	hook_ctx.dump_path = dump_path;
235	hook_ctx.replace_data = replace_data;
236	hook_ctx.client = client;
237	hook_ctx.server = server;
238	hook_ctx.server2 = server2;
239	ssh_packet_set_input_hook(client, packet_hook, &hook_ctx);
240	ssh_packet_set_input_hook(server, packet_hook, &hook_ctx);
241	ssh_packet_set_input_hook(server2, packet_hook, &hook_ctx);
242
243	TEST_START("ssh_add_hostkey");
244	ASSERT_INT_EQ(ssh_add_hostkey(server, prvkey), 0);
245	ASSERT_INT_EQ(ssh_add_hostkey(client, pubkey), 0);
246	TEST_DONE();
247
248	TEST_START("kex");
249	run_kex(client, server);
250	TEST_DONE();
251
252	TEST_START("rekeying client");
253	ASSERT_INT_EQ(kex_send_kexinit(client), 0);
254	run_kex(client, server);
255	TEST_DONE();
256
257	TEST_START("rekeying server");
258	ASSERT_INT_EQ(kex_send_kexinit(server), 0);
259	run_kex(client, server);
260	TEST_DONE();
261
262	TEST_START("ssh_packet_get_state");
263	state = sshbuf_new();
264	ASSERT_PTR_NE(state, NULL);
265	ASSERT_INT_EQ(ssh_packet_get_state(server, state), 0);
266	ASSERT_INT_GE(sshbuf_len(state), 1);
267	TEST_DONE();
268
269	TEST_START("ssh_packet_set_state");
270	ASSERT_INT_EQ(ssh_add_hostkey(server2, prvkey), 0);
271	kex_free(server2->kex);	/* XXX or should ssh_packet_set_state()? */
272	ASSERT_INT_EQ(ssh_packet_set_state(server2, state), 0);
273	ASSERT_INT_EQ(sshbuf_len(state), 0);
274	sshbuf_free(state);
275	ASSERT_PTR_NE(server2->kex, NULL);
276	/* XXX we need to set the callbacks */
277#ifdef WITH_OPENSSL
278	server2->kex->kex[KEX_DH_GRP1_SHA1] = kexdh_server;
279	server2->kex->kex[KEX_DH_GRP14_SHA1] = kexdh_server;
280	server2->kex->kex[KEX_DH_GRP14_SHA256] = kexdh_server;
281	server2->kex->kex[KEX_DH_GRP16_SHA512] = kexdh_server;
282	server2->kex->kex[KEX_DH_GRP18_SHA512] = kexdh_server;
283	server2->kex->kex[KEX_DH_GEX_SHA1] = kexgex_server;
284	server2->kex->kex[KEX_DH_GEX_SHA256] = kexgex_server;
285# ifdef OPENSSL_HAS_ECC
286	server2->kex->kex[KEX_ECDH_SHA2] = kexecdh_server;
287# endif
288#endif
289	server2->kex->kex[KEX_C25519_SHA256] = kexc25519_server;
290	server2->kex->load_host_public_key = server->kex->load_host_public_key;
291	server2->kex->load_host_private_key = server->kex->load_host_private_key;
292	server2->kex->sign = server->kex->sign;
293	TEST_DONE();
294
295	TEST_START("rekeying server2");
296	ASSERT_INT_EQ(kex_send_kexinit(server2), 0);
297	run_kex(client, server2);
298	ASSERT_INT_EQ(kex_send_kexinit(client), 0);
299	run_kex(client, server2);
300	TEST_DONE();
301
302	TEST_START("cleanup");
303	sshkey_free(pubkey);
304	ssh_free(client);
305	ssh_free(server);
306	ssh_free(server2);
307	free(keyname);
308	TEST_DONE();
309}
310
311static void
312usage(void)
313{
314	fprintf(stderr,
315	    "Usage: kexfuzz [-hcdrv] [-D direction] [-f data_file]\n"
316	    "               [-K kex_alg] [-k private_key] [-i packet_index]\n"
317	    "\n"
318	    "Options:\n"
319	    "    -h               Display this help\n"
320	    "    -c               Count packets sent during KEX\n"
321	    "    -d               Dump mode: record KEX packet to data file\n"
322	    "    -r               Replace mode: replace packet with data file\n"
323	    "    -v               Turn on verbose logging\n"
324	    "    -D S2C|C2S       Packet direction for replacement or dump\n"
325	    "    -f data_file     Path to data file for replacement or dump\n"
326	    "    -K kex_alg       Name of KEX algorithm to test (see below)\n"
327	    "    -k private_key   Path to private key file\n"
328	    "    -i packet_index  Index of packet to replace or dump (from 0)\n"
329	    "\n"
330	    "Available KEX algorithms: %s\n", kex_alg_list(' '));
331}
332
333static void
334badusage(const char *bad)
335{
336	fprintf(stderr, "Invalid options\n");
337	fprintf(stderr, "%s\n", bad);
338	usage();
339	exit(1);
340}
341
342int
343main(int argc, char **argv)
344{
345	int ch, fd, r;
346	int count_flag = 0, dump_flag = 0, replace_flag = 0;
347	int packet_index = -1, direction = -1;
348	int s2c = 0, c2s = 0; /* packet counts */
349	const char *kex = NULL, *kpath = NULL, *data_path = NULL;
350	struct sshkey *key = NULL;
351	struct sshbuf *replace_data = NULL;
352
353	setvbuf(stdout, NULL, _IONBF, 0);
354	while ((ch = getopt(argc, argv, "hcdrvD:f:K:k:i:")) != -1) {
355		switch (ch) {
356		case 'h':
357			usage();
358			return 0;
359		case 'c':
360			count_flag = 1;
361			break;
362		case 'd':
363			dump_flag = 1;
364			break;
365		case 'r':
366			replace_flag = 1;
367			break;
368		case 'v':
369			do_debug = 1;
370			break;
371
372		case 'D':
373			if (strcasecmp(optarg, "s2c") == 0)
374				direction = S2C;
375			else if (strcasecmp(optarg, "c2s") == 0)
376				direction = C2S;
377			else
378				badusage("Invalid direction (-D)");
379			break;
380		case 'f':
381			data_path = optarg;
382			break;
383		case 'K':
384			kex = optarg;
385			break;
386		case 'k':
387			kpath = optarg;
388			break;
389		case 'i':
390			packet_index = atoi(optarg);
391			if (packet_index < 0)
392				badusage("Invalid packet index");
393			break;
394		default:
395			badusage("unsupported flag");
396		}
397	}
398	argc -= optind;
399	argv += optind;
400
401	log_init(argv[0], do_debug ? SYSLOG_LEVEL_DEBUG3 : SYSLOG_LEVEL_INFO,
402	    SYSLOG_FACILITY_USER, 1);
403
404	/* Must select a single mode */
405	if ((count_flag + dump_flag + replace_flag) != 1)
406		badusage("Must select one mode: -c, -d or -r");
407	/* KEX type is mandatory */
408	if (kex == NULL || !kex_names_valid(kex) || strchr(kex, ',') != NULL)
409		badusage("Missing or invalid kex type (-K flag)");
410	/* Valid key is mandatory */
411	if (kpath == NULL)
412		badusage("Missing private key (-k flag)");
413	if ((fd = open(kpath, O_RDONLY)) == -1)
414		err(1, "open %s", kpath);
415	if ((r = sshkey_load_private_type_fd(fd, KEY_UNSPEC, NULL,
416	    &key, NULL)) != 0)
417		errx(1, "Unable to load key %s: %s", kpath, ssh_err(r));
418	close(fd);
419	/* XXX check that it is a private key */
420	/* XXX support certificates */
421	if (key == NULL || key->type == KEY_UNSPEC || key->type == KEY_RSA1)
422		badusage("Invalid key file (-k flag)");
423
424	/* Replace (fuzz) mode */
425	if (replace_flag) {
426		if (packet_index == -1 || direction == -1 || data_path == NULL)
427			badusage("Replace (-r) mode must specify direction "
428			    "(-D) packet index (-i) and data path (-f)");
429		if ((fd = open(data_path, O_RDONLY)) == -1)
430			err(1, "open %s", data_path);
431		replace_data = sshbuf_new();
432		if ((r = sshkey_load_file(fd, replace_data)) != 0)
433			errx(1, "read %s: %s", data_path, ssh_err(r));
434		close(fd);
435	}
436
437	/* Dump mode */
438	if (dump_flag) {
439		if (packet_index == -1 || direction == -1 || data_path == NULL)
440			badusage("Dump (-d) mode must specify direction "
441			    "(-D), packet index (-i) and data path (-f)");
442	}
443
444	/* Count mode needs no further flags */
445
446	do_kex_with_key(kex, key, &c2s, &s2c,
447	    direction, packet_index,
448	    dump_flag ? data_path : NULL,
449	    replace_flag ? replace_data : NULL);
450	sshkey_free(key);
451	sshbuf_free(replace_data);
452
453	if (count_flag) {
454		printf("S2C: %d\n", s2c);
455		printf("C2S: %d\n", c2s);
456	}
457
458	return 0;
459}
460