npfctl.c revision 1.49 1 /* $NetBSD: npfctl.c,v 1.49 2016/12/27 13:43:38 christos Exp $ */
2
3 /*-
4 * Copyright (c) 2009-2014 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.49 2016/12/27 13:43:38 christos Exp $");
34
35 #include <sys/stat.h>
36 #include <sys/types.h>
37 #include <sys/mman.h>
38 #ifdef __NetBSD__
39 #include <sha1.h>
40 #include <sys/ioctl.h>
41 #include <sys/module.h>
42 #define SHA_DIGEST_LENGTH SHA1_DIGEST_LENGTH
43 #else
44 #include <openssl/sha.h>
45 #endif
46
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <err.h>
51 #include <fcntl.h>
52 #include <unistd.h>
53 #include <errno.h>
54
55 #include <arpa/inet.h>
56
57 #include "npfctl.h"
58
59 extern void npf_yyparse_string(const char *);
60
61 enum {
62 NPFCTL_START,
63 NPFCTL_STOP,
64 NPFCTL_RELOAD,
65 NPFCTL_SHOWCONF,
66 NPFCTL_FLUSH,
67 NPFCTL_VALIDATE,
68 NPFCTL_TABLE,
69 NPFCTL_RULE,
70 NPFCTL_STATS,
71 NPFCTL_SAVE,
72 NPFCTL_LOAD,
73 };
74
75 static const struct operations_s {
76 const char * cmd;
77 int action;
78 } operations[] = {
79 /* Start, stop, reload */
80 { "start", NPFCTL_START },
81 { "stop", NPFCTL_STOP },
82 { "reload", NPFCTL_RELOAD },
83 { "show", NPFCTL_SHOWCONF, },
84 { "flush", NPFCTL_FLUSH },
85 { "valid", NPFCTL_VALIDATE },
86 /* Table */
87 { "table", NPFCTL_TABLE },
88 /* Rule */
89 { "rule", NPFCTL_RULE },
90 /* Stats */
91 { "stats", NPFCTL_STATS },
92 /* Full state save/load */
93 { "save", NPFCTL_SAVE },
94 { "load", NPFCTL_LOAD },
95 /* --- */
96 { NULL, 0 }
97 };
98
99 bool
100 join(char *buf, size_t buflen, int count, char **args, const char *sep)
101 {
102 const u_int seplen = strlen(sep);
103 char *s = buf, *p = NULL;
104
105 for (int i = 0; i < count; i++) {
106 size_t len;
107
108 p = stpncpy(s, args[i], buflen);
109 len = p - s + seplen;
110 if (len >= buflen) {
111 return false;
112 }
113 buflen -= len;
114 strcpy(p, sep);
115 s = p + seplen;
116 }
117 *p = '\0';
118 return true;
119 }
120
121 __dead static void
122 usage(void)
123 {
124 const char *progname = getprogname();
125
126 fprintf(stderr,
127 "Usage:\t%s start | stop | flush | show | stats\n",
128 progname);
129 fprintf(stderr,
130 "\t%s validate | reload [<rule-file>]\n",
131 progname);
132 fprintf(stderr,
133 "\t%s rule \"rule-name\" { add | rem } <rule-syntax>\n",
134 progname);
135 fprintf(stderr,
136 "\t%s rule \"rule-name\" rem-id <rule-id>\n",
137 progname);
138 fprintf(stderr,
139 "\t%s rule \"rule-name\" { list | flush }\n",
140 progname);
141 fprintf(stderr,
142 "\t%s table <tid> { add | rem | test } <address/mask>\n",
143 progname);
144 fprintf(stderr,
145 "\t%s table <tid> { list | flush }\n",
146 progname);
147 fprintf(stderr,
148 "\t%s save | load\n",
149 progname);
150 exit(EXIT_FAILURE);
151 }
152
153 static int
154 npfctl_print_stats(int fd)
155 {
156 static const struct stats_s {
157 /* Note: -1 indicates a new section. */
158 int index;
159 const char * name;
160 } stats[] = {
161 { -1, "Packets passed" },
162 { NPF_STAT_PASS_DEFAULT, "default pass" },
163 { NPF_STAT_PASS_RULESET, "ruleset pass" },
164 { NPF_STAT_PASS_CONN, "state pass" },
165
166 { -1, "Packets blocked" },
167 { NPF_STAT_BLOCK_DEFAULT, "default block" },
168 { NPF_STAT_BLOCK_RULESET, "ruleset block" },
169
170 { -1, "State and NAT entries" },
171 { NPF_STAT_CONN_CREATE, "state allocations"},
172 { NPF_STAT_CONN_DESTROY, "state destructions"},
173 { NPF_STAT_NAT_CREATE, "NAT entry allocations" },
174 { NPF_STAT_NAT_DESTROY, "NAT entry destructions"},
175
176 { -1, "Network buffers" },
177 { NPF_STAT_NBUF_NONCONTIG, "non-contiguous cases" },
178 { NPF_STAT_NBUF_CONTIG_FAIL, "contig alloc failures" },
179
180 { -1, "Invalid packet state cases" },
181 { NPF_STAT_INVALID_STATE, "cases in total" },
182 { NPF_STAT_INVALID_STATE_TCP1, "TCP case I" },
183 { NPF_STAT_INVALID_STATE_TCP2, "TCP case II" },
184 { NPF_STAT_INVALID_STATE_TCP3, "TCP case III" },
185
186 { -1, "Packet race cases" },
187 { NPF_STAT_RACE_NAT, "NAT association race" },
188 { NPF_STAT_RACE_CONN, "duplicate state race" },
189
190 { -1, "Fragmentation" },
191 { NPF_STAT_FRAGMENTS, "fragments" },
192 { NPF_STAT_REASSEMBLY, "reassembled" },
193 { NPF_STAT_REASSFAIL, "failed reassembly" },
194
195 { -1, "Other" },
196 { NPF_STAT_ERROR, "unexpected errors" },
197 };
198 uint64_t *st = ecalloc(1, NPF_STATS_SIZE);
199
200 if (ioctl(fd, IOC_NPF_STATS, &st) != 0) {
201 err(EXIT_FAILURE, "ioctl(IOC_NPF_STATS)");
202 }
203
204 for (unsigned i = 0; i < __arraycount(stats); i++) {
205 const char *sname = stats[i].name;
206 int sidx = stats[i].index;
207
208 if (sidx == -1) {
209 printf("%s:\n", sname);
210 } else {
211 printf("\t%"PRIu64" %s\n", st[sidx], sname);
212 }
213 }
214
215 free(st);
216 return 0;
217 }
218
219 void
220 npfctl_print_error(const npf_error_t *ne)
221 {
222 const char *srcfile = ne->source_file;
223
224 if (srcfile) {
225 warnx("source %s line %d", srcfile, ne->source_line);
226 }
227 if (ne->id) {
228 warnx("object: %" PRIi64, ne->id);
229 }
230 }
231
232 char *
233 npfctl_print_addrmask(int alen, const npf_addr_t *addr, npf_netmask_t mask)
234 {
235 const unsigned buflen = 64;
236 char *buf = ecalloc(1, buflen);
237 struct sockaddr_storage ss;
238
239 memset(&ss, 0, sizeof(ss));
240
241 switch (alen) {
242 case 4: {
243 struct sockaddr_in *sin = (void *)&ss;
244 sin->sin_family = AF_INET;
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_family = AF_INET6;
251 memcpy(&sin6->sin6_addr, addr, sizeof(sin6->sin6_addr));
252 break;
253 }
254 default:
255 assert(false);
256 }
257 inet_ntop(ss.ss_family, (const void *)&ss, buf, buflen);
258 if (mask && mask != NPF_NO_NETMASK) {
259 const unsigned len = strlen(buf);
260 snprintf(&buf[len], buflen - len, "/%u", mask);
261 }
262 return buf;
263 }
264
265 __dead static void
266 npfctl_table(int fd, int argc, char **argv)
267 {
268 static const struct tblops_s {
269 const char * cmd;
270 int action;
271 } tblops[] = {
272 { "add", NPF_CMD_TABLE_ADD },
273 { "rem", NPF_CMD_TABLE_REMOVE },
274 { "del", NPF_CMD_TABLE_REMOVE },
275 { "test", NPF_CMD_TABLE_LOOKUP },
276 { "list", NPF_CMD_TABLE_LIST },
277 { "flush", NPF_CMD_TABLE_FLUSH },
278 { NULL, 0 }
279 };
280 npf_ioctl_table_t nct;
281 fam_addr_mask_t fam;
282 size_t buflen = 512;
283 char *cmd, *arg;
284 int n, alen;
285
286 /* Default action is list. */
287 memset(&nct, 0, sizeof(npf_ioctl_table_t));
288 nct.nct_name = argv[0];
289 cmd = argv[1];
290
291 for (n = 0; tblops[n].cmd != NULL; n++) {
292 if (strcmp(cmd, tblops[n].cmd) != 0) {
293 continue;
294 }
295 nct.nct_cmd = tblops[n].action;
296 break;
297 }
298 if (tblops[n].cmd == NULL) {
299 errx(EXIT_FAILURE, "invalid command '%s'", cmd);
300 }
301
302 switch (nct.nct_cmd) {
303 case NPF_CMD_TABLE_LIST:
304 case NPF_CMD_TABLE_FLUSH:
305 arg = NULL;
306 break;
307 default:
308 if (argc < 3) {
309 usage();
310 }
311 arg = argv[2];
312 }
313
314 again:
315 switch (nct.nct_cmd) {
316 case NPF_CMD_TABLE_LIST:
317 nct.nct_data.buf.buf = ecalloc(1, buflen);
318 nct.nct_data.buf.len = buflen;
319 break;
320 case NPF_CMD_TABLE_FLUSH:
321 break;
322 default:
323 if (!npfctl_parse_cidr(arg, &fam, &alen)) {
324 errx(EXIT_FAILURE, "invalid CIDR '%s'", arg);
325 }
326 nct.nct_data.ent.alen = alen;
327 memcpy(&nct.nct_data.ent.addr, &fam.fam_addr, alen);
328 nct.nct_data.ent.mask = fam.fam_mask;
329 }
330
331 if (ioctl(fd, IOC_NPF_TABLE, &nct) != -1) {
332 errno = 0;
333 }
334 switch (errno) {
335 case 0:
336 break;
337 case EEXIST:
338 errx(EXIT_FAILURE, "entry already exists or is conflicting");
339 case ENOENT:
340 errx(EXIT_FAILURE, "no matching entry was not found");
341 case EINVAL:
342 errx(EXIT_FAILURE, "invalid address, mask or table ID");
343 case ENOMEM:
344 if (nct.nct_cmd == NPF_CMD_TABLE_LIST) {
345 /* XXX */
346 free(nct.nct_data.buf.buf);
347 buflen <<= 1;
348 goto again;
349 }
350 /* FALLTHROUGH */
351 default:
352 err(EXIT_FAILURE, "ioctl(IOC_NPF_TABLE)");
353 }
354
355 if (nct.nct_cmd == NPF_CMD_TABLE_LIST) {
356 npf_ioctl_ent_t *ent = nct.nct_data.buf.buf;
357 char *buf;
358
359 while (nct.nct_data.buf.len--) {
360 if (!ent->alen)
361 break;
362 buf = npfctl_print_addrmask(ent->alen,
363 &ent->addr, ent->mask);
364 puts(buf);
365 ent++;
366 }
367 free(nct.nct_data.buf.buf);
368 } else {
369 printf("%s: %s\n", getprogname(),
370 nct.nct_cmd == NPF_CMD_TABLE_LOOKUP ?
371 "matching entry found" : "success");
372 }
373 exit(EXIT_SUCCESS);
374 }
375
376 static nl_rule_t *
377 npfctl_parse_rule(int argc, char **argv)
378 {
379 char rule_string[1024];
380 nl_rule_t *rl;
381
382 /* Get the rule string and parse it. */
383 if (!join(rule_string, sizeof(rule_string), argc, argv, " ")) {
384 errx(EXIT_FAILURE, "command too long");
385 }
386 npfctl_parse_string(rule_string);
387 if ((rl = npfctl_rule_ref()) == NULL) {
388 errx(EXIT_FAILURE, "could not parse the rule");
389 }
390 return rl;
391 }
392
393 #ifdef __NetBSD__
394 static unsigned char *
395 SHA1(const unsigned char *d, size_t l, unsigned char *md)
396 {
397 SHA1_CTX c;
398
399 SHA1Init(&c);
400 SHA1Update(&c, d, l);
401 SHA1Final(md, &c);
402 return md;
403 }
404 #endif
405
406 static void
407 npfctl_generate_key(nl_rule_t *rl, void *key)
408 {
409 void *meta;
410 size_t len;
411
412 if ((meta = npf_rule_export(rl, &len)) == NULL) {
413 errx(EXIT_FAILURE, "error generating rule key");
414 }
415 __CTASSERT(NPF_RULE_MAXKEYLEN >= SHA_DIGEST_LENGTH);
416 memset(key, 0, NPF_RULE_MAXKEYLEN);
417 SHA1(meta, len, key);
418 free(meta);
419 }
420
421 __dead static void
422 npfctl_rule(int fd, int argc, char **argv)
423 {
424 static const struct ruleops_s {
425 const char * cmd;
426 int action;
427 bool extra_arg;
428 } ruleops[] = {
429 { "add", NPF_CMD_RULE_ADD, true },
430 { "rem", NPF_CMD_RULE_REMKEY, true },
431 { "del", NPF_CMD_RULE_REMKEY, true },
432 { "rem-id", NPF_CMD_RULE_REMOVE, true },
433 { "list", NPF_CMD_RULE_LIST, false },
434 { "flush", NPF_CMD_RULE_FLUSH, false },
435 { NULL, 0, 0 }
436 };
437 uint8_t key[NPF_RULE_MAXKEYLEN];
438 const char *ruleset_name = argv[0];
439 const char *cmd = argv[1];
440 int error, action = 0;
441 uint64_t rule_id;
442 bool extra_arg;
443 nl_rule_t *rl;
444
445 for (int n = 0; ruleops[n].cmd != NULL; n++) {
446 if (strcmp(cmd, ruleops[n].cmd) == 0) {
447 action = ruleops[n].action;
448 extra_arg = ruleops[n].extra_arg;
449 break;
450 }
451 }
452 argc -= 2;
453 argv += 2;
454
455 if (!action || (extra_arg && argc == 0)) {
456 usage();
457 }
458
459 switch (action) {
460 case NPF_CMD_RULE_ADD:
461 rl = npfctl_parse_rule(argc, argv);
462 npfctl_generate_key(rl, key);
463 npf_rule_setkey(rl, key, sizeof(key));
464 error = npf_ruleset_add(fd, ruleset_name, rl, &rule_id);
465 break;
466 case NPF_CMD_RULE_REMKEY:
467 rl = npfctl_parse_rule(argc, argv);
468 npfctl_generate_key(rl, key);
469 error = npf_ruleset_remkey(fd, ruleset_name, key, sizeof(key));
470 break;
471 case NPF_CMD_RULE_REMOVE:
472 rule_id = strtoull(argv[0], NULL, 16);
473 error = npf_ruleset_remove(fd, ruleset_name, rule_id);
474 break;
475 case NPF_CMD_RULE_LIST:
476 error = npfctl_ruleset_show(fd, ruleset_name);
477 break;
478 case NPF_CMD_RULE_FLUSH:
479 error = npf_ruleset_flush(fd, ruleset_name);
480 break;
481 default:
482 abort();
483 }
484
485 switch (error) {
486 case 0:
487 /* Success. */
488 break;
489 case ESRCH:
490 errx(EXIT_FAILURE, "ruleset \"%s\" not found", ruleset_name);
491 case ENOENT:
492 errx(EXIT_FAILURE, "rule was not found");
493 default:
494 errx(EXIT_FAILURE, "rule operation: %s", strerror(error));
495 }
496 if (action == NPF_CMD_RULE_ADD) {
497 printf("OK %" PRIx64 "\n", rule_id);
498 }
499 exit(EXIT_SUCCESS);
500 }
501
502 static bool bpfjit = true;
503
504 void
505 npfctl_bpfjit(bool onoff)
506 {
507 bpfjit = onoff;
508 }
509
510 static void
511 npfctl_preload_bpfjit(void)
512 {
513 #ifdef __NetBSD__
514 modctl_load_t args = {
515 .ml_filename = "bpfjit",
516 .ml_flags = MODCTL_NO_PROP,
517 .ml_props = NULL,
518 .ml_propslen = 0
519 };
520
521 if (!bpfjit)
522 return;
523
524 if (modctl(MODCTL_LOAD, &args) != 0 && errno != EEXIST) {
525 static const char *p = "; performance will be degraded";
526 if (errno == ENOENT)
527 warnx("the bpfjit module seems to be missing%s", p);
528 else
529 warn("error loading the bpfjit module%s", p);
530 warnx("To disable this warning `set bpf.jit off' in "
531 "/etc/npf.conf");
532 }
533 #endif
534 }
535
536 static int
537 npfctl_load(int fd)
538 {
539 nl_config_t *ncf;
540 npf_error_t errinfo;
541 struct stat sb;
542 size_t blen;
543 void *blob;
544 int error;
545
546 /*
547 * The file may change while reading - we are not handling this,
548 * leaving this responsibility for the caller.
549 */
550 if (stat(NPF_DB_PATH, &sb) == -1) {
551 err(EXIT_FAILURE, "stat");
552 }
553 if ((blen = sb.st_size) == 0) {
554 err(EXIT_FAILURE, "saved configuration file is empty");
555 }
556 if ((blob = mmap(NULL, blen, PROT_READ,
557 MAP_FILE | MAP_PRIVATE, fd, 0)) == MAP_FAILED) {
558 err(EXIT_FAILURE, "mmap");
559 }
560 ncf = npf_config_import(blob, blen);
561 munmap(blob, blen);
562 if (ncf == NULL) {
563 return errno;
564 }
565
566 /*
567 * Configuration imported - submit it now.
568 **/
569 errno = error = npf_config_submit(ncf, fd, &errinfo);
570 if (error) {
571 npfctl_print_error(&errinfo);
572 }
573 npf_config_destroy(ncf);
574 return error;
575 }
576
577 static void
578 npfctl(int action, int argc, char **argv)
579 {
580 int fd, ver, boolval, ret = 0;
581 nl_config_t *ncf;
582 const char *fun = "";
583
584 fd = open(NPF_DEV_PATH, O_RDONLY);
585 if (fd == -1) {
586 err(EXIT_FAILURE, "cannot open '%s'", NPF_DEV_PATH);
587 }
588 if (ioctl(fd, IOC_NPF_VERSION, &ver) == -1) {
589 err(EXIT_FAILURE, "ioctl(IOC_NPF_VERSION)");
590 }
591 if (ver != NPF_VERSION) {
592 errx(EXIT_FAILURE,
593 "incompatible NPF interface version (%d, kernel %d)\n"
594 "Hint: update userland?", NPF_VERSION, ver);
595 }
596
597 switch (action) {
598 case NPFCTL_START:
599 boolval = true;
600 ret = ioctl(fd, IOC_NPF_SWITCH, &boolval);
601 fun = "ioctl(IOC_NPF_SWITCH)";
602 break;
603 case NPFCTL_STOP:
604 boolval = false;
605 ret = ioctl(fd, IOC_NPF_SWITCH, &boolval);
606 fun = "ioctl(IOC_NPF_SWITCH)";
607 break;
608 case NPFCTL_RELOAD:
609 npfctl_config_init(false);
610 npfctl_parse_file(argc < 3 ? NPF_CONF_PATH : argv[2]);
611 npfctl_preload_bpfjit();
612 errno = ret = npfctl_config_send(fd, NULL);
613 fun = "npfctl_config_send";
614 break;
615 case NPFCTL_SHOWCONF:
616 ret = npfctl_config_show(fd);
617 fun = "npfctl_config_show";
618 break;
619 case NPFCTL_FLUSH:
620 ret = npf_config_flush(fd);
621 fun = "npf_config_flush";
622 break;
623 case NPFCTL_VALIDATE:
624 npfctl_config_init(false);
625 npfctl_parse_file(argc < 3 ? NPF_CONF_PATH : argv[2]);
626 ret = npfctl_config_show(0);
627 fun = "npfctl_config_show";
628 break;
629 case NPFCTL_TABLE:
630 if ((argc -= 2) < 2) {
631 usage();
632 }
633 argv += 2;
634 npfctl_table(fd, argc, argv);
635 break;
636 case NPFCTL_RULE:
637 if ((argc -= 2) < 2) {
638 usage();
639 }
640 argv += 2;
641 npfctl_rule(fd, argc, argv);
642 break;
643 case NPFCTL_LOAD:
644 npfctl_preload_bpfjit();
645 ret = npfctl_load(fd);
646 fun = "npfctl_config_load";
647 break;
648 case NPFCTL_SAVE:
649 ncf = npf_config_retrieve(fd);
650 if (ncf) {
651 npfctl_config_save(ncf, NPF_DB_PATH);
652 npf_config_destroy(ncf);
653 } else {
654 ret = errno;
655 }
656 fun = "npfctl_config_save";
657 break;
658 case NPFCTL_STATS:
659 ret = npfctl_print_stats(fd);
660 fun = "npfctl_print_stats";
661 break;
662 }
663 if (ret) {
664 err(EXIT_FAILURE, "%s", fun);
665 }
666 close(fd);
667 }
668
669 int
670 main(int argc, char **argv)
671 {
672 char *cmd;
673
674 if (argc < 2) {
675 usage();
676 }
677 npfctl_show_init();
678 cmd = argv[1];
679
680 if (strcmp(cmd, "debug") == 0) {
681 const char *cfg = argc > 2 ? argv[2] : "/etc/npf.conf";
682 const char *out = argc > 3 ? argv[3] : "/tmp/npf.plist";
683
684 npfctl_config_init(true);
685 npfctl_parse_file(cfg);
686 npfctl_config_send(0, out);
687 return EXIT_SUCCESS;
688 }
689
690 /* Find and call the subroutine. */
691 for (int n = 0; operations[n].cmd != NULL; n++) {
692 const char *opcmd = operations[n].cmd;
693 if (strncmp(cmd, opcmd, strlen(opcmd)) != 0)
694 continue;
695 npfctl(operations[n].action, argc, argv);
696 return EXIT_SUCCESS;
697 }
698 usage();
699 }
700