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
40 "ipfw syntax summary (but please do read the ipfw(8) manpage):\n\n"
41 "\tipfw [-abcdefhnNqStTv] <command>\n\n"
42 "where <command> is one of the following:\n\n"
43 "add [num] [set N] [prob x] RULE-BODY\n"
44 "{pipe|queue} N config PIPE-BODY\n"
45 "[pipe|queue] {zero|delete|show} [N{,N}]\n"
46 "nat N config {ip IPADDR|if IFNAME|log|deny_in|same_ports|unreg_only|unreg_cgn|\n"
47 " reset|reverse|proxy_only|redirect_addr linkspec|\n"
48 " redirect_port linkspec|redirect_proto linkspec|\n"
49 " port_range lower-upper}\n"
50 "set [disable N... enable N...] | move [rule] X to Y | swap X Y | show\n"
51 "set N {show|list|zero|resetlog|delete} [N{,N}] | flush\n"
52 "table N {add ip[/bits] [value] | delete ip[/bits] | flush | list}\n"
53 "table all {flush | list}\n"
55 "RULE-BODY: check-state [PARAMS] | ACTION [PARAMS] ADDR [OPTION_LIST]\n"
56 "ACTION: check-state | allow | count | deny | unreach{,6} CODE |\n"
57 " skipto N | {divert|tee} PORT | forward ADDR |\n"
58 " pipe N | queue N | nat N | setfib FIB | reass\n"
59 "PARAMS: [log [logamount LOGLIMIT]] [altq QUEUE_NAME]\n"
60 "ADDR: [ MAC dst src ether_type ] \n"
61 " [ ip from IPADDR [ PORT ] to IPADDR [ PORTLIST ] ]\n"
62 " [ ipv6|ip6 from IP6ADDR [ PORT ] to IP6ADDR [ PORTLIST ] ]\n"
63 "IPADDR: [not] { any | me | ip/bits{x,y,z} | table(t[,v]) | IPLIST }\n"
64 "IP6ADDR: [not] { any | me | me6 | ip6/bits | IP6LIST }\n"
65 "IP6LIST: { ip6 | ip6/bits }[,IP6LIST]\n"
66 "IPLIST: { ip | ip/bits | ip:mask }[,IPLIST]\n"
67 "OPTION_LIST: OPTION [OPTION_LIST]\n"
68 "OPTION: bridged | diverted | diverted-loopback | diverted-output |\n"
69 " {dst-ip|src-ip} IPADDR | {dst-ip6|src-ip6|dst-ipv6|src-ipv6} IP6ADDR |\n"
70 " {dst-port|src-port} LIST |\n"
71 " estab | frag | {gid|uid} N | icmptypes LIST | in | out | ipid LIST |\n"
72 " iplen LIST | ipoptions SPEC | ipprecedence | ipsec | iptos SPEC |\n"
73 " ipttl LIST | ipversion VER | keep-state | layer2 | limit ... |\n"
74 " icmp6types LIST | ext6hdr LIST | flow-id N[,N] | fib FIB |\n"
75 " mac ... | mac-type LIST | proto LIST | {recv|xmit|via} {IF|IPADDR} |\n"
76 " setup | {tcpack|tcpseq|tcpwin} NN | tcpflags SPEC | tcpoptions SPEC |\n"
77 " tcpdatalen LIST | verrevpath | versrcreach | antispoof\n"
84 * Called with the arguments, including program name because getopt
85 * wants it to be present.
86 * Returns 0 if successful, 1 if empty command, errx() in case of errors.
87 * First thing we do is process parameters creating an argv[] array
88 * which includes the program name and a NULL entry at the end.
89 * If we are called with a single string, we split it on whitespace.
90 * Also, arguments with a trailing ',' are joined to the next one.
91 * The pointers (av[]) and data are in a single chunk of memory.
92 * av[0] points to the original program name, all other entries
93 * point into the allocated chunk.
96 ipfw_main(int oldac, char **oldav)
100 char **av, **save_av;
101 int do_acct = 0; /* Show packet/byte count */
102 int try_next = 0; /* set if pipe cmd not found */
103 int av_size; /* compute the av size */
104 char *av_p; /* used to build the av list */
106 #define WHITESP " \t\f\v\n\r"
108 return 1; /* need at least one argument */
112 * If we are called with one argument, try to split it into
113 * words for subsequent parsing. Spaces after a ',' are
114 * removed by copying the string in-place.
116 char *arg = oldav[1]; /* The string is the first arg. */
118 int copy = 0; /* 1 if we need to copy, 0 otherwise */
121 for (i = j = 0; i < l; i++) {
122 if (arg[i] == '#') /* comment marker */
126 copy = !strchr("," WHITESP, arg[i]);
128 copy = !strchr(WHITESP, arg[i]);
133 if (!copy && j > 0) /* last char was a 'blank', remove it */
135 l = j; /* the new argument length */
137 if (l == 0) /* empty string! */
141 * First, count number of arguments. Because of the previous
142 * processing, this is just the number of blanks plus 1.
144 for (i = 0, ac = 1; i < l; i++)
145 if (strchr(WHITESP, arg[i]) != NULL)
149 * Allocate the argument list structure as a single block
150 * of memory, containing pointers and the argument
151 * strings. We include one entry for the program name
152 * because getopt expects it, and a NULL at the end
153 * to simplify further parsing.
155 ac++; /* add 1 for the program name */
156 av_size = (ac+1) * sizeof(char *) + l + 1;
157 av = safe_calloc(av_size, 1);
160 * Init the argument pointer to the end of the array
161 * and copy arguments from arg[] to av[]. For each one,
162 * j is the initial character, i is the one past the end.
164 av_p = (char *)&av[ac+1];
165 for (ac = 1, i = j = 0; i < l; i++) {
166 if (strchr(WHITESP, arg[i]) != NULL || i == l-1) {
169 bcopy(arg+j, av_p, i-j);
171 av_p += i-j; /* the length of the string */
179 * If an argument ends with ',' join with the next one.
184 * Allocate the argument list structure as a single block
185 * of memory, containing both pointers and the argument
186 * strings. We include some space for the program name
187 * because getopt expects it.
188 * We add an extra pointer to the end of the array,
189 * to make simpler further parsing.
191 for (i=0; i<oldac; i++)
192 l += strlen(oldav[i]);
194 av_size = (oldac+1) * sizeof(char *) + l + oldac;
195 av = safe_calloc(av_size, 1);
198 * Init the argument pointer to the end of the array
199 * and copy arguments from arg[] to av[]
201 av_p = (char *)&av[oldac+1];
202 for (first = i = ac = 1, l = 0; i < oldac; i++) {
203 char *arg = oldav[i];
207 if (arg[k-1] != ',' || i == oldac-1) {
210 for (l=0; first <= i; first++) {
211 strcat(av_p, oldav[first]);
212 av_p += strlen(oldav[first]);
223 * set the progname pointer to the original string
224 * and terminate the array with null
229 /* Set the force flag for non-interactive processes */
231 g_co.do_force = !isatty(STDIN_FILENO);
233 #ifdef EMULATE_SYSCTL /* sysctl emulation */
234 if ( ac >= 2 && !strcmp(av[1], "sysctl")) {
239 printf( "sysctl emulation usage:\n"
240 " ipfw sysctl name[=value]\n"
241 " ipfw sysctl -a\n");
244 s = strchr(av[2], '=');
246 s = !strcmp(av[2], "-a") ? NULL : av[2];
247 sysctlbyname(s, NULL, NULL, NULL, 0);
248 } else { /* ipfw sysctl x.y.z=value */
249 /* assume an INT value, will extend later */
251 printf("ipfw sysctl: missing value\n\n");
255 i = strtol(s+1, NULL, 0);
256 sysctlbyname(av[2], NULL, NULL, &i, sizeof(int));
262 /* Save arguments for final freeing of memory. */
265 optind = optreset = 1; /* restart getopt() */
266 while ((ch = getopt(ac, av, "abcdDefhinNp:qs:STtv")) != -1)
273 g_co.comment_only = 1;
290 /* nop for compatibility */
300 break; /* NOTREACHED */
303 g_co.do_value_as_ip = 1;
315 errx(EX_USAGE, "An absolute pathname must be used "
324 g_co.do_sort = atoi(optarg);
332 g_co.do_time = TIMESTAMP_STRING;
336 g_co.do_time = TIMESTAMP_NUMERIC;
339 case 'v': /* verbose */
350 NEED1("bad arguments, for usage summary ``ipfw''");
353 * An undocumented behaviour of ipfw1 was to allow rule numbers first,
354 * e.g. "100 add allow ..." instead of "add 100 allow ...".
355 * In case, swap first and second argument to get the normal form.
357 if (ac > 1 && isdigit(*av[0])) {
365 * Optional: pipe, queue or nat.
370 if (!strncmp(*av, "nat", strlen(*av)))
372 else if (!strncmp(*av, "pipe", strlen(*av)))
374 else if (_substrcmp(*av, "queue") == 0)
376 else if (_substrcmp(*av, "flowset") == 0)
378 else if (_substrcmp(*av, "sched") == 0)
380 else if (!strncmp(*av, "set", strlen(*av))) {
381 if (ac > 1 && isdigit(av[1][0])) {
382 g_co.use_set = strtonum(av[1], 0, resvd_set_number,
386 "invalid set number %s\n", av[1]);
387 ac -= 2; av += 2; g_co.use_set++;
391 if (g_co.do_pipe || g_co.do_nat) {
395 NEED1("missing command");
398 * For pipes, queues and nats we normally say 'nat|pipe NN config'
399 * but the code is easier to parse as 'nat|pipe config NN'
400 * so we swap the two arguments.
402 if ((g_co.do_pipe || g_co.do_nat) && ac > 1 && isdigit(*av[0])) {
409 if (g_co.use_set == 0) {
410 if (_substrcmp(*av, "add") == 0)
412 else if (g_co.do_nat && _substrcmp(*av, "show") == 0)
413 ipfw_show_nat(ac, av);
414 else if (g_co.do_pipe && _substrcmp(*av, "config") == 0)
415 ipfw_config_pipe(ac, av);
416 else if (g_co.do_nat && _substrcmp(*av, "config") == 0)
417 ipfw_config_nat(ac, av);
418 else if (_substrcmp(*av, "set") == 0)
419 ipfw_sets_handler(av);
420 else if (_substrcmp(*av, "table") == 0)
421 ipfw_table_handler(ac, av);
422 else if (_substrcmp(*av, "enable") == 0)
423 ipfw_sysctl_handler(av, 1);
424 else if (_substrcmp(*av, "disable") == 0)
425 ipfw_sysctl_handler(av, 0);
430 if (g_co.use_set || try_next) {
431 if (_substrcmp(*av, "delete") == 0)
433 else if (!strncmp(*av, "nat64clat", strlen(*av)))
434 ipfw_nat64clat_handler(ac, av);
435 else if (!strncmp(*av, "nat64stl", strlen(*av)))
436 ipfw_nat64stl_handler(ac, av);
437 else if (!strncmp(*av, "nat64lsn", strlen(*av)))
438 ipfw_nat64lsn_handler(ac, av);
439 else if (!strncmp(*av, "nptv6", strlen(*av)))
440 ipfw_nptv6_handler(ac, av);
441 else if (_substrcmp(*av, "flush") == 0)
442 ipfw_flush(g_co.do_force);
443 else if (_substrcmp(*av, "zero") == 0)
444 ipfw_zero(ac, av, 0 /* IP_FW_ZERO */);
445 else if (_substrcmp(*av, "resetlog") == 0)
446 ipfw_zero(ac, av, 1 /* IP_FW_RESETLOG */);
447 else if (_substrcmp(*av, "print") == 0 ||
448 _substrcmp(*av, "list") == 0)
449 ipfw_list(ac, av, do_acct);
450 else if (_substrcmp(*av, "show") == 0)
451 ipfw_list(ac, av, 1 /* show counters */);
452 else if (_substrcmp(*av, "table") == 0)
453 ipfw_table_handler(ac, av);
454 else if (_substrcmp(*av, "internal") == 0)
455 ipfw_internal_handler(ac, av);
457 errx(EX_USAGE, "bad command `%s'", *av);
460 /* Free memory allocated in the argument parsing. */
467 ipfw_readfile(int ac, char *av[])
471 char *progname = av[0]; /* original program name */
472 const char *cmd = NULL; /* preprocessor name, if any */
473 const char *filename = av[ac-1]; /* file to read */
478 while ((c = getopt(ac, av, "cfNnp:qS")) != -1) {
498 * ipfw -p cmd [args] filename
500 * We are done with getopt(). All arguments
501 * except the filename go to the preprocessor,
502 * so we need to do the following:
503 * - check that a filename is actually present;
504 * - advance av by optind-1 to skip arguments
506 * - decrease ac by optind, to remove the args
507 * already processed and the final filename;
508 * - set the last entry in av[] to NULL so
509 * popen() can detect the end of the array;
510 * - set optind=ac to let getopt() terminate.
513 errx(EX_USAGE, "no filename argument");
530 errx(EX_USAGE, "bad arguments, for usage"
531 " summary ``ipfw''");
536 if (cmd == NULL && ac != optind + 1)
537 errx(EX_USAGE, "extraneous filename arguments %s", av[ac-1]);
539 if ((f = fopen(filename, "r")) == NULL)
540 err(EX_UNAVAILABLE, "fopen: %s", filename);
542 if (cmd != NULL) { /* pipe through preprocessor */
545 if (pipe(pipedes) == -1)
546 err(EX_OSERR, "cannot create pipe");
550 err(EX_OSERR, "cannot fork");
554 * Child, will run the preprocessor with the
555 * file on stdin and the pipe on stdout.
557 if (dup2(fileno(f), 0) == -1
558 || dup2(pipedes[1], 1) == -1)
559 err(EX_OSERR, "dup2()");
564 err(EX_OSERR, "execvp(%s) failed", cmd);
565 } else { /* parent, will reopen f as the pipe */
568 if ((f = fdopen(pipedes[0], "r")) == NULL) {
569 int savederrno = errno;
571 (void)kill(preproc, SIGTERM);
573 err(EX_OSERR, "fdopen()");
578 while (fgets(buf, sizeof(buf), f)) { /* read commands */
583 snprintf(linename, sizeof(linename), "Line %d", lineno);
584 setprogname(linename); /* XXX */
593 if (waitpid(preproc, &status, 0) == -1)
594 errx(EX_OSERR, "waitpid()");
595 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
597 "preprocessor exited with status %d",
598 WEXITSTATUS(status));
599 else if (WIFSIGNALED(status))
601 "preprocessor exited with signal %d",
607 main(int ac, char *av[])
609 #if defined(_WIN32) && defined(TCC)
613 unsigned short wVersionRequested = MAKEWORD(2, 2);
614 ret = WSAStartup(wVersionRequested, &wsaData);
616 /* Tell the user that we could not find a usable */
618 printf("WSAStartup failed with error: %d\n", ret);
624 * If the last argument is an absolute pathname, interpret it
625 * as a file to be preprocessed.
628 if (ac > 1 && av[ac - 1][0] == '/') {
629 if (access(av[ac - 1], R_OK) == 0)
630 ipfw_readfile(ac, av);
632 err(EX_USAGE, "pathname: %s", av[ac - 1]);
634 if (ipfw_main(ac, av)) {
636 "usage: ipfw [options]\n"
637 "do \"ipfw -h\" or \"man ipfw\" for details");