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