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