xref: /netbsd-src/usr.sbin/npf/npfctl/npfctl.c (revision 6a493d6bc668897c91594964a732d38505b70cbb)
1 /*	$NetBSD: npfctl.c,v 1.40 2013/11/12 00:46:34 rmind 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.40 2013/11/12 00:46:34 rmind 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 
51 extern void		npf_yyparse_string(const char *);
52 
53 enum {
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 
67 static 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 
91 bool
92 join(char *buf, size_t buflen, int count, char **args, const char *sep)
93 {
94 	const u_int seplen = strlen(sep);
95 	char *s = buf, *p = NULL;
96 
97 	for (int i = 0; i < count; i++) {
98 		size_t len;
99 
100 		p = stpncpy(s, args[i], buflen);
101 		len = p - s + seplen;
102 		if (len >= buflen) {
103 			return false;
104 		}
105 		buflen -= len;
106 		strcpy(p, sep);
107 		s = p + seplen;
108 	}
109 	*p = '\0';
110 	return true;
111 }
112 
113 __dead static void
114 usage(void)
115 {
116 	const char *progname = getprogname();
117 
118 	fprintf(stderr,
119 	    "Usage:\t%s start | stop | flush | show | stats\n",
120 	    progname);
121 	fprintf(stderr,
122 	    "\t%s validate | reload [<rule-file>]\n",
123 	    progname);
124 	fprintf(stderr,
125 	    "\t%s rule \"rule-name\" { add | rem } <rule-syntax>\n",
126 	    progname);
127 	fprintf(stderr,
128 	    "\t%s rule \"rule-name\" rem-id <rule-id>\n",
129 	    progname);
130 	fprintf(stderr,
131 	    "\t%s rule \"rule-name\" { list | flush }\n",
132 	    progname);
133 	fprintf(stderr,
134 	    "\t%s table <tid> { add | rem | test } <address/mask>\n",
135 	    progname);
136 	fprintf(stderr,
137 	    "\t%s table <tid> { list | flush }\n",
138 	    progname);
139 	fprintf(stderr,
140 	    "\t%s sess-load | sess-save\n",
141 	    progname);
142 	exit(EXIT_FAILURE);
143 }
144 
145 static int
146 npfctl_print_stats(int fd)
147 {
148 	static const struct stats_s {
149 		/* Note: -1 indicates a new section. */
150 		int		index;
151 		const char *	name;
152 	} stats[] = {
153 		{ -1, "Packets passed"					},
154 		{ NPF_STAT_PASS_DEFAULT,	"default pass"		},
155 		{ NPF_STAT_PASS_RULESET,	"ruleset pass"		},
156 		{ NPF_STAT_PASS_SESSION,	"session pass"		},
157 
158 		{ -1, "Packets blocked"					},
159 		{ NPF_STAT_BLOCK_DEFAULT,	"default block"		},
160 		{ NPF_STAT_BLOCK_RULESET,	"ruleset block"		},
161 
162 		{ -1, "Session and NAT entries"				},
163 		{ NPF_STAT_SESSION_CREATE,	"session allocations"	},
164 		{ NPF_STAT_SESSION_DESTROY,	"session destructions"	},
165 		{ NPF_STAT_NAT_CREATE,		"NAT entry allocations"	},
166 		{ NPF_STAT_NAT_DESTROY,		"NAT entry destructions"},
167 
168 		{ -1, "Network buffers"					},
169 		{ NPF_STAT_NBUF_NONCONTIG,	"non-contiguous cases"	},
170 		{ NPF_STAT_NBUF_CONTIG_FAIL,	"contig alloc failures"	},
171 
172 		{ -1, "Invalid packet state cases"			},
173 		{ NPF_STAT_INVALID_STATE,	"cases in total"	},
174 		{ NPF_STAT_INVALID_STATE_TCP1,	"TCP case I"		},
175 		{ NPF_STAT_INVALID_STATE_TCP2,	"TCP case II"		},
176 		{ NPF_STAT_INVALID_STATE_TCP3,	"TCP case III"		},
177 
178 		{ -1, "Packet race cases"				},
179 		{ NPF_STAT_RACE_NAT,		"NAT association race"	},
180 		{ NPF_STAT_RACE_SESSION,	"duplicate session race"},
181 
182 		{ -1, "Fragmentation"					},
183 		{ NPF_STAT_FRAGMENTS,		"fragments"		},
184 		{ NPF_STAT_REASSEMBLY,		"reassembled"		},
185 		{ NPF_STAT_REASSFAIL,		"failed reassembly"	},
186 
187 		{ -1, "Other"						},
188 		{ NPF_STAT_ERROR,		"unexpected errors"	},
189 	};
190 	uint64_t *st = ecalloc(1, NPF_STATS_SIZE);
191 
192 	if (ioctl(fd, IOC_NPF_STATS, &st) != 0) {
193 		err(EXIT_FAILURE, "ioctl(IOC_NPF_STATS)");
194 	}
195 
196 	for (unsigned i = 0; i < __arraycount(stats); i++) {
197 		const char *sname = stats[i].name;
198 		int sidx = stats[i].index;
199 
200 		if (sidx == -1) {
201 			printf("%s:\n", sname);
202 		} else {
203 			printf("\t%"PRIu64" %s\n", st[sidx], sname);
204 		}
205 	}
206 
207 	free(st);
208 	return 0;
209 }
210 
211 void
212 npfctl_print_error(const nl_error_t *ne)
213 {
214 	const char *srcfile = ne->ne_source_file;
215 
216 	if (srcfile) {
217 		warnx("source %s line %d", srcfile, ne->ne_source_line);
218 	}
219 	if (ne->ne_id) {
220 		warnx("object: %d", ne->ne_id);
221 	}
222 }
223 
224 char *
225 npfctl_print_addrmask(int alen, const npf_addr_t *addr, npf_netmask_t mask)
226 {
227 	struct sockaddr_storage ss;
228 	char *buf = ecalloc(1, 64);
229 	int len;
230 
231 	switch (alen) {
232 	case 4: {
233 		struct sockaddr_in *sin = (void *)&ss;
234 		sin->sin_len = sizeof(*sin);
235 		sin->sin_family = AF_INET;
236 		sin->sin_port = 0;
237 		memcpy(&sin->sin_addr, addr, sizeof(sin->sin_addr));
238 		break;
239 	}
240 	case 16: {
241 		struct sockaddr_in6 *sin6 = (void *)&ss;
242 		sin6->sin6_len = sizeof(*sin6);
243 		sin6->sin6_family = AF_INET6;
244 		sin6->sin6_port = 0;
245 		sin6->sin6_scope_id = 0;
246 		memcpy(&sin6->sin6_addr, addr, sizeof(sin6->sin6_addr));
247 		break;
248 	}
249 	default:
250 		assert(false);
251 	}
252 	len = sockaddr_snprintf(buf, 64, "%a", (struct sockaddr *)&ss);
253 	if (mask && mask != NPF_NO_NETMASK) {
254 		snprintf(&buf[len], 64 - len, "/%u", mask);
255 	}
256 	return buf;
257 }
258 
259 __dead static void
260 npfctl_table(int fd, int argc, char **argv)
261 {
262 	static const struct tblops_s {
263 		const char *	cmd;
264 		int		action;
265 	} tblops[] = {
266 		{ "add",	NPF_CMD_TABLE_ADD		},
267 		{ "rem",	NPF_CMD_TABLE_REMOVE		},
268 		{ "del",	NPF_CMD_TABLE_REMOVE		},
269 		{ "test",	NPF_CMD_TABLE_LOOKUP		},
270 		{ "list",	NPF_CMD_TABLE_LIST		},
271 		{ "flush",	NPF_CMD_TABLE_FLUSH		},
272 		{ NULL,		0				}
273 	};
274 	npf_ioctl_table_t nct;
275 	fam_addr_mask_t fam;
276 	size_t buflen = 512;
277 	char *cmd, *arg;
278 	int n, alen;
279 
280 	/* Default action is list. */
281 	memset(&nct, 0, sizeof(npf_ioctl_table_t));
282 	nct.nct_name = argv[0];
283 	cmd = argv[1];
284 
285 	for (n = 0; tblops[n].cmd != NULL; n++) {
286 		if (strcmp(cmd, tblops[n].cmd) != 0) {
287 			continue;
288 		}
289 		nct.nct_cmd = tblops[n].action;
290 		break;
291 	}
292 	if (tblops[n].cmd == NULL) {
293 		errx(EXIT_FAILURE, "invalid command '%s'", cmd);
294 	}
295 
296 	switch (nct.nct_cmd) {
297 	case NPF_CMD_TABLE_LIST:
298 	case NPF_CMD_TABLE_FLUSH:
299 		arg = NULL;
300 		break;
301 	default:
302 		if (argc < 3) {
303 			usage();
304 		}
305 		arg = argv[2];
306 	}
307 
308 again:
309 	switch (nct.nct_cmd) {
310 	case NPF_CMD_TABLE_LIST:
311 		nct.nct_data.buf.buf = ecalloc(1, buflen);
312 		nct.nct_data.buf.len = buflen;
313 		break;
314 	case NPF_CMD_TABLE_FLUSH:
315 		break;
316 	default:
317 		if (!npfctl_parse_cidr(arg, &fam, &alen)) {
318 			errx(EXIT_FAILURE, "invalid CIDR '%s'", arg);
319 		}
320 		nct.nct_data.ent.alen = alen;
321 		memcpy(&nct.nct_data.ent.addr, &fam.fam_addr, alen);
322 		nct.nct_data.ent.mask = fam.fam_mask;
323 	}
324 
325 	if (ioctl(fd, IOC_NPF_TABLE, &nct) != -1) {
326 		errno = 0;
327 	}
328 	switch (errno) {
329 	case 0:
330 		break;
331 	case EEXIST:
332 		errx(EXIT_FAILURE, "entry already exists or is conflicting");
333 	case ENOENT:
334 		errx(EXIT_FAILURE, "no matching entry was not found");
335 	case EINVAL:
336 		errx(EXIT_FAILURE, "invalid address, mask or table ID");
337 	case ENOMEM:
338 		if (nct.nct_cmd == NPF_CMD_TABLE_LIST) {
339 			/* XXX */
340 			free(nct.nct_data.buf.buf);
341 			buflen <<= 1;
342 			goto again;
343 		}
344 		/* FALLTHROUGH */
345 	default:
346 		err(EXIT_FAILURE, "ioctl(IOC_NPF_TABLE)");
347 	}
348 
349 	if (nct.nct_cmd == NPF_CMD_TABLE_LIST) {
350 		npf_ioctl_ent_t *ent = nct.nct_data.buf.buf;
351 		char *buf;
352 
353 		while (nct.nct_data.buf.len--) {
354 			if (!ent->alen)
355 				break;
356 			buf = npfctl_print_addrmask(ent->alen,
357 			    &ent->addr, ent->mask);
358 			puts(buf);
359 			ent++;
360 		}
361 		free(nct.nct_data.buf.buf);
362 	} else {
363 		printf("%s: %s\n", getprogname(),
364 		    nct.nct_cmd == NPF_CMD_TABLE_LOOKUP ?
365 		    "matching entry found" : "success");
366 	}
367 	exit(EXIT_SUCCESS);
368 }
369 
370 static nl_rule_t *
371 npfctl_parse_rule(int argc, char **argv)
372 {
373 	char rule_string[1024];
374 	nl_rule_t *rl;
375 
376 	/* Get the rule string and parse it. */
377 	if (!join(rule_string, sizeof(rule_string), argc, argv, " ")) {
378 		errx(EXIT_FAILURE, "command too long");
379 	}
380 	npfctl_parse_string(rule_string);
381 	if ((rl = npfctl_rule_ref()) == NULL) {
382 		errx(EXIT_FAILURE, "could not parse the rule");
383 	}
384 	return rl;
385 }
386 
387 static void
388 npfctl_generate_key(nl_rule_t *rl, void *key)
389 {
390 	void *meta;
391 	size_t len;
392 
393 	if ((meta = npf_rule_export(rl, &len)) == NULL) {
394 		errx(EXIT_FAILURE, "error generating rule key");
395 	}
396 	__CTASSERT(NPF_RULE_MAXKEYLEN >= SHA_DIGEST_LENGTH);
397 	memset(key, 0, NPF_RULE_MAXKEYLEN);
398 	SHA1(meta, len, key);
399 	free(meta);
400 }
401 
402 __dead static void
403 npfctl_rule(int fd, int argc, char **argv)
404 {
405 	static const struct ruleops_s {
406 		const char *	cmd;
407 		int		action;
408 		bool		extra_arg;
409 	} ruleops[] = {
410 		{ "add",	NPF_CMD_RULE_ADD,	true	},
411 		{ "rem",	NPF_CMD_RULE_REMKEY,	true	},
412 		{ "del",	NPF_CMD_RULE_REMKEY,	true	},
413 		{ "rem-id",	NPF_CMD_RULE_REMOVE,	true	},
414 		{ "list",	NPF_CMD_RULE_LIST,	false	},
415 		{ "flush",	NPF_CMD_RULE_FLUSH,	false	},
416 		{ NULL,		0,			0	}
417 	};
418 	uint8_t key[NPF_RULE_MAXKEYLEN];
419 	const char *ruleset_name = argv[0];
420 	const char *cmd = argv[1];
421 	int error, action = 0;
422 	uint64_t rule_id;
423 	bool extra_arg;
424 	nl_rule_t *rl;
425 
426 	for (int n = 0; ruleops[n].cmd != NULL; n++) {
427 		if (strcmp(cmd, ruleops[n].cmd) == 0) {
428 			action = ruleops[n].action;
429 			extra_arg = ruleops[n].extra_arg;
430 			break;
431 		}
432 	}
433 	argc -= 2;
434 	argv += 2;
435 
436 	if (!action || (extra_arg && argc == 0)) {
437 		usage();
438 	}
439 
440 	switch (action) {
441 	case NPF_CMD_RULE_ADD:
442 		rl = npfctl_parse_rule(argc, argv);
443 		npfctl_generate_key(rl, key);
444 		npf_rule_setkey(rl, key, sizeof(key));
445 		error = npf_ruleset_add(fd, ruleset_name, rl, &rule_id);
446 		break;
447 	case NPF_CMD_RULE_REMKEY:
448 		rl = npfctl_parse_rule(argc, argv);
449 		npfctl_generate_key(rl, key);
450 		error = npf_ruleset_remkey(fd, ruleset_name, key, sizeof(key));
451 		break;
452 	case NPF_CMD_RULE_REMOVE:
453 		rule_id = strtoull(argv[0], NULL, 16);
454 		error = npf_ruleset_remove(fd, ruleset_name, rule_id);
455 		break;
456 	case NPF_CMD_RULE_LIST:
457 		error = npfctl_ruleset_show(fd, ruleset_name);
458 		break;
459 	case NPF_CMD_RULE_FLUSH:
460 		error = npf_ruleset_flush(fd, ruleset_name);
461 		break;
462 	default:
463 		assert(false);
464 	}
465 
466 	switch (error) {
467 	case 0:
468 		/* Success. */
469 		break;
470 	case ESRCH:
471 		errx(EXIT_FAILURE, "ruleset \"%s\" not found", ruleset_name);
472 	case ENOENT:
473 		errx(EXIT_FAILURE, "rule was not found");
474 	default:
475 		errx(EXIT_FAILURE, "rule operation: %s", strerror(error));
476 	}
477 	if (action == NPF_CMD_RULE_ADD) {
478 		printf("OK %" PRIx64 "\n", rule_id);
479 	}
480 	exit(EXIT_SUCCESS);
481 }
482 
483 static void
484 npfctl(int action, int argc, char **argv)
485 {
486 	int fd, ver, boolval, ret = 0;
487 
488 	fd = open(NPF_DEV_PATH, O_RDONLY);
489 	if (fd == -1) {
490 		err(EXIT_FAILURE, "cannot open '%s'", NPF_DEV_PATH);
491 	}
492 	if (ioctl(fd, IOC_NPF_VERSION, &ver) == -1) {
493 		err(EXIT_FAILURE, "ioctl(IOC_NPF_VERSION)");
494 	}
495 	if (ver != NPF_VERSION) {
496 		errx(EXIT_FAILURE,
497 		    "incompatible NPF interface version (%d, kernel %d)\n"
498 		    "Hint: update userland?", NPF_VERSION, ver);
499 	}
500 
501 	const char *fun = "";
502 	switch (action) {
503 	case NPFCTL_START:
504 		boolval = true;
505 		ret = ioctl(fd, IOC_NPF_SWITCH, &boolval);
506 		fun = "ioctl(IOC_NPF_SWITCH)";
507 		break;
508 	case NPFCTL_STOP:
509 		boolval = false;
510 		ret = ioctl(fd, IOC_NPF_SWITCH, &boolval);
511 		fun = "ioctl(IOC_NPF_SWITCH)";
512 		break;
513 	case NPFCTL_RELOAD:
514 		npfctl_config_init(false);
515 		npfctl_parse_file(argc < 3 ? NPF_CONF_PATH : argv[2]);
516 		errno = ret = npfctl_config_send(fd, NULL);
517 		fun = "npfctl_config_send";
518 		break;
519 	case NPFCTL_SHOWCONF:
520 		ret = npfctl_config_show(fd);
521 		fun = "npfctl_config_show";
522 		break;
523 	case NPFCTL_FLUSH:
524 		ret = npf_config_flush(fd);
525 		fun = "npf_config_flush";
526 		break;
527 	case NPFCTL_VALIDATE:
528 		npfctl_config_init(false);
529 		npfctl_parse_file(argc < 3 ? NPF_CONF_PATH : argv[2]);
530 		ret = npfctl_config_show(0);
531 		fun = "npfctl_config_show";
532 		break;
533 	case NPFCTL_TABLE:
534 		if ((argc -= 2) < 2) {
535 			usage();
536 		}
537 		argv += 2;
538 		npfctl_table(fd, argc, argv);
539 		break;
540 	case NPFCTL_RULE:
541 		if ((argc -= 2) < 2) {
542 			usage();
543 		}
544 		argv += 2;
545 		npfctl_rule(fd, argc, argv);
546 		break;
547 	case NPFCTL_STATS:
548 		ret = npfctl_print_stats(fd);
549 		fun = "npfctl_print_stats";
550 		break;
551 	case NPFCTL_SESSIONS_SAVE:
552 		if (npf_sessions_recv(fd, NPF_SESSDB_PATH) != 0) {
553 			errx(EXIT_FAILURE, "could not save sessions to '%s'",
554 			    NPF_SESSDB_PATH);
555 		}
556 		break;
557 	case NPFCTL_SESSIONS_LOAD:
558 		if (npf_sessions_send(fd, NPF_SESSDB_PATH) != 0) {
559 			errx(EXIT_FAILURE, "no sessions loaded from '%s'",
560 			    NPF_SESSDB_PATH);
561 		}
562 		break;
563 	}
564 	if (ret) {
565 		err(EXIT_FAILURE, "%s", fun);
566 	}
567 	close(fd);
568 }
569 
570 int
571 main(int argc, char **argv)
572 {
573 	char *cmd;
574 
575 	if (argc < 2) {
576 		usage();
577 	}
578 	cmd = argv[1];
579 
580 	if (strcmp(cmd, "debug") == 0) {
581 		const char *cfg = argc > 2 ? argv[2] : "/etc/npf.conf";
582 		const char *out = argc > 3 ? argv[3] : "/tmp/npf.plist";
583 
584 		npfctl_config_init(true);
585 		npfctl_parse_file(cfg);
586 		npfctl_config_send(0, out);
587 		return EXIT_SUCCESS;
588 	}
589 
590 	/* Find and call the subroutine. */
591 	for (int n = 0; operations[n].cmd != NULL; n++) {
592 		const char *opcmd = operations[n].cmd;
593 		if (strncmp(cmd, opcmd, strlen(opcmd)) != 0)
594 			continue;
595 		npfctl(operations[n].action, argc, argv);
596 		return EXIT_SUCCESS;
597 	}
598 	usage();
599 }
600