1 /*-
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
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 #ifdef FSTACK
35 #include <stdint.h>
36 #include "compat.h"
37
38 #include "ff_ipc.h"
39 #endif
40
41 #include "ipfw2.h"
42
43 static void
help(void)44 help(void)
45 {
46 fprintf(stderr,
47 "ipfw syntax summary (but please do read the ipfw(8) manpage):\n\n"
48 #ifndef FSTACK
49 "\tipfw [-abcdefhnNqStTv] <command>\n\n"
50 #else
51 "\tipfw -P <f-stack proc_id> [-abcdefhnNqStTv] <command>\n\n"
52 #endif
53 "where <command> is one of the following:\n\n"
54 "add [num] [set N] [prob x] RULE-BODY\n"
55 "{pipe|queue} N config PIPE-BODY\n"
56 "[pipe|queue] {zero|delete|show} [N{,N}]\n"
57 "nat N config {ip IPADDR|if IFNAME|log|deny_in|same_ports|unreg_only|unreg_cgn|\n"
58 " reset|reverse|proxy_only|redirect_addr linkspec|\n"
59 " redirect_port linkspec|redirect_proto linkspec}\n"
60 "set [disable N... enable N...] | move [rule] X to Y | swap X Y | show\n"
61 "set N {show|list|zero|resetlog|delete} [N{,N}] | flush\n"
62 "table N {add ip[/bits] [value] | delete ip[/bits] | flush | list}\n"
63 "table all {flush | list}\n"
64 "\n"
65 "RULE-BODY: check-state [PARAMS] | ACTION [PARAMS] ADDR [OPTION_LIST]\n"
66 "ACTION: check-state | allow | count | deny | unreach{,6} CODE |\n"
67 " skipto N | {divert|tee} PORT | forward ADDR |\n"
68 " pipe N | queue N | nat N | setfib FIB | reass\n"
69 "PARAMS: [log [logamount LOGLIMIT]] [altq QUEUE_NAME]\n"
70 "ADDR: [ MAC dst src ether_type ] \n"
71 " [ ip from IPADDR [ PORT ] to IPADDR [ PORTLIST ] ]\n"
72 " [ ipv6|ip6 from IP6ADDR [ PORT ] to IP6ADDR [ PORTLIST ] ]\n"
73 "IPADDR: [not] { any | me | ip/bits{x,y,z} | table(t[,v]) | IPLIST }\n"
74 "IP6ADDR: [not] { any | me | me6 | ip6/bits | IP6LIST }\n"
75 "IP6LIST: { ip6 | ip6/bits }[,IP6LIST]\n"
76 "IPLIST: { ip | ip/bits | ip:mask }[,IPLIST]\n"
77 "OPTION_LIST: OPTION [OPTION_LIST]\n"
78 "OPTION: bridged | diverted | diverted-loopback | diverted-output |\n"
79 " {dst-ip|src-ip} IPADDR | {dst-ip6|src-ip6|dst-ipv6|src-ipv6} IP6ADDR |\n"
80 " {dst-port|src-port} LIST |\n"
81 " estab | frag | {gid|uid} N | icmptypes LIST | in | out | ipid LIST |\n"
82 " iplen LIST | ipoptions SPEC | ipprecedence | ipsec | iptos SPEC |\n"
83 " ipttl LIST | ipversion VER | keep-state | layer2 | limit ... |\n"
84 " icmp6types LIST | ext6hdr LIST | flow-id N[,N] | fib FIB |\n"
85 " mac ... | mac-type LIST | proto LIST | {recv|xmit|via} {IF|IPADDR} |\n"
86 " setup | {tcpack|tcpseq|tcpwin} NN | tcpflags SPEC | tcpoptions SPEC |\n"
87 " tcpdatalen LIST | verrevpath | versrcreach | antispoof\n"
88 );
89
90 #ifdef FSTACK
91 ff_ipc_exit();
92 #endif
93
94 exit(0);
95 }
96
97 /*
98 * Called with the arguments, including program name because getopt
99 * wants it to be present.
100 * Returns 0 if successful, 1 if empty command, errx() in case of errors.
101 * First thing we do is process parameters creating an argv[] array
102 * which includes the program name and a NULL entry at the end.
103 * If we are called with a single string, we split it on whitespace.
104 * Also, arguments with a trailing ',' are joined to the next one.
105 * The pointers (av[]) and data are in a single chunk of memory.
106 * av[0] points to the original program name, all other entries
107 * point into the allocated chunk.
108 */
109 static int
ipfw_main(int oldac,char ** oldav)110 ipfw_main(int oldac, char **oldav)
111 {
112 int ch, ac;
113 const char *errstr;
114 char **av, **save_av;
115 int do_acct = 0; /* Show packet/byte count */
116 int try_next = 0; /* set if pipe cmd not found */
117 int av_size; /* compute the av size */
118 char *av_p; /* used to build the av list */
119
120 #define WHITESP " \t\f\v\n\r"
121 if (oldac < 2)
122 return 1; /* need at least one argument */
123
124 if (oldac == 2) {
125 /*
126 * If we are called with one argument, try to split it into
127 * words for subsequent parsing. Spaces after a ',' are
128 * removed by copying the string in-place.
129 */
130 char *arg = oldav[1]; /* The string is the first arg. */
131 int l = strlen(arg);
132 int copy = 0; /* 1 if we need to copy, 0 otherwise */
133 int i, j;
134
135 for (i = j = 0; i < l; i++) {
136 if (arg[i] == '#') /* comment marker */
137 break;
138 if (copy) {
139 arg[j++] = arg[i];
140 copy = !strchr("," WHITESP, arg[i]);
141 } else {
142 copy = !strchr(WHITESP, arg[i]);
143 if (copy)
144 arg[j++] = arg[i];
145 }
146 }
147 if (!copy && j > 0) /* last char was a 'blank', remove it */
148 j--;
149 l = j; /* the new argument length */
150 arg[j++] = '\0';
151 if (l == 0) /* empty string! */
152 return 1;
153
154 /*
155 * First, count number of arguments. Because of the previous
156 * processing, this is just the number of blanks plus 1.
157 */
158 for (i = 0, ac = 1; i < l; i++)
159 if (strchr(WHITESP, arg[i]) != NULL)
160 ac++;
161
162 /*
163 * Allocate the argument list structure as a single block
164 * of memory, containing pointers and the argument
165 * strings. We include one entry for the program name
166 * because getopt expects it, and a NULL at the end
167 * to simplify further parsing.
168 */
169 ac++; /* add 1 for the program name */
170 av_size = (ac+1) * sizeof(char *) + l + 1;
171 av = safe_calloc(av_size, 1);
172
173 /*
174 * Init the argument pointer to the end of the array
175 * and copy arguments from arg[] to av[]. For each one,
176 * j is the initial character, i is the one past the end.
177 */
178 av_p = (char *)&av[ac+1];
179 for (ac = 1, i = j = 0; i < l; i++) {
180 if (strchr(WHITESP, arg[i]) != NULL || i == l-1) {
181 if (i == l-1)
182 i++;
183 bcopy(arg+j, av_p, i-j);
184 av[ac] = av_p;
185 av_p += i-j; /* the length of the string */
186 *av_p++ = '\0';
187 ac++;
188 j = i + 1;
189 }
190 }
191 } else {
192 /*
193 * If an argument ends with ',' join with the next one.
194 */
195 int first, i, l=0;
196
197 /*
198 * Allocate the argument list structure as a single block
199 * of memory, containing both pointers and the argument
200 * strings. We include some space for the program name
201 * because getopt expects it.
202 * We add an extra pointer to the end of the array,
203 * to make simpler further parsing.
204 */
205 for (i=0; i<oldac; i++)
206 l += strlen(oldav[i]);
207
208 av_size = (oldac+1) * sizeof(char *) + l + oldac;
209 av = safe_calloc(av_size, 1);
210
211 /*
212 * Init the argument pointer to the end of the array
213 * and copy arguments from arg[] to av[]
214 */
215 av_p = (char *)&av[oldac+1];
216 for (first = i = ac = 1, l = 0; i < oldac; i++) {
217 char *arg = oldav[i];
218 int k = strlen(arg);
219
220 l += k;
221 if (arg[k-1] != ',' || i == oldac-1) {
222 /* Time to copy. */
223 av[ac] = av_p;
224 for (l=0; first <= i; first++) {
225 strcat(av_p, oldav[first]);
226 av_p += strlen(oldav[first]);
227 }
228 *av_p++ = '\0';
229 ac++;
230 l = 0;
231 first = i+1;
232 }
233 }
234 }
235
236 /*
237 * set the progname pointer to the original string
238 * and terminate the array with null
239 */
240 av[0] = oldav[0];
241 av[ac] = NULL;
242
243 /* Set the force flag for non-interactive processes */
244 if (!g_co.do_force)
245 g_co.do_force = !isatty(STDIN_FILENO);
246
247 #ifdef EMULATE_SYSCTL /* sysctl emulation */
248 if ( ac >= 2 && !strcmp(av[1], "sysctl")) {
249 char *s;
250 int i;
251
252 if (ac != 3) {
253 printf( "sysctl emulation usage:\n"
254 " ipfw sysctl name[=value]\n"
255 " ipfw sysctl -a\n");
256 return 0;
257 }
258 s = strchr(av[2], '=');
259 if (s == NULL) {
260 s = !strcmp(av[2], "-a") ? NULL : av[2];
261 sysctlbyname(s, NULL, NULL, NULL, 0);
262 } else { /* ipfw sysctl x.y.z=value */
263 /* assume an INT value, will extend later */
264 if (s[1] == '\0') {
265 printf("ipfw sysctl: missing value\n\n");
266 return 0;
267 }
268 *s = '\0';
269 i = strtol(s+1, NULL, 0);
270 sysctlbyname(av[2], NULL, NULL, &i, sizeof(int));
271 }
272 return 0;
273 }
274 #endif
275
276 /* Save arguments for final freeing of memory. */
277 save_av = av;
278
279 optind = optreset = 1; /* restart getopt() */
280 #ifndef FSTACK
281 while ((ch = getopt(ac, av, "abcdDefhinNp:qs:STtv")) != -1)
282 #else
283 while ((ch = getopt(ac, av, "abcdDefhinNp:qs:STtvP:")) != -1)
284 #endif
285 switch (ch) {
286 case 'a':
287 do_acct = 1;
288 break;
289
290 case 'b':
291 g_co.comment_only = 1;
292 g_co.do_compact = 1;
293 break;
294
295 case 'c':
296 g_co.do_compact = 1;
297 break;
298
299 case 'd':
300 g_co.do_dynamic = 1;
301 break;
302
303 case 'D':
304 g_co.do_dynamic = 2;
305 break;
306
307 case 'e':
308 /* nop for compatibility */
309 break;
310
311 case 'f':
312 g_co.do_force = 1;
313 break;
314
315 case 'h': /* help */
316 free(save_av);
317 help();
318 break; /* NOTREACHED */
319
320 case 'i':
321 g_co.do_value_as_ip = 1;
322 break;
323
324 case 'n':
325 g_co.test_only = 1;
326 break;
327
328 case 'N':
329 g_co.do_resolv = 1;
330 break;
331
332 case 'p':
333 errx(EX_USAGE, "An absolute pathname must be used "
334 "with -p option.");
335 /* NOTREACHED */
336
337 case 'q':
338 g_co.do_quiet = 1;
339 break;
340
341 case 's': /* sort */
342 g_co.do_sort = atoi(optarg);
343 break;
344
345 case 'S':
346 g_co.show_sets = 1;
347 break;
348
349 case 't':
350 g_co.do_time = TIMESTAMP_STRING;
351 break;
352
353 case 'T':
354 g_co.do_time = TIMESTAMP_NUMERIC;
355 break;
356
357 case 'v': /* verbose */
358 g_co.verbose = 1;
359 break;
360
361 #ifdef FSTACK
362 case 'P':
363 ff_set_proc_id(atoi(optarg));
364 break;
365 #endif
366
367 default:
368 free(save_av);
369 return 1;
370 }
371
372 ac -= optind;
373 av += optind;
374 NEED1("bad arguments, for usage summary ``ipfw''");
375
376 /*
377 * An undocumented behaviour of ipfw1 was to allow rule numbers first,
378 * e.g. "100 add allow ..." instead of "add 100 allow ...".
379 * In case, swap first and second argument to get the normal form.
380 */
381 if (ac > 1 && isdigit(*av[0])) {
382 char *p = av[0];
383
384 av[0] = av[1];
385 av[1] = p;
386 }
387
388 /*
389 * Optional: pipe, queue or nat.
390 */
391 g_co.do_nat = 0;
392 g_co.do_pipe = 0;
393 g_co.use_set = 0;
394 if (!strncmp(*av, "nat", strlen(*av)))
395 g_co.do_nat = 1;
396 else if (!strncmp(*av, "pipe", strlen(*av)))
397 g_co.do_pipe = 1;
398 else if (_substrcmp(*av, "queue") == 0)
399 g_co.do_pipe = 2;
400 else if (_substrcmp(*av, "flowset") == 0)
401 g_co.do_pipe = 2;
402 else if (_substrcmp(*av, "sched") == 0)
403 g_co.do_pipe = 3;
404 else if (!strncmp(*av, "set", strlen(*av))) {
405 if (ac > 1 && isdigit(av[1][0])) {
406 g_co.use_set = strtonum(av[1], 0, resvd_set_number,
407 &errstr);
408 if (errstr)
409 errx(EX_DATAERR,
410 "invalid set number %s\n", av[1]);
411 ac -= 2; av += 2; g_co.use_set++;
412 }
413 }
414
415 if (g_co.do_pipe || g_co.do_nat) {
416 ac--;
417 av++;
418 }
419 NEED1("missing command");
420
421 /*
422 * For pipes, queues and nats we normally say 'nat|pipe NN config'
423 * but the code is easier to parse as 'nat|pipe config NN'
424 * so we swap the two arguments.
425 */
426 if ((g_co.do_pipe || g_co.do_nat) && ac > 1 && isdigit(*av[0])) {
427 char *p = av[0];
428
429 av[0] = av[1];
430 av[1] = p;
431 }
432
433 if (g_co.use_set == 0) {
434 if (_substrcmp(*av, "add") == 0)
435 ipfw_add(av);
436 else if (g_co.do_nat && _substrcmp(*av, "show") == 0)
437 ipfw_show_nat(ac, av);
438 else if (g_co.do_pipe && _substrcmp(*av, "config") == 0)
439 #ifdef DUMMYNET
440 ipfw_config_pipe(ac, av);
441 #else
442 {
443 errx(EX_UNAVAILABLE, "ipfw_config_pipe not supported");
444 }
445 #endif
446 else if (g_co.do_nat && _substrcmp(*av, "config") == 0)
447 ipfw_config_nat(ac, av);
448 else if (_substrcmp(*av, "set") == 0)
449 ipfw_sets_handler(av);
450 else if (_substrcmp(*av, "table") == 0)
451 ipfw_table_handler(ac, av);
452 else if (_substrcmp(*av, "enable") == 0)
453 ipfw_sysctl_handler(av, 1);
454 else if (_substrcmp(*av, "disable") == 0)
455 ipfw_sysctl_handler(av, 0);
456 else
457 try_next = 1;
458 }
459
460 if (g_co.use_set || try_next) {
461 if (_substrcmp(*av, "delete") == 0)
462 ipfw_delete(av);
463 else if (!strncmp(*av, "nat64clat", strlen(*av)))
464 ipfw_nat64clat_handler(ac, av);
465 else if (!strncmp(*av, "nat64stl", strlen(*av)))
466 ipfw_nat64stl_handler(ac, av);
467 else if (!strncmp(*av, "nat64lsn", strlen(*av)))
468 ipfw_nat64lsn_handler(ac, av);
469 else if (!strncmp(*av, "nptv6", strlen(*av)))
470 ipfw_nptv6_handler(ac, av);
471 else if (_substrcmp(*av, "flush") == 0)
472 ipfw_flush(g_co.do_force);
473 else if (_substrcmp(*av, "zero") == 0)
474 ipfw_zero(ac, av, 0 /* IP_FW_ZERO */);
475 else if (_substrcmp(*av, "resetlog") == 0)
476 ipfw_zero(ac, av, 1 /* IP_FW_RESETLOG */);
477 else if (_substrcmp(*av, "print") == 0 ||
478 _substrcmp(*av, "list") == 0)
479 ipfw_list(ac, av, do_acct);
480 else if (_substrcmp(*av, "show") == 0)
481 ipfw_list(ac, av, 1 /* show counters */);
482 else if (_substrcmp(*av, "table") == 0)
483 ipfw_table_handler(ac, av);
484 else if (_substrcmp(*av, "internal") == 0)
485 ipfw_internal_handler(ac, av);
486 else
487 errx(EX_USAGE, "bad command `%s'", *av);
488 }
489
490 /* Free memory allocated in the argument parsing. */
491 free(save_av);
492 return 0;
493 }
494
495
496 static void
ipfw_readfile(int ac,char * av[])497 ipfw_readfile(int ac, char *av[])
498 {
499 #define MAX_ARGS 32
500 char buf[4096];
501 char *progname = av[0]; /* original program name */
502 const char *cmd = NULL; /* preprocessor name, if any */
503 const char *filename = av[ac-1]; /* file to read */
504 int c, lineno=0;
505 FILE *f = NULL;
506 pid_t preproc = 0;
507
508 #ifndef FSTACK
509 while ((c = getopt(ac, av, "cfNnp:qS")) != -1) {
510 #else
511 while ((c = getopt(ac, av, "cfNnp:qSP:")) != -1) {
512 #endif
513 switch(c) {
514 case 'c':
515 g_co.do_compact = 1;
516 break;
517
518 case 'f':
519 g_co.do_force = 1;
520 break;
521
522 case 'N':
523 g_co.do_resolv = 1;
524 break;
525
526 case 'n':
527 g_co.test_only = 1;
528 break;
529
530 case 'p':
531 /*
532 * ipfw -p cmd [args] filename
533 *
534 * We are done with getopt(). All arguments
535 * except the filename go to the preprocessor,
536 * so we need to do the following:
537 * - check that a filename is actually present;
538 * - advance av by optind-1 to skip arguments
539 * already processed;
540 * - decrease ac by optind, to remove the args
541 * already processed and the final filename;
542 * - set the last entry in av[] to NULL so
543 * popen() can detect the end of the array;
544 * - set optind=ac to let getopt() terminate.
545 */
546 if (optind == ac)
547 errx(EX_USAGE, "no filename argument");
548 cmd = optarg;
549 av[ac-1] = NULL;
550 av += optind - 1;
551 ac -= optind;
552 optind = ac;
553 break;
554
555 case 'q':
556 g_co.do_quiet = 1;
557 break;
558
559 case 'S':
560 g_co.show_sets = 1;
561 break;
562
563 #ifdef FSTACK
564 case 'P':
565 ff_set_proc_id(atoi(optarg));
566 break;
567 #endif
568
569 default:
570 errx(EX_USAGE, "bad arguments, for usage"
571 " summary ``ipfw''");
572 }
573
574 }
575
576 if (cmd == NULL && ac != optind + 1)
577 errx(EX_USAGE, "extraneous filename arguments %s", av[ac-1]);
578
579 if ((f = fopen(filename, "r")) == NULL)
580 err(EX_UNAVAILABLE, "fopen: %s", filename);
581
582 if (cmd != NULL) { /* pipe through preprocessor */
583 int pipedes[2];
584
585 if (pipe(pipedes) == -1)
586 err(EX_OSERR, "cannot create pipe");
587
588 preproc = fork();
589 if (preproc == -1)
590 err(EX_OSERR, "cannot fork");
591
592 if (preproc == 0) {
593 /*
594 * Child, will run the preprocessor with the
595 * file on stdin and the pipe on stdout.
596 */
597 if (dup2(fileno(f), 0) == -1
598 || dup2(pipedes[1], 1) == -1)
599 err(EX_OSERR, "dup2()");
600 fclose(f);
601 close(pipedes[1]);
602 close(pipedes[0]);
603 execvp(cmd, av);
604 err(EX_OSERR, "execvp(%s) failed", cmd);
605 } else { /* parent, will reopen f as the pipe */
606 fclose(f);
607 close(pipedes[1]);
608 if ((f = fdopen(pipedes[0], "r")) == NULL) {
609 int savederrno = errno;
610
611 (void)kill(preproc, SIGTERM);
612 errno = savederrno;
613 err(EX_OSERR, "fdopen()");
614 }
615 }
616 }
617
618 while (fgets(buf, sizeof(buf), f)) { /* read commands */
619 char linename[20];
620 char *args[2];
621
622 lineno++;
623 snprintf(linename, sizeof(linename), "Line %d", lineno);
624 #ifndef FSTACK
625 setprogname(linename); /* XXX */
626 #endif
627 args[0] = progname;
628 args[1] = buf;
629 ipfw_main(2, args);
630 }
631 fclose(f);
632 if (cmd != NULL) {
633 int status;
634
635 if (waitpid(preproc, &status, 0) == -1)
636 errx(EX_OSERR, "waitpid()");
637 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
638 errx(EX_UNAVAILABLE,
639 "preprocessor exited with status %d",
640 WEXITSTATUS(status));
641 else if (WIFSIGNALED(status))
642 errx(EX_UNAVAILABLE,
643 "preprocessor exited with signal %d",
644 WTERMSIG(status));
645 }
646 }
647
648 int
649 main(int ac, char *av[])
650 {
651 #if defined(_WIN32) && defined(TCC)
652 {
653 WSADATA wsaData;
654 int ret=0;
655 unsigned short wVersionRequested = MAKEWORD(2, 2);
656 ret = WSAStartup(wVersionRequested, &wsaData);
657 if (ret != 0) {
658 /* Tell the user that we could not find a usable */
659 /* Winsock DLL. */
660 printf("WSAStartup failed with error: %d\n", ret);
661 return 1;
662 }
663 }
664 #endif
665 /*
666 * If the last argument is an absolute pathname, interpret it
667 * as a file to be preprocessed.
668 */
669 #ifdef FSTACK
670 ff_ipc_init();
671 #endif
672 if (ac > 1 && av[ac - 1][0] == '/') {
673 if (access(av[ac - 1], R_OK) == 0)
674 ipfw_readfile(ac, av);
675 else
676 err(EX_USAGE, "pathname: %s", av[ac - 1]);
677 } else {
678 if (ipfw_main(ac, av)) {
679 errx(EX_USAGE,
680 "usage: ipfw [options]\n"
681 "do \"ipfw -h\" or \"man ipfw\" for details");
682 }
683 }
684 #ifdef FSTACK
685 ff_ipc_exit();
686 #endif
687 return EX_OK;
688 }
689