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