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
41 "ipfw syntax summary (but please do read the ipfw(8) manpage):\n\n"
42 "\tipfw [-abcdefhnNqStTv] <command>\n\n"
43 "where <command> is one of the following:\n\n"
44 "add [num] [set N] [prob x] RULE-BODY\n"
45 "{pipe|queue} N config PIPE-BODY\n"
46 "[pipe|queue] {zero|delete|show} [N{,N}]\n"
47 "nat N config {ip IPADDR|if IFNAME|log|deny_in|same_ports|unreg_only|unreg_cgn|\n"
48 " reset|reverse|proxy_only|redirect_addr linkspec|\n"
49 " redirect_port linkspec|redirect_proto linkspec|\n"
50 " port_range lower-upper}\n"
51 "set [disable N... enable N...] | move [rule] X to Y | swap X Y | show\n"
52 "set N {show|list|zero|resetlog|delete} [N{,N}] | flush\n"
53 "table N {add ip[/bits] [value] | delete ip[/bits] | flush | list}\n"
54 "table all {flush | list}\n"
56 "RULE-BODY: check-state [PARAMS] | ACTION [PARAMS] ADDR [OPTION_LIST]\n"
57 "ACTION: check-state | allow | count | deny | unreach{,6} CODE |\n"
58 " skipto N | {divert|tee} PORT | forward ADDR |\n"
59 " pipe N | queue N | nat N | setfib FIB | reass\n"
60 "PARAMS: [log [logamount LOGLIMIT]] [altq QUEUE_NAME]\n"
61 "ADDR: [ MAC dst src ether_type ] \n"
62 " [ ip from IPADDR [ PORT ] to IPADDR [ PORTLIST ] ]\n"
63 " [ ipv6|ip6 from IP6ADDR [ PORT ] to IP6ADDR [ PORTLIST ] ]\n"
64 "IPADDR: [not] { any | me | ip/bits{x,y,z} | table(t[,v]) | IPLIST }\n"
65 "IP6ADDR: [not] { any | me | me6 | ip6/bits | IP6LIST }\n"
66 "IP6LIST: { ip6 | ip6/bits }[,IP6LIST]\n"
67 "IPLIST: { ip | ip/bits | ip:mask }[,IPLIST]\n"
68 "OPTION_LIST: OPTION [OPTION_LIST]\n"
69 "OPTION: bridged | diverted | diverted-loopback | diverted-output |\n"
70 " {dst-ip|src-ip} IPADDR | {dst-ip6|src-ip6|dst-ipv6|src-ipv6} IP6ADDR |\n"
71 " {dst-port|src-port} LIST |\n"
72 " estab | frag | {gid|uid} N | icmptypes LIST | in | out | ipid LIST |\n"
73 " iplen LIST | ipoptions SPEC | ipprecedence | ipsec | iptos SPEC |\n"
74 " ipttl LIST | ipversion VER | keep-state | layer2 | limit ... |\n"
75 " icmp6types LIST | ext6hdr LIST | flow-id N[,N] | fib FIB |\n"
76 " mac ... | mac-type LIST | proto LIST | {recv|xmit|via} {IF|IPADDR} |\n"
77 " setup | {tcpack|tcpseq|tcpwin} NN | tcpflags SPEC | tcpoptions SPEC |\n"
78 " tcpdatalen LIST | verrevpath | versrcreach | antispoof\n"
82 "dnctl syntax summary (but please do read the dnctl(8) manpage):\n\n"
83 "\tdnctl [-hnsv] <command>\n\n"
84 "where <command> is one of the following:\n\n"
85 "[pipe|queue|sched] N config PIPE-BODY\n"
86 "[pipe|queue|sched] {delete|list|show} [N{,N}]\n"
95 * Called with the arguments, including program name because getopt
96 * wants it to be present.
97 * Returns 0 if successful, 1 if empty command, errx() in case of errors.
98 * First thing we do is process parameters creating an argv[] array
99 * which includes the program name and a NULL entry at the end.
100 * If we are called with a single string, we split it on whitespace.
101 * Also, arguments with a trailing ',' are joined to the next one.
102 * The pointers (av[]) and data are in a single chunk of memory.
103 * av[0] points to the original program name, all other entries
104 * point into the allocated chunk.
107 ipfw_main(int oldac, char **oldav)
111 char **av, **save_av;
112 int do_acct = 0; /* Show packet/byte count */
113 int try_next = 0; /* set if pipe cmd not found */
114 int av_size; /* compute the av size */
115 char *av_p; /* used to build the av list */
117 #define WHITESP " \t\f\v\n\r"
119 return 1; /* need at least one argument */
123 * If we are called with one argument, try to split it into
124 * words for subsequent parsing. Spaces after a ',' are
125 * removed by copying the string in-place.
127 char *arg = oldav[1]; /* The string is the first arg. */
129 int copy = 0; /* 1 if we need to copy, 0 otherwise */
132 for (i = j = 0; i < l; i++) {
133 if (arg[i] == '#') /* comment marker */
137 copy = !strchr("," WHITESP, arg[i]);
139 copy = !strchr(WHITESP, arg[i]);
144 if (!copy && j > 0) /* last char was a 'blank', remove it */
146 l = j; /* the new argument length */
148 if (l == 0) /* empty string! */
152 * First, count number of arguments. Because of the previous
153 * processing, this is just the number of blanks plus 1.
155 for (i = 0, ac = 1; i < l; i++)
156 if (strchr(WHITESP, arg[i]) != NULL)
160 * Allocate the argument list structure as a single block
161 * of memory, containing pointers and the argument
162 * strings. We include one entry for the program name
163 * because getopt expects it, and a NULL at the end
164 * to simplify further parsing.
166 ac++; /* add 1 for the program name */
167 av_size = (ac+1) * sizeof(char *) + l + 1;
168 av = safe_calloc(av_size, 1);
171 * Init the argument pointer to the end of the array
172 * and copy arguments from arg[] to av[]. For each one,
173 * j is the initial character, i is the one past the end.
175 av_p = (char *)&av[ac+1];
176 for (ac = 1, i = j = 0; i < l; i++) {
177 if (strchr(WHITESP, arg[i]) != NULL || i == l-1) {
180 bcopy(arg+j, av_p, i-j);
182 av_p += i-j; /* the length of the string */
190 * If an argument ends with ',' join with the next one.
195 * Allocate the argument list structure as a single block
196 * of memory, containing both pointers and the argument
197 * strings. We include some space for the program name
198 * because getopt expects it.
199 * We add an extra pointer to the end of the array,
200 * to make simpler further parsing.
202 for (i=0; i<oldac; i++)
203 l += strlen(oldav[i]);
205 av_size = (oldac+1) * sizeof(char *) + l + oldac;
206 av = safe_calloc(av_size, 1);
209 * Init the argument pointer to the end of the array
210 * and copy arguments from arg[] to av[]
212 av_p = (char *)&av[oldac+1];
213 for (first = i = ac = 1, l = 0; i < oldac; i++) {
214 char *arg = oldav[i];
218 if (arg[k-1] != ',' || i == oldac-1) {
221 for (l=0; first <= i; first++) {
222 strcat(av_p, oldav[first]);
223 av_p += strlen(oldav[first]);
234 * set the progname pointer to the original string
235 * and terminate the array with null
240 /* Set the force flag for non-interactive processes */
242 g_co.do_force = !isatty(STDIN_FILENO);
244 #ifdef EMULATE_SYSCTL /* sysctl emulation */
245 if (is_ipfw() && ac >= 2 &&
246 !strcmp(av[1], "sysctl")) {
251 printf( "sysctl emulation usage:\n"
252 " ipfw sysctl name[=value]\n"
253 " ipfw sysctl -a\n");
256 s = strchr(av[2], '=');
258 s = !strcmp(av[2], "-a") ? NULL : av[2];
259 sysctlbyname(s, NULL, NULL, NULL, 0);
260 } else { /* ipfw sysctl x.y.z=value */
261 /* assume an INT value, will extend later */
263 printf("ipfw sysctl: missing value\n\n");
267 i = strtol(s+1, NULL, 0);
268 sysctlbyname(av[2], NULL, NULL, &i, sizeof(int));
274 /* Save arguments for final freeing of memory. */
277 optind = optreset = 1; /* restart getopt() */
279 while ((ch = getopt(ac, av, "abcdDefhinNp:qs:STtv")) != -1)
286 g_co.comment_only = 1;
303 /* nop for compatibility */
313 break; /* NOTREACHED */
316 g_co.do_value_as_ip = 1;
328 errx(EX_USAGE, "An absolute pathname must be used "
337 g_co.do_sort = atoi(optarg);
345 g_co.do_time = TIMESTAMP_STRING;
349 g_co.do_time = TIMESTAMP_NUMERIC;
352 case 'v': /* verbose */
361 while ((ch = getopt(ac, av, "hns:v")) != -1)
367 break; /* NOTREACHED */
374 g_co.do_sort = atoi(optarg);
377 case 'v': /* verbose */
390 NEED1("bad arguments, for usage summary ``ipfw''");
393 * An undocumented behaviour of ipfw1 was to allow rule numbers first,
394 * e.g. "100 add allow ..." instead of "add 100 allow ...".
395 * In case, swap first and second argument to get the normal form.
397 if (ac > 1 && isdigit(*av[0])) {
405 * Optional: pipe, queue or nat.
410 if (is_ipfw() && !strncmp(*av, "nat", strlen(*av)))
412 else if (!strncmp(*av, "pipe", strlen(*av)))
414 else if (_substrcmp(*av, "queue") == 0)
416 else if (_substrcmp(*av, "flowset") == 0)
418 else if (_substrcmp(*av, "sched") == 0)
420 else if (is_ipfw() && !strncmp(*av, "set", strlen(*av))) {
421 if (ac > 1 && isdigit(av[1][0])) {
422 g_co.use_set = strtonum(av[1], 0, resvd_set_number,
426 "invalid set number %s\n", av[1]);
427 ac -= 2; av += 2; g_co.use_set++;
431 if (g_co.do_pipe || g_co.do_nat) {
435 NEED1("missing command");
438 * For pipes, queues and nats we normally say 'nat|pipe NN config'
439 * but the code is easier to parse as 'nat|pipe config NN'
440 * so we swap the two arguments.
442 if ((g_co.do_pipe || g_co.do_nat) && ac > 1 && isdigit(*av[0])) {
449 if (! is_ipfw() && g_co.do_pipe == 0) {
453 if (g_co.use_set == 0) {
454 if (is_ipfw() && _substrcmp(*av, "add") == 0)
456 else if (g_co.do_nat && _substrcmp(*av, "show") == 0)
457 ipfw_show_nat(ac, av);
458 else if (g_co.do_pipe && _substrcmp(*av, "config") == 0)
459 ipfw_config_pipe(ac, av);
460 else if (g_co.do_nat && _substrcmp(*av, "config") == 0)
461 ipfw_config_nat(ac, av);
462 else if (is_ipfw() && _substrcmp(*av, "set") == 0)
463 ipfw_sets_handler(av);
464 else if (is_ipfw() && _substrcmp(*av, "table") == 0)
465 ipfw_table_handler(ac, av);
466 else if (is_ipfw() && _substrcmp(*av, "enable") == 0)
467 ipfw_sysctl_handler(av, 1);
468 else if (is_ipfw() && _substrcmp(*av, "disable") == 0)
469 ipfw_sysctl_handler(av, 0);
474 if (g_co.use_set || try_next) {
475 if (_substrcmp(*av, "delete") == 0)
477 else if (is_ipfw() && !strncmp(*av, "nat64clat", strlen(*av)))
478 ipfw_nat64clat_handler(ac, av);
479 else if (is_ipfw() && !strncmp(*av, "nat64stl", strlen(*av)))
480 ipfw_nat64stl_handler(ac, av);
481 else if (is_ipfw() && !strncmp(*av, "nat64lsn", strlen(*av)))
482 ipfw_nat64lsn_handler(ac, av);
483 else if (is_ipfw() && !strncmp(*av, "nptv6", strlen(*av)))
484 ipfw_nptv6_handler(ac, av);
485 else if (_substrcmp(*av, "flush") == 0)
486 ipfw_flush(g_co.do_force);
487 else if (is_ipfw() && _substrcmp(*av, "zero") == 0)
488 ipfw_zero(ac, av, 0 /* IP_FW_ZERO */);
489 else if (is_ipfw() && _substrcmp(*av, "resetlog") == 0)
490 ipfw_zero(ac, av, 1 /* IP_FW_RESETLOG */);
491 else if (_substrcmp(*av, "print") == 0 ||
492 _substrcmp(*av, "list") == 0)
493 ipfw_list(ac, av, do_acct);
494 else if (_substrcmp(*av, "show") == 0)
495 ipfw_list(ac, av, 1 /* show counters */);
496 else if (is_ipfw() && _substrcmp(*av, "table") == 0)
497 ipfw_table_handler(ac, av);
498 else if (is_ipfw() && _substrcmp(*av, "internal") == 0)
499 ipfw_internal_handler(ac, av);
501 errx(EX_USAGE, "bad command `%s'", *av);
504 /* Free memory allocated in the argument parsing. */
511 ipfw_readfile(int ac, char *av[])
515 char *progname = av[0]; /* original program name */
516 const char *cmd = NULL; /* preprocessor name, if any */
517 const char *filename = av[ac-1]; /* file to read */
523 while ((c = getopt(ac, av, "cfNnp:qS")) != -1) {
543 * ipfw -p cmd [args] filename
545 * We are done with getopt(). All arguments
546 * except the filename go to the preprocessor,
547 * so we need to do the following:
548 * - check that a filename is actually present;
549 * - advance av by optind-1 to skip arguments
551 * - decrease ac by optind, to remove the args
552 * already processed and the final filename;
553 * - set the last entry in av[] to NULL so
554 * popen() can detect the end of the array;
555 * - set optind=ac to let getopt() terminate.
558 errx(EX_USAGE, "no filename argument");
575 errx(EX_USAGE, "bad arguments, for usage"
576 " summary ``ipfw''");
580 while ((c = getopt(ac, av, "nq")) != -1) {
591 errx(EX_USAGE, "bad arguments, for usage"
592 " summary ``dnctl''");
597 if (cmd == NULL && ac != optind + 1)
598 errx(EX_USAGE, "extraneous filename arguments %s", av[ac-1]);
600 if ((f = fopen(filename, "r")) == NULL)
601 err(EX_UNAVAILABLE, "fopen: %s", filename);
603 if (cmd != NULL) { /* pipe through preprocessor */
606 if (pipe(pipedes) == -1)
607 err(EX_OSERR, "cannot create pipe");
611 err(EX_OSERR, "cannot fork");
615 * Child, will run the preprocessor with the
616 * file on stdin and the pipe on stdout.
618 if (dup2(fileno(f), 0) == -1
619 || dup2(pipedes[1], 1) == -1)
620 err(EX_OSERR, "dup2()");
625 err(EX_OSERR, "execvp(%s) failed", cmd);
626 } else { /* parent, will reopen f as the pipe */
629 if ((f = fdopen(pipedes[0], "r")) == NULL) {
630 int savederrno = errno;
632 (void)kill(preproc, SIGTERM);
634 err(EX_OSERR, "fdopen()");
639 while (fgets(buf, sizeof(buf), f)) { /* read commands */
644 snprintf(linename, sizeof(linename), "Line %d", lineno);
645 setprogname(linename); /* XXX */
654 if (waitpid(preproc, &status, 0) == -1)
655 errx(EX_OSERR, "waitpid()");
656 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
658 "preprocessor exited with status %d",
659 WEXITSTATUS(status));
660 else if (WIFSIGNALED(status))
662 "preprocessor exited with signal %d",
668 main(int ac, char *av[])
670 #if defined(_WIN32) && defined(TCC)
674 unsigned short wVersionRequested = MAKEWORD(2, 2);
675 ret = WSAStartup(wVersionRequested, &wsaData);
677 /* Tell the user that we could not find a usable */
679 printf("WSAStartup failed with error: %d\n", ret);
685 if (strcmp(av[0], "dnctl") == 0)
686 g_co.prog = cmdline_prog_dnctl;
688 g_co.prog = cmdline_prog_ipfw;
691 * If the last argument is an absolute pathname, interpret it
692 * as a file to be preprocessed.
695 if (ac > 1 && av[ac - 1][0] == '/') {
696 if (access(av[ac - 1], R_OK) == 0)
697 ipfw_readfile(ac, av);
699 err(EX_USAGE, "pathname: %s", av[ac - 1]);
701 if (ipfw_main(ac, av)) {
703 "usage: %s [options]\n"
704 "do \"%s -h\" or \"man %s\" for details", av[0],