]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - sbin/ipfw/main.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.git] / sbin / ipfw / main.c
1 /*
2  * Copyright (c) 2002-2003 Luigi Rizzo
3  * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
4  * Copyright (c) 1994 Ugen J.S.Antsilevich
5  *
6  * Idea and grammar partially left from:
7  * Copyright (c) 1993 Daniel Boulet
8  *
9  * Redistribution and use in source forms, with and without modification,
10  * are permitted provided that this entire comment appears intact.
11  *
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.
15  *
16  * This software is provided ``AS IS'' without any warranties of any kind.
17  *
18  * Command line interface for IP firewall facility
19  *
20  * $FreeBSD$
21  */
22
23 #include <sys/wait.h>
24 #include <ctype.h>
25 #include <err.h>
26 #include <errno.h>
27 #include <signal.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 #include <sysexits.h>
32 #include <unistd.h>
33
34 #include "ipfw2.h"
35
36 static void
37 help(void)
38 {
39         fprintf(stderr,
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"
53 "\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\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"
77 );
78
79         exit(0);
80 }
81
82 /*
83  * Free a the (locally allocated) copy of command line arguments.
84  */
85 static void
86 free_args(int ac, char **av)
87 {
88         int i;
89
90         for (i=0; i < ac; i++)
91                 free(av[i]);
92         free(av);
93 }
94
95 /*
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  */
100 static int
101 ipfw_main(int oldac, char **oldav)
102 {
103         int ch, ac, save_ac;
104         const char *errstr;
105         char **av, **save_av;
106         int do_acct = 0;                /* Show packet/byte count */
107
108 #define WHITESP         " \t\f\v\n\r"
109         if (oldac < 2)
110                 return 1;       /* need at least one argument */
111
112         if (oldac == 2) {
113                 /*
114                  * If we are called with a single string, try to split it into
115                  * arguments for subsequent parsing.
116                  * But first, remove spaces after a ',', by copying the string
117                  * in-place.
118                  */
119                 char *arg = oldav[1];   /* The string is the first arg. */
120                 int l = strlen(arg);
121                 int copy = 0;           /* 1 if we need to copy, 0 otherwise */
122                 int i, j;
123
124                 for (i = j = 0; i < l; i++) {
125                         if (arg[i] == '#')      /* comment marker */
126                                 break;
127                         if (copy) {
128                                 arg[j++] = arg[i];
129                                 copy = !index("," WHITESP, arg[i]);
130                         } else {
131                                 copy = !index(WHITESP, arg[i]);
132                                 if (copy)
133                                         arg[j++] = arg[i];
134                         }
135                 }
136                 if (!copy && j > 0)     /* last char was a 'blank', remove it */
137                         j--;
138                 l = j;                  /* the new argument length */
139                 arg[j++] = '\0';
140                 if (l == 0)             /* empty string! */
141                         return 1;
142
143                 /*
144                  * First, count number of arguments. Because of the previous
145                  * processing, this is just the number of blanks plus 1.
146                  */
147                 for (i = 0, ac = 1; i < l; i++)
148                         if (index(WHITESP, arg[i]) != NULL)
149                                 ac++;
150
151                 /*
152                  * Allocate the argument list, including one entry for
153                  * the program name because getopt expects it.
154                  */
155                 av = safe_calloc(ac + 1, sizeof(char *));
156
157                 /*
158                  * Second, copy arguments from arg[] to av[]. For each one,
159                  * j is the initial character, i is the one past the end.
160                  */
161                 for (ac = 1, i = j = 0; i < l; i++)
162                         if (index(WHITESP, arg[i]) != NULL || i == l-1) {
163                                 if (i == l-1)
164                                         i++;
165                                 av[ac] = safe_calloc(i-j+1, 1);
166                                 bcopy(arg+j, av[ac], i-j);
167                                 ac++;
168                                 j = i + 1;
169                         }
170         } else {
171                 /*
172                  * If an argument ends with ',' join with the next one.
173                  */
174                 int first, i, l;
175
176                 av = safe_calloc(oldac, sizeof(char *));
177                 for (first = i = ac = 1, l = 0; i < oldac; i++) {
178                         char *arg = oldav[i];
179                         int k = strlen(arg);
180
181                         l += k;
182                         if (arg[k-1] != ',' || i == oldac-1) {
183                                 /* Time to copy. */
184                                 av[ac] = safe_calloc(l+1, 1);
185                                 for (l=0; first <= i; first++) {
186                                         strcat(av[ac]+l, oldav[first]);
187                                         l += strlen(oldav[first]);
188                                 }
189                                 ac++;
190                                 l = 0;
191                                 first = i+1;
192                         }
193                 }
194         }
195
196         av[0] = strdup(oldav[0]);       /* copy progname from the caller */
197         /* Set the force flag for non-interactive processes */
198         if (!co.do_force)
199                 co.do_force = !isatty(STDIN_FILENO);
200
201         /* Save arguments for final freeing of memory. */
202         save_ac = ac;
203         save_av = av;
204
205         optind = optreset = 1;  /* restart getopt() */
206         while ((ch = getopt(ac, av, "abcdefhinNqs:STtv")) != -1)
207                 switch (ch) {
208                 case 'a':
209                         do_acct = 1;
210                         break;
211
212                 case 'b':
213                         co.comment_only = 1;
214                         co.do_compact = 1;
215                         break;
216
217                 case 'c':
218                         co.do_compact = 1;
219                         break;
220
221                 case 'd':
222                         co.do_dynamic = 1;
223                         break;
224
225                 case 'e':
226                         co.do_expired = 1;
227                         break;
228
229                 case 'f':
230                         co.do_force = 1;
231                         break;
232
233                 case 'h': /* help */
234                         free_args(save_ac, save_av);
235                         help();
236                         break;  /* NOTREACHED */
237
238                 case 'i':
239                         co.do_value_as_ip = 1;
240                         break;
241
242                 case 'n':
243                         co.test_only = 1;
244                         break;
245
246                 case 'N':
247                         co.do_resolv = 1;
248                         break;
249
250                 case 'q':
251                         co.do_quiet = 1;
252                         break;
253
254                 case 's': /* sort */
255                         co.do_sort = atoi(optarg);
256                         break;
257
258                 case 'S':
259                         co.show_sets = 1;
260                         break;
261
262                 case 't':
263                         co.do_time = 1;
264                         break;
265
266                 case 'T':
267                         co.do_time = 2; /* numeric timestamp */
268                         break;
269
270                 case 'v': /* verbose */
271                         co.verbose = 1;
272                         break;
273
274                 default:
275                         free_args(save_ac, save_av);
276                         return 1;
277                 }
278
279         ac -= optind;
280         av += optind;
281         NEED1("bad arguments, for usage summary ``ipfw''");
282
283         /*
284          * An undocumented behaviour of ipfw1 was to allow rule numbers first,
285          * e.g. "100 add allow ..." instead of "add 100 allow ...".
286          * In case, swap first and second argument to get the normal form.
287          */
288         if (ac > 1 && isdigit(*av[0])) {
289                 char *p = av[0];
290
291                 av[0] = av[1];
292                 av[1] = p;
293         }
294
295         /*
296          * Optional: pipe, queue or nat.
297          */
298         co.do_nat = 0;
299         co.do_pipe = 0;
300         if (!strncmp(*av, "nat", strlen(*av)))
301                 co.do_nat = 1;
302         else if (!strncmp(*av, "pipe", strlen(*av)))
303                 co.do_pipe = 1;
304         else if (_substrcmp(*av, "queue") == 0)
305                 co.do_pipe = 2;
306         else if (!strncmp(*av, "set", strlen(*av))) {
307                 if (ac > 1 && isdigit(av[1][0])) {
308                         co.use_set = strtonum(av[1], 0, resvd_set_number,
309                                         &errstr);
310                         if (errstr)
311                                 errx(EX_DATAERR,
312                                     "invalid set number %s\n", av[1]);
313                         ac -= 2; av += 2; co.use_set++;
314                 }
315         }
316
317         if (co.do_pipe || co.do_nat) {
318                 ac--;
319                 av++;
320         }
321         NEED1("missing command");
322
323         /*
324          * For pipes, queues and nats we normally say 'nat|pipe NN config'
325          * but the code is easier to parse as 'nat|pipe config NN'
326          * so we swap the two arguments.
327          */
328         if ((co.do_pipe || co.do_nat) && ac > 1 && isdigit(*av[0])) {
329                 char *p = av[0];
330
331                 av[0] = av[1];
332                 av[1] = p;
333         }
334
335         int try_next = 0;
336         if (co.use_set == 0) {
337                 if (_substrcmp(*av, "add") == 0)
338                         ipfw_add(ac, av);
339                 else if (co.do_nat && _substrcmp(*av, "show") == 0)
340                         ipfw_show_nat(ac, av);
341                 else if (co.do_pipe && _substrcmp(*av, "config") == 0)
342                         ipfw_config_pipe(ac, av);
343                 else if (co.do_nat && _substrcmp(*av, "config") == 0)
344                         ipfw_config_nat(ac, av);
345                 else if (_substrcmp(*av, "set") == 0)
346                         ipfw_sets_handler(ac, av);
347                 else if (_substrcmp(*av, "table") == 0)
348                         ipfw_table_handler(ac, av);
349                 else if (_substrcmp(*av, "enable") == 0)
350                         ipfw_sysctl_handler(ac, av, 1);
351                 else if (_substrcmp(*av, "disable") == 0)
352                         ipfw_sysctl_handler(ac, av, 0);
353                 else
354                         try_next = 1;
355         }
356
357         if (co.use_set || try_next) {
358                 if (_substrcmp(*av, "delete") == 0)
359                         ipfw_delete(ac, av);
360                 else if (_substrcmp(*av, "flush") == 0)
361                         ipfw_flush(co.do_force);
362                 else if (_substrcmp(*av, "zero") == 0)
363                         ipfw_zero(ac, av, 0 /* IP_FW_ZERO */);
364                 else if (_substrcmp(*av, "resetlog") == 0)
365                         ipfw_zero(ac, av, 1 /* IP_FW_RESETLOG */);
366                 else if (_substrcmp(*av, "print") == 0 ||
367                          _substrcmp(*av, "list") == 0)
368                         ipfw_list(ac, av, do_acct);
369                 else if (_substrcmp(*av, "show") == 0)
370                         ipfw_list(ac, av, 1 /* show counters */);
371                 else
372                         errx(EX_USAGE, "bad command `%s'", *av);
373         }
374
375         /* Free memory allocated in the argument parsing. */
376         free_args(save_ac, save_av);
377         return 0;
378 }
379
380
381 static void
382 ipfw_readfile(int ac, char *av[])
383 {
384 #define MAX_ARGS        32
385         char    buf[BUFSIZ];
386         char *progname = av[0];         /* original program name */
387         const char *cmd = NULL;         /* preprocessor name, if any */
388         const char *filename = av[ac-1]; /* file to read */
389         int     c, lineno=0;
390         FILE    *f = NULL;
391         pid_t   preproc = 0;
392
393         while ((c = getopt(ac, av, "cfNnp:qS")) != -1) {
394                 switch(c) {
395                 case 'c':
396                         co.do_compact = 1;
397                         break;
398
399                 case 'f':
400                         co.do_force = 1;
401                         break;
402
403                 case 'N':
404                         co.do_resolv = 1;
405                         break;
406
407                 case 'n':
408                         co.test_only = 1;
409                         break;
410
411                 case 'p':
412                         /*
413                          * ipfw -p cmd [args] filename
414                          *
415                          * We are done with getopt(). All arguments
416                          * except the filename go to the preprocessor,
417                          * so we need to do the following:
418                          * - check that a filename is actually present;
419                          * - advance av by optind-1 to skip arguments
420                          *   already processed;
421                          * - decrease ac by optind, to remove the args
422                          *   already processed and the final filename;
423                          * - set the last entry in av[] to NULL so
424                          *   popen() can detect the end of the array;
425                          * - set optind=ac to let getopt() terminate.
426                          */
427                         if (optind == ac)
428                                 errx(EX_USAGE, "no filename argument");
429                         cmd = optarg;
430                         av[ac-1] = NULL;
431                         av += optind - 1;
432                         ac -= optind;
433                         optind = ac;
434                         break;
435
436                 case 'q':
437                         co.do_quiet = 1;
438                         break;
439
440                 case 'S':
441                         co.show_sets = 1;
442                         break;
443
444                 default:
445                         errx(EX_USAGE, "bad arguments, for usage"
446                              " summary ``ipfw''");
447                 }
448
449         }
450
451         if (cmd == NULL && ac != optind + 1)
452                 errx(EX_USAGE, "extraneous filename arguments %s", av[ac-1]);
453
454         if ((f = fopen(filename, "r")) == NULL)
455                 err(EX_UNAVAILABLE, "fopen: %s", filename);
456
457         if (cmd != NULL) {                      /* pipe through preprocessor */
458                 int pipedes[2];
459
460                 if (pipe(pipedes) == -1)
461                         err(EX_OSERR, "cannot create pipe");
462
463                 preproc = fork();
464                 if (preproc == -1)
465                         err(EX_OSERR, "cannot fork");
466
467                 if (preproc == 0) {
468                         /*
469                          * Child, will run the preprocessor with the
470                          * file on stdin and the pipe on stdout.
471                          */
472                         if (dup2(fileno(f), 0) == -1
473                             || dup2(pipedes[1], 1) == -1)
474                                 err(EX_OSERR, "dup2()");
475                         fclose(f);
476                         close(pipedes[1]);
477                         close(pipedes[0]);
478                         execvp(cmd, av);
479                         err(EX_OSERR, "execvp(%s) failed", cmd);
480                 } else { /* parent, will reopen f as the pipe */
481                         fclose(f);
482                         close(pipedes[1]);
483                         if ((f = fdopen(pipedes[0], "r")) == NULL) {
484                                 int savederrno = errno;
485
486                                 (void)kill(preproc, SIGTERM);
487                                 errno = savederrno;
488                                 err(EX_OSERR, "fdopen()");
489                         }
490                 }
491         }
492
493         while (fgets(buf, BUFSIZ, f)) {         /* read commands */
494                 char linename[10];
495                 char *args[2];
496
497                 lineno++;
498                 sprintf(linename, "Line %d", lineno);
499                 setprogname(linename); /* XXX */
500                 args[0] = progname;
501                 args[1] = buf;
502                 ipfw_main(2, args);
503         }
504         fclose(f);
505         if (cmd != NULL) {
506                 int status;
507
508                 if (waitpid(preproc, &status, 0) == -1)
509                         errx(EX_OSERR, "waitpid()");
510                 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
511                         errx(EX_UNAVAILABLE,
512                             "preprocessor exited with status %d",
513                             WEXITSTATUS(status));
514                 else if (WIFSIGNALED(status))
515                         errx(EX_UNAVAILABLE,
516                             "preprocessor exited with signal %d",
517                             WTERMSIG(status));
518         }
519 }
520
521 int
522 main(int ac, char *av[])
523 {
524         /*
525          * If the last argument is an absolute pathname, interpret it
526          * as a file to be preprocessed.
527          */
528
529         if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0)
530                 ipfw_readfile(ac, av);
531         else {
532                 if (ipfw_main(ac, av)) {
533                         errx(EX_USAGE,
534                             "usage: ipfw [options]\n"
535                             "do \"ipfw -h\" or \"man ipfw\" for details");
536                 }
537         }
538         return EX_OK;
539 }