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