1/*	$NetBSD: npfctl.c,v 1.10.2.15 2013/02/18 18:26:14 riz Exp $	*/
2
3/*-
4 * Copyright (c) 2009-2013 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This material is based upon work partially supported by The
8 * NetBSD Foundation under a contract with Mindaugas Rasiukevicius.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 *    notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 *    notice, this list of conditions and the following disclaimer in the
17 *    documentation and/or other materials provided with the distribution.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29 * POSSIBILITY OF SUCH DAMAGE.
30 */
31
32#include <sys/cdefs.h>
33__RCSID("$NetBSD: npfctl.c,v 1.10.2.15 2013/02/18 18:26:14 riz Exp $");
34
35#include <sys/ioctl.h>
36#include <sys/stat.h>
37#include <sys/types.h>
38
39#include <stdio.h>
40#include <stdlib.h>
41#include <string.h>
42#include <err.h>
43#include <fcntl.h>
44#include <unistd.h>
45#include <errno.h>
46
47#include <openssl/sha.h>
48
49#include "npfctl.h"
50
51extern void		npf_yyparse_string(const char *);
52
53enum {
54	NPFCTL_START,
55	NPFCTL_STOP,
56	NPFCTL_RELOAD,
57	NPFCTL_SHOWCONF,
58	NPFCTL_FLUSH,
59	NPFCTL_VALIDATE,
60	NPFCTL_TABLE,
61	NPFCTL_RULE,
62	NPFCTL_STATS,
63	NPFCTL_SESSIONS_SAVE,
64	NPFCTL_SESSIONS_LOAD,
65};
66
67static const struct operations_s {
68	const char *		cmd;
69	int			action;
70} operations[] = {
71	/* Start, stop, reload */
72	{	"start",		NPFCTL_START		},
73	{	"stop",			NPFCTL_STOP		},
74	{	"reload",		NPFCTL_RELOAD		},
75	{	"show",			NPFCTL_SHOWCONF,	},
76	{	"flush",		NPFCTL_FLUSH		},
77	{	"valid",		NPFCTL_VALIDATE		},
78	/* Table */
79	{	"table",		NPFCTL_TABLE		},
80	/* Rule */
81	{	"rule",			NPFCTL_RULE		},
82	/* Stats */
83	{	"stats",		NPFCTL_STATS		},
84	/* Sessions */
85	{	"sess-save",		NPFCTL_SESSIONS_SAVE	},
86	{	"sess-load",		NPFCTL_SESSIONS_LOAD	},
87	/* --- */
88	{	NULL,			0			}
89};
90
91static bool
92join(char *buf, size_t buflen, int count, char **args)
93{
94	char *s = buf, *p = NULL;
95
96	for (int i = 0; i < count; i++) {
97		size_t len;
98
99		p = stpncpy(s, args[i], buflen);
100		len = p - s + 1;
101		if (len >= buflen) {
102			return false;
103		}
104		buflen -= len;
105		*p = ' ';
106		s = p + 1;
107	}
108	*p = '\0';
109	return true;
110}
111
112__dead static void
113usage(void)
114{
115	const char *progname = getprogname();
116
117	fprintf(stderr,
118	    "usage:\t%s [ start | stop | reload | flush | show | stats ]\n",
119	    progname);
120	fprintf(stderr,
121	    "\t%s rule \"rule-name\" { add | rem } <rule-syntax>\n",
122	    progname);
123	fprintf(stderr,
124	    "\t%s rule \"rule-name\" rem-id <rule-id>\n",
125	    progname);
126	fprintf(stderr,
127	    "\t%s rule \"rule-name\" { list | flush }\n",
128	    progname);
129	fprintf(stderr,
130	    "\t%s table <tid> { add | rem | test } <address/mask>\n",
131	    progname);
132	fprintf(stderr,
133	    "\t%s table <tid> { list | flush }\n",
134	    progname);
135	fprintf(stderr,
136	    "\t%s ( sess-save | sess-load )\n",
137	    progname);
138	exit(EXIT_FAILURE);
139}
140
141static int
142npfctl_print_stats(int fd)
143{
144	static const struct stats_s {
145		/* Note: -1 indicates a new section. */
146		int		index;
147		const char *	name;
148	} stats[] = {
149		{ -1, "Packets passed"					},
150		{ NPF_STAT_PASS_DEFAULT,	"default pass"		},
151		{ NPF_STAT_PASS_RULESET,	"ruleset pass"		},
152		{ NPF_STAT_PASS_SESSION,	"session pass"		},
153
154		{ -1, "Packets blocked"					},
155		{ NPF_STAT_BLOCK_DEFAULT,	"default block"		},
156		{ NPF_STAT_BLOCK_RULESET,	"ruleset block"		},
157
158		{ -1, "Session and NAT entries"				},
159		{ NPF_STAT_SESSION_CREATE,	"session allocations"	},
160		{ NPF_STAT_SESSION_DESTROY,	"session destructions"	},
161		{ NPF_STAT_NAT_CREATE,		"NAT entry allocations"	},
162		{ NPF_STAT_NAT_DESTROY,		"NAT entry destructions"},
163
164		{ -1, "Network buffers"					},
165		{ NPF_STAT_NBUF_NONCONTIG,	"non-contiguous cases"	},
166		{ NPF_STAT_NBUF_CONTIG_FAIL,	"contig alloc failures"	},
167
168		{ -1, "Invalid packet state cases"			},
169		{ NPF_STAT_INVALID_STATE,	"cases in total"	},
170		{ NPF_STAT_INVALID_STATE_TCP1,	"TCP case I"		},
171		{ NPF_STAT_INVALID_STATE_TCP2,	"TCP case II"		},
172		{ NPF_STAT_INVALID_STATE_TCP3,	"TCP case III"		},
173
174		{ -1, "Packet race cases"				},
175		{ NPF_STAT_RACE_NAT,		"NAT association race"	},
176		{ NPF_STAT_RACE_SESSION,	"duplicate session race"},
177
178		{ -1, "Fragmentation"					},
179		{ NPF_STAT_FRAGMENTS,		"fragments"		},
180		{ NPF_STAT_REASSEMBLY,		"reassembled"		},
181		{ NPF_STAT_REASSFAIL,		"failed reassembly"	},
182
183		{ -1, "Other"						},
184		{ NPF_STAT_ERROR,		"unexpected errors"	},
185	};
186	uint64_t *st = ecalloc(1, NPF_STATS_SIZE);
187
188	if (ioctl(fd, IOC_NPF_STATS, &st) != 0) {
189		err(EXIT_FAILURE, "ioctl(IOC_NPF_STATS)");
190	}
191
192	for (unsigned i = 0; i < __arraycount(stats); i++) {
193		const char *sname = stats[i].name;
194		int sidx = stats[i].index;
195
196		if (sidx == -1) {
197			printf("%s:\n", sname);
198		} else {
199			printf("\t%"PRIu64" %s\n", st[sidx], sname);
200		}
201	}
202
203	free(st);
204	return 0;
205}
206
207void
208npfctl_print_error(const nl_error_t *ne)
209{
210	static const char *ncode_errors[] = {
211		[-NPF_ERR_OPCODE]	= "invalid instruction",
212		[-NPF_ERR_JUMP]		= "invalid jump",
213		[-NPF_ERR_REG]		= "invalid register",
214		[-NPF_ERR_INVAL]	= "invalid argument value",
215		[-NPF_ERR_RANGE]	= "processing out of range"
216	};
217	const int nc_err = ne->ne_ncode_error;
218	const char *srcfile = ne->ne_source_file;
219
220	if (srcfile) {
221		warnx("source %s line %d", srcfile, ne->ne_source_line);
222	}
223	if (nc_err) {
224		warnx("n-code error (%d): %s at offset 0x%x",
225		    nc_err, ncode_errors[-nc_err], ne->ne_ncode_errat);
226	}
227	if (ne->ne_id) {
228		warnx("object: %d", ne->ne_id);
229	}
230}
231
232char *
233npfctl_print_addrmask(int alen, npf_addr_t *addr, npf_netmask_t mask)
234{
235	struct sockaddr_storage ss;
236	char *buf = ecalloc(1, 64);
237	int len;
238
239	switch (alen) {
240	case 4: {
241		struct sockaddr_in *sin = (void *)&ss;
242		sin->sin_len = sizeof(*sin);
243		sin->sin_family = AF_INET;
244		sin->sin_port = 0;
245		memcpy(&sin->sin_addr, addr, sizeof(sin->sin_addr));
246		break;
247	}
248	case 16: {
249		struct sockaddr_in6 *sin6 = (void *)&ss;
250		sin6->sin6_len = sizeof(*sin6);
251		sin6->sin6_family = AF_INET6;
252		sin6->sin6_port = 0;
253		sin6->sin6_scope_id = 0;
254		memcpy(&sin6->sin6_addr, addr, sizeof(sin6->sin6_addr));
255		break;
256	}
257	default:
258		assert(false);
259	}
260	len = sockaddr_snprintf(buf, 64, "%a", (struct sockaddr *)&ss);
261	if (mask) {
262		snprintf(&buf[len], 64 - len, "/%u", mask);
263	}
264	return buf;
265}
266
267__dead static void
268npfctl_table(int fd, int argc, char **argv)
269{
270	static const struct tblops_s {
271		const char *	cmd;
272		int		action;
273	} tblops[] = {
274		{ "add",	NPF_CMD_TABLE_ADD		},
275		{ "rem",	NPF_CMD_TABLE_REMOVE		},
276		{ "del",	NPF_CMD_TABLE_REMOVE		},
277		{ "test",	NPF_CMD_TABLE_LOOKUP		},
278		{ "list",	NPF_CMD_TABLE_LIST		},
279		{ NULL,		0				}
280	};
281	npf_ioctl_table_t nct;
282	fam_addr_mask_t fam;
283	size_t buflen = 512;
284	char *cmd, *arg = NULL; /* XXX gcc */
285	int n, alen;
286
287	/* Default action is list. */
288	memset(&nct, 0, sizeof(npf_ioctl_table_t));
289	nct.nct_tid = atoi(argv[0]);
290	cmd = argv[1];
291
292	for (n = 0; tblops[n].cmd != NULL; n++) {
293		if (strcmp(cmd, tblops[n].cmd) != 0) {
294			continue;
295		}
296		nct.nct_cmd = tblops[n].action;
297		break;
298	}
299	if (tblops[n].cmd == NULL) {
300		errx(EXIT_FAILURE, "invalid command '%s'", cmd);
301	}
302	if (nct.nct_cmd != NPF_CMD_TABLE_LIST) {
303		if (argc < 3) {
304			usage();
305		}
306		arg = argv[2];
307	}
308again:
309	if (nct.nct_cmd == NPF_CMD_TABLE_LIST) {
310		nct.nct_data.buf.buf = ecalloc(1, buflen);
311		nct.nct_data.buf.len = buflen;
312	} else {
313		if (!npfctl_parse_cidr(arg, &fam, &alen)) {
314			errx(EXIT_FAILURE, "invalid CIDR '%s'", arg);
315		}
316		nct.nct_data.ent.alen = alen;
317		memcpy(&nct.nct_data.ent.addr, &fam.fam_addr, alen);
318		nct.nct_data.ent.mask = fam.fam_mask;
319	}
320
321	if (ioctl(fd, IOC_NPF_TABLE, &nct) != -1) {
322		errno = 0;
323	}
324	switch (errno) {
325	case 0:
326		break;
327	case EEXIST:
328		errx(EXIT_FAILURE, "entry already exists or is conflicting");
329	case ENOENT:
330		errx(EXIT_FAILURE, "no matching entry was not found");
331	case EINVAL:
332		errx(EXIT_FAILURE, "invalid address, mask or table ID");
333	case ENOMEM:
334		if (nct.nct_cmd == NPF_CMD_TABLE_LIST) {
335			/* XXX */
336			free(nct.nct_data.buf.buf);
337			buflen <<= 1;
338			goto again;
339		}
340		/* FALLTHROUGH */
341	default:
342		err(EXIT_FAILURE, "ioctl(IOC_NPF_TABLE)");
343	}
344
345	if (nct.nct_cmd == NPF_CMD_TABLE_LIST) {
346		npf_ioctl_ent_t *ent = nct.nct_data.buf.buf;
347		char *buf;
348
349		while (nct.nct_data.buf.len--) {
350			if (!ent->alen)
351				break;
352			buf = npfctl_print_addrmask(ent->alen,
353			    &ent->addr, ent->mask);
354			puts(buf);
355			ent++;
356		}
357		free(nct.nct_data.buf.buf);
358	} else {
359		printf("%s: %s\n", getprogname(),
360		    nct.nct_cmd == NPF_CMD_TABLE_LOOKUP ?
361		    "matching entry found" : "success");
362	}
363	exit(EXIT_SUCCESS);
364}
365
366static nl_rule_t *
367npfctl_parse_rule(int argc, char **argv)
368{
369	char rule_string[1024];
370	nl_rule_t *rl;
371
372	/* Get the rule string and parse it. */
373	if (!join(rule_string, sizeof(rule_string), argc, argv)) {
374		errx(EXIT_FAILURE, "command too long");
375	}
376	npfctl_parse_string(rule_string);
377	if ((rl = npfctl_rule_ref()) == NULL) {
378		errx(EXIT_FAILURE, "could not parse the rule");
379	}
380	return rl;
381}
382
383static void
384npfctl_generate_key(nl_rule_t *rl, void *key)
385{
386	void *meta;
387	size_t len;
388
389	if ((meta = npf_rule_export(rl, &len)) == NULL) {
390		errx(EXIT_FAILURE, "error generating rule key");
391	}
392	__CTASSERT(NPF_RULE_MAXKEYLEN >= SHA_DIGEST_LENGTH);
393	memset(key, 0, NPF_RULE_MAXKEYLEN);
394	SHA1(meta, len, key);
395	free(meta);
396}
397
398__dead static void
399npfctl_rule(int fd, int argc, char **argv)
400{
401	static const struct ruleops_s {
402		const char *	cmd;
403		int		action;
404	} ruleops[] = {
405		{ "add",	NPF_CMD_RULE_ADD		},
406		{ "rem",	NPF_CMD_RULE_REMKEY		},
407		{ "del",	NPF_CMD_RULE_REMKEY		},
408		{ "rem-id",	NPF_CMD_RULE_REMOVE		},
409		{ "list",	NPF_CMD_RULE_LIST		},
410		{ "flush",	NPF_CMD_RULE_FLUSH		},
411		{ NULL,		0				}
412	};
413	uint8_t key[NPF_RULE_MAXKEYLEN];
414	const char *ruleset_name = argv[0];
415	const char *cmd = argv[1];
416	int error, action = 0;
417	uint64_t rule_id;
418	nl_rule_t *rl;
419
420	for (int n = 0; ruleops[n].cmd != NULL; n++) {
421		if (strcmp(cmd, ruleops[n].cmd) == 0) {
422			action = ruleops[n].action;
423			break;
424		}
425	}
426
427	bool narg = action == NPF_CMD_RULE_LIST || action == NPF_CMD_RULE_FLUSH;
428	if (!action || (argc < 3 && !narg)) {
429		usage();
430	}
431	argc -= 2;
432	argv += 2;
433
434	switch (action) {
435	case NPF_CMD_RULE_ADD:
436		rl = npfctl_parse_rule(argc, argv);
437		npfctl_generate_key(rl, key);
438		npf_rule_setkey(rl, key, sizeof(key));
439		error = npf_ruleset_add(fd, ruleset_name, rl, &rule_id);
440		break;
441	case NPF_CMD_RULE_REMKEY:
442		rl = npfctl_parse_rule(argc, argv);
443		npfctl_generate_key(rl, key);
444		error = npf_ruleset_remkey(fd, ruleset_name, key, sizeof(key));
445		break;
446	case NPF_CMD_RULE_REMOVE:
447		rule_id = strtoull(argv[0], NULL, 16);
448		error = npf_ruleset_remove(fd, ruleset_name, rule_id);
449		break;
450	case NPF_CMD_RULE_LIST:
451		error = npfctl_ruleset_show(fd, ruleset_name);
452		break;
453	case NPF_CMD_RULE_FLUSH:
454		error = npf_ruleset_flush(fd, ruleset_name);
455		break;
456	default:
457		assert(false);
458	}
459
460	switch (error) {
461	case 0:
462		/* Success. */
463		break;
464	case ESRCH:
465		errx(EXIT_FAILURE, "ruleset \"%s\" not found", ruleset_name);
466	case ENOENT:
467		errx(EXIT_FAILURE, "rule was not found");
468	default:
469		errx(EXIT_FAILURE, "rule operation: %s", strerror(error));
470	}
471	if (action == NPF_CMD_RULE_ADD) {
472		printf("OK %" PRIx64 "\n", rule_id);
473	}
474	exit(EXIT_SUCCESS);
475}
476
477static void
478npfctl(int action, int argc, char **argv)
479{
480	int fd, ver, boolval, ret = 0;
481
482	fd = open(NPF_DEV_PATH, O_RDONLY);
483	if (fd == -1) {
484		err(EXIT_FAILURE, "cannot open '%s'", NPF_DEV_PATH);
485	}
486	if (ioctl(fd, IOC_NPF_VERSION, &ver) == -1) {
487		err(EXIT_FAILURE, "ioctl(IOC_NPF_VERSION)");
488	}
489	if (ver != NPF_VERSION) {
490		errx(EXIT_FAILURE,
491		    "incompatible NPF interface version (%d, kernel %d)\n"
492		    "Hint: update userland?", NPF_VERSION, ver);
493	}
494
495	const char *fun = "";
496	switch (action) {
497	case NPFCTL_START:
498		boolval = true;
499		ret = ioctl(fd, IOC_NPF_SWITCH, &boolval);
500		fun = "ioctl(IOC_NPF_SWITCH)";
501		break;
502	case NPFCTL_STOP:
503		boolval = false;
504		ret = ioctl(fd, IOC_NPF_SWITCH, &boolval);
505		fun = "ioctl(IOC_NPF_SWITCH)";
506		break;
507	case NPFCTL_RELOAD:
508		npfctl_config_init(false);
509		npfctl_parse_file(argc < 3 ? NPF_CONF_PATH : argv[2]);
510		errno = ret = npfctl_config_send(fd, NULL);
511		fun = "npfctl_config_send";
512		break;
513	case NPFCTL_SHOWCONF:
514		ret = npfctl_config_show(fd);
515		fun = "npfctl_config_show";
516		break;
517	case NPFCTL_FLUSH:
518		ret = npf_config_flush(fd);
519		fun = "npf_config_flush";
520		break;
521	case NPFCTL_VALIDATE:
522		npfctl_config_init(false);
523		npfctl_parse_file(argc < 3 ? NPF_CONF_PATH : argv[2]);
524		ret = npfctl_config_show(0);
525		fun = "npfctl_config_show";
526		break;
527	case NPFCTL_TABLE:
528		if ((argc -= 2) < 2) {
529			usage();
530		}
531		argv += 2;
532		npfctl_table(fd, argc, argv);
533		break;
534	case NPFCTL_RULE:
535		if ((argc -= 2) < 2) {
536			usage();
537		}
538		argv += 2;
539		npfctl_rule(fd, argc, argv);
540		break;
541	case NPFCTL_STATS:
542		ret = npfctl_print_stats(fd);
543		fun = "npfctl_print_stats";
544		break;
545	case NPFCTL_SESSIONS_SAVE:
546		if (npf_sessions_recv(fd, NPF_SESSDB_PATH) != 0) {
547			errx(EXIT_FAILURE, "could not save sessions to '%s'",
548			    NPF_SESSDB_PATH);
549		}
550		break;
551	case NPFCTL_SESSIONS_LOAD:
552		if (npf_sessions_send(fd, NPF_SESSDB_PATH) != 0) {
553			errx(EXIT_FAILURE, "no sessions loaded from '%s'",
554			    NPF_SESSDB_PATH);
555		}
556		break;
557	}
558	if (ret) {
559		err(EXIT_FAILURE, "%s", fun);
560	}
561	close(fd);
562}
563
564int
565main(int argc, char **argv)
566{
567	char *cmd;
568
569	if (argc < 2) {
570		usage();
571	}
572	cmd = argv[1];
573
574	if (strcmp(cmd, "debug") == 0) {
575		const char *cfg = argc > 2 ? argv[2] : "/etc/npf.conf";
576		const char *out = argc > 3 ? argv[3] : "/tmp/npf.plist";
577
578		npfctl_config_init(true);
579		npfctl_parse_file(cfg);
580		npfctl_config_send(0, out);
581		return EXIT_SUCCESS;
582	}
583
584	/* Find and call the subroutine. */
585	for (int n = 0; operations[n].cmd != NULL; n++) {
586		const char *opcmd = operations[n].cmd;
587		if (strncmp(cmd, opcmd, strlen(opcmd)) != 0)
588			continue;
589		npfctl(operations[n].action, argc, argv);
590		return EXIT_SUCCESS;
591	}
592	usage();
593}
594