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