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
20 * $FreeBSD: head/sbin/ipfw/main.c 206494 2010-04-12 08:27:53Z luigi $
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|reset|\n"
47 " reverse|proxy_only|redirect_addr linkspec|\n"
48 " redirect_port linkspec|redirect_proto linkspec}\n"
49 "set [disable N... enable N...] | move [rule] X to Y | swap X Y | show\n"
50 "set N {show|list|zero|resetlog|delete} [N{,N}] | flush\n"
51 "table N {add ip[/bits] [value] | delete ip[/bits] | flush | list}\n"
52 "table all {flush | list}\n"
54 "RULE-BODY: check-state [PARAMS] | ACTION [PARAMS] ADDR [OPTION_LIST]\n"
55 "ACTION: check-state | allow | count | deny | unreach{,6} CODE |\n"
56 " skipto N | {divert|tee} PORT | forward ADDR |\n"
57 " pipe N | queue N | nat N | setfib FIB | reass\n"
58 "PARAMS: [log [logamount LOGLIMIT]] [altq QUEUE_NAME]\n"
59 "ADDR: [ MAC dst src ether_type ] \n"
60 " [ ip from IPADDR [ PORT ] to IPADDR [ PORTLIST ] ]\n"
61 " [ ipv6|ip6 from IP6ADDR [ PORT ] to IP6ADDR [ PORTLIST ] ]\n"
62 "IPADDR: [not] { any | me | ip/bits{x,y,z} | table(t[,v]) | IPLIST }\n"
63 "IP6ADDR: [not] { any | me | me6 | ip6/bits | IP6LIST }\n"
64 "IP6LIST: { ip6 | ip6/bits }[,IP6LIST]\n"
65 "IPLIST: { ip | ip/bits | ip:mask }[,IPLIST]\n"
66 "OPTION_LIST: OPTION [OPTION_LIST]\n"
67 "OPTION: bridged | diverted | diverted-loopback | diverted-output |\n"
68 " {dst-ip|src-ip} IPADDR | {dst-ip6|src-ip6|dst-ipv6|src-ipv6} IP6ADDR |\n"
69 " {dst-port|src-port} LIST |\n"
70 " estab | frag | {gid|uid} N | icmptypes LIST | in | out | ipid LIST |\n"
71 " iplen LIST | ipoptions SPEC | ipprecedence | ipsec | iptos SPEC |\n"
72 " ipttl LIST | ipversion VER | keep-state | layer2 | limit ... |\n"
73 " icmp6types LIST | ext6hdr LIST | flow-id N[,N] | fib FIB |\n"
74 " mac ... | mac-type LIST | proto LIST | {recv|xmit|via} {IF|IPADDR} |\n"
75 " setup | {tcpack|tcpseq|tcpwin} NN | tcpflags SPEC | tcpoptions SPEC |\n"
76 " tcpdatalen LIST | verrevpath | versrcreach | antispoof\n"
83 * Called with the arguments, including program name because getopt
84 * wants it to be present.
85 * Returns 0 if successful, 1 if empty command, errx() in case of errors.
86 * First thing we do is process parameters creating an argv[] array
87 * which includes the program name and a NULL entry at the end.
88 * If we are called with a single string, we split it on whitespace.
89 * Also, arguments with a trailing ',' are joined to the next one.
90 * The pointers (av[]) and data are in a single chunk of memory.
91 * av[0] points to the original program name, all other entries
92 * point into the allocated chunk.
95 ipfw_main(int oldac, char **oldav)
100 int do_acct = 0; /* Show packet/byte count */
101 int try_next = 0; /* set if pipe cmd not found */
102 int av_size; /* compute the av size */
103 char *av_p; /* used to build the av list */
105 #define WHITESP " \t\f\v\n\r"
107 return 1; /* need at least one argument */
111 * If we are called with one argument, try to split it into
112 * words for subsequent parsing. Spaces after a ',' are
113 * removed by copying the string in-place.
115 char *arg = oldav[1]; /* The string is the first arg. */
117 int copy = 0; /* 1 if we need to copy, 0 otherwise */
120 for (i = j = 0; i < l; i++) {
121 if (arg[i] == '#') /* comment marker */
125 copy = !strchr("," WHITESP, arg[i]);
127 copy = !strchr(WHITESP, arg[i]);
132 if (!copy && j > 0) /* last char was a 'blank', remove it */
134 l = j; /* the new argument length */
136 if (l == 0) /* empty string! */
140 * First, count number of arguments. Because of the previous
141 * processing, this is just the number of blanks plus 1.
143 for (i = 0, ac = 1; i < l; i++)
144 if (strchr(WHITESP, arg[i]) != NULL)
148 * Allocate the argument list structure as a single block
149 * of memory, containing pointers and the argument
150 * strings. We include one entry for the program name
151 * because getopt expects it, and a NULL at the end
152 * to simplify further parsing.
154 ac++; /* add 1 for the program name */
155 av_size = (ac+1) * sizeof(char *) + l + 1;
156 av = safe_calloc(av_size, 1);
159 * Init the argument pointer to the end of the array
160 * and copy arguments from arg[] to av[]. For each one,
161 * j is the initial character, i is the one past the end.
163 av_p = (char *)&av[ac+1];
164 for (ac = 1, i = j = 0; i < l; i++) {
165 if (strchr(WHITESP, arg[i]) != NULL || i == l-1) {
168 bcopy(arg+j, av_p, i-j);
170 av_p += i-j; /* the length of the string */
178 * If an argument ends with ',' join with the next one.
183 * Allocate the argument list structure as a single block
184 * of memory, containing both pointers and the argument
185 * strings. We include some space for the program name
186 * because getopt expects it.
187 * We add an extra pointer to the end of the array,
188 * to make simpler further parsing.
190 for (i=0; i<oldac; i++)
191 l += strlen(oldav[i]);
193 av_size = (oldac+1) * sizeof(char *) + l + oldac;
194 av = safe_calloc(av_size, 1);
197 * Init the argument pointer to the end of the array
198 * and copy arguments from arg[] to av[]
200 av_p = (char *)&av[oldac+1];
201 for (first = i = ac = 1, l = 0; i < oldac; i++) {
202 char *arg = oldav[i];
206 if (arg[k-1] != ',' || i == oldac-1) {
209 for (l=0; first <= i; first++) {
210 strcat(av_p, oldav[first]);
211 av_p += strlen(oldav[first]);
222 * set the progname pointer to the original string
223 * and terminate the array with null
228 /* Set the force flag for non-interactive processes */
230 co.do_force = !isatty(STDIN_FILENO);
232 #ifdef EMULATE_SYSCTL /* sysctl emulation */
233 if ( ac >= 2 && !strcmp(av[1], "sysctl")) {
238 printf( "sysctl emulation usage:\n"
239 " ipfw sysctl name[=value]\n"
240 " ipfw sysctl -a\n");
243 s = strchr(av[2], '=');
245 s = !strcmp(av[2], "-a") ? NULL : av[2];
246 sysctlbyname(s, NULL, NULL, NULL, 0);
247 } else { /* ipfw sysctl x.y.z=value */
248 /* assume an INT value, will extend later */
250 printf("ipfw sysctl: missing value\n\n");
254 i = strtol(s+1, NULL, 0);
255 sysctlbyname(av[2], NULL, NULL, &i, sizeof(int));
261 /* Save arguments for final freeing of memory. */
264 optind = optreset = 1; /* restart getopt() */
265 while ((ch = getopt(ac, av, "abcdefhinNp:qs:STtv")) != -1)
295 break; /* NOTREACHED */
298 co.do_value_as_ip = 1;
314 errx(EX_USAGE, "An absolute pathname must be used "
319 co.do_sort = atoi(optarg);
331 co.do_time = 2; /* numeric timestamp */
334 case 'v': /* verbose */
345 NEED1("bad arguments, for usage summary ``ipfw''");
348 * An undocumented behaviour of ipfw1 was to allow rule numbers first,
349 * e.g. "100 add allow ..." instead of "add 100 allow ...".
350 * In case, swap first and second argument to get the normal form.
352 if (ac > 1 && isdigit(*av[0])) {
360 * Optional: pipe, queue or nat.
365 if (!strncmp(*av, "nat", strlen(*av)))
367 else if (!strncmp(*av, "pipe", strlen(*av)))
369 else if (_substrcmp(*av, "queue") == 0)
371 else if (_substrcmp(*av, "flowset") == 0)
373 else if (_substrcmp(*av, "sched") == 0)
375 else if (!strncmp(*av, "set", strlen(*av))) {
376 if (ac > 1 && isdigit(av[1][0])) {
377 co.use_set = strtonum(av[1], 0, resvd_set_number,
381 "invalid set number %s\n", av[1]);
382 ac -= 2; av += 2; co.use_set++;
386 if (co.do_pipe || co.do_nat) {
390 NEED1("missing command");
393 * For pipes, queues and nats we normally say 'nat|pipe NN config'
394 * but the code is easier to parse as 'nat|pipe config NN'
395 * so we swap the two arguments.
397 if ((co.do_pipe || co.do_nat) && ac > 1 && isdigit(*av[0])) {
404 if (co.use_set == 0) {
405 if (_substrcmp(*av, "add") == 0)
407 else if (co.do_nat && _substrcmp(*av, "show") == 0)
408 ipfw_show_nat(ac, av);
409 else if (co.do_pipe && _substrcmp(*av, "config") == 0)
410 ipfw_config_pipe(ac, av);
411 else if (co.do_nat && _substrcmp(*av, "config") == 0)
412 ipfw_config_nat(ac, av);
413 else if (_substrcmp(*av, "set") == 0)
414 ipfw_sets_handler(av);
415 else if (_substrcmp(*av, "table") == 0)
416 ipfw_table_handler(ac, av);
417 else if (_substrcmp(*av, "enable") == 0)
418 ipfw_sysctl_handler(av, 1);
419 else if (_substrcmp(*av, "disable") == 0)
420 ipfw_sysctl_handler(av, 0);
425 if (co.use_set || try_next) {
426 if (_substrcmp(*av, "delete") == 0)
428 else if (_substrcmp(*av, "flush") == 0)
429 ipfw_flush(co.do_force);
430 else if (_substrcmp(*av, "zero") == 0)
431 ipfw_zero(ac, av, 0 /* IP_FW_ZERO */);
432 else if (_substrcmp(*av, "resetlog") == 0)
433 ipfw_zero(ac, av, 1 /* IP_FW_RESETLOG */);
434 else if (_substrcmp(*av, "print") == 0 ||
435 _substrcmp(*av, "list") == 0)
436 ipfw_list(ac, av, do_acct);
437 else if (_substrcmp(*av, "show") == 0)
438 ipfw_list(ac, av, 1 /* show counters */);
440 errx(EX_USAGE, "bad command `%s'", *av);
443 /* Free memory allocated in the argument parsing. */
450 ipfw_readfile(int ac, char *av[])
454 char *progname = av[0]; /* original program name */
455 const char *cmd = NULL; /* preprocessor name, if any */
456 const char *filename = av[ac-1]; /* file to read */
461 while ((c = getopt(ac, av, "cfNnp:qS")) != -1) {
481 * ipfw -p cmd [args] filename
483 * We are done with getopt(). All arguments
484 * except the filename go to the preprocessor,
485 * so we need to do the following:
486 * - check that a filename is actually present;
487 * - advance av by optind-1 to skip arguments
489 * - decrease ac by optind, to remove the args
490 * already processed and the final filename;
491 * - set the last entry in av[] to NULL so
492 * popen() can detect the end of the array;
493 * - set optind=ac to let getopt() terminate.
496 errx(EX_USAGE, "no filename argument");
513 errx(EX_USAGE, "bad arguments, for usage"
514 " summary ``ipfw''");
519 if (cmd == NULL && ac != optind + 1)
520 errx(EX_USAGE, "extraneous filename arguments %s", av[ac-1]);
522 if ((f = fopen(filename, "r")) == NULL)
523 err(EX_UNAVAILABLE, "fopen: %s", filename);
525 if (cmd != NULL) { /* pipe through preprocessor */
528 if (pipe(pipedes) == -1)
529 err(EX_OSERR, "cannot create pipe");
533 err(EX_OSERR, "cannot fork");
537 * Child, will run the preprocessor with the
538 * file on stdin and the pipe on stdout.
540 if (dup2(fileno(f), 0) == -1
541 || dup2(pipedes[1], 1) == -1)
542 err(EX_OSERR, "dup2()");
547 err(EX_OSERR, "execvp(%s) failed", cmd);
548 } else { /* parent, will reopen f as the pipe */
551 if ((f = fdopen(pipedes[0], "r")) == NULL) {
552 int savederrno = errno;
554 (void)kill(preproc, SIGTERM);
556 err(EX_OSERR, "fdopen()");
561 while (fgets(buf, sizeof(buf), f)) { /* read commands */
566 snprintf(linename, sizeof(linename), "Line %d", lineno);
567 setprogname(linename); /* XXX */
576 if (waitpid(preproc, &status, 0) == -1)
577 errx(EX_OSERR, "waitpid()");
578 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
580 "preprocessor exited with status %d",
581 WEXITSTATUS(status));
582 else if (WIFSIGNALED(status))
584 "preprocessor exited with signal %d",
590 main(int ac, char *av[])
592 #if defined(_WIN32) && defined(TCC)
596 unsigned short wVersionRequested = MAKEWORD(2, 2);
597 ret = WSAStartup(wVersionRequested, &wsaData);
599 /* Tell the user that we could not find a usable */
601 printf("WSAStartup failed with error: %d\n", ret);
607 * If the last argument is an absolute pathname, interpret it
608 * as a file to be preprocessed.
611 if (ac > 1 && av[ac - 1][0] == '/') {
612 if (access(av[ac - 1], R_OK) == 0)
613 ipfw_readfile(ac, av);
615 err(EX_USAGE, "pathname: %s", av[ac - 1]);
617 if (ipfw_main(ac, av)) {
619 "usage: ipfw [options]\n"
620 "do \"ipfw -h\" or \"man ipfw\" for details");