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