2 * Copyright (c) 2002-2003,2010 Luigi Rizzo
3 * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
4 * Copyright (c) 1994 Ugen J.S.Antsilevich
6 * Idea and grammar partially left from:
7 * Copyright (c) 1993 Daniel Boulet
9 * Redistribution and use in source forms, with and without modification,
10 * are permitted provided that this entire comment appears intact.
12 * Redistribution in binary form may occur without any restrictions.
13 * Obviously, it would be nice if you gave credit where credit is due
14 * but requiring it would be too onerous.
16 * This software is provided ``AS IS'' without any warranties of any kind.
18 * Command line interface for IP firewall facility
42 "ipfw syntax summary (but please do read the ipfw(8) manpage):\n\n"
43 "\tipfw [-abcdefhnNqStTv] <command>\n\n"
44 "where <command> is one of the following:\n\n"
45 "add [num] [set N] [prob x] RULE-BODY\n"
46 "{pipe|queue} N config PIPE-BODY\n"
47 "[pipe|queue] {zero|delete|show} [N{,N}]\n"
48 "nat N config {ip IPADDR|if IFNAME|log|deny_in|same_ports|unreg_only|unreg_cgn|\n"
49 " reset|reverse|proxy_only|redirect_addr linkspec|\n"
50 " redirect_port linkspec|redirect_proto linkspec|\n"
51 " port_range lower-upper}\n"
52 "set [disable N... enable N...] | move [rule] X to Y | swap X Y | show\n"
53 "set N {show|list|zero|resetlog|delete} [N{,N}] | flush\n"
54 "table N {add ip[/bits] [value] | delete ip[/bits] | flush | list}\n"
55 "table all {flush | list}\n"
57 "RULE-BODY: check-state [PARAMS] | ACTION [PARAMS] ADDR [OPTION_LIST]\n"
58 "ACTION: check-state | allow | count | deny | unreach{,6} CODE |\n"
59 " skipto N | {divert|tee} PORT | forward ADDR |\n"
60 " pipe N | queue N | nat N | setfib FIB | reass\n"
61 "PARAMS: [log [logamount LOGLIMIT]] [altq QUEUE_NAME]\n"
62 "ADDR: [ MAC dst src ether_type ] \n"
63 " [ ip from IPADDR [ PORT ] to IPADDR [ PORTLIST ] ]\n"
64 " [ ipv6|ip6 from IP6ADDR [ PORT ] to IP6ADDR [ PORTLIST ] ]\n"
65 "IPADDR: [not] { any | me | ip/bits{x,y,z} | table(t[,v]) | IPLIST }\n"
66 "IP6ADDR: [not] { any | me | me6 | ip6/bits | IP6LIST }\n"
67 "IP6LIST: { ip6 | ip6/bits }[,IP6LIST]\n"
68 "IPLIST: { ip | ip/bits | ip:mask }[,IPLIST]\n"
69 "OPTION_LIST: OPTION [OPTION_LIST]\n"
70 "OPTION: bridged | diverted | diverted-loopback | diverted-output |\n"
71 " {dst-ip|src-ip} IPADDR | {dst-ip6|src-ip6|dst-ipv6|src-ipv6} IP6ADDR |\n"
72 " {dst-port|src-port} LIST |\n"
73 " estab | frag | {gid|uid} N | icmptypes LIST | in | out | ipid LIST |\n"
74 " iplen LIST | ipoptions SPEC | ipprecedence | ipsec | iptos SPEC |\n"
75 " ipttl LIST | ipversion VER | keep-state | layer2 | limit ... |\n"
76 " icmp6types LIST | ext6hdr LIST | flow-id N[,N] | fib FIB |\n"
77 " mac ... | mac-type LIST | proto LIST | {recv|xmit|via} {IF|IPADDR} |\n"
78 " setup | {tcpack|tcpseq|tcpwin} NN | tcpflags SPEC | tcpoptions SPEC |\n"
79 " tcpdatalen LIST | verrevpath | versrcreach | antispoof\n"
83 "dnctl syntax summary (but please do read the dnctl(8) manpage):\n\n"
84 "\tdnctl [-hnsv] <command>\n\n"
85 "where <command> is one of the following:\n\n"
86 "[pipe|queue|sched] N config PIPE-BODY\n"
87 "[pipe|queue|sched] {delete|list|show} [N{,N}]\n"
96 * Called with the arguments, including program name because getopt
97 * wants it to be present.
98 * Returns 0 if successful, 1 if empty command, errx() in case of errors.
99 * First thing we do is process parameters creating an argv[] array
100 * which includes the program name and a NULL entry at the end.
101 * If we are called with a single string, we split it on whitespace.
102 * Also, arguments with a trailing ',' are joined to the next one.
103 * The pointers (av[]) and data are in a single chunk of memory.
104 * av[0] points to the original program name, all other entries
105 * point into the allocated chunk.
108 ipfw_main(int oldac, char **oldav)
112 char **av, **save_av;
113 int do_acct = 0; /* Show packet/byte count */
114 int try_next = 0; /* set if pipe cmd not found */
115 int av_size; /* compute the av size */
116 char *av_p; /* used to build the av list */
118 #define WHITESP " \t\f\v\n\r"
120 return 1; /* need at least one argument */
124 * If we are called with one argument, try to split it into
125 * words for subsequent parsing. Spaces after a ',' are
126 * removed by copying the string in-place.
128 char *arg = oldav[1]; /* The string is the first arg. */
130 int copy = 0; /* 1 if we need to copy, 0 otherwise */
133 for (i = j = 0; i < l; i++) {
134 if (arg[i] == '#') /* comment marker */
138 copy = !strchr("," WHITESP, arg[i]);
140 copy = !strchr(WHITESP, arg[i]);
145 if (!copy && j > 0) /* last char was a 'blank', remove it */
147 l = j; /* the new argument length */
149 if (l == 0) /* empty string! */
153 * First, count number of arguments. Because of the previous
154 * processing, this is just the number of blanks plus 1.
156 for (i = 0, ac = 1; i < l; i++)
157 if (strchr(WHITESP, arg[i]) != NULL)
161 * Allocate the argument list structure as a single block
162 * of memory, containing pointers and the argument
163 * strings. We include one entry for the program name
164 * because getopt expects it, and a NULL at the end
165 * to simplify further parsing.
167 ac++; /* add 1 for the program name */
168 av_size = (ac+1) * sizeof(char *) + l + 1;
169 av = safe_calloc(av_size, 1);
172 * Init the argument pointer to the end of the array
173 * and copy arguments from arg[] to av[]. For each one,
174 * j is the initial character, i is the one past the end.
176 av_p = (char *)&av[ac+1];
177 for (ac = 1, i = j = 0; i < l; i++) {
178 if (strchr(WHITESP, arg[i]) != NULL || i == l-1) {
181 bcopy(arg+j, av_p, i-j);
183 av_p += i-j; /* the length of the string */
191 * If an argument ends with ',' join with the next one.
196 * Allocate the argument list structure as a single block
197 * of memory, containing both pointers and the argument
198 * strings. We include some space for the program name
199 * because getopt expects it.
200 * We add an extra pointer to the end of the array,
201 * to make simpler further parsing.
203 for (i=0; i<oldac; i++)
204 l += strlen(oldav[i]);
206 av_size = (oldac+1) * sizeof(char *) + l + oldac;
207 av = safe_calloc(av_size, 1);
210 * Init the argument pointer to the end of the array
211 * and copy arguments from arg[] to av[]
213 av_p = (char *)&av[oldac+1];
214 for (first = i = ac = 1, l = 0; i < oldac; i++) {
215 char *arg = oldav[i];
219 if (arg[k-1] != ',' || i == oldac-1) {
222 for (l=0; first <= i; first++) {
223 strcat(av_p, oldav[first]);
224 av_p += strlen(oldav[first]);
235 * set the progname pointer to the original string
236 * and terminate the array with null
241 /* Set the force flag for non-interactive processes */
243 g_co.do_force = !isatty(STDIN_FILENO);
245 #ifdef EMULATE_SYSCTL /* sysctl emulation */
246 if (is_ipfw() && ac >= 2 &&
247 !strcmp(av[1], "sysctl")) {
252 printf( "sysctl emulation usage:\n"
253 " ipfw sysctl name[=value]\n"
254 " ipfw sysctl -a\n");
257 s = strchr(av[2], '=');
259 s = !strcmp(av[2], "-a") ? NULL : av[2];
260 sysctlbyname(s, NULL, NULL, NULL, 0);
261 } else { /* ipfw sysctl x.y.z=value */
262 /* assume an INT value, will extend later */
264 printf("ipfw sysctl: missing value\n\n");
268 i = strtol(s+1, NULL, 0);
269 sysctlbyname(av[2], NULL, NULL, &i, sizeof(int));
275 /* Save arguments for final freeing of memory. */
278 optind = optreset = 1; /* restart getopt() */
280 while ((ch = getopt(ac, av, "abcdDefhinNp:qs:STtv")) != -1)
287 g_co.comment_only = 1;
304 /* nop for compatibility */
314 break; /* NOTREACHED */
317 g_co.do_value_as_ip = 1;
329 errx(EX_USAGE, "An absolute pathname must be used "
338 g_co.do_sort = atoi(optarg);
346 g_co.do_time = TIMESTAMP_STRING;
350 g_co.do_time = TIMESTAMP_NUMERIC;
353 case 'v': /* verbose */
362 while ((ch = getopt(ac, av, "hns:v")) != -1)
368 break; /* NOTREACHED */
375 g_co.do_sort = atoi(optarg);
378 case 'v': /* verbose */
391 NEED1("bad arguments, for usage summary ``ipfw''");
394 * An undocumented behaviour of ipfw1 was to allow rule numbers first,
395 * e.g. "100 add allow ..." instead of "add 100 allow ...".
396 * In case, swap first and second argument to get the normal form.
398 if (ac > 1 && isdigit(*av[0])) {
406 * Optional: pipe, queue or nat.
411 if (is_ipfw() && !strncmp(*av, "nat", strlen(*av)))
413 else if (!strncmp(*av, "pipe", strlen(*av)))
415 else if (_substrcmp(*av, "queue") == 0)
417 else if (_substrcmp(*av, "flowset") == 0)
419 else if (_substrcmp(*av, "sched") == 0)
421 else if (is_ipfw() && !strncmp(*av, "set", strlen(*av))) {
422 if (ac > 1 && isdigit(av[1][0])) {
423 g_co.use_set = strtonum(av[1], 0, resvd_set_number,
427 "invalid set number %s\n", av[1]);
428 ac -= 2; av += 2; g_co.use_set++;
432 if (g_co.do_pipe || g_co.do_nat) {
436 NEED1("missing command");
439 * For pipes, queues and nats we normally say 'nat|pipe NN config'
440 * but the code is easier to parse as 'nat|pipe config NN'
441 * so we swap the two arguments.
443 if ((g_co.do_pipe || g_co.do_nat) && ac > 1 && isdigit(*av[0])) {
450 if (! is_ipfw() && g_co.do_pipe == 0) {
454 if (g_co.use_set == 0) {
455 if (is_ipfw() && _substrcmp(*av, "add") == 0)
457 else if (g_co.do_nat && _substrcmp(*av, "show") == 0)
458 ipfw_show_nat(ac, av);
459 else if (g_co.do_pipe && _substrcmp(*av, "config") == 0)
460 ipfw_config_pipe(ac, av);
461 else if (g_co.do_nat && _substrcmp(*av, "config") == 0)
462 ipfw_config_nat(ac, av);
463 else if (is_ipfw() && _substrcmp(*av, "set") == 0)
464 ipfw_sets_handler(av);
465 else if (is_ipfw() && _substrcmp(*av, "table") == 0)
466 ipfw_table_handler(ac, av);
467 else if (is_ipfw() && _substrcmp(*av, "enable") == 0)
468 ipfw_sysctl_handler(av, 1);
469 else if (is_ipfw() && _substrcmp(*av, "disable") == 0)
470 ipfw_sysctl_handler(av, 0);
475 if (g_co.use_set || try_next) {
476 if (_substrcmp(*av, "delete") == 0)
478 else if (is_ipfw() && !strncmp(*av, "nat64clat", strlen(*av)))
479 ipfw_nat64clat_handler(ac, av);
480 else if (is_ipfw() && !strncmp(*av, "nat64stl", strlen(*av)))
481 ipfw_nat64stl_handler(ac, av);
482 else if (is_ipfw() && !strncmp(*av, "nat64lsn", strlen(*av)))
483 ipfw_nat64lsn_handler(ac, av);
484 else if (is_ipfw() && !strncmp(*av, "nptv6", strlen(*av)))
485 ipfw_nptv6_handler(ac, av);
486 else if (_substrcmp(*av, "flush") == 0)
487 ipfw_flush(g_co.do_force);
488 else if (is_ipfw() && _substrcmp(*av, "zero") == 0)
489 ipfw_zero(ac, av, 0 /* IP_FW_ZERO */);
490 else if (is_ipfw() && _substrcmp(*av, "resetlog") == 0)
491 ipfw_zero(ac, av, 1 /* IP_FW_RESETLOG */);
492 else if (_substrcmp(*av, "print") == 0 ||
493 _substrcmp(*av, "list") == 0)
494 ipfw_list(ac, av, do_acct);
495 else if (_substrcmp(*av, "show") == 0)
496 ipfw_list(ac, av, 1 /* show counters */);
497 else if (is_ipfw() && _substrcmp(*av, "table") == 0)
498 ipfw_table_handler(ac, av);
499 else if (is_ipfw() && _substrcmp(*av, "internal") == 0)
500 ipfw_internal_handler(ac, av);
502 errx(EX_USAGE, "bad command `%s'", *av);
505 /* Free memory allocated in the argument parsing. */
512 ipfw_readfile(int ac, char *av[])
516 char *progname = av[0]; /* original program name */
517 const char *cmd = NULL; /* preprocessor name, if any */
518 const char *filename = av[ac-1]; /* file to read */
524 while ((c = getopt(ac, av, "cfNnp:qS")) != -1) {
544 * ipfw -p cmd [args] filename
546 * We are done with getopt(). All arguments
547 * except the filename go to the preprocessor,
548 * so we need to do the following:
549 * - check that a filename is actually present;
550 * - advance av by optind-1 to skip arguments
552 * - decrease ac by optind, to remove the args
553 * already processed and the final filename;
554 * - set the last entry in av[] to NULL so
555 * popen() can detect the end of the array;
556 * - set optind=ac to let getopt() terminate.
559 errx(EX_USAGE, "no filename argument");
576 errx(EX_USAGE, "bad arguments, for usage"
577 " summary ``ipfw''");
581 while ((c = getopt(ac, av, "nq")) != -1) {
592 errx(EX_USAGE, "bad arguments, for usage"
593 " summary ``dnctl''");
598 if (cmd == NULL && ac != optind + 1)
599 errx(EX_USAGE, "extraneous filename arguments %s", av[ac-1]);
601 if ((f = fopen(filename, "r")) == NULL)
602 err(EX_UNAVAILABLE, "fopen: %s", filename);
604 if (cmd != NULL) { /* pipe through preprocessor */
607 if (pipe(pipedes) == -1)
608 err(EX_OSERR, "cannot create pipe");
612 err(EX_OSERR, "cannot fork");
616 * Child, will run the preprocessor with the
617 * file on stdin and the pipe on stdout.
619 if (dup2(fileno(f), 0) == -1
620 || dup2(pipedes[1], 1) == -1)
621 err(EX_OSERR, "dup2()");
626 err(EX_OSERR, "execvp(%s) failed", cmd);
627 } else { /* parent, will reopen f as the pipe */
630 if ((f = fdopen(pipedes[0], "r")) == NULL) {
631 int savederrno = errno;
633 (void)kill(preproc, SIGTERM);
635 err(EX_OSERR, "fdopen()");
640 while (fgets(buf, sizeof(buf), f)) { /* read commands */
645 snprintf(linename, sizeof(linename), "Line %d", lineno);
646 setprogname(linename); /* XXX */
655 if (waitpid(preproc, &status, 0) == -1)
656 errx(EX_OSERR, "waitpid()");
657 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
659 "preprocessor exited with status %d",
660 WEXITSTATUS(status));
661 else if (WIFSIGNALED(status))
663 "preprocessor exited with signal %d",
669 main(int ac, char *av[])
671 #if defined(_WIN32) && defined(TCC)
675 unsigned short wVersionRequested = MAKEWORD(2, 2);
676 ret = WSAStartup(wVersionRequested, &wsaData);
678 /* Tell the user that we could not find a usable */
680 printf("WSAStartup failed with error: %d\n", ret);
686 if (strcmp("dnctl", basename(av[0])) == 0)
687 g_co.prog = cmdline_prog_dnctl;
689 g_co.prog = cmdline_prog_ipfw;
692 * If the last argument is an absolute pathname, interpret it
693 * as a file to be preprocessed.
696 if (ac > 1 && av[ac - 1][0] == '/') {
697 if (access(av[ac - 1], R_OK) == 0)
698 ipfw_readfile(ac, av);
700 err(EX_USAGE, "pathname: %s", av[ac - 1]);
702 if (ipfw_main(ac, av)) {
704 "usage: %s [options]\n"
705 "do \"%s -h\" or \"man %s\" for details", av[0],