xref: /src/sbin/ipfw/ipfw2.c (revision 32cd3ee5901ea33d41ff550e5f40ce743c8d4165)
1 /*-
2  * Copyright (c) 2002-2003 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  * NEW command line interface for IP firewall facility
19  */
20 
21 #include <sys/types.h>
22 #include <sys/param.h>
23 #include <sys/socket.h>
24 #include <sys/sockio.h>
25 #include <sys/sysctl.h>
26 
27 #include "ipfw2.h"
28 
29 #include <ctype.h>
30 #include <err.h>
31 #include <errno.h>
32 #include <grp.h>
33 #include <jail.h>
34 #include <netdb.h>
35 #include <pwd.h>
36 #include <stdio.h>
37 #include <stdarg.h>
38 #include <stdint.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <sysexits.h>
42 #include <time.h>	/* ctime */
43 #include <timeconv.h>	/* _long_to_time */
44 #include <unistd.h>
45 #include <fcntl.h>
46 #include <stddef.h>	/* offsetof */
47 
48 #include <net/ethernet.h>
49 #include <net/if.h>		/* only IFNAMSIZ */
50 #include <net/if_dl.h>
51 #include <net/route.h>
52 #include <netinet/in.h>
53 #include <netinet/in_systm.h>	/* only n_short, n_long */
54 #include <netinet/ip.h>
55 #include <netinet/ip_icmp.h>
56 #include <netinet/ip_fw.h>
57 #include <netinet/tcp.h>
58 #include <arpa/inet.h>
59 
60 struct cmdline_opts g_co;	/* global options */
61 
62 struct format_opts {
63 	int bcwidth;
64 	int pcwidth;
65 	int show_counters;
66 	int show_time;		/* show timestamp */
67 	uint32_t set_mask;	/* enabled sets mask */
68 	uint32_t flags;		/* request flags */
69 	uint32_t first;		/* first rule to request */
70 	uint32_t last;		/* last rule to request */
71 	uint32_t dcnt;		/* number of dynamic states */
72 	ipfw_obj_ctlv *tstate;	/* table state data */
73 };
74 
75 int resvd_set_number = RESVD_SET;
76 
77 static int ipfw_socket = -1;
78 
79 #define	CHECK_LENGTH(v, len) do {				\
80 	if ((v) < (len))					\
81 		errx(EX_DATAERR, "Rule too long");		\
82 	} while (0)
83 /*
84  * Check if we have enough space in cmd buffer. Note that since
85  * first 8? u32 words are reserved by reserved header, full cmd
86  * buffer can't be used, so we need to protect from buffer overrun
87  * only. At the beginning, cblen is less than actual buffer size by
88  * size of ipfw_insn_u32 instruction + 1 u32 work. This eliminates need
89  * for checking small instructions fitting in given range.
90  * We also (ab)use the fact that ipfw_insn is always the first field
91  * for any custom instruction.
92  */
93 #define	CHECK_CMDLEN	CHECK_LENGTH(cblen, F_LEN((ipfw_insn *)cmd))
94 
95 #define GET_UINT_ARG(arg, min, max, tok, s_x) do {			\
96 	if (!av[0])							\
97 		errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
98 	if (_substrcmp(*av, "tablearg") == 0) {				\
99 		arg = IP_FW_TARG;					\
100 		break;							\
101 	}								\
102 									\
103 	{								\
104 	long _xval;							\
105 	char *end;							\
106 									\
107 	_xval = strtol(*av, &end, 10);					\
108 									\
109 	if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
110 		errx(EX_DATAERR, "%s: invalid argument: %s",		\
111 		    match_value(s_x, tok), *av);			\
112 									\
113 	if (errno == ERANGE || _xval < min || _xval > max)		\
114 		errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
115 		    match_value(s_x, tok), min, max, *av);		\
116 									\
117 	if (_xval == IP_FW_TARG)					\
118 		errx(EX_DATAERR, "%s: illegal argument value: %s",	\
119 		    match_value(s_x, tok), *av);			\
120 	arg = _xval;							\
121 	}								\
122 } while (0)
123 
124 static struct _s_x f_tcpflags[] = {
125 	{ "syn", TH_SYN },
126 	{ "fin", TH_FIN },
127 	{ "ack", TH_ACK },
128 	{ "psh", TH_PUSH },
129 	{ "rst", TH_RST },
130 	{ "urg", TH_URG },
131 	{ "tcp flag", 0 },
132 	{ NULL,	0 }
133 };
134 
135 static struct _s_x f_tcpopts[] = {
136 	{ "mss",	IP_FW_TCPOPT_MSS },
137 	{ "maxseg",	IP_FW_TCPOPT_MSS },
138 	{ "window",	IP_FW_TCPOPT_WINDOW },
139 	{ "sack",	IP_FW_TCPOPT_SACK },
140 	{ "ts",		IP_FW_TCPOPT_TS },
141 	{ "timestamp",	IP_FW_TCPOPT_TS },
142 	{ "cc",		IP_FW_TCPOPT_CC },
143 	{ "tcp option",	0 },
144 	{ NULL,	0 }
145 };
146 
147 /*
148  * IP options span the range 0 to 255 so we need to remap them
149  * (though in fact only the low 5 bits are significant).
150  */
151 static struct _s_x f_ipopts[] = {
152 	{ "ssrr",	IP_FW_IPOPT_SSRR},
153 	{ "lsrr",	IP_FW_IPOPT_LSRR},
154 	{ "rr",		IP_FW_IPOPT_RR},
155 	{ "ts",		IP_FW_IPOPT_TS},
156 	{ "ip option",	0 },
157 	{ NULL,	0 }
158 };
159 
160 static struct _s_x f_iptos[] = {
161 	{ "lowdelay",	IPTOS_LOWDELAY},
162 	{ "throughput",	IPTOS_THROUGHPUT},
163 	{ "reliability", IPTOS_RELIABILITY},
164 	{ "mincost",	IPTOS_MINCOST},
165 	{ "congestion",	IPTOS_ECN_CE},
166 	{ "ecntransport", IPTOS_ECN_ECT0},
167 	{ "ip tos option", 0},
168 	{ NULL,	0 }
169 };
170 
171 static struct _s_x f_ipoff[] = {
172 	{ "rf", IP_RF >> 8 },
173 	{ "df", IP_DF >> 8 },
174 	{ "mf", IP_MF >> 8 },
175 	{ "offset", 0x1 },
176 	{ NULL, 0}
177 };
178 
179 struct _s_x f_ipdscp[] = {
180 	{ "af11", IPTOS_DSCP_AF11 >> 2 },	/* 001010 */
181 	{ "af12", IPTOS_DSCP_AF12 >> 2 },	/* 001100 */
182 	{ "af13", IPTOS_DSCP_AF13 >> 2 },	/* 001110 */
183 	{ "af21", IPTOS_DSCP_AF21 >> 2 },	/* 010010 */
184 	{ "af22", IPTOS_DSCP_AF22 >> 2 },	/* 010100 */
185 	{ "af23", IPTOS_DSCP_AF23 >> 2 },	/* 010110 */
186 	{ "af31", IPTOS_DSCP_AF31 >> 2 },	/* 011010 */
187 	{ "af32", IPTOS_DSCP_AF32 >> 2 },	/* 011100 */
188 	{ "af33", IPTOS_DSCP_AF33 >> 2 },	/* 011110 */
189 	{ "af41", IPTOS_DSCP_AF41 >> 2 },	/* 100010 */
190 	{ "af42", IPTOS_DSCP_AF42 >> 2 },	/* 100100 */
191 	{ "af43", IPTOS_DSCP_AF43 >> 2 },	/* 100110 */
192 	{ "be", IPTOS_DSCP_CS0 >> 2 }, 	/* 000000 */
193 	{ "va", IPTOS_DSCP_VA >> 2 },	/* 101100 */
194 	{ "ef", IPTOS_DSCP_EF >> 2 },	/* 101110 */
195 	{ "cs0", IPTOS_DSCP_CS0 >> 2 },	/* 000000 */
196 	{ "cs1", IPTOS_DSCP_CS1 >> 2 },	/* 001000 */
197 	{ "cs2", IPTOS_DSCP_CS2 >> 2 },	/* 010000 */
198 	{ "cs3", IPTOS_DSCP_CS3 >> 2 },	/* 011000 */
199 	{ "cs4", IPTOS_DSCP_CS4 >> 2 },	/* 100000 */
200 	{ "cs5", IPTOS_DSCP_CS5 >> 2 },	/* 101000 */
201 	{ "cs6", IPTOS_DSCP_CS6 >> 2 },	/* 110000 */
202 	{ "cs7", IPTOS_DSCP_CS7 >> 2 },	/* 100000 */
203 	{ NULL, 0 }
204 };
205 
206 static struct _s_x limit_masks[] = {
207 	{"all",		DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
208 	{"src-addr",	DYN_SRC_ADDR},
209 	{"src-port",	DYN_SRC_PORT},
210 	{"dst-addr",	DYN_DST_ADDR},
211 	{"dst-port",	DYN_DST_PORT},
212 	{NULL,		0}
213 };
214 
215 /*
216  * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
217  * This is only used in this code.
218  */
219 #define IPPROTO_ETHERTYPE	0x1000
220 static struct _s_x ether_types[] = {
221     /*
222      * Note, we cannot use "-:&/" in the names because they are field
223      * separators in the type specifications. Also, we use s = NULL as
224      * end-delimiter, because a type of 0 can be legal.
225      */
226 	{ "ip",		0x0800 },
227 	{ "ipv4",	0x0800 },
228 	{ "ipv6",	0x86dd },
229 	{ "arp",	0x0806 },
230 	{ "rarp",	0x8035 },
231 	{ "vlan",	0x8100 },
232 	{ "loop",	0x9000 },
233 	{ "trail",	0x1000 },
234 	{ "at",		0x809b },
235 	{ "atalk",	0x809b },
236 	{ "aarp",	0x80f3 },
237 	{ "pppoe_disc",	0x8863 },
238 	{ "pppoe_sess",	0x8864 },
239 	{ "ipx_8022",	0x00E0 },
240 	{ "ipx_8023",	0x0000 },
241 	{ "ipx_ii",	0x8137 },
242 	{ "ipx_snap",	0x8137 },
243 	{ "ipx",	0x8137 },
244 	{ "ns",		0x0600 },
245 	{ NULL,		0 }
246 };
247 
248 static struct _s_x rule_eactions[] = {
249 	{ "nat64clat",		TOK_NAT64CLAT },
250 	{ "nat64lsn",		TOK_NAT64LSN },
251 	{ "nat64stl",		TOK_NAT64STL },
252 	{ "nptv6",		TOK_NPTV6 },
253 	{ "tcp-setmss",		TOK_TCPSETMSS },
254 	{ NULL, 0 }	/* terminator */
255 };
256 
257 static struct _s_x rule_actions[] = {
258 	{ "abort6",		TOK_ABORT6 },
259 	{ "abort",		TOK_ABORT },
260 	{ "accept",		TOK_ACCEPT },
261 	{ "pass",		TOK_ACCEPT },
262 	{ "allow",		TOK_ACCEPT },
263 	{ "permit",		TOK_ACCEPT },
264 	{ "count",		TOK_COUNT },
265 	{ "pipe",		TOK_PIPE },
266 	{ "queue",		TOK_QUEUE },
267 	{ "divert",		TOK_DIVERT },
268 	{ "tee",		TOK_TEE },
269 	{ "netgraph",		TOK_NETGRAPH },
270 	{ "ngtee",		TOK_NGTEE },
271 	{ "fwd",		TOK_FORWARD },
272 	{ "forward",		TOK_FORWARD },
273 	{ "skipto",		TOK_SKIPTO },
274 	{ "deny",		TOK_DENY },
275 	{ "drop",		TOK_DENY },
276 	{ "reject",		TOK_REJECT },
277 	{ "reset6",		TOK_RESET6 },
278 	{ "reset",		TOK_RESET },
279 	{ "unreach6",		TOK_UNREACH6 },
280 	{ "unreach",		TOK_UNREACH },
281 	{ "check-state",	TOK_CHECKSTATE },
282 	{ "//",			TOK_COMMENT },
283 	{ "nat",		TOK_NAT },
284 	{ "reass",		TOK_REASS },
285 	{ "setfib",		TOK_SETFIB },
286 	{ "setdscp",		TOK_SETDSCP },
287 	{ "call",		TOK_CALL },
288 	{ "return",		TOK_RETURN },
289 	{ "eaction",		TOK_EACTION },
290 	{ "tcp-setmss",		TOK_TCPSETMSS },
291 	{ "setmark",		TOK_SETMARK },
292 	{ NULL, 0 }	/* terminator */
293 };
294 
295 static struct _s_x return_types[] = {
296 	{ "next-rulenum",	RETURN_NEXT_RULENUM },
297 	{ "next-rule",		RETURN_NEXT_RULE },
298 	{ NULL, 0 }	/* terminator */
299 };
300 
301 static struct _s_x rule_action_params[] = {
302 	{ "altq",		TOK_ALTQ },
303 	{ "log",		TOK_LOG },
304 	{ "tag",		TOK_TAG },
305 	{ "untag",		TOK_UNTAG },
306 	{ NULL, 0 }	/* terminator */
307 };
308 
309 /*
310  * The 'lookup' instruction accepts one of the following arguments.
311  * Arguments are passed as o.arg1 and o->value in O_DST_LOOKUP option.
312  */
313 static struct _s_x lookup_keys[] = {
314 	{ "dst-ip",		LOOKUP_DST_IP },
315 	{ "src-ip",		LOOKUP_SRC_IP },
316 	{ "dst-ip6",		LOOKUP_DST_IP6 },
317 	{ "src-ip6",		LOOKUP_SRC_IP6 },
318 	{ "dst-ip4",		LOOKUP_DST_IP4 },
319 	{ "src-ip4",		LOOKUP_SRC_IP4 },
320 	{ "dst-port",		LOOKUP_DST_PORT },
321 	{ "src-port",		LOOKUP_SRC_PORT },
322 	{ "dst-mac",		LOOKUP_DST_MAC },
323 	{ "src-mac",		LOOKUP_SRC_MAC },
324 	{ "uid",		LOOKUP_UID },
325 	{ "jail",		LOOKUP_JAIL },
326 	{ "dscp",		LOOKUP_DSCP },
327 	{ "mark",		LOOKUP_MARK },
328 	{ "rulenum",		LOOKUP_RULENUM },
329 	{ NULL,			0 },
330 };
331 
332 /*
333  * table(name,valuename=value) instruction accepts one of the
334  * following arguments as valuename.
335  */
336 static struct _s_x tvalue_names[] = {
337 	{ "tag",		TVALUE_TAG },
338 	{ "pipe",		TVALUE_PIPE },
339 	{ "divert",		TVALUE_DIVERT },
340 	{ "skipto",		TVALUE_SKIPTO },
341 	{ "netgraph",		TVALUE_NETGRAPH },
342 	{ "fib",		TVALUE_FIB },
343 	{ "nat",		TVALUE_NAT },
344 	{ "nh4",		TVALUE_NH4 },
345 	{ "nh6",		TVALUE_NH6 },
346 	{ "dscp",		TVALUE_DSCP },
347 	{ "limit",		TVALUE_LIMIT },
348 	{ "mark",		TVALUE_MARK },
349 	{ NULL,			0 }
350 };
351 
352 static struct _s_x rule_options[] = {
353 	{ "tagged",		TOK_TAGGED },
354 	{ "uid",		TOK_UID },
355 	{ "gid",		TOK_GID },
356 	{ "jail",		TOK_JAIL },
357 	{ "in",			TOK_IN },
358 	{ "limit",		TOK_LIMIT },
359 	{ "set-limit",		TOK_SETLIMIT },
360 	{ "keep-state",		TOK_KEEPSTATE },
361 	{ "record-state",	TOK_RECORDSTATE },
362 	{ "bridged",		TOK_LAYER2 },
363 	{ "layer2",		TOK_LAYER2 },
364 	{ "out",		TOK_OUT },
365 	{ "diverted",		TOK_DIVERTED },
366 	{ "diverted-loopback",	TOK_DIVERTEDLOOPBACK },
367 	{ "diverted-output",	TOK_DIVERTEDOUTPUT },
368 	{ "xmit",		TOK_XMIT },
369 	{ "recv",		TOK_RECV },
370 	{ "via",		TOK_VIA },
371 	{ "fragment",		TOK_FRAG },
372 	{ "frag",		TOK_FRAG },
373 	{ "fib",		TOK_FIB },
374 	{ "ipoptions",		TOK_IPOPTS },
375 	{ "ipopts",		TOK_IPOPTS },
376 	{ "iplen",		TOK_IPLEN },
377 	{ "ipid",		TOK_IPID },
378 	{ "ipprecedence",	TOK_IPPRECEDENCE },
379 	{ "dscp",		TOK_DSCP },
380 	{ "iptos",		TOK_IPTOS },
381 	{ "ipttl",		TOK_IPTTL },
382 	{ "ipversion",		TOK_IPVER },
383 	{ "ipver",		TOK_IPVER },
384 	{ "estab",		TOK_ESTAB },
385 	{ "established",	TOK_ESTAB },
386 	{ "setup",		TOK_SETUP },
387 	{ "sockarg",		TOK_SOCKARG },
388 	{ "tcpdatalen",		TOK_TCPDATALEN },
389 	{ "tcpflags",		TOK_TCPFLAGS },
390 	{ "tcpflgs",		TOK_TCPFLAGS },
391 	{ "tcpmss",		TOK_TCPMSS },
392 	{ "tcpoptions",		TOK_TCPOPTS },
393 	{ "tcpopts",		TOK_TCPOPTS },
394 	{ "tcpseq",		TOK_TCPSEQ },
395 	{ "tcpack",		TOK_TCPACK },
396 	{ "tcpwin",		TOK_TCPWIN },
397 	{ "icmptype",		TOK_ICMPTYPES },
398 	{ "icmptypes",		TOK_ICMPTYPES },
399 	{ "dst-ip",		TOK_DSTIP },
400 	{ "src-ip",		TOK_SRCIP },
401 	{ "dst-port",		TOK_DSTPORT },
402 	{ "src-port",		TOK_SRCPORT },
403 	{ "dst-mac",		TOK_DSTMAC },
404 	{ "src-mac",		TOK_SRCMAC },
405 	{ "proto",		TOK_PROTO },
406 	{ "MAC",		TOK_MAC },
407 	{ "mac",		TOK_MAC },
408 	{ "mac-type",		TOK_MACTYPE },
409 	{ "verrevpath",		TOK_VERREVPATH },
410 	{ "versrcreach",	TOK_VERSRCREACH },
411 	{ "antispoof",		TOK_ANTISPOOF },
412 	{ "ipsec",		TOK_IPSEC },
413 	{ "icmp6type",		TOK_ICMP6TYPES },
414 	{ "icmp6types",		TOK_ICMP6TYPES },
415 	{ "ext6hdr",		TOK_EXT6HDR },
416 	{ "flow-id",		TOK_FLOWID },
417 	{ "ipv6",		TOK_IPV6 },
418 	{ "ip6",		TOK_IPV6 },
419 	{ "ipv4",		TOK_IPV4 },
420 	{ "ip4",		TOK_IPV4 },
421 	{ "dst-ipv6",		TOK_DSTIP6 },
422 	{ "dst-ip6",		TOK_DSTIP6 },
423 	{ "src-ipv6",		TOK_SRCIP6 },
424 	{ "src-ip6",		TOK_SRCIP6 },
425 	{ "lookup",		TOK_LOOKUP },
426 	{ "flow",		TOK_FLOW },
427 	{ "mark",		TOK_MARK },
428 	{ "defer-action",	TOK_SKIPACTION },
429 	{ "defer-immediate-action",	TOK_SKIPACTION },
430 	{ "//",			TOK_COMMENT },
431 
432 	{ "not",		TOK_NOT },		/* pseudo option */
433 	{ "!", /* escape ? */	TOK_NOT },		/* pseudo option */
434 	{ "or",			TOK_OR },		/* pseudo option */
435 	{ "|", /* escape */	TOK_OR },		/* pseudo option */
436 	{ "{",			TOK_STARTBRACE },	/* pseudo option */
437 	{ "(",			TOK_STARTBRACE },	/* pseudo option */
438 	{ "}",			TOK_ENDBRACE },		/* pseudo option */
439 	{ ")",			TOK_ENDBRACE },		/* pseudo option */
440 	{ NULL, 0 }	/* terminator */
441 };
442 
443 void bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg);
444 static int ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
445     ipfw_cfg_lheader **pcfg, size_t *psize);
446 static int ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
447     ipfw_cfg_lheader *cfg, size_t sz, int ac, char **av);
448 static void ipfw_list_tifaces(void);
449 
450 struct tidx;
451 static uint32_t pack_object(struct tidx *tstate, const char *name, int otype);
452 static uint32_t pack_table(struct tidx *tstate, const char *name);
453 
454 static char *table_search_ctlv(ipfw_obj_ctlv *ctlv, uint32_t idx);
455 static void object_sort_ctlv(ipfw_obj_ctlv *ctlv);
456 static char *object_search_ctlv(ipfw_obj_ctlv *ctlv, uint32_t idx,
457     uint16_t type);
458 
459 int
is_ipfw(void)460 is_ipfw(void)
461 {
462 	return (g_co.prog == cmdline_prog_ipfw);
463 }
464 
465 /*
466  * Simple string buffer API.
467  * Used to simplify buffer passing between function and for
468  * transparent overrun handling.
469  */
470 
471 /*
472  * Allocates new buffer of given size @sz.
473  *
474  * Returns 0 on success.
475  */
476 int
bp_alloc(struct buf_pr * b,size_t size)477 bp_alloc(struct buf_pr *b, size_t size)
478 {
479 	memset(b, 0, sizeof(struct buf_pr));
480 
481 	if ((b->buf = calloc(1, size)) == NULL)
482 		return (ENOMEM);
483 
484 	b->ptr = b->buf;
485 	b->size = size;
486 	b->avail = b->size;
487 
488 	return (0);
489 }
490 
491 void
bp_free(struct buf_pr * b)492 bp_free(struct buf_pr *b)
493 {
494 
495 	free(b->buf);
496 }
497 
498 /*
499  * Flushes buffer so new writer start from beginning.
500  */
501 void
bp_flush(struct buf_pr * b)502 bp_flush(struct buf_pr *b)
503 {
504 
505 	b->ptr = b->buf;
506 	b->avail = b->size;
507 	b->buf[0] = '\0';
508 }
509 
510 /*
511  * Print message specified by @format and args.
512  * Automatically manage buffer space and transparently handle
513  * buffer overruns.
514  *
515  * Returns number of bytes that should have been printed.
516  */
517 int
bprintf(struct buf_pr * b,const char * format,...)518 bprintf(struct buf_pr *b, const char *format, ...)
519 {
520 	va_list args;
521 	int i;
522 
523 	va_start(args, format);
524 
525 	i = vsnprintf(b->ptr, b->avail, format, args);
526 	va_end(args);
527 
528 	if (i < 0 || (size_t)i > b->avail) {
529 		/* Overflow or print error */
530 		b->avail = 0;
531 	} else {
532 		b->ptr += i;
533 		b->avail -= i;
534 	}
535 
536 	b->needed += i;
537 
538 	return (i);
539 }
540 
541 /*
542  * Special values printer for tablearg-aware opcodes.
543  */
544 void
bprint_uint_arg(struct buf_pr * bp,const char * str,uint32_t arg)545 bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg)
546 {
547 
548 	if (str != NULL)
549 		bprintf(bp, "%s", str);
550 	if (arg == IP_FW_TARG)
551 		bprintf(bp, "tablearg");
552 	else
553 		bprintf(bp, "%u", arg);
554 }
555 
556 /*
557  * Helper routine to print a possibly unaligned uint64_t on
558  * various platform. If width > 0, print the value with
559  * the desired width, followed by a space;
560  * otherwise, return the required width.
561  */
562 int
pr_u64(struct buf_pr * b,void * pd,int width)563 pr_u64(struct buf_pr *b, void *pd, int width)
564 {
565 #ifdef TCC
566 #define U64_FMT "I64"
567 #else
568 #define U64_FMT "llu"
569 #endif
570 	uint64_t u;
571 	unsigned long long d;
572 
573 	bcopy (pd, &u, sizeof(u));
574 	d = u;
575 	return (width > 0) ?
576 		bprintf(b, "%*" U64_FMT " ", width, d) :
577 		snprintf(NULL, 0, "%" U64_FMT, d) ;
578 #undef U64_FMT
579 }
580 
581 
582 void *
safe_calloc(size_t number,size_t size)583 safe_calloc(size_t number, size_t size)
584 {
585 	void *ret = calloc(number, size);
586 
587 	if (ret == NULL)
588 		err(EX_OSERR, "calloc");
589 	return ret;
590 }
591 
592 void *
safe_realloc(void * ptr,size_t size)593 safe_realloc(void *ptr, size_t size)
594 {
595 	void *ret = realloc(ptr, size);
596 
597 	if (ret == NULL)
598 		err(EX_OSERR, "realloc");
599 	return ret;
600 }
601 
602 /*
603  * Compare things like interface or table names.
604  */
605 int
stringnum_cmp(const char * a,const char * b)606 stringnum_cmp(const char *a, const char *b)
607 {
608 	int la, lb;
609 
610 	la = strlen(a);
611 	lb = strlen(b);
612 
613 	if (la > lb)
614 		return (1);
615 	else if (la < lb)
616 		return (-01);
617 
618 	return (strcmp(a, b));
619 }
620 
621 struct debug_header {
622 	uint16_t cmd_type;
623 	uint16_t spare1;
624 	uint32_t opt_name;
625 	uint32_t total_len;
626 	uint32_t spare2;
627 };
628 
629 /*
630  * conditionally runs the command.
631  * Selected options or negative -> getsockopt
632  */
633 int
do_cmd(int optname,void * optval,uintptr_t optlen)634 do_cmd(int optname, void *optval, uintptr_t optlen)
635 {
636 	int i;
637 
638 	if (g_co.debug_only) {
639 		struct debug_header dbg = {
640 			.cmd_type = 1,
641 			.opt_name = optname,
642 			.total_len = optlen + sizeof(struct debug_header),
643 		};
644 		write(1, &dbg, sizeof(dbg));
645 		write(1, optval, optlen);
646 	}
647 
648 	if (g_co.test_only)
649 		return (0);
650 
651 	if (ipfw_socket == -1)
652 		ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
653 	if (ipfw_socket < 0)
654 		err(EX_UNAVAILABLE, "socket");
655 
656 	if (optname == IP_FW3 || optname < 0) {
657 		if (optname < 0)
658 			optname = -optname;
659 		i = getsockopt(ipfw_socket, IPPROTO_IP, optname, optval,
660 			(socklen_t *)optlen);
661 	} else {
662 		i = setsockopt(ipfw_socket, IPPROTO_IP, optname, optval, optlen);
663 	}
664 	return (i);
665 }
666 
667 /*
668  * do_set3 - pass ipfw control cmd to kernel
669  * @optname: option name
670  * @optval: pointer to option data
671  * @optlen: option length
672  *
673  * Assumes op3 header is already embedded.
674  * Calls setsockopt() with IP_FW3 as kernel-visible opcode.
675  * Returns 0 on success or errno otherwise.
676  */
677 int
do_set3(int optname,ip_fw3_opheader * op3,size_t optlen)678 do_set3(int optname, ip_fw3_opheader *op3, size_t optlen)
679 {
680 
681 	op3->opcode = optname;
682 	op3->version = IP_FW3_OPVER; /* use last version */
683 
684 	if (g_co.debug_only) {
685 		struct debug_header dbg = {
686 			.cmd_type = 2,
687 			.opt_name = optname,
688 			.total_len = optlen, sizeof(struct debug_header),
689 		};
690 		write(1, &dbg, sizeof(dbg));
691 		write(1, op3, optlen);
692 	}
693 
694 	if (g_co.test_only)
695 		return (0);
696 
697 	if (ipfw_socket == -1)
698 		ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
699 	if (ipfw_socket < 0)
700 		err(EX_UNAVAILABLE, "socket");
701 
702 
703 	return (setsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, optlen));
704 }
705 
706 /*
707  * do_get3 - pass ipfw control cmd to kernel
708  * @optname: option name
709  * @optval: pointer to option data
710  * @optlen: pointer to option length
711  *
712  * Assumes op3 header is already embedded.
713  * Calls getsockopt() with IP_FW3 as kernel-visible opcode.
714  * Returns 0 on success or errno otherwise.
715  */
716 int
do_get3(int optname,ip_fw3_opheader * op3,size_t * optlen)717 do_get3(int optname, ip_fw3_opheader *op3, size_t *optlen)
718 {
719 	int error;
720 	socklen_t len;
721 
722 	op3->opcode = optname;
723 	op3->version = IP_FW3_OPVER; /* use last version */
724 
725 	if (g_co.debug_only) {
726 		struct debug_header dbg = {
727 			.cmd_type = 3,
728 			.opt_name = optname,
729 			.total_len = *optlen + sizeof(struct debug_header),
730 		};
731 		write(1, &dbg, sizeof(dbg));
732 		write(1, op3, *optlen);
733 	}
734 
735 	if (g_co.test_only)
736 		return (0);
737 
738 	if (ipfw_socket == -1)
739 		ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
740 	if (ipfw_socket < 0)
741 		err(EX_UNAVAILABLE, "socket");
742 
743 
744 	len = *optlen;
745 	error = getsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, &len);
746 	*optlen = len;
747 
748 	return (error);
749 }
750 
751 /**
752  * match_token takes a table and a string, returns the value associated
753  * with the string (-1 in case of failure).
754  */
755 int
match_token(struct _s_x * table,const char * string)756 match_token(struct _s_x *table, const char *string)
757 {
758 	struct _s_x *pt;
759 	uint i = strlen(string);
760 
761 	for (pt = table ; i && pt->s != NULL ; pt++)
762 		if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
763 			return pt->x;
764 	return (-1);
765 }
766 
767 /**
768  * match_token_relaxed takes a table and a string, returns the value associated
769  * with the string for the best match.
770  *
771  * Returns:
772  * value from @table for matched records
773  * -1 for non-matched records
774  * -2 if more than one records match @string.
775  */
776 int
match_token_relaxed(struct _s_x * table,const char * string)777 match_token_relaxed(struct _s_x *table, const char *string)
778 {
779 	struct _s_x *pt, *m;
780 	int i, c;
781 
782 	i = strlen(string);
783 	c = 0;
784 
785 	for (pt = table ; i != 0 && pt->s != NULL ; pt++) {
786 		if (strncmp(pt->s, string, i) != 0)
787 			continue;
788 		m = pt;
789 		c++;
790 	}
791 
792 	if (c == 1)
793 		return (m->x);
794 
795 	return (c > 0 ? -2: -1);
796 }
797 
798 int
get_token(struct _s_x * table,const char * string,const char * errbase)799 get_token(struct _s_x *table, const char *string, const char *errbase)
800 {
801 	int tcmd;
802 
803 	if ((tcmd = match_token_relaxed(table, string)) < 0)
804 		errx(EX_USAGE, "%s %s %s",
805 		    (tcmd == 0) ? "invalid" : "ambiguous", errbase, string);
806 
807 	return (tcmd);
808 }
809 
810 /**
811  * match_value takes a table and a value, returns the string associated
812  * with the value (NULL in case of failure).
813  */
814 char const *
match_value(struct _s_x * p,int value)815 match_value(struct _s_x *p, int value)
816 {
817 	for (; p->s != NULL; p++)
818 		if (p->x == value)
819 			return p->s;
820 	return NULL;
821 }
822 
823 size_t
concat_tokens(char * buf,size_t bufsize,struct _s_x * table,const char * delimiter)824 concat_tokens(char *buf, size_t bufsize, struct _s_x *table,
825     const char *delimiter)
826 {
827 	struct _s_x *pt;
828 	int l;
829 	size_t sz;
830 
831 	for (sz = 0, pt = table ; pt->s != NULL; pt++) {
832 		l = snprintf(buf + sz, bufsize - sz, "%s%s",
833 		    (sz == 0) ? "" : delimiter, pt->s);
834 		sz += l;
835 		bufsize += l;
836 		if (sz > bufsize)
837 			return (bufsize);
838 	}
839 
840 	return (sz);
841 }
842 
843 /*
844  * helper function to process a set of flags and set bits in the
845  * appropriate masks.
846  */
847 int
fill_flags(struct _s_x * flags,char * p,char ** e,uint32_t * set,uint32_t * clear)848 fill_flags(struct _s_x *flags, char *p, char **e, uint32_t *set,
849     uint32_t *clear)
850 {
851 	char *q;	/* points to the separator */
852 	int val;
853 	uint32_t *which;	/* mask we are working on */
854 
855 	while (p && *p) {
856 		if (*p == '!') {
857 			p++;
858 			which = clear;
859 		} else
860 			which = set;
861 		q = strchr(p, ',');
862 		if (q)
863 			*q++ = '\0';
864 		val = match_token(flags, p);
865 		if (val <= 0) {
866 			if (e != NULL)
867 				*e = p;
868 			return (-1);
869 		}
870 		*which |= (uint32_t)val;
871 		p = q;
872 	}
873 	return (0);
874 }
875 
876 void
print_flags_buffer(char * buf,size_t sz,struct _s_x * list,uint32_t set)877 print_flags_buffer(char *buf, size_t sz, struct _s_x *list, uint32_t set)
878 {
879 	char const *comma = "";
880 	int i, l;
881 
882 	for (i = 0; list[i].x != 0; i++) {
883 		if ((set & list[i].x) == 0)
884 			continue;
885 
886 		set &= ~list[i].x;
887 		l = snprintf(buf, sz, "%s%s", comma, list[i].s);
888 		if (l < 0 || (size_t)l >= sz)
889 			return;
890 		comma = ",";
891 		buf += l;
892 		sz -=l;
893 	}
894 }
895 
896 /*
897  * _substrcmp takes two strings and returns 1 if they do not match,
898  * and 0 if they match exactly or the first string is a sub-string
899  * of the second.  A warning is printed to stderr in the case that the
900  * first string is a sub-string of the second.
901  *
902  * This function will be removed in the future through the usual
903  * deprecation process.
904  */
905 int
_substrcmp(const char * str1,const char * str2)906 _substrcmp(const char *str1, const char* str2)
907 {
908 
909 	if (strncmp(str1, str2, strlen(str1)) != 0)
910 		return 1;
911 
912 	if (strlen(str1) != strlen(str2))
913 		warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
914 		    str1, str2);
915 	return 0;
916 }
917 
918 /*
919  * _substrcmp2 takes three strings and returns 1 if the first two do not match,
920  * and 0 if they match exactly or the second string is a sub-string
921  * of the first.  A warning is printed to stderr in the case that the
922  * first string does not match the third.
923  *
924  * This function exists to warn about the bizarre construction
925  * strncmp(str, "by", 2) which is used to allow people to use a shortcut
926  * for "bytes".  The problem is that in addition to accepting "by",
927  * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
928  * other string beginning with "by".
929  *
930  * This function will be removed in the future through the usual
931  * deprecation process.
932  */
933 int
_substrcmp2(const char * str1,const char * str2,const char * str3)934 _substrcmp2(const char *str1, const char* str2, const char* str3)
935 {
936 
937 	if (strncmp(str1, str2, strlen(str2)) != 0)
938 		return 1;
939 
940 	if (strcmp(str1, str3) != 0)
941 		warnx("DEPRECATED: '%s' matched '%s'",
942 		    str1, str3);
943 	return 0;
944 }
945 
946 /*
947  * prints one port, symbolic or numeric
948  */
949 static void
print_port(struct buf_pr * bp,int proto,uint16_t port)950 print_port(struct buf_pr *bp, int proto, uint16_t port)
951 {
952 
953 	if (proto == IPPROTO_ETHERTYPE) {
954 		char const *s;
955 
956 		if (g_co.do_resolv && (s = match_value(ether_types, port)) )
957 			bprintf(bp, "%s", s);
958 		else
959 			bprintf(bp, "0x%04x", port);
960 	} else {
961 		struct servent *se = NULL;
962 		if (g_co.do_resolv) {
963 			struct protoent *pe = getprotobynumber(proto);
964 
965 			se = getservbyport(htons(port), pe ? pe->p_name : NULL);
966 		}
967 		if (se)
968 			bprintf(bp, "%s", se->s_name);
969 		else
970 			bprintf(bp, "%d", port);
971 	}
972 }
973 
974 static struct _s_x _port_name[] = {
975 	{"dst-port",	O_IP_DSTPORT},
976 	{"src-port",	O_IP_SRCPORT},
977 	{"ipid",	O_IPID},
978 	{"iplen",	O_IPLEN},
979 	{"ipttl",	O_IPTTL},
980 	{"mac-type",	O_MAC_TYPE},
981 	{"tcpdatalen",	O_TCPDATALEN},
982 	{"tcpmss",	O_TCPMSS},
983 	{"tcpwin",	O_TCPWIN},
984 	{"tagged",	O_TAGGED},
985 	{NULL,		0}
986 };
987 
988 /*
989  * Print the values in a list 16-bit items of the types above.
990  * XXX todo: add support for mask.
991  */
992 static void
print_newports(struct buf_pr * bp,const ipfw_insn_u16 * cmd,int proto,int opcode)993 print_newports(struct buf_pr *bp, const ipfw_insn_u16 *cmd, int proto, int opcode)
994 {
995 	const uint16_t *p = cmd->ports;
996 	int i;
997 	char const *sep;
998 
999 	if (opcode != 0) {
1000 		sep = match_value(_port_name, opcode);
1001 		if (sep == NULL)
1002 			sep = "???";
1003 		bprintf(bp, " %s", sep);
1004 	}
1005 	sep = " ";
1006 	for (i = F_LEN((const ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
1007 		bprintf(bp, "%s", sep);
1008 		print_port(bp, proto, p[0]);
1009 		if (p[0] != p[1]) {
1010 			bprintf(bp, "-");
1011 			print_port(bp, proto, p[1]);
1012 		}
1013 		sep = ",";
1014 	}
1015 }
1016 
1017 /*
1018  * Like strtol, but also translates service names into port numbers
1019  * for some protocols.
1020  * In particular:
1021  *	proto == -1 disables the protocol check;
1022  *	proto == IPPROTO_ETHERTYPE looks up an internal table
1023  *	proto == <some value in /etc/protocols> matches the values there.
1024  * Returns *end == s in case the parameter is not found.
1025  */
1026 static int
strtoport(char * s,char ** end,int base,int proto)1027 strtoport(char *s, char **end, int base, int proto)
1028 {
1029 	char *p, *buf;
1030 	char *s1;
1031 	int i;
1032 
1033 	*end = s;		/* default - not found */
1034 	if (*s == '\0')
1035 		return 0;	/* not found */
1036 
1037 	if (isdigit(*s))
1038 		return strtol(s, end, base);
1039 
1040 	/*
1041 	 * find separator. '\\' escapes the next char.
1042 	 */
1043 	for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\' ||
1044 	    *s1 == '_' || *s1 == '.') ; s1++)
1045 		if (*s1 == '\\' && s1[1] != '\0')
1046 			s1++;
1047 
1048 	buf = safe_calloc(s1 - s + 1, 1);
1049 
1050 	/*
1051 	 * copy into a buffer skipping backslashes
1052 	 */
1053 	for (p = s, i = 0; p != s1 ; p++)
1054 		if (*p != '\\')
1055 			buf[i++] = *p;
1056 	buf[i++] = '\0';
1057 
1058 	if (proto == IPPROTO_ETHERTYPE) {
1059 		i = match_token(ether_types, buf);
1060 		free(buf);
1061 		if (i != -1) {	/* found */
1062 			*end = s1;
1063 			return i;
1064 		}
1065 	} else {
1066 		struct protoent *pe = NULL;
1067 		struct servent *se;
1068 
1069 		if (proto != 0)
1070 			pe = getprotobynumber(proto);
1071 		setservent(1);
1072 		se = getservbyname(buf, pe ? pe->p_name : NULL);
1073 		free(buf);
1074 		if (se != NULL) {
1075 			*end = s1;
1076 			return ntohs(se->s_port);
1077 		}
1078 	}
1079 	return 0;	/* not found */
1080 }
1081 
1082 /*
1083  * Fill the body of the command with the list of port ranges.
1084  */
1085 static int
fill_newports(ipfw_insn_u16 * cmd,char * av,int proto,int cblen)1086 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
1087 {
1088 	uint16_t a, b, *p = cmd->ports;
1089 	int i = 0;
1090 	char *s = av;
1091 
1092 	while (*s) {
1093 		a = strtoport(av, &s, 0, proto);
1094 		if (s == av) 			/* empty or invalid argument */
1095 			return (0);
1096 
1097 		CHECK_LENGTH(cblen, i + 2);
1098 
1099 		switch (*s) {
1100 		case '-':			/* a range */
1101 			av = s + 1;
1102 			b = strtoport(av, &s, 0, proto);
1103 			/* Reject expressions like '1-abc' or '1-2-3'. */
1104 			if (s == av || (*s != ',' && *s != '\0'))
1105 				return (0);
1106 			p[0] = a;
1107 			p[1] = b;
1108 			break;
1109 		case ',':			/* comma separated list */
1110 		case '\0':
1111 			p[0] = p[1] = a;
1112 			break;
1113 		default:
1114 			warnx("port list: invalid separator <%c> in <%s>",
1115 				*s, av);
1116 			return (0);
1117 		}
1118 
1119 		i++;
1120 		p += 2;
1121 		av = s + 1;
1122 	}
1123 	if (i > 0) {
1124 		if (i + 1 > F_LEN_MASK)
1125 			errx(EX_DATAERR, "too many ports/ranges\n");
1126 		cmd->o.len |= i + 1;	/* leave F_NOT and F_OR untouched */
1127 	}
1128 	return (i);
1129 }
1130 
1131 /*
1132  * Fill the body of the command with the list of DiffServ codepoints.
1133  */
1134 static void
fill_dscp(ipfw_insn * cmd,char * av,int cblen)1135 fill_dscp(ipfw_insn *cmd, char *av, int cblen)
1136 {
1137 	uint32_t *low, *high;
1138 	char *s = av, *a;
1139 	int code;
1140 
1141 	cmd->opcode = O_DSCP;
1142 	cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
1143 
1144 	CHECK_CMDLEN;
1145 
1146 	low = (uint32_t *)(cmd + 1);
1147 	high = low + 1;
1148 
1149 	*low = 0;
1150 	*high = 0;
1151 
1152 	while (s != NULL) {
1153 		a = strchr(s, ',');
1154 
1155 		if (a != NULL)
1156 			*a++ = '\0';
1157 
1158 		if (isalpha(*s)) {
1159 			if ((code = match_token(f_ipdscp, s)) == -1)
1160 				errx(EX_DATAERR, "Unknown DSCP code");
1161 		} else {
1162 			code = strtoul(s, NULL, 10);
1163 			if (code < 0 || code > 63)
1164 				errx(EX_DATAERR, "Invalid DSCP value");
1165 		}
1166 
1167 		if (code >= 32)
1168 			*high |= 1 << (code - 32);
1169 		else
1170 			*low |= 1 << code;
1171 
1172 		s = a;
1173 	}
1174 }
1175 
1176 /*
1177  * Fill the body of the command with mark value and mask.
1178  */
1179 static void
fill_mark(ipfw_insn * cmd,char * av,int cblen)1180 fill_mark(ipfw_insn *cmd, char *av, int cblen)
1181 {
1182 	uint32_t *value, *mask;
1183 	char *value_str;
1184 
1185 	cmd->opcode = O_MARK;
1186 	cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
1187 
1188 	CHECK_CMDLEN;
1189 
1190 	value = (uint32_t *)(cmd + 1);
1191 	mask = value + 1;
1192 
1193 	value_str = strsep(&av, ":");
1194 
1195 	if (strcmp(value_str, "tablearg") == 0) {
1196 		cmd->arg1 = IP_FW_TARG;
1197 		*value = 0;
1198 	} else {
1199 		/* This is not a tablearg */
1200 		cmd->arg1 |= 0x8000;
1201 		*value = strtoul(value_str, NULL, 0);
1202 	}
1203 	if (av)
1204 		*mask = strtoul(av, NULL, 0);
1205 	else
1206 		*mask = 0xFFFFFFFF;
1207 
1208 	if ((*value & *mask) != *value)
1209 		errx(EX_DATAERR, "Static mark value: some bits in value are"
1210 		    " set that will be masked out by mask "
1211 		    "(%#x & %#x) = %#x != %#x",
1212 		    *value, *mask, (*value & *mask), *value);
1213 }
1214 
1215 static struct _s_x icmpcodes[] = {
1216       { "net",			ICMP_UNREACH_NET },
1217       { "host",			ICMP_UNREACH_HOST },
1218       { "protocol",		ICMP_UNREACH_PROTOCOL },
1219       { "port",			ICMP_UNREACH_PORT },
1220       { "needfrag",		ICMP_UNREACH_NEEDFRAG },
1221       { "srcfail",		ICMP_UNREACH_SRCFAIL },
1222       { "net-unknown",		ICMP_UNREACH_NET_UNKNOWN },
1223       { "host-unknown",		ICMP_UNREACH_HOST_UNKNOWN },
1224       { "isolated",		ICMP_UNREACH_ISOLATED },
1225       { "net-prohib",		ICMP_UNREACH_NET_PROHIB },
1226       { "host-prohib",		ICMP_UNREACH_HOST_PROHIB },
1227       { "tosnet",		ICMP_UNREACH_TOSNET },
1228       { "toshost",		ICMP_UNREACH_TOSHOST },
1229       { "filter-prohib",	ICMP_UNREACH_FILTER_PROHIB },
1230       { "host-precedence",	ICMP_UNREACH_HOST_PRECEDENCE },
1231       { "precedence-cutoff",	ICMP_UNREACH_PRECEDENCE_CUTOFF },
1232       { NULL, 0 }
1233 };
1234 
1235 static uint16_t
get_reject_code(const char * str)1236 get_reject_code(const char *str)
1237 {
1238 	int val;
1239 	char *s;
1240 
1241 	val = strtoul(str, &s, 0);
1242 	if (s == str || *s != '\0' || val >= 0x100)
1243 		val = match_token(icmpcodes, str);
1244 	if (val < 0)
1245 		errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
1246 	return (val);
1247 }
1248 
1249 static void
print_reject_code(struct buf_pr * bp,uint16_t code)1250 print_reject_code(struct buf_pr *bp, uint16_t code)
1251 {
1252 	char const *s;
1253 
1254 	if ((s = match_value(icmpcodes, code)) != NULL)
1255 		bprintf(bp, "unreach %s", s);
1256 	else
1257 		bprintf(bp, "unreach %u", code);
1258 }
1259 
1260 /*
1261  * Returns the number of bits set (from left) in a contiguous bitmask,
1262  * or -1 if the mask is not contiguous.
1263  * XXX this needs a proper fix.
1264  * This effectively works on masks in big-endian (network) format.
1265  * when compiled on little endian architectures.
1266  *
1267  * First bit is bit 7 of the first byte -- note, for MAC addresses,
1268  * the first bit on the wire is bit 0 of the first byte.
1269  * len is the max length in bits.
1270  */
1271 int
contigmask(const uint8_t * p,int len)1272 contigmask(const uint8_t *p, int len)
1273 {
1274 	int i, n;
1275 
1276 	for (i=0; i<len ; i++)
1277 		if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
1278 			break;
1279 	for (n=i+1; n < len; n++)
1280 		if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
1281 			return -1; /* mask not contiguous */
1282 	return i;
1283 }
1284 
1285 /*
1286  * print flags set/clear in the two bitmasks passed as parameters.
1287  * There is a specialized check for f_tcpflags.
1288  */
1289 static void
print_flags(struct buf_pr * bp,char const * name,const ipfw_insn * cmd,struct _s_x * list)1290 print_flags(struct buf_pr *bp, char const *name, const ipfw_insn *cmd,
1291     struct _s_x *list)
1292 {
1293 	char const *comma = "";
1294 	int i;
1295 	uint8_t set = cmd->arg1 & 0xff;
1296 	uint8_t clear = (cmd->arg1 >> 8) & 0xff;
1297 
1298 	if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
1299 		bprintf(bp, " setup");
1300 		return;
1301 	}
1302 
1303 	bprintf(bp, " %s ", name);
1304 	for (i=0; list[i].x != 0; i++) {
1305 		if (set & list[i].x) {
1306 			set &= ~list[i].x;
1307 			bprintf(bp, "%s%s", comma, list[i].s);
1308 			comma = ",";
1309 		}
1310 		if (clear & list[i].x) {
1311 			clear &= ~list[i].x;
1312 			bprintf(bp, "%s!%s", comma, list[i].s);
1313 			comma = ",";
1314 		}
1315 	}
1316 }
1317 
1318 static void
print_tvalue(struct buf_pr * bp,const ipfw_insn_lookup * cmd)1319 print_tvalue(struct buf_pr *bp, const ipfw_insn_lookup *cmd)
1320 {
1321 	char maskbuf[INET6_ADDRSTRLEN];
1322 	const char *name;
1323 
1324 	name = match_value(tvalue_names, IPFW_TVALUE_TYPE(&cmd->o));
1325 	switch(IPFW_TVALUE_TYPE(&cmd->o)) {
1326 	case TVALUE_NH6:
1327 		if (inet_ntop(AF_INET6, &insntoc(&cmd->o, lookup)->ip6,
1328 		    maskbuf, sizeof(maskbuf)) == NULL)
1329 			strcpy(maskbuf, "<invalid>");
1330 		bprintf(bp, ",%s=%s", name != NULL ? name: "<invalid>",
1331 		    maskbuf);
1332 		return;
1333 	case TVALUE_NH4:
1334 		bprintf(bp, ",%s=%s", name != NULL ? name: "<invalid>",
1335 		    inet_ntoa(cmd->ip4));
1336 		return;
1337 	}
1338 	bprintf(bp, ",%s=%u", name != NULL ? name: "<invalid>",
1339 	    cmd->u32);
1340 }
1341 
1342 
1343 /*
1344  * Print the ip address contained in a command.
1345  */
1346 static void
print_ip(struct buf_pr * bp,const struct format_opts * fo,const ipfw_insn_ip * cmd)1347 print_ip(struct buf_pr *bp, const struct format_opts *fo,
1348     const ipfw_insn_ip *cmd)
1349 {
1350 	char maskbuf[INET6_ADDRSTRLEN];
1351 	const uint32_t *a = insntoc(cmd, u32)->d;
1352 	struct hostent *he = NULL;
1353 	const struct in_addr *ia;
1354 	const ipfw_insn_lookup *l = insntoc(cmd, lookup);
1355 	const char *key;
1356 	char *t;
1357 	uint32_t len = F_LEN(&cmd->o);
1358 
1359 	bprintf(bp, " ");
1360 	switch (cmd->o.opcode) {
1361 	case O_IP_SRC_ME:
1362 	case O_IP_DST_ME:
1363 		bprintf(bp, "me");
1364 		return;
1365 
1366 	case O_TABLE_LOOKUP: {
1367 		key = match_value(lookup_keys,
1368 		    IPFW_LOOKUP_TYPE(&cmd->o));
1369 		t = table_search_ctlv(fo->tstate,
1370 		    insntoc(&cmd->o, kidx)->kidx);
1371 		if (IPFW_LOOKUP_MASKING(&cmd->o) == 0 ||
1372 		    len != F_INSN_SIZE(ipfw_insn_lookup)) {
1373 			bprintf(bp, "lookup %s %s",
1374 			    (key != NULL ? key : "<invalid>"), t);
1375 			return;
1376 		}
1377 		switch (IPFW_LOOKUP_TYPE(&cmd->o)) {
1378 		case LOOKUP_DST_IP6:
1379 		case LOOKUP_SRC_IP6:
1380 			if (inet_ntop(AF_INET6, &l->ip6,
1381 			     maskbuf, sizeof(maskbuf)) == NULL)
1382 				strcpy(maskbuf, "<invalid>");
1383 			bprintf(bp, "lookup %s:%s %s", key, maskbuf, t);
1384 			break;
1385 		case LOOKUP_DST_IP:
1386 		case LOOKUP_SRC_IP:
1387 		case LOOKUP_DST_IP4:
1388 		case LOOKUP_SRC_IP4:
1389 			bprintf(bp, "lookup %s:%s %s", key,
1390 			    inet_ntoa(l->ip4), t);
1391 			break;
1392 		case LOOKUP_DST_MAC:
1393 		case LOOKUP_SRC_MAC:
1394 			bprintf(bp, "lookup %s:%s %s", key,
1395 			    ether_ntoa((const struct ether_addr *)&l->mac), t);
1396 			break;
1397 		default:
1398 			bprintf(bp, "lookup %s:%#x %s",
1399 			    (key != NULL ? key : "<invalid>"),
1400 			    l->u32, t);
1401 		}
1402 		return;
1403 	}
1404 	case O_IP_DST_LOOKUP:
1405 	case O_IP_SRC_LOOKUP:
1406 		t = table_search_ctlv(fo->tstate,
1407 		    insntoc(&cmd->o, kidx)->kidx);
1408 		/*
1409 		 * XXX: compatibility layer, to be removed.
1410 		 * Properly show rules loaded into new kernel modules by
1411 		 * an old ipfw binary.
1412 		 */
1413 		if (IPFW_LOOKUP_MASKING(&cmd->o) != 0 &&
1414 		    len == F_INSN_SIZE(ipfw_insn_table)) {
1415 			key = match_value(lookup_keys,
1416 			    IPFW_LOOKUP_TYPE(&cmd->o));
1417 			bprintf(bp, "lookup %s:%#x %s",
1418 			    (key != NULL ? key : "<invalid>"),
1419 			    insntoc(&cmd->o, table)->value, t);
1420 			return;
1421 		}
1422 		bprintf(bp, "table(%s", t);
1423 		if (IPFW_LOOKUP_MATCH_TVALUE(&cmd->o) != 0)
1424 			print_tvalue(bp, l);
1425 		bprintf(bp, ")");
1426 		return;
1427 	}
1428 
1429 	if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
1430 		const uint32_t *map = (const uint32_t *)&cmd->mask;
1431 		struct in_addr addr;
1432 		uint32_t x;
1433 		int i, j;
1434 		char comma = '{';
1435 
1436 		x = cmd->o.arg1 - 1;
1437 		x = htonl(~x);
1438 		addr.s_addr = htonl(cmd->addr.s_addr);
1439 		bprintf(bp, "%s/%d", inet_ntoa(addr),
1440 		    contigmask((uint8_t *)&x, 32));
1441 		x = cmd->addr.s_addr;
1442 		x &= 0xff; /* base */
1443 		/*
1444 		 * Print bits and ranges.
1445 		 * Locate first bit set (i), then locate first bit unset (j).
1446 		 * If we have 3+ consecutive bits set, then print them as a
1447 		 * range, otherwise only print the initial bit and rescan.
1448 		 */
1449 		for (i=0; i < cmd->o.arg1; i++)
1450 			if (map[i/32] & (1<<(i & 31))) {
1451 				for (j=i+1; j < cmd->o.arg1; j++)
1452 					if (!(map[ j/32] & (1<<(j & 31))))
1453 						break;
1454 				bprintf(bp, "%c%d", comma, i+x);
1455 				if (j>i+2) { /* range has at least 3 elements */
1456 					bprintf(bp, "-%d", j-1+x);
1457 					i = j-1;
1458 				}
1459 				comma = ',';
1460 			}
1461 		bprintf(bp, "}");
1462 		return;
1463 	}
1464 	/*
1465 	 * len == 2 indicates a single IP, whereas lists of 1 or more
1466 	 * addr/mask pairs have len = (2n+1). We convert len to n so we
1467 	 * use that to count the number of entries.
1468 	 */
1469     for (len = len / 2; len > 0; len--, a += 2) {
1470 	int mb =	/* mask length */
1471 	    (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1472 		32 : contigmask((const uint8_t *)&(a[1]), 32);
1473 	if (mb == 32 && g_co.do_resolv)
1474 		he = gethostbyaddr((const char *)&(a[0]), sizeof(in_addr_t),
1475 		    AF_INET);
1476 	if (he != NULL)		/* resolved to name */
1477 		bprintf(bp, "%s", he->h_name);
1478 	else if (mb == 0)	/* any */
1479 		bprintf(bp, "any");
1480 	else {		/* numeric IP followed by some kind of mask */
1481 		ia = (const struct in_addr *)&a[0];
1482 		bprintf(bp, "%s", inet_ntoa(*ia));
1483 		if (mb < 0) {
1484 			ia = (const struct in_addr *)&a[1];
1485 			bprintf(bp, ":%s", inet_ntoa(*ia));
1486 		} else if (mb < 32)
1487 			bprintf(bp, "/%d", mb);
1488 	}
1489 	if (len > 1)
1490 		bprintf(bp, ",");
1491     }
1492 }
1493 
1494 /*
1495  * prints a MAC address/mask pair
1496  */
1497 static void
format_mac(struct buf_pr * bp,const uint8_t * addr,const uint8_t * mask)1498 format_mac(struct buf_pr *bp, const uint8_t *addr, const uint8_t *mask)
1499 {
1500 	int l = contigmask(mask, 48);
1501 
1502 	if (l == 0)
1503 		bprintf(bp, " any");
1504 	else {
1505 		bprintf(bp, " %02x:%02x:%02x:%02x:%02x:%02x",
1506 		    addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1507 		if (l == -1)
1508 			bprintf(bp, "&%02x:%02x:%02x:%02x:%02x:%02x",
1509 			    mask[0], mask[1], mask[2],
1510 			    mask[3], mask[4], mask[5]);
1511 		else if (l < 48)
1512 			bprintf(bp, "/%d", l);
1513 	}
1514 }
1515 
1516 static void
print_mac(struct buf_pr * bp,const ipfw_insn_mac * mac)1517 print_mac(struct buf_pr *bp, const ipfw_insn_mac *mac)
1518 {
1519 
1520 	bprintf(bp, " MAC");
1521 	format_mac(bp, mac->addr, mac->mask);
1522 	format_mac(bp, mac->addr + 6, mac->mask + 6);
1523 }
1524 
1525 static void
print_mac_lookup(struct buf_pr * bp,const struct format_opts * fo,const ipfw_insn * cmd)1526 print_mac_lookup(struct buf_pr *bp, const struct format_opts *fo,
1527     const ipfw_insn *cmd)
1528 {
1529 	char *t;
1530 
1531 	bprintf(bp, " ");
1532 
1533 	t = table_search_ctlv(fo->tstate, insntoc(cmd, kidx)->kidx);
1534 	bprintf(bp, "table(%s", t);
1535 	if (IPFW_LOOKUP_MATCH_TVALUE(cmd) != 0)
1536 		print_tvalue(bp, insntoc(cmd, lookup));
1537 	bprintf(bp, ")");
1538 }
1539 
1540 static void
fill_icmptypes(ipfw_insn_u32 * cmd,char * av)1541 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1542 {
1543 	uint8_t type;
1544 
1545 	cmd->d[0] = 0;
1546 	while (*av) {
1547 		if (*av == ',')
1548 			av++;
1549 
1550 		type = strtoul(av, &av, 0);
1551 
1552 		if (*av != ',' && *av != '\0')
1553 			errx(EX_DATAERR, "invalid ICMP type");
1554 
1555 		if (type > 31)
1556 			errx(EX_DATAERR, "ICMP type out of range");
1557 
1558 		cmd->d[0] |= 1 << type;
1559 	}
1560 	cmd->o.opcode = O_ICMPTYPE;
1561 	cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1562 }
1563 
1564 static void
print_icmptypes(struct buf_pr * bp,const ipfw_insn_u32 * cmd)1565 print_icmptypes(struct buf_pr *bp, const ipfw_insn_u32 *cmd)
1566 {
1567 	int i;
1568 	char sep= ' ';
1569 
1570 	bprintf(bp, " icmptypes");
1571 	for (i = 0; i < 32; i++) {
1572 		if ( (cmd->d[0] & (1 << (i))) == 0)
1573 			continue;
1574 		bprintf(bp, "%c%d", sep, i);
1575 		sep = ',';
1576 	}
1577 }
1578 
1579 static void
print_dscp(struct buf_pr * bp,const ipfw_insn_u32 * cmd)1580 print_dscp(struct buf_pr *bp, const ipfw_insn_u32 *cmd)
1581 {
1582 	const uint32_t *v;
1583 	const char *code;
1584 	int i = 0;
1585 	char sep= ' ';
1586 
1587 	bprintf(bp, " dscp");
1588 	v = cmd->d;
1589 	while (i < 64) {
1590 		if (*v & (1 << i)) {
1591 			if ((code = match_value(f_ipdscp, i)) != NULL)
1592 				bprintf(bp, "%c%s", sep, code);
1593 			else
1594 				bprintf(bp, "%c%d", sep, i);
1595 			sep = ',';
1596 		}
1597 
1598 		if ((++i % 32) == 0)
1599 			v++;
1600 	}
1601 }
1602 
1603 struct show_state {
1604 	struct ip_fw_rule	*rule;
1605 	const ipfw_insn_kidx	*eaction;
1606 	uint8_t			*printed;
1607 	int			flags;
1608 #define	HAVE_PROTO		0x0001
1609 #define	HAVE_SRCIP		0x0002
1610 #define	HAVE_DSTIP		0x0004
1611 #define	HAVE_PROBE_STATE	0x0008
1612 	int			proto;
1613 	int			or_block;
1614 };
1615 
1616 static int
init_show_state(struct show_state * state,struct ip_fw_rule * rule)1617 init_show_state(struct show_state *state, struct ip_fw_rule *rule)
1618 {
1619 
1620 	state->printed = calloc(rule->cmd_len, sizeof(uint8_t));
1621 	if (state->printed == NULL)
1622 		return (ENOMEM);
1623 	state->rule = rule;
1624 	state->eaction = NULL;
1625 	state->flags = 0;
1626 	state->proto = 0;
1627 	state->or_block = 0;
1628 	return (0);
1629 }
1630 
1631 static void
free_show_state(struct show_state * state)1632 free_show_state(struct show_state *state)
1633 {
1634 
1635 	free(state->printed);
1636 }
1637 
1638 static uint8_t
is_printed_opcode(struct show_state * state,const ipfw_insn * cmd)1639 is_printed_opcode(struct show_state *state, const ipfw_insn *cmd)
1640 {
1641 
1642 	return (state->printed[cmd - state->rule->cmd]);
1643 }
1644 
1645 static void
mark_printed(struct show_state * state,const ipfw_insn * cmd)1646 mark_printed(struct show_state *state, const ipfw_insn *cmd)
1647 {
1648 
1649 	state->printed[cmd - state->rule->cmd] = 1;
1650 }
1651 
1652 static void
print_limit_mask(struct buf_pr * bp,const ipfw_insn_limit * limit)1653 print_limit_mask(struct buf_pr *bp, const ipfw_insn_limit *limit)
1654 {
1655 	struct _s_x *p = limit_masks;
1656 	char const *comma = " ";
1657 	uint8_t x;
1658 
1659 	for (x = limit->limit_mask; p->x != 0; p++) {
1660 		if ((x & p->x) == p->x) {
1661 			x &= ~p->x;
1662 			bprintf(bp, "%s%s", comma, p->s);
1663 			comma = ",";
1664 		}
1665 	}
1666 	bprint_uint_arg(bp, " ", limit->conn_limit);
1667 }
1668 
1669 static int
print_instruction(struct buf_pr * bp,const struct format_opts * fo,struct show_state * state,const ipfw_insn * cmd)1670 print_instruction(struct buf_pr *bp, const struct format_opts *fo,
1671     struct show_state *state, const ipfw_insn *cmd)
1672 {
1673 	struct protoent *pe;
1674 	struct passwd *pwd;
1675 	struct group *grp;
1676 	const char *s;
1677 	double d;
1678 
1679 	if (is_printed_opcode(state, cmd))
1680 		return (0);
1681 	if ((cmd->len & F_OR) != 0 && state->or_block == 0)
1682 		bprintf(bp, " {");
1683 	if (cmd->opcode != O_IN && (cmd->len & F_NOT) != 0)
1684 		bprintf(bp, " not");
1685 
1686 	switch (cmd->opcode) {
1687 	case O_PROB:
1688 		d = 1.0 * insntoc(cmd, u32)->d[0] / 0x7fffffff;
1689 		bprintf(bp, "prob %f ", d);
1690 		break;
1691 	case O_PROBE_STATE: /* no need to print anything here */
1692 		state->flags |= HAVE_PROBE_STATE;
1693 		break;
1694 	case O_IP_SRC:
1695 	case O_IP_SRC_LOOKUP:
1696 	case O_IP_SRC_MASK:
1697 	case O_IP_SRC_ME:
1698 	case O_IP_SRC_SET:
1699 		if (state->flags & HAVE_SRCIP)
1700 			bprintf(bp, " src-ip");
1701 		/* FALLTHROUGH */
1702 	case O_TABLE_LOOKUP:
1703 		print_ip(bp, fo, insntoc(cmd, ip));
1704 		break;
1705 	case O_IP_DST:
1706 	case O_IP_DST_MASK:
1707 	case O_IP_DST_ME:
1708 	case O_IP_DST_SET:
1709 	case O_IP_DST_LOOKUP:
1710 		/*
1711 		 * Special handling for O_IP_DST_LOOKUP when
1712 		 * lookup type is not LOOKUP_NONE.
1713 		 */
1714 		if ((state->flags & HAVE_DSTIP) != 0 && (
1715 		    cmd->opcode != O_IP_DST_LOOKUP ||
1716 		    IPFW_LOOKUP_TYPE(cmd) == LOOKUP_NONE))
1717 			bprintf(bp, " dst-ip");
1718 		print_ip(bp, fo, insntoc(cmd, ip));
1719 		break;
1720 	case O_IP6_SRC:
1721 	case O_IP6_SRC_MASK:
1722 	case O_IP6_SRC_ME:
1723 		if (state->flags & HAVE_SRCIP)
1724 			bprintf(bp, " src-ip6");
1725 		print_ip6(bp, insntoc(cmd, ip6));
1726 		break;
1727 	case O_IP6_DST:
1728 	case O_IP6_DST_MASK:
1729 	case O_IP6_DST_ME:
1730 		if (state->flags & HAVE_DSTIP)
1731 			bprintf(bp, " dst-ip6");
1732 		print_ip6(bp, insntoc(cmd, ip6));
1733 		break;
1734 	case O_MAC_SRC_LOOKUP:
1735 		bprintf(bp, " src-mac");
1736 		print_mac_lookup(bp, fo, cmd);
1737 		break;
1738 	case O_MAC_DST_LOOKUP:
1739 		bprintf(bp, " dst-mac");
1740 		print_mac_lookup(bp, fo, cmd);
1741 		break;
1742 	case O_FLOW6ID:
1743 		print_flow6id(bp, insntoc(cmd, u32));
1744 		break;
1745 	case O_IP_DSTPORT:
1746 	case O_IP_SRCPORT:
1747 		print_newports(bp, insntoc(cmd, u16), state->proto,
1748 		    (state->flags & (HAVE_SRCIP | HAVE_DSTIP)) ==
1749 		    (HAVE_SRCIP | HAVE_DSTIP) ?  cmd->opcode: 0);
1750 		break;
1751 	case O_PROTO:
1752 		pe = getprotobynumber(cmd->arg1);
1753 		if (state->flags & HAVE_PROTO)
1754 			bprintf(bp, " proto");
1755 		if (pe != NULL)
1756 			bprintf(bp, " %s", pe->p_name);
1757 		else
1758 			bprintf(bp, " %u", cmd->arg1);
1759 		state->proto = cmd->arg1;
1760 		break;
1761 	case O_MACADDR2:
1762 		print_mac(bp, insntoc(cmd, mac));
1763 		break;
1764 	case O_MAC_TYPE:
1765 		print_newports(bp, insntoc(cmd, u16),
1766 		    IPPROTO_ETHERTYPE, cmd->opcode);
1767 		break;
1768 	case O_FRAG:
1769 		print_flags(bp, "frag", cmd, f_ipoff);
1770 		break;
1771 	case O_FIB:
1772 		bprintf(bp, " fib %u", cmd->arg1);
1773 		break;
1774 	case O_SOCKARG:
1775 		bprintf(bp, " sockarg");
1776 		break;
1777 	case O_IN:
1778 		bprintf(bp, cmd->len & F_NOT ? " out" : " in");
1779 		break;
1780 	case O_DIVERTED:
1781 		switch (cmd->arg1) {
1782 		case 3:
1783 			bprintf(bp, " diverted");
1784 			break;
1785 		case 2:
1786 			bprintf(bp, " diverted-output");
1787 			break;
1788 		case 1:
1789 			bprintf(bp, " diverted-loopback");
1790 			break;
1791 		default:
1792 			bprintf(bp, " diverted-?<%u>", cmd->arg1);
1793 			break;
1794 		}
1795 		break;
1796 	case O_LAYER2:
1797 		bprintf(bp, " layer2");
1798 		break;
1799 	case O_XMIT:
1800 	case O_RECV:
1801 	case O_VIA:
1802 		if (cmd->opcode == O_XMIT)
1803 			s = "xmit";
1804 		else if (cmd->opcode == O_RECV)
1805 			s = "recv";
1806 		else /* if (cmd->opcode == O_VIA) */
1807 			s = "via";
1808 		switch (insntoc(cmd, if)->name[0]) {
1809 		case '\0':
1810 			bprintf(bp, " %s %s", s,
1811 			    inet_ntoa(insntoc(cmd, if)->p.ip));
1812 			break;
1813 		case '\1':
1814 			bprintf(bp, " %s table(%s)", s,
1815 			    table_search_ctlv(fo->tstate,
1816 			    insntoc(cmd, if)->p.kidx));
1817 			break;
1818 		default:
1819 			bprintf(bp, " %s %s", s,
1820 			    insntoc(cmd, if)->name);
1821 		}
1822 		break;
1823 	case O_IP_FLOW_LOOKUP:
1824 		s = table_search_ctlv(fo->tstate,
1825 		    insntoc(cmd, kidx)->kidx);
1826 		bprintf(bp, " flow table(%s", s);
1827 		if (IPFW_LOOKUP_MATCH_TVALUE(cmd) != 0)
1828 			print_tvalue(bp, insntoc(cmd, lookup));
1829 		bprintf(bp, ")");
1830 		break;
1831 	case O_IPID:
1832 	case O_IPTTL:
1833 	case O_IPLEN:
1834 	case O_TCPDATALEN:
1835 	case O_TCPMSS:
1836 	case O_TCPWIN:
1837 		if (F_LEN(cmd) == 1) {
1838 			switch (cmd->opcode) {
1839 			case O_IPID:
1840 				s = "ipid";
1841 				break;
1842 			case O_IPTTL:
1843 				s = "ipttl";
1844 				break;
1845 			case O_IPLEN:
1846 				s = "iplen";
1847 				break;
1848 			case O_TCPDATALEN:
1849 				s = "tcpdatalen";
1850 				break;
1851 			case O_TCPMSS:
1852 				s = "tcpmss";
1853 				break;
1854 			case O_TCPWIN:
1855 				s = "tcpwin";
1856 				break;
1857 			default:
1858 				s = "<unknown>";
1859 				break;
1860 			}
1861 			bprintf(bp, " %s %u", s, cmd->arg1);
1862 		} else
1863 			print_newports(bp, insntoc(cmd, u16), 0,
1864 			    cmd->opcode);
1865 		break;
1866 	case O_IPVER:
1867 		bprintf(bp, " ipver %u", cmd->arg1);
1868 		break;
1869 	case O_IPPRECEDENCE:
1870 		bprintf(bp, " ipprecedence %u", cmd->arg1 >> 5);
1871 		break;
1872 	case O_DSCP:
1873 		print_dscp(bp, insntoc(cmd, u32));
1874 		break;
1875 	case O_IPOPT:
1876 		print_flags(bp, "ipoptions", cmd, f_ipopts);
1877 		break;
1878 	case O_IPTOS:
1879 		print_flags(bp, "iptos", cmd, f_iptos);
1880 		break;
1881 	case O_ICMPTYPE:
1882 		print_icmptypes(bp, insntoc(cmd, u32));
1883 		break;
1884 	case O_ESTAB:
1885 		bprintf(bp, " established");
1886 		break;
1887 	case O_TCPFLAGS:
1888 		print_flags(bp, "tcpflags", cmd, f_tcpflags);
1889 		break;
1890 	case O_TCPOPTS:
1891 		print_flags(bp, "tcpoptions", cmd, f_tcpopts);
1892 		break;
1893 	case O_TCPACK:
1894 		bprintf(bp, " tcpack %d",
1895 		    ntohl(insntoc(cmd, u32)->d[0]));
1896 		break;
1897 	case O_TCPSEQ:
1898 		bprintf(bp, " tcpseq %d",
1899 		    ntohl(insntoc(cmd, u32)->d[0]));
1900 		break;
1901 	case O_UID:
1902 		pwd = getpwuid(insntoc(cmd, u32)->d[0]);
1903 		if (pwd != NULL)
1904 			bprintf(bp, " uid %s", pwd->pw_name);
1905 		else
1906 			bprintf(bp, " uid %u",
1907 			    insntoc(cmd, u32)->d[0]);
1908 		break;
1909 	case O_GID:
1910 		grp = getgrgid(insntoc(cmd, u32)->d[0]);
1911 		if (grp != NULL)
1912 			bprintf(bp, " gid %s", grp->gr_name);
1913 		else
1914 			bprintf(bp, " gid %u",
1915 			    insntoc(cmd, u32)->d[0]);
1916 		break;
1917 	case O_JAIL:
1918 		bprintf(bp, " jail %d", insntoc(cmd, u32)->d[0]);
1919 		break;
1920 	case O_VERREVPATH:
1921 		bprintf(bp, " verrevpath");
1922 		break;
1923 	case O_VERSRCREACH:
1924 		bprintf(bp, " versrcreach");
1925 		break;
1926 	case O_ANTISPOOF:
1927 		bprintf(bp, " antispoof");
1928 		break;
1929 	case O_IPSEC:
1930 		bprintf(bp, " ipsec");
1931 		break;
1932 	case O_NOP:
1933 		bprintf(bp, " // %s", (const char *)(cmd + 1));
1934 		break;
1935 	case O_KEEP_STATE:
1936 		if (state->flags & HAVE_PROBE_STATE)
1937 			bprintf(bp, " keep-state");
1938 		else
1939 			bprintf(bp, " record-state");
1940 		bprintf(bp, " :%s",
1941 		    object_search_ctlv(fo->tstate,
1942 		    insntoc(cmd, kidx)->kidx,
1943 		    IPFW_TLV_STATE_NAME));
1944 		break;
1945 	case O_LIMIT:
1946 		if (state->flags & HAVE_PROBE_STATE)
1947 			bprintf(bp, " limit");
1948 		else
1949 			bprintf(bp, " set-limit");
1950 		print_limit_mask(bp, insntoc(cmd, limit));
1951 		bprintf(bp, " :%s",
1952 		    object_search_ctlv(fo->tstate,
1953 		    insntoc(cmd, kidx)->kidx,
1954 		    IPFW_TLV_STATE_NAME));
1955 		break;
1956 	case O_IP6:
1957 		if (state->flags & HAVE_PROTO)
1958 			bprintf(bp, " proto");
1959 		bprintf(bp, " ip6");
1960 		break;
1961 	case O_IP4:
1962 		if (state->flags & HAVE_PROTO)
1963 			bprintf(bp, " proto");
1964 		bprintf(bp, " ip4");
1965 		break;
1966 	case O_ICMP6TYPE:
1967 		print_icmp6types(bp, insntoc(cmd, u32));
1968 		break;
1969 	case O_EXT_HDR:
1970 		print_ext6hdr(bp, cmd);
1971 		break;
1972 	case O_TAGGED:
1973 		if (F_LEN(cmd) == 1)
1974 			bprint_uint_arg(bp, " tagged ", cmd->arg1);
1975 		else
1976 			print_newports(bp, insntoc(cmd, u16),
1977 				    0, O_TAGGED);
1978 		break;
1979 	case O_SKIP_ACTION:
1980 		bprintf(bp, " defer-immediate-action");
1981 		break;
1982 	case O_MARK:
1983 		bprintf(bp, " mark");
1984 		if (cmd->arg1 == IP_FW_TARG)
1985 			bprintf(bp, " tablearg");
1986 		else
1987 			bprintf(bp, " %#x", insntoc(cmd, u32)->d[0]);
1988 
1989 		if (insntoc(cmd, u32)->d[1] != 0xFFFFFFFF)
1990 			bprintf(bp, ":%#x", insntoc(cmd, u32)->d[1]);
1991 		break;
1992 
1993 	default:
1994 		bprintf(bp, " [opcode %d len %d]", cmd->opcode,
1995 		    cmd->len);
1996 	}
1997 	if (cmd->len & F_OR) {
1998 		bprintf(bp, " or");
1999 		state->or_block = 1;
2000 	} else if (state->or_block != 0) {
2001 		bprintf(bp, " }");
2002 		state->or_block = 0;
2003 	}
2004 	mark_printed(state, cmd);
2005 
2006 	return (1);
2007 }
2008 
2009 static ipfw_insn *
print_opcode(struct buf_pr * bp,struct format_opts * fo,struct show_state * state,int opcode)2010 print_opcode(struct buf_pr *bp, struct format_opts *fo,
2011     struct show_state *state, int opcode)
2012 {
2013 	ipfw_insn *cmd;
2014 	int l;
2015 
2016 	for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2017 	    l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2018 		/* We use zero opcode to print the rest of options */
2019 		if (opcode >= 0 && cmd->opcode != opcode)
2020 			continue;
2021 		/*
2022 		 * Skip O_NOP, when we printing the rest
2023 		 * of options, it will be handled separately.
2024 		 */
2025 		if (cmd->opcode == O_NOP && opcode != O_NOP)
2026 			continue;
2027 		if (!print_instruction(bp, fo, state, cmd))
2028 			continue;
2029 		return (cmd);
2030 	}
2031 	return (NULL);
2032 }
2033 
2034 static void
print_fwd(struct buf_pr * bp,const ipfw_insn * cmd)2035 print_fwd(struct buf_pr *bp, const ipfw_insn *cmd)
2036 {
2037 	char buf[INET6_ADDRSTRLEN + IF_NAMESIZE + 2];
2038 	const ipfw_insn_sa6 *sa6;
2039 	const ipfw_insn_sa *sa;
2040 	uint16_t port;
2041 
2042 	if (cmd->opcode == O_FORWARD_IP) {
2043 		sa = insntoc(cmd, sa);
2044 		port = sa->sa.sin_port;
2045 		if (sa->sa.sin_addr.s_addr == INADDR_ANY)
2046 			bprintf(bp, "fwd tablearg");
2047 		else
2048 			bprintf(bp, "fwd %s", inet_ntoa(sa->sa.sin_addr));
2049 	} else {
2050 		sa6 = insntoc(cmd, sa6);
2051 		port = sa6->sa.sin6_port;
2052 		bprintf(bp, "fwd ");
2053 		if (getnameinfo((const struct sockaddr *)&sa6->sa,
2054 		    sizeof(struct sockaddr_in6), buf, sizeof(buf), NULL, 0,
2055 		    NI_NUMERICHOST) == 0)
2056 			bprintf(bp, "%s", buf);
2057 	}
2058 	if (port != 0)
2059 		bprintf(bp, ",%u", port);
2060 }
2061 
2062 static void
print_logdst(struct buf_pr * bp,uint16_t arg1)2063 print_logdst(struct buf_pr *bp, uint16_t arg1)
2064 {
2065 	char const *comma = "";
2066 
2067 	bprintf(bp, " logdst ");
2068 	if (arg1 & IPFW_LOG_SYSLOG) {
2069 		bprintf(bp, "%ssyslog", comma);
2070 		comma = ",";
2071 	}
2072 	if (arg1 & IPFW_LOG_IPFW0) {
2073 		bprintf(bp, "%sbpf", comma);
2074 		comma = ",";
2075 	}
2076 	if (arg1 & IPFW_LOG_RTSOCK) {
2077 		bprintf(bp, "%srtsock", comma);
2078 		comma = ",";
2079 	}
2080 }
2081 
2082 static int
print_action_instruction(struct buf_pr * bp,const struct format_opts * fo,struct show_state * state,const ipfw_insn * cmd)2083 print_action_instruction(struct buf_pr *bp, const struct format_opts *fo,
2084     struct show_state *state, const ipfw_insn *cmd)
2085 {
2086 	const char *s;
2087 
2088 	if (is_printed_opcode(state, cmd))
2089 		return (0);
2090 	switch (cmd->opcode) {
2091 	case O_CHECK_STATE:
2092 		bprintf(bp, "check-state");
2093 		if (insntoc(cmd, kidx)->kidx != 0)
2094 			s = object_search_ctlv(fo->tstate,
2095 			    insntoc(cmd, kidx)->kidx,
2096 			    IPFW_TLV_STATE_NAME);
2097 		else
2098 			s = NULL;
2099 		bprintf(bp, " :%s", s ? s: "any");
2100 		break;
2101 	case O_ACCEPT:
2102 		bprintf(bp, "allow");
2103 		break;
2104 	case O_COUNT:
2105 		bprintf(bp, "count");
2106 		break;
2107 	case O_DENY:
2108 		bprintf(bp, "deny");
2109 		break;
2110 	case O_REJECT:
2111 		if (cmd->arg1 == ICMP_REJECT_RST)
2112 			bprintf(bp, "reset");
2113 		else if (cmd->arg1 == ICMP_REJECT_ABORT)
2114 			bprintf(bp, "abort");
2115 		else if (cmd->arg1 == ICMP_UNREACH_HOST)
2116 			bprintf(bp, "reject");
2117 		else if (cmd->arg1 == ICMP_UNREACH_NEEDFRAG &&
2118 		    cmd->len == F_INSN_SIZE(ipfw_insn_u16))
2119 			bprintf(bp, "needfrag %u",
2120 			    insntoc(cmd, u16)->ports[0]);
2121 		else
2122 			print_reject_code(bp, cmd->arg1);
2123 		break;
2124 	case O_UNREACH6:
2125 		if (cmd->arg1 == ICMP6_UNREACH_RST)
2126 			bprintf(bp, "reset6");
2127 		else if (cmd->arg1 == ICMP6_UNREACH_ABORT)
2128 			bprintf(bp, "abort6");
2129 		else
2130 			print_unreach6_code(bp, cmd->arg1);
2131 		break;
2132 	case O_SKIPTO:
2133 		bprint_uint_arg(bp, "skipto ", insntoc(cmd, u32)->d[0]);
2134 		break;
2135 	case O_PIPE:
2136 		bprint_uint_arg(bp, "pipe ", cmd->arg1);
2137 		break;
2138 	case O_QUEUE:
2139 		bprint_uint_arg(bp, "queue ", cmd->arg1);
2140 		break;
2141 	case O_DIVERT:
2142 		bprint_uint_arg(bp, "divert ", cmd->arg1);
2143 		break;
2144 	case O_TEE:
2145 		bprint_uint_arg(bp, "tee ", cmd->arg1);
2146 		break;
2147 	case O_NETGRAPH:
2148 		bprint_uint_arg(bp, "netgraph ", cmd->arg1);
2149 		break;
2150 	case O_NGTEE:
2151 		bprint_uint_arg(bp, "ngtee ", cmd->arg1);
2152 		break;
2153 	case O_FORWARD_IP:
2154 	case O_FORWARD_IP6:
2155 		print_fwd(bp, cmd);
2156 		break;
2157 	case O_LOG:
2158 		bprintf(bp, " log");
2159 		if (insntoc(cmd, log)->max_log > 0)
2160 			bprintf(bp, " logamount %d",
2161 			    insntoc(cmd, log)->max_log);
2162 		if (cmd->arg1 != IPFW_LOG_DEFAULT)
2163 			print_logdst(bp, cmd->arg1);
2164 		break;
2165 	case O_ALTQ:
2166 #ifndef NO_ALTQ
2167 		print_altq_cmd(bp, insntoc(cmd, altq));
2168 #endif
2169 		break;
2170 	case O_TAG:
2171 		bprint_uint_arg(bp, cmd->len & F_NOT ? " untag ":
2172 		    " tag ", cmd->arg1);
2173 		break;
2174 	case O_NAT:
2175 		if (cmd->arg1 != IP_FW_NAT44_GLOBAL)
2176 			bprint_uint_arg(bp, "nat ", cmd->arg1);
2177 		else
2178 			bprintf(bp, "nat global");
2179 		break;
2180 	case O_SETFIB:
2181 		if (cmd->arg1 == IP_FW_TARG)
2182 			bprint_uint_arg(bp, "setfib ", cmd->arg1);
2183 		else
2184 			bprintf(bp, "setfib %u", cmd->arg1 & 0x7FFF);
2185 		break;
2186 	case O_EXTERNAL_ACTION:
2187 		/*
2188 		 * The external action can consists of two following
2189 		 * each other opcodes - O_EXTERNAL_ACTION and
2190 		 * O_EXTERNAL_INSTANCE. The first contains the ID of
2191 		 * name of external action. The second contains the ID
2192 		 * of name of external action instance.
2193 		 * NOTE: in case when external action has no named
2194 		 * instances support, the second opcode isn't needed.
2195 		 */
2196 		state->eaction = insntoc(cmd, kidx);
2197 		s = object_search_ctlv(fo->tstate,
2198 		    state->eaction->kidx,
2199 		    IPFW_TLV_EACTION);
2200 		if (match_token(rule_eactions, s) != -1)
2201 			bprintf(bp, "%s", s);
2202 		else
2203 			bprintf(bp, "eaction %s", s);
2204 		break;
2205 	case O_EXTERNAL_INSTANCE:
2206 		if (state->eaction == NULL)
2207 			break;
2208 		/*
2209 		 * XXX: we need to teach ipfw(9) to rewrite opcodes
2210 		 * in the user buffer on rule addition. When we add
2211 		 * the rule, we specify zero TLV type for
2212 		 * O_EXTERNAL_INSTANCE object. To show correct
2213 		 * rule after `ipfw add` we need to search instance
2214 		 * name with zero type. But when we do `ipfw show`
2215 		 * we calculate TLV type using IPFW_TLV_EACTION_NAME()
2216 		 * macro.
2217 		 */
2218 		s = object_search_ctlv(fo->tstate,
2219 		    insntoc(cmd, kidx)->kidx, 0);
2220 		if (s == NULL)
2221 			s = object_search_ctlv(fo->tstate,
2222 			    insntoc(cmd, kidx)->kidx, IPFW_TLV_EACTION_NAME(
2223 			    state->eaction->kidx));
2224 		bprintf(bp, " %s", s);
2225 		break;
2226 	case O_EXTERNAL_DATA:
2227 		if (state->eaction == NULL)
2228 			break;
2229 		/*
2230 		 * Currently we support data formatting only for
2231 		 * external data with datalen u16. For unknown data
2232 		 * print its size in bytes.
2233 		 */
2234 		if (cmd->len == F_INSN_SIZE(ipfw_insn))
2235 			bprintf(bp, " %u", cmd->arg1);
2236 		else
2237 			bprintf(bp, " %ubytes",
2238 			    (unsigned)(cmd->len * sizeof(uint32_t)));
2239 		break;
2240 	case O_SETDSCP:
2241 		if (cmd->arg1 == IP_FW_TARG) {
2242 			bprintf(bp, "setdscp tablearg");
2243 			break;
2244 		}
2245 		s = match_value(f_ipdscp, cmd->arg1 & 0x3F);
2246 		if (s != NULL)
2247 			bprintf(bp, "setdscp %s", s);
2248 		else
2249 			bprintf(bp, "setdscp %u", cmd->arg1 & 0x3F);
2250 		break;
2251 	case O_REASS:
2252 		bprintf(bp, "reass");
2253 		break;
2254 	case O_CALLRETURN:
2255 		if (cmd->len & F_NOT) {
2256 			s = match_value(return_types, cmd->arg1);
2257 			bprintf(bp, "return %s", s ? s: "<invalid>");
2258 		} else
2259 			bprint_uint_arg(bp, "call ", insntoc(cmd, u32)->d[0]);
2260 		break;
2261 	case O_SETMARK:
2262 		if (cmd->arg1 == IP_FW_TARG) {
2263 			bprintf(bp, "setmark tablearg");
2264 			break;
2265 		}
2266 		bprintf(bp, "setmark %#x", insntoc(cmd, u32)->d[0]);
2267 		break;
2268 	default:
2269 		bprintf(bp, "** unrecognized action %d len %d ",
2270 			cmd->opcode, cmd->len);
2271 	}
2272 	mark_printed(state, cmd);
2273 
2274 	return (1);
2275 }
2276 
2277 
2278 static ipfw_insn *
print_action(struct buf_pr * bp,struct format_opts * fo,struct show_state * state,uint8_t opcode)2279 print_action(struct buf_pr *bp, struct format_opts *fo,
2280     struct show_state *state, uint8_t opcode)
2281 {
2282 	ipfw_insn *cmd;
2283 	int l;
2284 
2285 	for (l = state->rule->cmd_len - state->rule->act_ofs,
2286 	    cmd = ACTION_PTR(state->rule); l > 0;
2287 	    l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2288 		if (cmd->opcode != opcode)
2289 			continue;
2290 		if (!print_action_instruction(bp, fo, state, cmd))
2291 			continue;
2292 		return (cmd);
2293 	}
2294 	return (NULL);
2295 }
2296 
2297 static void
print_proto(struct buf_pr * bp,struct format_opts * fo,struct show_state * state)2298 print_proto(struct buf_pr *bp, struct format_opts *fo,
2299     struct show_state *state)
2300 {
2301 	ipfw_insn *cmd;
2302 	int l, proto, ip4, ip6;
2303 
2304 	/* Count all O_PROTO, O_IP4, O_IP6 instructions. */
2305 	proto = ip4 = ip6 = 0;
2306 	for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2307 	    l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2308 		switch (cmd->opcode) {
2309 		case O_PROTO:
2310 			proto++;
2311 			break;
2312 		case O_IP4:
2313 			ip4 = 1;
2314 			if (cmd->len & F_OR)
2315 				ip4++;
2316 			break;
2317 		case O_IP6:
2318 			ip6 = 1;
2319 			if (cmd->len & F_OR)
2320 				ip6++;
2321 			break;
2322 		default:
2323 			continue;
2324 		}
2325 	}
2326 	if (proto == 0 && ip4 == 0 && ip6 == 0) {
2327 		state->proto = IPPROTO_IP;
2328 		state->flags |= HAVE_PROTO;
2329 		bprintf(bp, " ip");
2330 		return;
2331 	}
2332 	/* To handle the case { ip4 or ip6 }, print opcode with F_OR first */
2333 	cmd = NULL;
2334 	if (ip4 || ip6)
2335 		cmd = print_opcode(bp, fo, state, ip4 > ip6 ? O_IP4: O_IP6);
2336 	if (cmd != NULL && (cmd->len & F_OR))
2337 		cmd = print_opcode(bp, fo, state, ip4 > ip6 ? O_IP6: O_IP4);
2338 	if (cmd == NULL || (cmd->len & F_OR))
2339 		for (l = proto; l > 0; l--) {
2340 			cmd = print_opcode(bp, fo, state, O_PROTO);
2341 			if (cmd == NULL || (cmd->len & F_OR) == 0)
2342 				break;
2343 		}
2344 	/* Initialize proto, it is used by print_newports() */
2345 	state->flags |= HAVE_PROTO;
2346 	if (state->proto == 0 && ip6 != 0)
2347 		state->proto = IPPROTO_IPV6;
2348 }
2349 
2350 static int
match_opcode(int opcode,const int opcodes[],size_t nops)2351 match_opcode(int opcode, const int opcodes[], size_t nops)
2352 {
2353 	size_t i;
2354 
2355 	for (i = 0; i < nops; i++)
2356 		if (opcode == opcodes[i])
2357 			return (1);
2358 	return (0);
2359 }
2360 
2361 static void
print_address(struct buf_pr * bp,struct format_opts * fo,struct show_state * state,const int opcodes[],size_t nops,int portop,int flag)2362 print_address(struct buf_pr *bp, struct format_opts *fo,
2363     struct show_state *state, const int opcodes[], size_t nops, int portop,
2364     int flag)
2365 {
2366 	ipfw_insn *cmd;
2367 	int count, l, portcnt, pf;
2368 
2369 	count = portcnt = 0;
2370 	for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2371 	    l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2372 		if (match_opcode(cmd->opcode, opcodes, nops)) {
2373 			/*
2374 			 * Special handling for O_IP_DST_LOOKUP when
2375 			 * lookup type is not LOOKUP_NONE.
2376 			 */
2377 			if (cmd->opcode == O_IP_DST_LOOKUP &&
2378 			    IPFW_LOOKUP_TYPE(cmd) != LOOKUP_NONE)
2379 				continue;
2380 			count++;
2381 		} else if (cmd->opcode == portop)
2382 			portcnt++;
2383 	}
2384 	if (count == 0)
2385 		bprintf(bp, " any");
2386 	for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2387 	    l > 0 && count > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2388 		if (!match_opcode(cmd->opcode, opcodes, nops))
2389 			continue;
2390 		print_instruction(bp, fo, state, cmd);
2391 		if ((cmd->len & F_OR) == 0)
2392 			break;
2393 		count--;
2394 	}
2395 	/*
2396 	 * If several O_IP_?PORT opcodes specified, leave them to the
2397 	 * options section.
2398 	 */
2399 	if (portcnt == 1) {
2400 		for (l = state->rule->act_ofs, cmd = state->rule->cmd, pf = 0;
2401 		    l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2402 			if (cmd->opcode != portop) {
2403 				pf = (cmd->len & F_OR);
2404 				continue;
2405 			}
2406 			/* Print opcode iff it is not in OR block. */
2407 			if (pf == 0 && (cmd->len & F_OR) == 0)
2408 				print_instruction(bp, fo, state, cmd);
2409 			break;
2410 		}
2411 	}
2412 	state->flags |= flag;
2413 }
2414 
2415 static const int action_opcodes[] = {
2416 	O_CHECK_STATE, O_ACCEPT, O_COUNT, O_DENY, O_REJECT,
2417 	O_UNREACH6, O_SKIPTO, O_PIPE, O_QUEUE, O_DIVERT, O_TEE,
2418 	O_NETGRAPH, O_NGTEE, O_FORWARD_IP, O_FORWARD_IP6, O_NAT,
2419 	O_SETFIB, O_SETDSCP, O_REASS, O_CALLRETURN, O_SETMARK,
2420 	/* keep the following opcodes at the end of the list */
2421 	O_EXTERNAL_ACTION, O_EXTERNAL_INSTANCE, O_EXTERNAL_DATA
2422 };
2423 
2424 static const int modifier_opcodes[] = {
2425 	O_LOG, O_ALTQ, O_TAG
2426 };
2427 
2428 static const int src_opcodes[] = {
2429 	O_IP_SRC, O_IP_SRC_LOOKUP, O_IP_SRC_MASK, O_IP_SRC_ME,
2430 	O_IP_SRC_SET, O_IP6_SRC, O_IP6_SRC_MASK, O_IP6_SRC_ME
2431 };
2432 
2433 static const int dst_opcodes[] = {
2434 	O_IP_DST, O_IP_DST_LOOKUP, O_IP_DST_MASK, O_IP_DST_ME,
2435 	O_IP_DST_SET, O_IP6_DST, O_IP6_DST_MASK, O_IP6_DST_ME
2436 };
2437 
2438 #if IPFW_DEFAULT_RULE > 65535
2439 #define	RULENUM_FORMAT	"%06d"
2440 #else
2441 #define	RULENUM_FORMAT	"%05d"
2442 #endif
2443 
2444 static void
show_static_rule(struct cmdline_opts * co,struct format_opts * fo,struct buf_pr * bp,struct ip_fw_rule * rule,struct ip_fw_bcounter * cntr)2445 show_static_rule(struct cmdline_opts *co, struct format_opts *fo,
2446     struct buf_pr *bp, struct ip_fw_rule *rule, struct ip_fw_bcounter *cntr)
2447 {
2448 	static int twidth = 0;
2449 	struct show_state state;
2450 	ipfw_insn *cmd;
2451 	size_t i;
2452 
2453 	/* Print # DISABLED or skip the rule */
2454 	if ((fo->set_mask & (1 << rule->set)) == 0) {
2455 		/* disabled mask */
2456 		if (!co->show_sets)
2457 			return;
2458 		else
2459 			bprintf(bp, "# DISABLED ");
2460 	}
2461 	if (init_show_state(&state, rule) != 0) {
2462 		warn("init_show_state() failed");
2463 		return;
2464 	}
2465 
2466 	bprintf(bp, RULENUM_FORMAT " ", rule->rulenum);
2467 
2468 	/* only if counters are available */
2469 	if (cntr != NULL) {
2470 		/* Print counters if enabled */
2471 		if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2472 			pr_u64(bp, &cntr->pcnt, fo->pcwidth);
2473 			pr_u64(bp, &cntr->bcnt, fo->bcwidth);
2474 		}
2475 
2476 		/* Print timestamp */
2477 		if (co->do_time == TIMESTAMP_NUMERIC)
2478 			bprintf(bp, "%10u ", cntr->timestamp);
2479 		else if (co->do_time == TIMESTAMP_STRING) {
2480 			char timestr[30];
2481 			time_t t = (time_t)0;
2482 
2483 			if (twidth == 0) {
2484 				strcpy(timestr, ctime(&t));
2485 				*strchr(timestr, '\n') = '\0';
2486 				twidth = strlen(timestr);
2487 			}
2488 			if (cntr->timestamp > 0) {
2489 				t = _long_to_time(cntr->timestamp);
2490 
2491 				strcpy(timestr, ctime(&t));
2492 				*strchr(timestr, '\n') = '\0';
2493 				bprintf(bp, "%s ", timestr);
2494 			} else {
2495 				bprintf(bp, "%*s ", twidth, "");
2496 			}
2497 		}
2498 	}
2499 
2500 	/* Print set number */
2501 	if (co->show_sets)
2502 		bprintf(bp, "set %d ", rule->set);
2503 
2504 	/* Print the optional "match probability" */
2505 	cmd = print_opcode(bp, fo, &state, O_PROB);
2506 	/* Print rule action */
2507 	for (i = 0; i < nitems(action_opcodes); i++) {
2508 		cmd = print_action(bp, fo, &state, action_opcodes[i]);
2509 		if (cmd == NULL)
2510 			continue;
2511 		/* Handle special cases */
2512 		switch (cmd->opcode) {
2513 		case O_CHECK_STATE:
2514 			goto end;
2515 		case O_EXTERNAL_ACTION:
2516 		case O_EXTERNAL_INSTANCE:
2517 			/* External action can have several instructions */
2518 			continue;
2519 		}
2520 		break;
2521 	}
2522 	/* Print rule modifiers */
2523 	for (i = 0; i < nitems(modifier_opcodes); i++)
2524 		print_action(bp, fo, &state, modifier_opcodes[i]);
2525 	/*
2526 	 * Print rule body
2527 	 */
2528 	if (co->comment_only != 0)
2529 		goto end;
2530 
2531 	if (rule->flags & IPFW_RULE_JUSTOPTS) {
2532 		state.flags |= HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP;
2533 		/*
2534 		 * Print `proto ip` if all opcodes has been already printed.
2535 		 */
2536 		if (memchr(state.printed, 0, rule->act_ofs) == NULL) {
2537 			bprintf(bp, " proto ip");
2538 			goto end;
2539 		}
2540 		goto justopts;
2541 	}
2542 
2543 	print_proto(bp, fo, &state);
2544 	if (co->do_compact != 0 && (rule->flags & IPFW_RULE_NOOPT))
2545 		goto justopts;
2546 
2547 	/* Print source */
2548 	bprintf(bp, " from");
2549 	print_address(bp, fo, &state, src_opcodes, nitems(src_opcodes),
2550 	    O_IP_SRCPORT, HAVE_SRCIP);
2551 
2552 	/* Print destination */
2553 	bprintf(bp, " to");
2554 	print_address(bp, fo, &state, dst_opcodes, nitems(dst_opcodes),
2555 	    O_IP_DSTPORT, HAVE_DSTIP);
2556 
2557 justopts:
2558 	/* Print the rest of options */
2559 	while (print_opcode(bp, fo, &state, -1))
2560 		;
2561 end:
2562 	/* Print comment at the end */
2563 	cmd = print_opcode(bp, fo, &state, O_NOP);
2564 	if (co->comment_only != 0 && cmd == NULL)
2565 		bprintf(bp, " // ...");
2566 	bprintf(bp, "\n");
2567 	free_show_state(&state);
2568 }
2569 
2570 static void
show_dyn_state(struct cmdline_opts * co,struct format_opts * fo,struct buf_pr * bp,ipfw_dyn_rule * d)2571 show_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2572     struct buf_pr *bp, ipfw_dyn_rule *d)
2573 {
2574 	struct protoent *pe;
2575 	struct in_addr a;
2576 	char buf[INET6_ADDRSTRLEN];
2577 
2578 	if (!d->expire && !(d->type == O_LIMIT_PARENT))
2579 		return;
2580 
2581 	bprintf(bp, RULENUM_FORMAT, d->rulenum);
2582 	if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2583 		bprintf(bp, " ");
2584 		pr_u64(bp, &d->pcnt, fo->pcwidth);
2585 		pr_u64(bp, &d->bcnt, fo->bcwidth);
2586 		bprintf(bp, "(%ds)", d->expire);
2587 	}
2588 	switch (d->type) {
2589 	case O_LIMIT_PARENT:
2590 		bprintf(bp, " PARENT %u", d->count);
2591 		break;
2592 	case O_LIMIT:
2593 		bprintf(bp, " LIMIT");
2594 		break;
2595 	case O_KEEP_STATE: /* bidir, no mask */
2596 		bprintf(bp, " STATE");
2597 		break;
2598 	}
2599 
2600 	if ((pe = getprotobynumber(d->id.proto)) != NULL)
2601 		bprintf(bp, " %s", pe->p_name);
2602 	else
2603 		bprintf(bp, " proto %u", d->id.proto);
2604 
2605 	if (d->id.addr_type == 4) {
2606 		a.s_addr = htonl(d->id.src_ip);
2607 		bprintf(bp, " %s %d", inet_ntoa(a), d->id.src_port);
2608 
2609 		a.s_addr = htonl(d->id.dst_ip);
2610 		bprintf(bp, " <-> %s %d", inet_ntoa(a), d->id.dst_port);
2611 	} else if (d->id.addr_type == 6) {
2612 		bprintf(bp, " %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
2613 		    sizeof(buf)), d->id.src_port);
2614 		bprintf(bp, " <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6,
2615 		    buf, sizeof(buf)), d->id.dst_port);
2616 	} else
2617 		bprintf(bp, " UNKNOWN <-> UNKNOWN");
2618 	if (d->kidx != 0)
2619 		bprintf(bp, " :%s", object_search_ctlv(fo->tstate,
2620 		    d->kidx, IPFW_TLV_STATE_NAME));
2621 
2622 #define	BOTH_SYN	(TH_SYN | (TH_SYN << 8))
2623 #define	BOTH_FIN	(TH_FIN | (TH_FIN << 8))
2624 	if (co->verbose) {
2625 		bprintf(bp, " state 0x%08x%s", d->state,
2626 		    d->state ? " ": ",");
2627 		if (d->state & IPFW_DYN_ORPHANED)
2628 			bprintf(bp, "ORPHANED,");
2629 		if ((d->state & BOTH_SYN) == BOTH_SYN)
2630 			bprintf(bp, "BOTH_SYN,");
2631 		else {
2632 			if (d->state & TH_SYN)
2633 				bprintf(bp, "F_SYN,");
2634 			if (d->state & (TH_SYN << 8))
2635 				bprintf(bp, "R_SYN,");
2636 		}
2637 		if ((d->state & BOTH_FIN) == BOTH_FIN)
2638 			bprintf(bp, "BOTH_FIN,");
2639 		else {
2640 			if (d->state & TH_FIN)
2641 				bprintf(bp, "F_FIN,");
2642 			if (d->state & (TH_FIN << 8))
2643 				bprintf(bp, "R_FIN,");
2644 		}
2645 		bprintf(bp, " f_ack 0x%x, r_ack 0x%x", d->ack_fwd,
2646 		    d->ack_rev);
2647 	}
2648 }
2649 
2650 static int
do_range_cmd(int cmd,ipfw_range_tlv * rt)2651 do_range_cmd(int cmd, ipfw_range_tlv *rt)
2652 {
2653 	ipfw_range_header rh;
2654 	size_t sz;
2655 
2656 	memset(&rh, 0, sizeof(rh));
2657 	memcpy(&rh.range, rt, sizeof(*rt));
2658 	rh.range.head.length = sizeof(*rt);
2659 	rh.range.head.type = IPFW_TLV_RANGE;
2660 	sz = sizeof(rh);
2661 
2662 	if (do_get3(cmd, &rh.opheader, &sz) != 0)
2663 		return (-1);
2664 	/* Save number of matched objects */
2665 	rt->new_set = rh.range.new_set;
2666 	return (0);
2667 }
2668 
2669 /*
2670  * This one handles all set-related commands
2671  * 	ipfw set { show | enable | disable }
2672  * 	ipfw set swap X Y
2673  * 	ipfw set move X to Y
2674  * 	ipfw set move rule X to Y
2675  */
2676 void
ipfw_sets_handler(char * av[])2677 ipfw_sets_handler(char *av[])
2678 {
2679 	ipfw_range_tlv rt;
2680 	const char *msg;
2681 	size_t size;
2682 	uint32_t masks[2], rulenum;
2683 	int i;
2684 	uint8_t cmd;
2685 
2686 	av++;
2687 	memset(&rt, 0, sizeof(rt));
2688 
2689 	if (av[0] == NULL)
2690 		errx(EX_USAGE, "set needs command");
2691 	if (_substrcmp(*av, "show") == 0) {
2692 		struct format_opts fo;
2693 		ipfw_cfg_lheader *cfg;
2694 
2695 		memset(&fo, 0, sizeof(fo));
2696 		if (ipfw_get_config(&g_co, &fo, &cfg, &size) != 0)
2697 			err(EX_OSERR, "requesting config failed");
2698 
2699 		for (i = 0, msg = "disable"; i < RESVD_SET; i++)
2700 			if ((cfg->set_mask & (1<<i)) == 0) {
2701 				printf("%s %d", msg, i);
2702 				msg = "";
2703 			}
2704 		msg = (cfg->set_mask != (uint32_t)-1) ? " enable" : "enable";
2705 		for (i = 0; i < RESVD_SET; i++)
2706 			if ((cfg->set_mask & (1<<i)) != 0) {
2707 				printf("%s %d", msg, i);
2708 				msg = "";
2709 			}
2710 		printf("\n");
2711 		free(cfg);
2712 	} else if (_substrcmp(*av, "swap") == 0) {
2713 		av++;
2714 		if ( av[0] == NULL || av[1] == NULL )
2715 			errx(EX_USAGE, "set swap needs 2 set numbers\n");
2716 		rt.set = atoi(av[0]);
2717 		rt.new_set = atoi(av[1]);
2718 		if (!isdigit(*(av[0])) || rt.set > RESVD_SET)
2719 			errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2720 		if (!isdigit(*(av[1])) || rt.new_set > RESVD_SET)
2721 			errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2722 		i = do_range_cmd(IP_FW_SET_SWAP, &rt);
2723 	} else if (_substrcmp(*av, "move") == 0) {
2724 		av++;
2725 		if (av[0] && _substrcmp(*av, "rule") == 0) {
2726 			rt.flags = IPFW_RCFLAG_RANGE; /* move rules to new set */
2727 			cmd = IP_FW_XMOVE;
2728 			av++;
2729 		} else
2730 			cmd = IP_FW_SET_MOVE; /* Move set to new one */
2731 		if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
2732 				av[3] != NULL ||  _substrcmp(av[1], "to") != 0)
2733 			errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2734 		rulenum = (uint32_t)strtoul(av[0], NULL, 10);
2735 		rt.new_set = atoi(av[2]);
2736 		if (cmd == IP_FW_XMOVE) {
2737 			rt.start_rule = rulenum;
2738 			rt.end_rule = rulenum;
2739 		} else
2740 			rt.set = rulenum;
2741 		rt.new_set = atoi(av[2]);
2742 		if (!isdigit(*(av[0])) || (cmd == 3 && rt.set > RESVD_SET) ||
2743 			(cmd == 2 && rt.start_rule == IPFW_DEFAULT_RULE) )
2744 			errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2745 		if (!isdigit(*(av[2])) || rt.new_set > RESVD_SET)
2746 			errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2747 		i = do_range_cmd(cmd, &rt);
2748 		if (i < 0)
2749 			err(EX_OSERR, "failed to move %s",
2750 			    cmd == IP_FW_SET_MOVE ? "set": "rule");
2751 	} else if (_substrcmp(*av, "disable") == 0 ||
2752 		   _substrcmp(*av, "enable") == 0 ) {
2753 		int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2754 
2755 		av++;
2756 		masks[0] = masks[1] = 0;
2757 
2758 		while (av[0]) {
2759 			if (isdigit(**av)) {
2760 				i = atoi(*av);
2761 				if (i < 0 || i > RESVD_SET)
2762 					errx(EX_DATAERR,
2763 					    "invalid set number %d\n", i);
2764 				masks[which] |= (1<<i);
2765 			} else if (_substrcmp(*av, "disable") == 0)
2766 				which = 0;
2767 			else if (_substrcmp(*av, "enable") == 0)
2768 				which = 1;
2769 			else
2770 				errx(EX_DATAERR,
2771 					"invalid set command %s\n", *av);
2772 			av++;
2773 		}
2774 		if ( (masks[0] & masks[1]) != 0 )
2775 			errx(EX_DATAERR,
2776 			    "cannot enable and disable the same set\n");
2777 
2778 		rt.set = masks[0];
2779 		rt.new_set = masks[1];
2780 		i = do_range_cmd(IP_FW_SET_ENABLE, &rt);
2781 		if (i)
2782 			warn("set enable/disable: setsockopt(IP_FW_SET_ENABLE)");
2783 	} else
2784 		errx(EX_USAGE, "invalid set command %s\n", *av);
2785 }
2786 
2787 static void
manage_skipto_cache(int op)2788 manage_skipto_cache(int op)
2789 {
2790 	ipfw_cmd_header req;
2791 
2792 	memset(&req, 0, sizeof(req));
2793 	req.size = sizeof(req);
2794 	req.cmd = op ? SKIPTO_CACHE_ENABLE : SKIPTO_CACHE_DISABLE;
2795 
2796 	do_set3(IP_FW_SKIPTO_CACHE, &req.opheader, sizeof(req));
2797 }
2798 
2799 void
ipfw_sysctl_handler(char * av[],int which)2800 ipfw_sysctl_handler(char *av[], int which)
2801 {
2802 	av++;
2803 
2804 	if (av[0] == NULL) {
2805 		warnx("missing keyword to enable/disable\n");
2806 	} else if (_substrcmp(*av, "firewall") == 0) {
2807 		sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2808 		    &which, sizeof(which));
2809 		sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
2810 		    &which, sizeof(which));
2811 	} else if (_substrcmp(*av, "one_pass") == 0) {
2812 		sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2813 		    &which, sizeof(which));
2814 	} else if (_substrcmp(*av, "debug") == 0) {
2815 		sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2816 		    &which, sizeof(which));
2817 	} else if (_substrcmp(*av, "verbose") == 0) {
2818 		sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2819 		    &which, sizeof(which));
2820 	} else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2821 		sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2822 		    &which, sizeof(which));
2823 	} else if (_substrcmp(*av, "skipto_cache") == 0) {
2824 		manage_skipto_cache(which);
2825 #ifndef NO_ALTQ
2826 	} else if (_substrcmp(*av, "altq") == 0) {
2827 		altq_set_enabled(which);
2828 #endif
2829 	} else {
2830 		warnx("unrecognize enable/disable keyword: %s\n", *av);
2831 	}
2832 }
2833 
2834 typedef void state_cb(struct cmdline_opts *co, struct format_opts *fo,
2835     void *arg, void *state);
2836 
2837 static void
prepare_format_dyn(struct cmdline_opts * co,struct format_opts * fo,void * arg __unused,void * _state)2838 prepare_format_dyn(struct cmdline_opts *co, struct format_opts *fo,
2839     void *arg __unused, void *_state)
2840 {
2841 	ipfw_dyn_rule *d;
2842 	int width;
2843 
2844 	d = (ipfw_dyn_rule *)_state;
2845 	/* Count _ALL_ states */
2846 	fo->dcnt++;
2847 
2848 	if (fo->show_counters == 0)
2849 		return;
2850 
2851 	/* skip states from another set */
2852 	if (co->use_set != 0 && d->set != co->use_set - 1)
2853 		return;
2854 
2855 	width = pr_u64(NULL, &d->pcnt, 0);
2856 	if (width > fo->pcwidth)
2857 		fo->pcwidth = width;
2858 
2859 	width = pr_u64(NULL, &d->bcnt, 0);
2860 	if (width > fo->bcwidth)
2861 		fo->bcwidth = width;
2862 }
2863 
2864 static int
foreach_state(struct cmdline_opts * co,struct format_opts * fo,caddr_t base,size_t sz,state_cb dyn_bc,void * dyn_arg)2865 foreach_state(struct cmdline_opts *co, struct format_opts *fo,
2866     caddr_t base, size_t sz, state_cb dyn_bc, void *dyn_arg)
2867 {
2868 	int ttype;
2869 	state_cb *fptr;
2870 	void *farg;
2871 	ipfw_obj_tlv *tlv;
2872 	ipfw_obj_ctlv *ctlv;
2873 
2874 	fptr = NULL;
2875 	ttype = 0;
2876 
2877 	while (sz > 0) {
2878 		ctlv = (ipfw_obj_ctlv *)base;
2879 		switch (ctlv->head.type) {
2880 		case IPFW_TLV_DYNSTATE_LIST:
2881 			base += sizeof(*ctlv);
2882 			sz -= sizeof(*ctlv);
2883 			ttype = IPFW_TLV_DYN_ENT;
2884 			fptr = dyn_bc;
2885 			farg = dyn_arg;
2886 			break;
2887 		default:
2888 			return (sz);
2889 		}
2890 
2891 		while (sz > 0) {
2892 			tlv = (ipfw_obj_tlv *)base;
2893 			if (tlv->type != ttype)
2894 				break;
2895 
2896 			fptr(co, fo, farg, tlv + 1);
2897 			sz -= tlv->length;
2898 			base += tlv->length;
2899 		}
2900 	}
2901 
2902 	return (sz);
2903 }
2904 
2905 static void
prepare_format_opts(struct cmdline_opts * co,struct format_opts * fo,ipfw_obj_tlv * rtlv,int rcnt,caddr_t dynbase,size_t dynsz)2906 prepare_format_opts(struct cmdline_opts *co, struct format_opts *fo,
2907     ipfw_obj_tlv *rtlv, int rcnt, caddr_t dynbase, size_t dynsz)
2908 {
2909 	int bcwidth, pcwidth, width;
2910 	int n;
2911 	struct ip_fw_bcounter *cntr;
2912 	struct ip_fw_rule *r;
2913 
2914 	bcwidth = 0;
2915 	pcwidth = 0;
2916 	if (fo->show_counters != 0) {
2917 		for (n = 0; n < rcnt; n++,
2918 		    rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2919 			cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2920 			r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2921 			/* skip rules from another set */
2922 			if (co->use_set && r->set != co->use_set - 1)
2923 				continue;
2924 
2925 			/* packet counter */
2926 			width = pr_u64(NULL, &cntr->pcnt, 0);
2927 			if (width > pcwidth)
2928 				pcwidth = width;
2929 
2930 			/* byte counter */
2931 			width = pr_u64(NULL, &cntr->bcnt, 0);
2932 			if (width > bcwidth)
2933 				bcwidth = width;
2934 		}
2935 	}
2936 	fo->bcwidth = bcwidth;
2937 	fo->pcwidth = pcwidth;
2938 
2939 	fo->dcnt = 0;
2940 	if (co->do_dynamic && dynsz > 0)
2941 		foreach_state(co, fo, dynbase, dynsz, prepare_format_dyn, NULL);
2942 }
2943 
2944 static int
list_static_range(struct cmdline_opts * co,struct format_opts * fo,struct buf_pr * bp,ipfw_obj_tlv * rtlv,int rcnt)2945 list_static_range(struct cmdline_opts *co, struct format_opts *fo,
2946     struct buf_pr *bp, ipfw_obj_tlv *rtlv, int rcnt)
2947 {
2948 	int n, seen;
2949 	struct ip_fw_rule *r;
2950 	struct ip_fw_bcounter *cntr;
2951 
2952 	for (n = seen = 0; n < rcnt; n++,
2953 	    rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2954 
2955 		if ((fo->show_counters | fo->show_time) != 0) {
2956 			cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2957 			r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2958 		} else {
2959 			cntr = NULL;
2960 			r = (struct ip_fw_rule *)(rtlv + 1);
2961 		}
2962 		if (r->rulenum > fo->last)
2963 			break;
2964 		if (co->use_set && r->set != co->use_set - 1)
2965 			continue;
2966 		if (r->rulenum >= fo->first && r->rulenum <= fo->last) {
2967 			show_static_rule(co, fo, bp, r, cntr);
2968 			printf("%s", bp->buf);
2969 			bp_flush(bp);
2970 			seen++;
2971 		}
2972 	}
2973 
2974 	return (seen);
2975 }
2976 
2977 static void
list_dyn_state(struct cmdline_opts * co,struct format_opts * fo,void * _arg,void * _state)2978 list_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2979     void *_arg, void *_state)
2980 {
2981 	ipfw_dyn_rule *d;
2982 	struct buf_pr *bp;
2983 
2984 	d = (ipfw_dyn_rule *)_state;
2985 	bp = (struct buf_pr *)_arg;
2986 
2987 	if (d->rulenum > fo->last)
2988 		return;
2989 	if (co->use_set != 0 && d->set != co->use_set - 1)
2990 		return;
2991 	if (d->rulenum >= fo->first) {
2992 		show_dyn_state(co, fo, bp, d);
2993 		printf("%s\n", bp->buf);
2994 		bp_flush(bp);
2995 	}
2996 }
2997 
2998 static int
list_dyn_range(struct cmdline_opts * co,struct format_opts * fo,struct buf_pr * bp,caddr_t base,size_t sz)2999 list_dyn_range(struct cmdline_opts *co, struct format_opts *fo,
3000     struct buf_pr *bp, caddr_t base, size_t sz)
3001 {
3002 
3003 	sz = foreach_state(co, fo, base, sz, list_dyn_state, bp);
3004 	return (sz);
3005 }
3006 
3007 void
ipfw_list(int ac,char * av[],int show_counters)3008 ipfw_list(int ac, char *av[], int show_counters)
3009 {
3010 	ipfw_cfg_lheader *cfg;
3011 	struct format_opts sfo;
3012 	size_t sz;
3013 	int error;
3014 	int lac;
3015 	char **lav;
3016 	uint32_t rnum;
3017 	char *endptr;
3018 
3019 	if (g_co.test_only) {
3020 		fprintf(stderr, "Testing only, list disabled\n");
3021 		return;
3022 	}
3023 	if (g_co.do_pipe) {
3024 		dummynet_list(ac, av, show_counters);
3025 		return;
3026 	}
3027 
3028 	ac--;
3029 	av++;
3030 	memset(&sfo, 0, sizeof(sfo));
3031 
3032 	/* Determine rule range to request */
3033 	if (ac > 0) {
3034 		for (lac = ac, lav = av; lac != 0; lac--) {
3035 			rnum = strtoul(*lav++, &endptr, 10);
3036 			if (sfo.first == 0 || rnum < sfo.first)
3037 				sfo.first = rnum;
3038 
3039 			if (*endptr == '-')
3040 				rnum = strtoul(endptr + 1, &endptr, 10);
3041 			if (sfo.last == 0 || rnum > sfo.last)
3042 				sfo.last = rnum;
3043 		}
3044 	}
3045 
3046 	/* get configuration from kernel */
3047 	cfg = NULL;
3048 	sfo.show_counters = show_counters;
3049 	sfo.show_time = g_co.do_time;
3050 	if (g_co.do_dynamic != 2)
3051 		sfo.flags |= IPFW_CFG_GET_STATIC;
3052 	if (g_co.do_dynamic != 0)
3053 		sfo.flags |= IPFW_CFG_GET_STATES;
3054 	if ((sfo.show_counters | sfo.show_time) != 0)
3055 		sfo.flags |= IPFW_CFG_GET_COUNTERS;
3056 	if (ipfw_get_config(&g_co, &sfo, &cfg, &sz) != 0)
3057 		err(EX_OSERR, "retrieving config failed");
3058 
3059 	error = ipfw_show_config(&g_co, &sfo, cfg, sz, ac, av);
3060 
3061 	free(cfg);
3062 
3063 	if (error != EX_OK)
3064 		exit(error);
3065 }
3066 
3067 static int
ipfw_show_config(struct cmdline_opts * co,struct format_opts * fo,ipfw_cfg_lheader * cfg,size_t sz,int ac,char * av[])3068 ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
3069     ipfw_cfg_lheader *cfg, size_t sz, int ac, char *av[])
3070 {
3071 	caddr_t dynbase;
3072 	size_t dynsz;
3073 	int rcnt;
3074 	int exitval = EX_OK;
3075 	int lac;
3076 	char **lav;
3077 	char *endptr;
3078 	size_t readsz;
3079 	struct buf_pr bp;
3080 	ipfw_obj_ctlv *ctlv;
3081 	ipfw_obj_tlv *rbase;
3082 
3083 	/*
3084 	 * Handle tablenames TLV first, if any
3085 	 */
3086 	rbase = NULL;
3087 	dynbase = NULL;
3088 	dynsz = 0;
3089 	readsz = sizeof(*cfg);
3090 	rcnt = 0;
3091 
3092 	fo->set_mask = cfg->set_mask;
3093 
3094 	ctlv = (ipfw_obj_ctlv *)(cfg + 1);
3095 	if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
3096 		object_sort_ctlv(ctlv);
3097 		fo->tstate = ctlv;
3098 		readsz += ctlv->head.length;
3099 		ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
3100 	}
3101 
3102 	if (cfg->flags & IPFW_CFG_GET_STATIC) {
3103 		/* We've requested static rules */
3104 		if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
3105 			rbase = (ipfw_obj_tlv *)(ctlv + 1);
3106 			rcnt = ctlv->count;
3107 			readsz += ctlv->head.length;
3108 			ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
3109 			    ctlv->head.length);
3110 		}
3111 	}
3112 
3113 	if ((cfg->flags & IPFW_CFG_GET_STATES) && (readsz != sz))  {
3114 		/* We may have some dynamic states */
3115 		dynsz = sz - readsz;
3116 		/* Skip empty header */
3117 		if (dynsz != sizeof(ipfw_obj_ctlv))
3118 			dynbase = (caddr_t)ctlv;
3119 		else
3120 			dynsz = 0;
3121 	}
3122 
3123 	prepare_format_opts(co, fo, rbase, rcnt, dynbase, dynsz);
3124 	bp_alloc(&bp, 4096);
3125 
3126 	/* if no rule numbers were specified, list all rules */
3127 	if (ac == 0) {
3128 		fo->first = 0;
3129 		fo->last = IPFW_DEFAULT_RULE;
3130 		if (cfg->flags & IPFW_CFG_GET_STATIC)
3131 			list_static_range(co, fo, &bp, rbase, rcnt);
3132 
3133 		if (co->do_dynamic && dynsz > 0) {
3134 			printf("## Dynamic rules (%d %zu):\n", fo->dcnt,
3135 			    dynsz);
3136 			list_dyn_range(co, fo, &bp, dynbase, dynsz);
3137 		}
3138 
3139 		bp_free(&bp);
3140 		return (EX_OK);
3141 	}
3142 
3143 	/* display specific rules requested on command line */
3144 	for (lac = ac, lav = av; lac != 0; lac--) {
3145 		/* convert command line rule # */
3146 		fo->last = fo->first = strtoul(*lav++, &endptr, 10);
3147 		if (*endptr == '-')
3148 			fo->last = strtoul(endptr + 1, &endptr, 10);
3149 		if (*endptr) {
3150 			exitval = EX_USAGE;
3151 			warnx("invalid rule number: %s", *(lav - 1));
3152 			continue;
3153 		}
3154 
3155 		if ((cfg->flags & IPFW_CFG_GET_STATIC) == 0)
3156 			continue;
3157 
3158 		if (list_static_range(co, fo, &bp, rbase, rcnt) == 0) {
3159 			/* give precedence to other error(s) */
3160 			if (exitval == EX_OK)
3161 				exitval = EX_UNAVAILABLE;
3162 			if (fo->first == fo->last)
3163 				warnx("rule %u does not exist", fo->first);
3164 			else
3165 				warnx("no rules in range %u-%u",
3166 				    fo->first, fo->last);
3167 		}
3168 	}
3169 
3170 	if (co->do_dynamic && dynsz > 0) {
3171 		printf("## Dynamic rules:\n");
3172 		for (lac = ac, lav = av; lac != 0; lac--) {
3173 			fo->last = fo->first = strtoul(*lav++, &endptr, 10);
3174 			if (*endptr == '-')
3175 				fo->last = strtoul(endptr+1, &endptr, 10);
3176 			if (*endptr)
3177 				/* already warned */
3178 				continue;
3179 			list_dyn_range(co, fo, &bp, dynbase, dynsz);
3180 		}
3181 	}
3182 
3183 	bp_free(&bp);
3184 	return (exitval);
3185 }
3186 
3187 
3188 /*
3189  * Retrieves current ipfw configuration of given type
3190  * and stores its pointer to @pcfg.
3191  *
3192  * Caller is responsible for freeing @pcfg.
3193  *
3194  * Returns 0 on success.
3195  */
3196 
3197 static int
ipfw_get_config(struct cmdline_opts * co,struct format_opts * fo,ipfw_cfg_lheader ** pcfg,size_t * psize)3198 ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
3199     ipfw_cfg_lheader **pcfg, size_t *psize)
3200 {
3201 	ipfw_cfg_lheader *cfg;
3202 	size_t sz;
3203 	int i;
3204 
3205 
3206 	if (co->test_only != 0) {
3207 		fprintf(stderr, "Testing only, list disabled\n");
3208 		return (0);
3209 	}
3210 
3211 	/* Start with some data size */
3212 	sz = 4096;
3213 	cfg = NULL;
3214 
3215 	for (i = 0; i < 16; i++) {
3216 		if (cfg != NULL)
3217 			free(cfg);
3218 		if ((cfg = calloc(1, sz)) == NULL)
3219 			return (ENOMEM);
3220 
3221 		cfg->flags = fo->flags;
3222 		cfg->start_rule = fo->first;
3223 		cfg->end_rule = fo->last;
3224 
3225 		if (do_get3(IP_FW_XGET, &cfg->opheader, &sz) != 0) {
3226 			if (errno != ENOMEM) {
3227 				free(cfg);
3228 				return (errno);
3229 			}
3230 
3231 			/* Buffer size is not enough. Try to increase */
3232 			sz = sz * 2;
3233 			if (sz < cfg->size)
3234 				sz = cfg->size;
3235 			continue;
3236 		}
3237 
3238 		*pcfg = cfg;
3239 		*psize = sz;
3240 		return (0);
3241 	}
3242 
3243 	free(cfg);
3244 	return (ENOMEM);
3245 }
3246 
3247 static int
lookup_host(char * host,struct in_addr * ipaddr)3248 lookup_host (char *host, struct in_addr *ipaddr)
3249 {
3250 	struct hostent *he;
3251 
3252 	if (!inet_aton(host, ipaddr)) {
3253 		if ((he = gethostbyname(host)) == NULL)
3254 			return(-1);
3255 		*ipaddr = *(struct in_addr *)he->h_addr_list[0];
3256 	}
3257 	return(0);
3258 }
3259 
3260 struct tidx {
3261 	ipfw_obj_ntlv *idx;
3262 	uint32_t count;
3263 	uint32_t size;
3264 	uint16_t counter;
3265 	uint8_t set;
3266 };
3267 
3268 int
ipfw_check_object_name(const char * name)3269 ipfw_check_object_name(const char *name)
3270 {
3271 	int c, i, l;
3272 
3273 	/*
3274 	 * Check that name is null-terminated and contains
3275 	 * valid symbols only. Valid mask is:
3276 	 * [a-zA-Z0-9\-_\.]{1,63}
3277 	 */
3278 	l = strlen(name);
3279 	if (l == 0 || l >= 64)
3280 		return (EINVAL);
3281 	for (i = 0; i < l; i++) {
3282 		c = name[i];
3283 		if (isalpha(c) || isdigit(c) || c == '_' ||
3284 		    c == '-' || c == '.')
3285 			continue;
3286 		return (EINVAL);
3287 	}
3288 	return (0);
3289 }
3290 
3291 static const char *default_state_name = "default";
3292 
3293 static int
state_check_name(const char * name)3294 state_check_name(const char *name)
3295 {
3296 
3297 	if (ipfw_check_object_name(name) != 0)
3298 		return (EINVAL);
3299 	if (strcmp(name, "any") == 0)
3300 		return (EINVAL);
3301 	return (0);
3302 }
3303 
3304 static int
eaction_check_name(const char * name)3305 eaction_check_name(const char *name)
3306 {
3307 
3308 	if (ipfw_check_object_name(name) != 0)
3309 		return (EINVAL);
3310 	/* Restrict some 'special' names */
3311 	if (match_token(rule_actions, name) != -1 &&
3312 	    match_token(rule_action_params, name) != -1)
3313 		return (EINVAL);
3314 	return (0);
3315 }
3316 
3317 static uint32_t
pack_object(struct tidx * tstate,const char * name,int otype)3318 pack_object(struct tidx *tstate, const char *name, int otype)
3319 {
3320 	ipfw_obj_ntlv *ntlv;
3321 	uint32_t i;
3322 
3323 	for (i = 0; i < tstate->count; i++) {
3324 		if (strcmp(tstate->idx[i].name, name) != 0)
3325 			continue;
3326 		if (tstate->idx[i].set != tstate->set)
3327 			continue;
3328 		if (tstate->idx[i].head.type != otype)
3329 			continue;
3330 
3331 		return (tstate->idx[i].idx);
3332 	}
3333 
3334 	if (tstate->count + 1 > tstate->size) {
3335 		tstate->size += 4;
3336 		tstate->idx = realloc(tstate->idx, tstate->size *
3337 		    sizeof(ipfw_obj_ntlv));
3338 		if (tstate->idx == NULL)
3339 			return (0);
3340 	}
3341 
3342 	ntlv = &tstate->idx[i];
3343 	memset(ntlv, 0, sizeof(ipfw_obj_ntlv));
3344 	strlcpy(ntlv->name, name, sizeof(ntlv->name));
3345 	ntlv->head.type = otype;
3346 	ntlv->head.length = sizeof(ipfw_obj_ntlv);
3347 	ntlv->set = tstate->set;
3348 	ntlv->idx = ++tstate->counter;
3349 	tstate->count++;
3350 
3351 	return (ntlv->idx);
3352 }
3353 
3354 static uint32_t
pack_table(struct tidx * tstate,const char * name)3355 pack_table(struct tidx *tstate, const char *name)
3356 {
3357 
3358 	if (table_check_name(name) != 0)
3359 		return (0);
3360 
3361 	return (pack_object(tstate, name, IPFW_TLV_TBL_NAME));
3362 }
3363 
3364 /*
3365  * Parse table(NAME, value) and table(NAME,key=value)
3366  */
3367 static void
fill_table_value(ipfw_insn_lookup * cmd,char * s)3368 fill_table_value(ipfw_insn_lookup *cmd, char *s)
3369 {
3370 	char *p;
3371 	int i;
3372 
3373 	p = strchr(s, '=');
3374 	if (p != NULL) {
3375 		*p++ = '\0';
3376 		i = match_token(tvalue_names, s);
3377 		if (i == -1)
3378 			errx(EX_USAGE,
3379 			    "format: unknown table value name %s", s);
3380 	} else {
3381 		i = TVALUE_TAG;
3382 		p = s;
3383 	}
3384 
3385 	IPFW_SET_TVALUE_TYPE(&cmd->o, i);
3386 
3387 	if (i == TVALUE_NH6) {
3388 		if (inet_pton(AF_INET6, p, &cmd->ip6) != 1)
3389 			errx(EX_USAGE, "invalid IPv6 address provided");
3390 	/* mask in a dotted-quad notation */
3391 	} else if (strchr(p, '.') != NULL) {
3392 		if (inet_aton(p, &cmd->ip4) != 1)
3393 			errx(EX_USAGE, "invalid IPv4 address provided");
3394 		if (i == TVALUE_NH4)
3395 			return;
3396 		cmd->u32 = ntohl(cmd->u32);
3397 	} else
3398 		cmd->u32 = strtoul(p, NULL, 0);
3399 }
3400 
3401 void
fill_table(ipfw_insn * cmd,char * av,uint8_t opcode,struct tidx * tstate)3402 fill_table(ipfw_insn *cmd, char *av, uint8_t opcode, struct tidx *tstate)
3403 {
3404 	ipfw_insn_kidx *c = insntod(cmd, kidx);
3405 	char *p;
3406 
3407 	if ((p = strchr(av + 6, ')')) == NULL)
3408 		errx(EX_DATAERR, "forgotten parenthesis: '%s'", av);
3409 	*p = '\0';
3410 	p = strchr(av + 6, ',');
3411 	if (p)
3412 		*p++ = '\0';
3413 
3414 	if ((c->kidx = pack_table(tstate, av + 6)) == 0)
3415 		errx(EX_DATAERR, "Invalid table name: %s", av + 6);
3416 
3417 	cmd->opcode = opcode;
3418 	if (p) {
3419 		cmd->len |= F_INSN_SIZE(ipfw_insn_lookup);
3420 		IPFW_SET_LOOKUP_MATCH_TVALUE(cmd, 1);
3421 		fill_table_value(insntod(cmd, lookup), p);
3422 	} else {
3423 		/* table(NAME) */
3424 		IPFW_SET_LOOKUP_TYPE(cmd, LOOKUP_NONE);
3425 		cmd->len |= F_INSN_SIZE(ipfw_insn_kidx);
3426 	}
3427 }
3428 
3429 /*
3430  * fills the addr and mask fields in the instruction as appropriate from av.
3431  * Update length as appropriate.
3432  * The following formats are allowed:
3433  *	me	returns O_IP_*_ME
3434  *	1.2.3.4		single IP address
3435  *	1.2.3.4:5.6.7.8	address:mask
3436  *	1.2.3.4/24	address/mask
3437  *	1.2.3.4/26{1,6,5,4,23}	set of addresses in a subnet
3438  * We can have multiple comma-separated address/mask entries.
3439  */
3440 static void
fill_ip(ipfw_insn_ip * cmd,char * av,int cblen,struct tidx * tstate)3441 fill_ip(ipfw_insn_ip *cmd, char *av, int cblen, struct tidx *tstate)
3442 {
3443 	int len = 0;
3444 	uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
3445 
3446 	cmd->o.len &= ~F_LEN_MASK;	/* zero len */
3447 
3448 	if (_substrcmp(av, "any") == 0)
3449 		return;
3450 
3451 	if (_substrcmp(av, "me") == 0) {
3452 		cmd->o.len |= F_INSN_SIZE(ipfw_insn);
3453 		return;
3454 	}
3455 
3456 	if (strncmp(av, "table(", 6) == 0) {
3457 		fill_table(&cmd->o, av, O_IP_DST_LOOKUP, tstate);
3458 		return;
3459 	}
3460 
3461     while (av) {
3462 	/*
3463 	 * After the address we can have '/' or ':' indicating a mask,
3464 	 * ',' indicating another address follows, '{' indicating a
3465 	 * set of addresses of unspecified size.
3466 	 */
3467 	char *t = NULL, *p = strpbrk(av, "/:,{");
3468 	int masklen;
3469 	char md, nd = '\0';
3470 
3471 	CHECK_LENGTH(cblen, (int)F_INSN_SIZE(ipfw_insn) + 2 + len);
3472 
3473 	if (p) {
3474 		md = *p;
3475 		*p++ = '\0';
3476 		if ((t = strpbrk(p, ",{")) != NULL) {
3477 			nd = *t;
3478 			*t = '\0';
3479 		}
3480 	} else
3481 		md = '\0';
3482 
3483 	if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
3484 		errx(EX_NOHOST, "hostname ``%s'' unknown", av);
3485 	switch (md) {
3486 	case ':':
3487 		if (!inet_aton(p, (struct in_addr *)&d[1]))
3488 			errx(EX_DATAERR, "bad netmask ``%s''", p);
3489 		break;
3490 	case '/':
3491 		masklen = atoi(p);
3492 		if (masklen == 0)
3493 			d[1] = htonl(0U);	/* mask */
3494 		else if (masklen > 32)
3495 			errx(EX_DATAERR, "bad width ``%s''", p);
3496 		else
3497 			d[1] = htonl(~0U << (32 - masklen));
3498 		break;
3499 	case '{':	/* no mask, assume /24 and put back the '{' */
3500 		d[1] = htonl(~0U << (32 - 24));
3501 		*(--p) = md;
3502 		break;
3503 
3504 	case ',':	/* single address plus continuation */
3505 		*(--p) = md;
3506 		/* FALLTHROUGH */
3507 	case 0:		/* initialization value */
3508 	default:
3509 		d[1] = htonl(~0U);	/* force /32 */
3510 		break;
3511 	}
3512 	d[0] &= d[1];		/* mask base address with mask */
3513 	if (t)
3514 		*t = nd;
3515 	/* find next separator */
3516 	if (p)
3517 		p = strpbrk(p, ",{");
3518 	if (p && *p == '{') {
3519 		/*
3520 		 * We have a set of addresses. They are stored as follows:
3521 		 *   arg1	is the set size (powers of 2, 2..256)
3522 		 *   addr	is the base address IN HOST FORMAT
3523 		 *   mask..	is an array of arg1 bits (rounded up to
3524 		 *		the next multiple of 32) with bits set
3525 		 *		for each host in the map.
3526 		 */
3527 		uint32_t *map = (uint32_t *)&cmd->mask;
3528 		int low, high;
3529 		int i = contigmask((uint8_t *)&(d[1]), 32);
3530 
3531 		if (len > 0)
3532 			errx(EX_DATAERR, "address set cannot be in a list");
3533 		if (i < 24 || i > 31)
3534 			errx(EX_DATAERR, "invalid set with mask %d\n", i);
3535 		cmd->o.arg1 = 1<<(32-i);	/* map length		*/
3536 		d[0] = ntohl(d[0]);		/* base addr in host format */
3537 		cmd->o.opcode = O_IP_DST_SET;	/* default */
3538 		cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
3539 		for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
3540 			map[i] = 0;	/* clear map */
3541 
3542 		av = p + 1;
3543 		low = d[0] & 0xff;
3544 		high = low + cmd->o.arg1 - 1;
3545 		/*
3546 		 * Here, i stores the previous value when we specify a range
3547 		 * of addresses within a mask, e.g. 45-63. i = -1 means we
3548 		 * have no previous value.
3549 		 */
3550 		i = -1;	/* previous value in a range */
3551 		while (isdigit(*av)) {
3552 			char *s;
3553 			int a = strtol(av, &s, 0);
3554 
3555 			if (s == av) { /* no parameter */
3556 			    if (*av != '}')
3557 				errx(EX_DATAERR, "set not closed\n");
3558 			    if (i != -1)
3559 				errx(EX_DATAERR, "incomplete range %d-", i);
3560 			    break;
3561 			}
3562 			if (a < low || a > high)
3563 			    errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
3564 				a, low, high);
3565 			a -= low;
3566 			if (i == -1)	/* no previous in range */
3567 			    i = a;
3568 			else {		/* check that range is valid */
3569 			    if (i > a)
3570 				errx(EX_DATAERR, "invalid range %d-%d",
3571 					i+low, a+low);
3572 			    if (*s == '-')
3573 				errx(EX_DATAERR, "double '-' in range");
3574 			}
3575 			for (; i <= a; i++)
3576 			    map[i/32] |= 1<<(i & 31);
3577 			i = -1;
3578 			if (*s == '-')
3579 			    i = a;
3580 			else if (*s == '}')
3581 			    break;
3582 			av = s+1;
3583 		}
3584 		return;
3585 	}
3586 	av = p;
3587 	if (av)			/* then *av must be a ',' */
3588 		av++;
3589 
3590 	/* Check this entry */
3591 	if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
3592 		/*
3593 		 * 'any' turns the entire list into a NOP.
3594 		 * 'not any' never matches, so it is removed from the
3595 		 * list unless it is the only item, in which case we
3596 		 * report an error.
3597 		 */
3598 		if (cmd->o.len & F_NOT) {	/* "not any" never matches */
3599 			if (av == NULL && len == 0) /* only this entry */
3600 				errx(EX_DATAERR, "not any never matches");
3601 		}
3602 		/* else do nothing and skip this entry */
3603 		return;
3604 	}
3605 	/* A single IP can be stored in an optimized format */
3606 	if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
3607 		cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
3608 		return;
3609 	}
3610 	len += 2;	/* two words... */
3611 	d += 2;
3612     } /* end while */
3613     if (len + 1 > F_LEN_MASK)
3614 	errx(EX_DATAERR, "address list too long");
3615     cmd->o.len |= len+1;
3616 }
3617 
3618 
3619 /* n2mask sets n bits of the mask */
3620 void
n2mask(struct in6_addr * mask,int n)3621 n2mask(struct in6_addr *mask, int n)
3622 {
3623 	static int	minimask[9] =
3624 	    { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
3625 	u_char		*p;
3626 
3627 	memset(mask, 0, sizeof(struct in6_addr));
3628 	p = (u_char *) mask;
3629 	for (; n > 0; p++, n -= 8) {
3630 		if (n >= 8)
3631 			*p = 0xff;
3632 		else
3633 			*p = minimask[n];
3634 	}
3635 	return;
3636 }
3637 
3638 static void
fill_flags_cmd(ipfw_insn * cmd,enum ipfw_opcodes opcode,struct _s_x * flags,char * p)3639 fill_flags_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3640 	struct _s_x *flags, char *p)
3641 {
3642 	char *e;
3643 	uint32_t set = 0, clear = 0;
3644 
3645 	if (fill_flags(flags, p, &e, &set, &clear) != 0)
3646 		errx(EX_DATAERR, "invalid flag %s", e);
3647 
3648 	cmd->opcode = opcode;
3649 	cmd->len =  (cmd->len & (F_NOT | F_OR)) | 1;
3650 	cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3651 }
3652 
3653 
3654 void
ipfw_delete(char * av[])3655 ipfw_delete(char *av[])
3656 {
3657 	ipfw_range_tlv rt;
3658 	char *sep;
3659 	uint32_t i, j;
3660 	int exitval = EX_OK;
3661 	int do_set = 0;
3662 
3663 	av++;
3664 	NEED1("missing rule specification");
3665 	if ( *av && _substrcmp(*av, "set") == 0) {
3666 		/* Do not allow using the following syntax:
3667 		 *	ipfw set N delete set M
3668 		 */
3669 		if (g_co.use_set)
3670 			errx(EX_DATAERR, "invalid syntax");
3671 		do_set = 1;	/* delete set */
3672 		av++;
3673 	}
3674 
3675 	/* Rule number */
3676 	while (*av && isdigit(**av)) {
3677 		i = strtol(*av, &sep, 10);
3678 		j = i;
3679 		if (*sep== '-')
3680 			j = strtol(sep + 1, NULL, 10);
3681 		av++;
3682 		if (g_co.do_nat) {
3683 			exitval = ipfw_delete_nat(i);
3684 		} else if (g_co.do_pipe) {
3685 			exitval = ipfw_delete_pipe(g_co.do_pipe, i);
3686 		} else {
3687 			memset(&rt, 0, sizeof(rt));
3688 			if (do_set != 0) {
3689 				rt.set = i & 31;
3690 				rt.flags = IPFW_RCFLAG_SET;
3691 			} else {
3692 				rt.start_rule = i;
3693 				rt.end_rule = j;
3694 				if (rt.start_rule == 0 && rt.end_rule == 0)
3695 					rt.flags |= IPFW_RCFLAG_ALL;
3696 				else
3697 					rt.flags |= IPFW_RCFLAG_RANGE;
3698 				if (g_co.use_set != 0) {
3699 					rt.set = g_co.use_set - 1;
3700 					rt.flags |= IPFW_RCFLAG_SET;
3701 				}
3702 			}
3703 			if (g_co.do_dynamic == 2)
3704 				rt.flags |= IPFW_RCFLAG_DYNAMIC;
3705 			i = do_range_cmd(IP_FW_XDEL, &rt);
3706 			if (i != 0) {
3707 				exitval = EX_UNAVAILABLE;
3708 				if (g_co.do_quiet)
3709 					continue;
3710 				warn("rule %u: setsockopt(IP_FW_XDEL)",
3711 				    rt.start_rule);
3712 			} else if (rt.new_set == 0 && do_set == 0 &&
3713 			    g_co.do_dynamic != 2) {
3714 				exitval = EX_UNAVAILABLE;
3715 				if (g_co.do_quiet)
3716 					continue;
3717 				if (rt.start_rule != rt.end_rule)
3718 					warnx("no rules in %u-%u range",
3719 					    rt.start_rule, rt.end_rule);
3720 				else
3721 					warnx("rule %u not found",
3722 					    rt.start_rule);
3723 			}
3724 		}
3725 	}
3726 	if (exitval != EX_OK && g_co.do_force == 0)
3727 		exit(exitval);
3728 }
3729 
3730 /*
3731  * fill the interface structure. We do not check the name as we can
3732  * create interfaces dynamically, so checking them at insert time
3733  * makes relatively little sense.
3734  * Interface names containing '*', '?', or '[' are assumed to be shell
3735  * patterns which match interfaces.
3736  */
3737 static void
fill_iface(ipfw_insn_if * cmd,char * arg,int cblen,struct tidx * tstate)3738 fill_iface(ipfw_insn_if *cmd, char *arg, int cblen, struct tidx *tstate)
3739 {
3740 	char *p;
3741 	uint32_t uidx;
3742 
3743 	cmd->name[0] = '\0';
3744 	cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3745 
3746 	CHECK_CMDLEN;
3747 
3748 	/* Parse the interface or address */
3749 	if (strcmp(arg, "any") == 0)
3750 		cmd->o.len = 0;		/* effectively ignore this command */
3751 	else if (strncmp(arg, "table(", 6) == 0) {
3752 		if ((p = strchr(arg + 6, ')')) == NULL)
3753 			errx(EX_DATAERR, "forgotten parenthesis: '%s'", arg);
3754 		*p = '\0';
3755 		p = strchr(arg + 6, ',');
3756 		if (p)
3757 			*p++ = '\0';
3758 		if ((uidx = pack_table(tstate, arg + 6)) == 0)
3759 			errx(EX_DATAERR, "Invalid table name: %s", arg + 6);
3760 
3761 		cmd->name[0] = '\1'; /* Special value indicating table */
3762 		cmd->p.kidx = uidx;
3763 	} else if (!isdigit(*arg)) {
3764 		strlcpy(cmd->name, arg, sizeof(cmd->name));
3765 		cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3766 	} else if (!inet_aton(arg, &cmd->p.ip))
3767 		errx(EX_DATAERR, "bad ip address ``%s''", arg);
3768 }
3769 
3770 static void
get_mac_addr_mask(const char * p,uint8_t * addr,uint8_t * mask)3771 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
3772 {
3773 	int i;
3774 	size_t l;
3775 	char *ap, *ptr, *optr;
3776 	struct ether_addr *mac;
3777 	const char *macset = "0123456789abcdefABCDEF:";
3778 
3779 	if (strcmp(p, "any") == 0) {
3780 		for (i = 0; i < ETHER_ADDR_LEN; i++)
3781 			addr[i] = mask[i] = 0;
3782 		return;
3783 	}
3784 
3785 	optr = ptr = strdup(p);
3786 	if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
3787 		l = strlen(ap);
3788 		if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
3789 			errx(EX_DATAERR, "Incorrect MAC address");
3790 		bcopy(mac, addr, ETHER_ADDR_LEN);
3791 	} else
3792 		errx(EX_DATAERR, "Incorrect MAC address");
3793 
3794 	if (ptr != NULL) { /* we have mask? */
3795 		if (p[ptr - optr - 1] == '/') { /* mask len */
3796 			long ml = strtol(ptr, &ap, 10);
3797 			if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
3798 				errx(EX_DATAERR, "Incorrect mask length");
3799 			for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
3800 				mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
3801 		} else { /* mask */
3802 			l = strlen(ptr);
3803 			if (strspn(ptr, macset) != l ||
3804 			    (mac = ether_aton(ptr)) == NULL)
3805 				errx(EX_DATAERR, "Incorrect mask");
3806 			bcopy(mac, mask, ETHER_ADDR_LEN);
3807 		}
3808 	} else { /* default mask: ff:ff:ff:ff:ff:ff */
3809 		for (i = 0; i < ETHER_ADDR_LEN; i++)
3810 			mask[i] = 0xff;
3811 	}
3812 	for (i = 0; i < ETHER_ADDR_LEN; i++)
3813 		addr[i] &= mask[i];
3814 
3815 	free(optr);
3816 }
3817 
3818 /*
3819  * helper function, updates the pointer to cmd with the length
3820  * of the current command, and also cleans up the first word of
3821  * the new command in case it has been clobbered before.
3822  */
3823 static ipfw_insn *
next_cmd(ipfw_insn * cmd,int * len)3824 next_cmd(ipfw_insn *cmd, int *len)
3825 {
3826 	*len -= F_LEN(cmd);
3827 	CHECK_LENGTH(*len, 0);
3828 	cmd += F_LEN(cmd);
3829 	bzero(cmd, sizeof(*cmd));
3830 	return cmd;
3831 }
3832 
3833 /*
3834  * Takes arguments and copies them into a comment
3835  */
3836 static void
fill_comment(ipfw_insn * cmd,char ** av,int cblen)3837 fill_comment(ipfw_insn *cmd, char **av, int cblen)
3838 {
3839 	int i, l;
3840 	char *p = (char *)(cmd + 1);
3841 
3842 	cmd->opcode = O_NOP;
3843 	cmd->len =  (cmd->len & (F_NOT | F_OR));
3844 
3845 	/* Compute length of comment string. */
3846 	for (i = 0, l = 0; av[i] != NULL; i++)
3847 		l += strlen(av[i]) + 1;
3848 	if (l == 0)
3849 		return;
3850 	if (l > 84)
3851 		errx(EX_DATAERR,
3852 		    "comment too long (max 80 chars)");
3853 	l = 1 + (l+3)/4;
3854 	cmd->len =  (cmd->len & (F_NOT | F_OR)) | l;
3855 	CHECK_CMDLEN;
3856 
3857 	for (i = 0; av[i] != NULL; i++) {
3858 		strcpy(p, av[i]);
3859 		p += strlen(av[i]);
3860 		*p++ = ' ';
3861 	}
3862 	*(--p) = '\0';
3863 }
3864 
3865 /*
3866  * A function to fill simple commands of size 1.
3867  * Existing flags are preserved.
3868  */
3869 static void
fill_cmd(ipfw_insn * cmd,enum ipfw_opcodes opcode,int flags,uint16_t arg)3870 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3871 {
3872 	cmd->opcode = opcode;
3873 	cmd->len =  ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3874 	cmd->arg1 = arg;
3875 }
3876 
3877 /*
3878  * Fetch and add the MAC address and type, with masks. This generates one or
3879  * two microinstructions, and returns the pointer to the last one.
3880  */
3881 static ipfw_insn *
add_mac(ipfw_insn * cmd,char * av[],int cblen)3882 add_mac(ipfw_insn *cmd, char *av[], int cblen)
3883 {
3884 	ipfw_insn_mac *mac;
3885 
3886 	if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
3887 		errx(EX_DATAERR, "MAC dst src");
3888 
3889 	cmd->opcode = O_MACADDR2;
3890 	cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3891 	CHECK_CMDLEN;
3892 
3893 	mac = (ipfw_insn_mac *)cmd;
3894 	get_mac_addr_mask(av[0], mac->addr, mac->mask);	/* dst */
3895 	get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
3896 	    &(mac->mask[ETHER_ADDR_LEN])); /* src */
3897 	return cmd;
3898 }
3899 
3900 static ipfw_insn *
add_mactype(ipfw_insn * cmd,char * av,int cblen)3901 add_mactype(ipfw_insn *cmd, char *av, int cblen)
3902 {
3903 	if (!av)
3904 		errx(EX_DATAERR, "missing MAC type");
3905 	if (strcmp(av, "any") != 0) { /* we have a non-null type */
3906 		fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
3907 		    cblen);
3908 		cmd->opcode = O_MAC_TYPE;
3909 		return cmd;
3910 	} else
3911 		return NULL;
3912 }
3913 
3914 static ipfw_insn *
add_proto0(ipfw_insn * cmd,char * av,u_char * protop)3915 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
3916 {
3917 	struct protoent *pe;
3918 	char *ep;
3919 	int proto;
3920 
3921 	proto = strtol(av, &ep, 10);
3922 	if (*ep != '\0' || proto <= 0) {
3923 		if ((pe = getprotobyname(av)) == NULL)
3924 			return NULL;
3925 		proto = pe->p_proto;
3926 	}
3927 
3928 	fill_cmd(cmd, O_PROTO, 0, proto);
3929 	*protop = proto;
3930 	return cmd;
3931 }
3932 
3933 static ipfw_insn *
add_proto(ipfw_insn * cmd,char * av,u_char * protop)3934 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
3935 {
3936 	u_char proto = IPPROTO_IP;
3937 
3938 	if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3939 		; /* do not set O_IP4 nor O_IP6 */
3940 	else if (strcmp(av, "ip4") == 0)
3941 		/* explicit "just IPv4" rule */
3942 		fill_cmd(cmd, O_IP4, 0, 0);
3943 	else if (strcmp(av, "ip6") == 0) {
3944 		/* explicit "just IPv6" rule */
3945 		proto = IPPROTO_IPV6;
3946 		fill_cmd(cmd, O_IP6, 0, 0);
3947 	} else
3948 		return add_proto0(cmd, av, protop);
3949 
3950 	*protop = proto;
3951 	return cmd;
3952 }
3953 
3954 static ipfw_insn *
add_proto_compat(ipfw_insn * cmd,char * av,u_char * protop)3955 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
3956 {
3957 	u_char proto = IPPROTO_IP;
3958 
3959 	if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3960 		; /* do not set O_IP4 nor O_IP6 */
3961 	else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3962 		/* explicit "just IPv4" rule */
3963 		fill_cmd(cmd, O_IP4, 0, 0);
3964 	else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3965 		/* explicit "just IPv6" rule */
3966 		proto = IPPROTO_IPV6;
3967 		fill_cmd(cmd, O_IP6, 0, 0);
3968 	} else
3969 		return add_proto0(cmd, av, protop);
3970 
3971 	*protop = proto;
3972 	return cmd;
3973 }
3974 
3975 static ipfw_insn *
add_srcip(ipfw_insn * cmd,char * av,int cblen,struct tidx * tstate)3976 add_srcip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3977 {
3978 	fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3979 	if (cmd->opcode == O_IP_DST_SET)			/* set */
3980 		cmd->opcode = O_IP_SRC_SET;
3981 	else if (cmd->opcode == O_IP_DST_LOOKUP)		/* table */
3982 		cmd->opcode = O_IP_SRC_LOOKUP;
3983 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))		/* me */
3984 		cmd->opcode = O_IP_SRC_ME;
3985 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))	/* one IP */
3986 		cmd->opcode = O_IP_SRC;
3987 	else							/* addr/mask */
3988 		cmd->opcode = O_IP_SRC_MASK;
3989 	return cmd;
3990 }
3991 
3992 static ipfw_insn *
add_dstip(ipfw_insn * cmd,char * av,int cblen,struct tidx * tstate)3993 add_dstip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3994 {
3995 	fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3996 	if (cmd->opcode == O_IP_DST_SET)			/* set */
3997 		;
3998 	else if (cmd->opcode == O_IP_DST_LOOKUP)		/* table */
3999 		;
4000 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))		/* me */
4001 		cmd->opcode = O_IP_DST_ME;
4002 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))	/* one IP */
4003 		cmd->opcode = O_IP_DST;
4004 	else							/* addr/mask */
4005 		cmd->opcode = O_IP_DST_MASK;
4006 	return cmd;
4007 }
4008 
4009 static ipfw_insn *
add_srcmac(ipfw_insn * cmd,char * av,struct tidx * tstate)4010 add_srcmac(ipfw_insn *cmd, char *av, struct tidx *tstate)
4011 {
4012 
4013 	if (strncmp(av, "table(", 6) == 0)
4014 		fill_table(cmd, av, O_MAC_SRC_LOOKUP, tstate);
4015 	else
4016 		errx(EX_DATAERR, "only mac table lookup is supported %s", av);
4017 	return cmd;
4018 }
4019 
4020 static ipfw_insn *
add_dstmac(ipfw_insn * cmd,char * av,struct tidx * tstate)4021 add_dstmac(ipfw_insn *cmd, char *av, struct tidx *tstate)
4022 {
4023 
4024 	if (strncmp(av, "table(", 6) == 0)
4025 		fill_table(cmd, av, O_MAC_DST_LOOKUP, tstate);
4026 	else
4027 		errx(EX_DATAERR, "only mac table lookup is supported %s", av);
4028 	return cmd;
4029 }
4030 
4031 
4032 static struct _s_x f_reserved_keywords[] = {
4033 	{ "altq",	TOK_OR },
4034 	{ "//",		TOK_OR },
4035 	{ "diverted",	TOK_OR },
4036 	{ "dst-port",	TOK_OR },
4037 	{ "src-port",	TOK_OR },
4038 	{ "established",	TOK_OR },
4039 	{ "keep-state",	TOK_OR },
4040 	{ "frag",	TOK_OR },
4041 	{ "icmptypes",	TOK_OR },
4042 	{ "in",		TOK_OR },
4043 	{ "out",	TOK_OR },
4044 	{ "ip6",	TOK_OR },
4045 	{ "any",	TOK_OR },
4046 	{ "to",		TOK_OR },
4047 	{ "via",	TOK_OR },
4048 	{ "{",		TOK_OR },
4049 	{ "lookup",	TOK_OR },
4050 	{ "tagged",	TOK_OR },
4051 	{ NULL, 0 }	/* terminator */
4052 };
4053 
4054 static ipfw_insn *
add_ports(ipfw_insn * cmd,char * av,u_char proto,int opcode,int cblen)4055 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
4056 {
4057 
4058 	if (match_token(f_reserved_keywords, av) != -1)
4059 		return (NULL);
4060 
4061 	if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
4062 		/* XXX todo: check that we have a protocol with ports */
4063 		cmd->opcode = opcode;
4064 		return cmd;
4065 	}
4066 	return NULL;
4067 }
4068 
4069 static ipfw_insn *
add_src(ipfw_insn * cmd,char * av,u_char proto,int cblen,struct tidx * tstate)4070 add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
4071 {
4072 	struct in6_addr a;
4073 	char *host, *ch, buf[INET6_ADDRSTRLEN];
4074 	ipfw_insn *ret = NULL;
4075 	size_t len;
4076 
4077 	/* Copy first address in set if needed */
4078 	if ((ch = strpbrk(av, "/,")) != NULL) {
4079 		len = ch - av;
4080 		strlcpy(buf, av, sizeof(buf));
4081 		if (len < sizeof(buf))
4082 			buf[len] = '\0';
4083 		host = buf;
4084 	} else
4085 		host = av;
4086 
4087 	if (proto == IPPROTO_IPV6  || strcmp(av, "me6") == 0 ||
4088 	    inet_pton(AF_INET6, host, &a) == 1)
4089 		ret = add_srcip6(cmd, av, cblen, tstate);
4090 	/* XXX: should check for IPv4, not !IPv6 */
4091 	if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
4092 	    inet_pton(AF_INET6, host, &a) != 1))
4093 		ret = add_srcip(cmd, av, cblen, tstate);
4094 	if (ret == NULL && strcmp(av, "any") != 0)
4095 		ret = cmd;
4096 
4097 	return ret;
4098 }
4099 
4100 static ipfw_insn *
add_dst(ipfw_insn * cmd,char * av,u_char proto,int cblen,struct tidx * tstate)4101 add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
4102 {
4103 	struct in6_addr a;
4104 	char *host, *ch, buf[INET6_ADDRSTRLEN];
4105 	ipfw_insn *ret = NULL;
4106 	size_t len;
4107 
4108 	/* Copy first address in set if needed */
4109 	if ((ch = strpbrk(av, "/,")) != NULL) {
4110 		len = ch - av;
4111 		strlcpy(buf, av, sizeof(buf));
4112 		if (len < sizeof(buf))
4113 			buf[len] = '\0';
4114 		host = buf;
4115 	} else
4116 		host = av;
4117 
4118 	if (proto == IPPROTO_IPV6  || strcmp(av, "me6") == 0 ||
4119 	    inet_pton(AF_INET6, host, &a) == 1)
4120 		ret = add_dstip6(cmd, av, cblen, tstate);
4121 	/* XXX: should check for IPv4, not !IPv6 */
4122 	if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
4123 	    inet_pton(AF_INET6, host, &a) != 1))
4124 		ret = add_dstip(cmd, av, cblen, tstate);
4125 	if (ret == NULL && strcmp(av, "any") != 0)
4126 		ret = cmd;
4127 
4128 	return ret;
4129 }
4130 
4131 static uint16_t
parse_logdst(char * logdst_iter)4132 parse_logdst(char *logdst_iter)
4133 {
4134 	char *token;
4135 	uint16_t ret;
4136 
4137 	ret = IPFW_LOG_DEFAULT;
4138 	while ((token = strsep(&logdst_iter, ",")) != NULL) {
4139 		if (_substrcmp(token, "syslog") == 0) {
4140 			ret |= IPFW_LOG_SYSLOG;
4141 			continue;
4142 		}
4143 		/* ipfw0 is compatibility keyword. */
4144 		if (_substrcmp(token, "bpf") == 0 ||
4145 		    _substrcmp(token, "ipfw0") == 0) {
4146 			ret |= IPFW_LOG_IPFW0;
4147 			continue;
4148 		}
4149 		if (_substrcmp(token, "rtsock") == 0) {
4150 			ret |= IPFW_LOG_RTSOCK;
4151 			continue;
4152 		}
4153 		errx(EX_DATAERR,
4154 		    "unsupported logdst token");
4155 	}
4156 	return (ret);
4157 }
4158 
4159 static inline uint32_t
arg_or_targ_relaxed(const char * arg,const char * action,uint32_t maxarg)4160 arg_or_targ_relaxed(const char *arg, const char *action, uint32_t maxarg)
4161 {
4162 	uint32_t arg1 = (uint32_t)(-1);
4163 
4164 	if (arg == NULL)
4165 		errx(EX_USAGE, "missing argument for %s", action);
4166 	if (isdigit(arg[0])) {
4167 		arg1 = strtoul(arg, NULL, 10);
4168 		if (arg1 < IPFW_ARG_MIN || arg1 > maxarg)
4169 			errx(EX_DATAERR, "illegal argument %s(%u) for %s",
4170 			    arg, arg1, action);
4171 	} else if (_substrcmp(arg, "tablearg") == 0)
4172 		arg1 = IP_FW_TARG;
4173 	return (arg1);
4174 }
4175 
4176 static inline uint32_t
arg_or_targ(const char * arg,const char * action)4177 arg_or_targ(const char *arg, const char *action)
4178 {
4179 	uint32_t arg1 = arg_or_targ_relaxed(arg, action, IPFW_ARG_MAX);
4180 
4181 	if (arg1 == (uint32_t)(-1))
4182 		errx(EX_DATAERR, "illegal argument %s(%u) for %s",
4183 		    arg, arg1, action);
4184 	return (arg1);
4185 }
4186 
4187 static uint16_t
get_divert_port(const char * arg,const char * action)4188 get_divert_port(const char *arg, const char *action)
4189 {
4190 	uint32_t arg1 = arg_or_targ_relaxed(arg, action, IPFW_ARG_MAX);
4191 
4192 	if (arg1 != (uint32_t)(-1))
4193 		return (arg1);
4194 
4195 	struct servent *s;
4196 	setservent(1);
4197 	s = getservbyname(arg, "divert");
4198 	if (s == NULL)
4199 		errx(EX_DATAERR, "illegal divert/tee port");
4200 	return (ntohs(s->s_port));
4201 }
4202 
4203 static void
get_lookup_bitmask(int ltype,ipfw_insn_lookup * cmd,const char * src)4204 get_lookup_bitmask(int ltype, ipfw_insn_lookup *cmd, const char *src)
4205 {
4206 	struct ether_addr *mac;
4207 	const char *macset = "0123456789abcdefABCDEF:";
4208 
4209 	if (ltype == LOOKUP_SRC_IP6 || ltype == LOOKUP_DST_IP6) {
4210 		if (inet_pton(AF_INET6, src, &cmd->ip6) != 1)
4211 			errx(EX_USAGE, "invalid IPv6 mask provided");
4212 		return;
4213 	} else if (ltype == LOOKUP_SRC_MAC || ltype == LOOKUP_DST_MAC) {
4214 		if (strspn(src, macset) != strlen(src) ||
4215 		    (mac = ether_aton(src)) == NULL)
4216 			errx(EX_DATAERR, "Incorrect MAC address");
4217 
4218 		bcopy(mac, cmd->mac, ETHER_ADDR_LEN);
4219 		return;
4220 	/* mask in a dotted-quad notation */
4221 	} else if (strchr(src, '.') != NULL) {
4222 		if (inet_aton(src, &cmd->ip4) != 1)
4223 			errx(EX_USAGE, "invalid dotted-quad mask provided");
4224 		switch (ltype) {
4225 		case LOOKUP_SRC_IP4:
4226 		case LOOKUP_DST_IP4:
4227 			return;
4228 		}
4229 		cmd->u32 = ntohl(cmd->u32);
4230 		return;
4231 	}
4232 	cmd->u32 = strtoul(src, NULL, 0);
4233 }
4234 
4235 /*
4236  * Parse arguments and assemble the microinstructions which make up a rule.
4237  * Rules are added into the 'rulebuf' and then copied in the correct order
4238  * into the actual rule.
4239  *
4240  * The syntax for a rule starts with the action, followed by
4241  * optional action parameters, and the various match patterns.
4242  * In the assembled microcode, the first opcode must be an O_PROBE_STATE
4243  * (generated if the rule includes a keep-state option), then the
4244  * various match patterns, log/altq actions, and the actual action.
4245  *
4246  */
4247 static void
compile_rule(char * av[],uint32_t * rbuf,int * rbufsize,struct tidx * tstate)4248 compile_rule(char *av[], uint32_t *rbuf, int *rbufsize, struct tidx *tstate)
4249 {
4250 	/*
4251 	 * rules are added into the 'rulebuf' and then copied in
4252 	 * the correct order into the actual rule.
4253 	 * Some things that need to go out of order (prob, action etc.)
4254 	 * go into actbuf[].
4255 	 */
4256 	static uint32_t actbuf[255], cmdbuf[255];
4257 	int rblen, ablen, cblen;
4258 
4259 	ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
4260 	ipfw_insn *first_cmd;	/* first match pattern */
4261 
4262 	struct ip_fw_rule *rule;
4263 
4264 	/*
4265 	 * various flags used to record that we entered some fields.
4266 	 */
4267 	ipfw_insn *have_state = NULL;	/* any state-related option */
4268 	int have_rstate = 0;
4269 	ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
4270 	ipfw_insn *have_skipcmd = NULL;
4271 	size_t len;
4272 
4273 	int i;
4274 
4275 	int open_par = 0;	/* open parenthesis ( */
4276 
4277 	/* proto is here because it is used to fetch ports */
4278 	u_char proto = IPPROTO_IP;	/* default protocol */
4279 
4280 	double match_prob = 1; /* match probability, default is always match */
4281 
4282 	bzero(actbuf, sizeof(actbuf));		/* actions go here */
4283 	bzero(cmdbuf, sizeof(cmdbuf));
4284 	bzero(rbuf, *rbufsize);
4285 
4286 	rule = (struct ip_fw_rule *)rbuf;
4287 	cmd = (ipfw_insn *)cmdbuf;
4288 	action = (ipfw_insn *)actbuf;
4289 
4290 	rblen = *rbufsize / sizeof(uint32_t);
4291 	rblen -= sizeof(struct ip_fw_rule) / sizeof(uint32_t);
4292 	ablen = nitems(actbuf);
4293 	cblen = nitems(cmdbuf);
4294 	cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
4295 
4296 #define	CHECK_RBUFLEN(len)	{ CHECK_LENGTH(rblen, len); rblen -= len; }
4297 #define	CHECK_ACTLEN		CHECK_LENGTH(ablen, action->len)
4298 
4299 	av++;
4300 
4301 	/* [rule N]	-- Rule number optional */
4302 	if (av[0] && isdigit(**av)) {
4303 		rule->rulenum = atoi(*av);
4304 		av++;
4305 	}
4306 
4307 	/* [set N]	-- set number (0..RESVD_SET), optional */
4308 	if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
4309 		int set = strtoul(av[1], NULL, 10);
4310 		if (set < 0 || set > RESVD_SET)
4311 			errx(EX_DATAERR, "illegal set %s", av[1]);
4312 		rule->set = set;
4313 		tstate->set = set;
4314 		av += 2;
4315 	}
4316 
4317 	/* [prob D]	-- match probability, optional */
4318 	if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
4319 		match_prob = strtod(av[1], NULL);
4320 
4321 		if (match_prob <= 0 || match_prob > 1)
4322 			errx(EX_DATAERR, "illegal match prob. %s", av[1]);
4323 		av += 2;
4324 	}
4325 
4326 	/* action	-- mandatory */
4327 	NEED1("missing action");
4328 	i = match_token(rule_actions, *av);
4329 	av++;
4330 	action->len = 1;	/* default */
4331 	CHECK_ACTLEN;
4332 	switch(i) {
4333 	case TOK_CHECKSTATE:
4334 		have_state = action;
4335 		action->opcode = O_CHECK_STATE;
4336 		action->len = F_INSN_SIZE(ipfw_insn_kidx);
4337 		CHECK_ACTLEN;
4338 		if (*av == NULL ||
4339 		    match_token(rule_options, *av) == TOK_COMMENT) {
4340 			insntod(have_state, kidx)->kidx = pack_object(tstate,
4341 			    default_state_name, IPFW_TLV_STATE_NAME);
4342 			break;
4343 		}
4344 		if (*av[0] == ':') {
4345 			if (strcmp(*av + 1, "any") == 0)
4346 				insntod(have_state, kidx)->kidx = 0;
4347 			else if (state_check_name(*av + 1) == 0)
4348 				insntod(have_state, kidx)->kidx = pack_object(
4349 				    tstate, *av + 1, IPFW_TLV_STATE_NAME);
4350 			else
4351 				errx(EX_DATAERR, "Invalid state name %s",
4352 				    *av);
4353 			av++;
4354 			break;
4355 		}
4356 		errx(EX_DATAERR, "Invalid state name %s", *av);
4357 		break;
4358 
4359 	case TOK_ABORT:
4360 		action->opcode = O_REJECT;
4361 		action->arg1 = ICMP_REJECT_ABORT;
4362 		break;
4363 
4364 	case TOK_ABORT6:
4365 		action->opcode = O_UNREACH6;
4366 		action->arg1 = ICMP6_UNREACH_ABORT;
4367 		break;
4368 
4369 	case TOK_ACCEPT:
4370 		action->opcode = O_ACCEPT;
4371 		break;
4372 
4373 	case TOK_DENY:
4374 		action->opcode = O_DENY;
4375 		action->arg1 = 0;
4376 		break;
4377 
4378 	case TOK_REJECT:
4379 		action->opcode = O_REJECT;
4380 		action->arg1 = ICMP_UNREACH_HOST;
4381 		break;
4382 
4383 	case TOK_RESET:
4384 		action->opcode = O_REJECT;
4385 		action->arg1 = ICMP_REJECT_RST;
4386 		break;
4387 
4388 	case TOK_RESET6:
4389 		action->opcode = O_UNREACH6;
4390 		action->arg1 = ICMP6_UNREACH_RST;
4391 		break;
4392 
4393 	case TOK_UNREACH:
4394 		action->opcode = O_REJECT;
4395 		NEED1("missing reject code");
4396 		action->arg1 = get_reject_code(*av);
4397 		av++;
4398 		if (action->arg1 == ICMP_UNREACH_NEEDFRAG && isdigit(**av)) {
4399 			uint16_t mtu;
4400 
4401 			mtu = strtoul(*av, NULL, 10);
4402 			if (mtu < 68 || mtu >= IP_MAXPACKET)
4403 				errx(EX_DATAERR, "illegal argument for %s",
4404 				    *(av - 1));
4405 			action->len = F_INSN_SIZE(ipfw_insn_u16);
4406 			insntod(action, u16)->ports[0] = mtu;
4407 			av++;
4408 		}
4409 		break;
4410 
4411 	case TOK_UNREACH6:
4412 		action->opcode = O_UNREACH6;
4413 		NEED1("missing unreach code");
4414 		action->arg1 = get_unreach6_code(*av);
4415 		av++;
4416 		break;
4417 
4418 	case TOK_COUNT:
4419 		action->opcode = O_COUNT;
4420 		break;
4421 
4422 	case TOK_NAT:
4423 		action->opcode = O_NAT;
4424 		action->len = F_INSN_SIZE(ipfw_insn_nat);
4425 		CHECK_ACTLEN;
4426 		if (*av != NULL && _substrcmp(*av, "global") == 0)
4427 			action->arg1 = IP_FW_NAT44_GLOBAL;
4428 		else
4429 			action->arg1 = arg_or_targ(av[0], *(av - 1));
4430 		av++;
4431 		break;
4432 	case TOK_QUEUE:
4433 		action->opcode = O_QUEUE;
4434 		action->arg1 = arg_or_targ(av[0], *(av - 1));
4435 		av++;
4436 		break;
4437 	case TOK_PIPE:
4438 		action->opcode = O_PIPE;
4439 		action->arg1 = arg_or_targ(av[0], *(av - 1));
4440 		av++;
4441 		break;
4442 	case TOK_SKIPTO:
4443 		action->opcode = O_SKIPTO;
4444 		action->len = F_INSN_SIZE(ipfw_insn_u32);
4445 		CHECK_ACTLEN;
4446 		insntod(action, u32)->d[0] =
4447 		    arg_or_targ_relaxed(av[0], *(av - 1), IPFW_DEFAULT_RULE);
4448 		av++;
4449 		break;
4450 	case TOK_NETGRAPH:
4451 		action->opcode = O_NETGRAPH;
4452 		action->arg1 = arg_or_targ(av[0], *(av - 1));
4453 		av++;
4454 		break;
4455 	case TOK_NGTEE:
4456 		action->opcode = O_NGTEE;
4457 		action->arg1 = arg_or_targ(av[0], *(av - 1));
4458 		av++;
4459 		break;
4460 	case TOK_DIVERT:
4461 		action->opcode = O_DIVERT;
4462 		action->arg1 = get_divert_port(av[0], *(av - 1));
4463 		av++;
4464 		break;
4465 	case TOK_TEE:
4466 		action->opcode = O_TEE;
4467 		action->arg1 = get_divert_port(av[0], *(av - 1));
4468 		av++;
4469 		break;
4470 	case TOK_CALL:
4471 		action->opcode = O_CALLRETURN;
4472 		action->len = F_INSN_SIZE(ipfw_insn_u32);
4473 		CHECK_ACTLEN;
4474 		insntod(action, u32)->d[0] =
4475 		    arg_or_targ_relaxed(av[0], *(av - 1), IPFW_DEFAULT_RULE);
4476 		av++;
4477 		break;
4478 
4479 	case TOK_FORWARD: {
4480 		/*
4481 		 * Locate the address-port separator (':' or ',').
4482 		 * Could be one of the following:
4483 		 *	hostname:port
4484 		 *	IPv4 a.b.c.d,port
4485 		 *	IPv4 a.b.c.d:port
4486 		 *	IPv6 w:x:y::z,port
4487 		 *	IPv6 [w:x:y::z]:port
4488 		 */
4489 		struct sockaddr_storage result;
4490 		struct addrinfo *res;
4491 		char *s, *end;
4492 		int family;
4493 		u_short port_number = 0;
4494 
4495 		NEED1("missing forward address[:port]");
4496 
4497 		if (strncmp(*av, "tablearg", 8) == 0 &&
4498 		    ((*av)[8] == '\0' || (*av)[8] == ',' || (*av)[8] == ':'))
4499 			memcpy(++(*av), "0.0.0.0", 7);
4500 
4501 		/*
4502 		 * Are we an bracket-enclosed IPv6 address?
4503 		 */
4504 		if (strchr(*av, '['))
4505 			(*av)++;
4506 
4507 		/*
4508 		 * locate the address-port separator (':' or ',')
4509 		 */
4510 		s = strchr(*av, ',');
4511 		if (s == NULL) {
4512 			s = strchr(*av, ']');
4513 			/* Prevent erroneous parsing on brackets. */
4514 			if (s != NULL)
4515 				*(s++) = '\0';
4516 			else
4517 				s = *av;
4518 
4519 			/* Distinguish between IPv4:port and IPv6 cases. */
4520 			s = strchr(s, ':');
4521 			if (s && strchr(s+1, ':'))
4522 				s = NULL; /* no port */
4523 		}
4524 
4525 		if (s != NULL) {
4526 			/* Terminate host portion and set s to start of port. */
4527 			*(s++) = '\0';
4528 			i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
4529 			if (s == end)
4530 				errx(EX_DATAERR,
4531 				    "illegal forwarding port ``%s''", s);
4532 			port_number = (u_short)i;
4533 		}
4534 
4535 		/*
4536 		 * Resolve the host name or address to a family and a
4537 		 * network representation of the address.
4538 		 */
4539 		if (getaddrinfo(*av, NULL, NULL, &res))
4540 			errx(EX_DATAERR, NULL);
4541 		/* Just use the first host in the answer. */
4542 		family = res->ai_family;
4543 		memcpy(&result, res->ai_addr, res->ai_addrlen);
4544 		freeaddrinfo(res);
4545 
4546  		if (family == PF_INET) {
4547 			ipfw_insn_sa *p = (ipfw_insn_sa *)action;
4548 
4549 			action->opcode = O_FORWARD_IP;
4550 			action->len = F_INSN_SIZE(ipfw_insn_sa);
4551 			CHECK_ACTLEN;
4552 
4553 			/*
4554 			 * In the kernel we assume AF_INET and use only
4555 			 * sin_port and sin_addr. Remember to set sin_len as
4556 			 * the routing code seems to use it too.
4557 			 */
4558 			p->sa.sin_len = sizeof(struct sockaddr_in);
4559 			p->sa.sin_family = AF_INET;
4560 			p->sa.sin_port = port_number;
4561 			p->sa.sin_addr.s_addr =
4562 			     ((struct sockaddr_in *)&result)->sin_addr.s_addr;
4563 		} else if (family == PF_INET6) {
4564 			ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
4565 
4566 			action->opcode = O_FORWARD_IP6;
4567 			action->len = F_INSN_SIZE(ipfw_insn_sa6);
4568 			CHECK_ACTLEN;
4569 
4570 			p->sa.sin6_len = sizeof(struct sockaddr_in6);
4571 			p->sa.sin6_family = AF_INET6;
4572 			p->sa.sin6_port = port_number;
4573 			p->sa.sin6_flowinfo = 0;
4574 			p->sa.sin6_scope_id =
4575 			    ((struct sockaddr_in6 *)&result)->sin6_scope_id;
4576 			bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
4577 			    &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
4578 		} else {
4579 			errx(EX_DATAERR, "Invalid address family in forward action");
4580 		}
4581 		av++;
4582 		break;
4583 	    }
4584 	case TOK_COMMENT:
4585 		/* pretend it is a 'count' rule followed by the comment */
4586 		action->opcode = O_COUNT;
4587 		av--;		/* go back... */
4588 		break;
4589 
4590 	case TOK_SETFIB:
4591 	    {
4592 		int numfibs;
4593 		size_t intsize = sizeof(int);
4594 
4595 		action->opcode = O_SETFIB;
4596 		NEED1("missing fib number");
4597 		if (_substrcmp(*av, "tablearg") == 0) {
4598 			action->arg1 = IP_FW_TARG;
4599 		} else {
4600 		        action->arg1 = strtoul(*av, NULL, 10);
4601 			if (sysctlbyname("net.fibs", &numfibs, &intsize,
4602 			    NULL, 0) == -1)
4603 				errx(EX_DATAERR, "fibs not supported.\n");
4604 			if (action->arg1 >= numfibs)  /* Temporary */
4605 				errx(EX_DATAERR, "fib too large.\n");
4606 			/* Add high-order bit to fib to make room for tablearg*/
4607 			action->arg1 |= 0x8000;
4608 		}
4609 		av++;
4610 		break;
4611 	    }
4612 
4613 	case TOK_SETDSCP:
4614 	    {
4615 		int code;
4616 
4617 		action->opcode = O_SETDSCP;
4618 		NEED1("missing DSCP code");
4619 		if (_substrcmp(*av, "tablearg") == 0) {
4620 			action->arg1 = IP_FW_TARG;
4621 		} else {
4622 			if (isalpha(*av[0])) {
4623 				if ((code = match_token(f_ipdscp, *av)) == -1)
4624 					errx(EX_DATAERR, "Unknown DSCP code");
4625 				action->arg1 = code;
4626 			} else
4627 			        action->arg1 = strtoul(*av, NULL, 10);
4628 			/*
4629 			 * Add high-order bit to DSCP to make room
4630 			 * for tablearg
4631 			 */
4632 			action->arg1 |= 0x8000;
4633 		}
4634 		av++;
4635 		break;
4636 	    }
4637 
4638 	case TOK_REASS:
4639 		action->opcode = O_REASS;
4640 		break;
4641 
4642 	case TOK_RETURN:
4643 		action->opcode = O_CALLRETURN;
4644 		action->len = F_INSN_SIZE(ipfw_insn_u32) | F_NOT;
4645 		CHECK_ACTLEN;
4646 		if (*av != NULL) {
4647 			/*
4648 			 * Return type is optional.
4649 			 * By default we use RETURN_NEXT_RULENUM.
4650 			 */
4651 			i = match_token(return_types, *av);
4652 			if (i >= 0) {
4653 				action->arg1 = i;
4654 				av++;
4655 			} else
4656 				action->arg1 = RETURN_NEXT_RULENUM;
4657 		}
4658 		break;
4659 
4660 	case TOK_SETMARK: {
4661 		action->opcode = O_SETMARK;
4662 		action->len = F_INSN_SIZE(ipfw_insn_u32);
4663 		NEED1("missing mark");
4664 		if (strcmp(*av, "tablearg") == 0) {
4665 			action->arg1 = IP_FW_TARG;
4666 		} else {
4667 		        insntod(action, u32)->d[0] = strtoul(*av, NULL, 0);
4668 			/* This is not a tablearg */
4669 			action->arg1 |= 0x8000;
4670 		}
4671 		av++;
4672 		CHECK_CMDLEN;
4673 		break;
4674 	}
4675 
4676 	case TOK_TCPSETMSS: {
4677 		u_long mss;
4678 		uint32_t idx;
4679 
4680 		idx = pack_object(tstate, "tcp-setmss", IPFW_TLV_EACTION);
4681 		if (idx == 0)
4682 			errx(EX_DATAERR, "pack_object failed");
4683 		action->opcode = O_EXTERNAL_ACTION;
4684 		action->len = F_INSN_SIZE(ipfw_insn_kidx);
4685 		CHECK_ACTLEN;
4686 		insntod(action, kidx)->kidx = idx;
4687 
4688 		NEED1("Missing MSS value");
4689 		action = next_cmd(action, &ablen);
4690 		action->len = 1;
4691 		CHECK_ACTLEN;
4692 		mss = strtoul(*av, NULL, 10);
4693 		if (mss == 0 || mss > UINT16_MAX)
4694 			errx(EX_USAGE, "invalid MSS value %s", *av);
4695 		fill_cmd(action, O_EXTERNAL_DATA, 0, (uint16_t)mss);
4696 		av++;
4697 		break;
4698 	}
4699 
4700 	default:
4701 		av--;
4702 		if (match_token(rule_eactions, *av) == -1)
4703 			errx(EX_DATAERR, "invalid action %s\n", *av);
4704 		/*
4705 		 * External actions support.
4706 		 * XXX: we support only syntax with instance name.
4707 		 *	For known external actions (from rule_eactions list)
4708 		 *	we can handle syntax directly. But with `eaction'
4709 		 *	keyword we can use only `eaction <name> <instance>'
4710 		 *	syntax.
4711 		 */
4712 	case TOK_EACTION: {
4713 		uint32_t idx;
4714 
4715 		NEED1("Missing eaction name");
4716 		if (eaction_check_name(*av) != 0)
4717 			errx(EX_DATAERR, "Invalid eaction name %s", *av);
4718 		idx = pack_object(tstate, *av, IPFW_TLV_EACTION);
4719 		if (idx == 0)
4720 			errx(EX_DATAERR, "pack_object failed");
4721 		action->opcode = O_EXTERNAL_ACTION;
4722 		action->len = F_INSN_SIZE(ipfw_insn_kidx);
4723 		CHECK_ACTLEN;
4724 		insntod(action, kidx)->kidx = idx;
4725 
4726 		av++;
4727 		NEED1("Missing eaction instance name");
4728 		if (eaction_check_name(*av) != 0)
4729 			errx(EX_DATAERR, "Invalid eaction instance name %s",
4730 			    *av);
4731 		/*
4732 		 * External action instance object has TLV type depended
4733 		 * from the external action name object index. Since we
4734 		 * currently don't know this index, use zero as TLV type.
4735 		 */
4736 		idx = pack_object(tstate, *av, 0);
4737 		if (idx == 0)
4738 			errx(EX_DATAERR, "pack_object failed");
4739 		action = next_cmd(action, &ablen);
4740 		action->opcode = O_EXTERNAL_INSTANCE;
4741 		action->len = F_INSN_SIZE(ipfw_insn_kidx);
4742 		CHECK_ACTLEN;
4743 		insntod(action, kidx)->kidx = idx;
4744 		av++;
4745 		}
4746 	}
4747 	action = next_cmd(action, &ablen);
4748 
4749 	/*
4750 	 * [altq queuename] -- altq tag, optional
4751 	 * [log [logamount N]]	-- log, optional
4752 	 *
4753 	 * If they exist, it go first in the cmdbuf, but then it is
4754 	 * skipped in the copy section to the end of the buffer.
4755 	 */
4756 	while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
4757 		av++;
4758 		switch (i) {
4759 		case TOK_LOG:
4760 		    {
4761 			ipfw_insn_log *c = (ipfw_insn_log *)cmd;
4762 			int l;
4763 
4764 			if (have_log)
4765 				errx(EX_DATAERR,
4766 				    "log cannot be specified more than once");
4767 			have_log = (ipfw_insn *)c;
4768 			cmd->len = F_INSN_SIZE(ipfw_insn_log);
4769 			CHECK_CMDLEN;
4770 			cmd->opcode = O_LOG;
4771 			cmd->arg1 = IPFW_LOG_DEFAULT;
4772 			/* logdst before logamount */
4773 			if (av[0] && _substrcmp(*av, "logdst") == 0) {
4774 				av++;
4775 				NEED1("logdst requires argument");
4776 				cmd->arg1 = parse_logdst(*av);
4777 				av++;
4778 			}
4779 
4780 			if (av[0] && _substrcmp(*av, "logamount") == 0) {
4781 				av++;
4782 				NEED1("logamount requires argument");
4783 				l = atoi(*av);
4784 				if (l < 0)
4785 					errx(EX_DATAERR,
4786 					    "logamount must be positive");
4787 				c->max_log = l;
4788 				av++;
4789 			} else {
4790 				len = sizeof(c->max_log);
4791 				if (sysctlbyname("net.inet.ip.fw.verbose_limit",
4792 				    &c->max_log, &len, NULL, 0) == -1) {
4793 					if (g_co.test_only) {
4794 						c->max_log = 0;
4795 						break;
4796 					}
4797 					errx(1, "sysctlbyname(\"%s\")",
4798 					    "net.inet.ip.fw.verbose_limit");
4799 				}
4800 			}
4801 
4802 			/* logdst after logamount */
4803 			if (av[0] && _substrcmp(*av, "logdst") == 0) {
4804 				av++;
4805 				NEED1("logdst requires argument");
4806 				cmd->arg1 = parse_logdst(*av);
4807 				av++;
4808 			}
4809 		    }
4810 			break;
4811 
4812 #ifndef NO_ALTQ
4813 		case TOK_ALTQ:
4814 		    {
4815 			ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
4816 
4817 			NEED1("missing altq queue name");
4818 			if (have_altq)
4819 				errx(EX_DATAERR,
4820 				    "altq cannot be specified more than once");
4821 			have_altq = (ipfw_insn *)a;
4822 			cmd->len = F_INSN_SIZE(ipfw_insn_altq);
4823 			CHECK_CMDLEN;
4824 			cmd->opcode = O_ALTQ;
4825 			a->qid = altq_name_to_qid(*av);
4826 			av++;
4827 		    }
4828 			break;
4829 #endif
4830 
4831 		case TOK_TAG:
4832 		case TOK_UNTAG: {
4833 			uint16_t tag;
4834 
4835 			if (have_tag)
4836 				errx(EX_USAGE, "tag and untag cannot be "
4837 				    "specified more than once");
4838 			GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
4839 			   rule_action_params);
4840 			have_tag = cmd;
4841 			fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
4842 			av++;
4843 			break;
4844 		}
4845 
4846 		default:
4847 			abort();
4848 		}
4849 		cmd = next_cmd(cmd, &cblen);
4850 	}
4851 
4852 	if (have_state)	{ /* must be a check-state, we are done */
4853 		if (*av != NULL &&
4854 		    match_token(rule_options, *av) == TOK_COMMENT) {
4855 			/* check-state has a comment */
4856 			av++;
4857 			fill_comment(cmd, av, cblen);
4858 			cmd = next_cmd(cmd, &cblen);
4859 			av[0] = NULL;
4860 		}
4861 		goto done;
4862 	}
4863 
4864 #define OR_START(target)					\
4865 	if (av[0] && (*av[0] == '(' || *av[0] == '{')) { 	\
4866 		if (open_par)					\
4867 			errx(EX_USAGE, "nested \"(\" not allowed\n"); \
4868 		prev = NULL;					\
4869 		open_par = 1;					\
4870 		if ( (av[0])[1] == '\0') {			\
4871 			av++;					\
4872 		} else						\
4873 			(*av)++;				\
4874 	}							\
4875 	target:							\
4876 
4877 
4878 #define	CLOSE_PAR						\
4879 	if (open_par) {						\
4880 		if (av[0] && (					\
4881 		    strcmp(*av, ")") == 0 ||			\
4882 		    strcmp(*av, "}") == 0)) {			\
4883 			prev = NULL;				\
4884 			open_par = 0;				\
4885 			av++;					\
4886 		} else						\
4887 			errx(EX_USAGE, "missing \")\"\n");	\
4888 	}
4889 
4890 #define NOT_BLOCK						\
4891 	if (av[0] && _substrcmp(*av, "not") == 0) {		\
4892 		if (cmd->len & F_NOT)				\
4893 			errx(EX_USAGE, "double \"not\" not allowed\n"); \
4894 		cmd->len |= F_NOT;				\
4895 		av++;						\
4896 	}
4897 
4898 #define OR_BLOCK(target)					\
4899 	if (av[0] && _substrcmp(*av, "or") == 0) {		\
4900 		if (prev == NULL || open_par == 0)		\
4901 			errx(EX_DATAERR, "invalid OR block");	\
4902 		prev->len |= F_OR;				\
4903 		av++;					\
4904 		goto target;					\
4905 	}							\
4906 	CLOSE_PAR;
4907 
4908 	first_cmd = cmd;
4909 
4910 #if 0
4911 	/*
4912 	 * MAC addresses, optional.
4913 	 * If we have this, we skip the part "proto from src to dst"
4914 	 * and jump straight to the option parsing.
4915 	 */
4916 	NOT_BLOCK;
4917 	NEED1("missing protocol");
4918 	if (_substrcmp(*av, "MAC") == 0 ||
4919 	    _substrcmp(*av, "mac") == 0) {
4920 		av++;			/* the "MAC" keyword */
4921 		add_mac(cmd, av);	/* exits in case of errors */
4922 		cmd = next_cmd(cmd);
4923 		av += 2;		/* dst-mac and src-mac */
4924 		NOT_BLOCK;
4925 		NEED1("missing mac type");
4926 		if (add_mactype(cmd, av[0]))
4927 			cmd = next_cmd(cmd);
4928 		av++;			/* any or mac-type */
4929 		goto read_options;
4930 	}
4931 #endif
4932 
4933 	/*
4934 	 * protocol, mandatory
4935 	 */
4936     OR_START(get_proto);
4937 	NOT_BLOCK;
4938 	NEED1("missing protocol");
4939 	if (add_proto_compat(cmd, *av, &proto)) {
4940 		av++;
4941 		if (F_LEN(cmd) != 0) {
4942 			prev = cmd;
4943 			cmd = next_cmd(cmd, &cblen);
4944 		}
4945 	} else if (first_cmd != cmd) {
4946 		errx(EX_DATAERR, "invalid protocol ``%s''", *av);
4947 	} else {
4948 		rule->flags |= IPFW_RULE_JUSTOPTS;
4949 		goto read_options;
4950 	}
4951     OR_BLOCK(get_proto);
4952 
4953 	first_cmd = cmd; /* update pointer to use in compact form */
4954 
4955 	/*
4956 	 * "from", mandatory
4957 	 */
4958 	if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
4959 		errx(EX_USAGE, "missing ``from''");
4960 	av++;
4961 
4962 	/*
4963 	 * source IP, mandatory
4964 	 */
4965     OR_START(source_ip);
4966 	NOT_BLOCK;	/* optional "not" */
4967 	NEED1("missing source address");
4968 	if (add_src(cmd, *av, proto, cblen, tstate)) {
4969 		av++;
4970 		if (F_LEN(cmd) != 0) {	/* ! any */
4971 			prev = cmd;
4972 			cmd = next_cmd(cmd, &cblen);
4973 		}
4974 	} else
4975 		errx(EX_USAGE, "bad source address %s", *av);
4976     OR_BLOCK(source_ip);
4977 
4978 	/*
4979 	 * source ports, optional
4980 	 */
4981 	NOT_BLOCK;	/* optional "not" */
4982 	if ( av[0] != NULL ) {
4983 		if (_substrcmp(*av, "any") == 0 ||
4984 		    add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4985 			av++;
4986 			if (F_LEN(cmd) != 0)
4987 				cmd = next_cmd(cmd, &cblen);
4988 		}
4989 	}
4990 
4991 	/*
4992 	 * "to", mandatory
4993 	 */
4994 	if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
4995 		errx(EX_USAGE, "missing ``to''");
4996 	av++;
4997 
4998 	/*
4999 	 * destination, mandatory
5000 	 */
5001     OR_START(dest_ip);
5002 	NOT_BLOCK;	/* optional "not" */
5003 	NEED1("missing dst address");
5004 	if (add_dst(cmd, *av, proto, cblen, tstate)) {
5005 		av++;
5006 		if (F_LEN(cmd) != 0) {	/* ! any */
5007 			prev = cmd;
5008 			cmd = next_cmd(cmd, &cblen);
5009 		}
5010 	} else
5011 		errx( EX_USAGE, "bad destination address %s", *av);
5012     OR_BLOCK(dest_ip);
5013 
5014 	/*
5015 	 * dest. ports, optional
5016 	 */
5017 	NOT_BLOCK;	/* optional "not" */
5018 	if (av[0]) {
5019 		if (_substrcmp(*av, "any") == 0 ||
5020 		    add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
5021 			av++;
5022 			if (F_LEN(cmd) != 0)
5023 				cmd = next_cmd(cmd, &cblen);
5024 		}
5025 	}
5026 	if (first_cmd == cmd)
5027 		rule->flags |= IPFW_RULE_NOOPT;
5028 
5029 read_options:
5030 	prev = NULL;
5031 	while ( av[0] != NULL ) {
5032 		char *s;
5033 		ipfw_insn_u32 *cmd32;	/* alias for cmd */
5034 
5035 		s = *av;
5036 		cmd32 = (ipfw_insn_u32 *)cmd;
5037 
5038 		if (*s == '!') {	/* alternate syntax for NOT */
5039 			if (cmd->len & F_NOT)
5040 				errx(EX_USAGE, "double \"not\" not allowed\n");
5041 			cmd->len = F_NOT;
5042 			s++;
5043 		}
5044 		i = match_token(rule_options, s);
5045 		av++;
5046 		switch(i) {
5047 		case TOK_NOT:
5048 			if (cmd->len & F_NOT)
5049 				errx(EX_USAGE, "double \"not\" not allowed\n");
5050 			cmd->len = F_NOT;
5051 			break;
5052 
5053 		case TOK_OR:
5054 			if (open_par == 0 || prev == NULL)
5055 				errx(EX_USAGE, "invalid \"or\" block\n");
5056 			prev->len |= F_OR;
5057 			break;
5058 
5059 		case TOK_STARTBRACE:
5060 			if (open_par)
5061 				errx(EX_USAGE, "+nested \"(\" not allowed\n");
5062 			open_par = 1;
5063 			break;
5064 
5065 		case TOK_ENDBRACE:
5066 			if (!open_par)
5067 				errx(EX_USAGE, "+missing \")\"\n");
5068 			open_par = 0;
5069 			prev = NULL;
5070 			break;
5071 
5072 		case TOK_IN:
5073 			fill_cmd(cmd, O_IN, 0, 0);
5074 			break;
5075 
5076 		case TOK_OUT:
5077 			cmd->len ^= F_NOT; /* toggle F_NOT */
5078 			fill_cmd(cmd, O_IN, 0, 0);
5079 			break;
5080 
5081 		case TOK_DIVERTED:
5082 			fill_cmd(cmd, O_DIVERTED, 0, 3);
5083 			break;
5084 
5085 		case TOK_DIVERTEDLOOPBACK:
5086 			fill_cmd(cmd, O_DIVERTED, 0, 1);
5087 			break;
5088 
5089 		case TOK_DIVERTEDOUTPUT:
5090 			fill_cmd(cmd, O_DIVERTED, 0, 2);
5091 			break;
5092 
5093 		case TOK_FRAG: {
5094 			uint32_t set = 0, clear = 0;
5095 
5096 			if (*av != NULL && fill_flags(f_ipoff, *av, NULL,
5097 			    &set, &clear) == 0)
5098 				av++;
5099 			else {
5100 				/*
5101 				 * Compatibility: no argument after "frag"
5102 				 * keyword equals to "frag offset".
5103 				 */
5104 				set = 0x01;
5105 				clear = 0;
5106 			}
5107 			fill_cmd(cmd, O_FRAG, 0,
5108 			    (set & 0xff) | ( (clear & 0xff) << 8));
5109 			break;
5110 		}
5111 
5112 		case TOK_LAYER2:
5113 			fill_cmd(cmd, O_LAYER2, 0, 0);
5114 			break;
5115 
5116 		case TOK_XMIT:
5117 		case TOK_RECV:
5118 		case TOK_VIA:
5119 			NEED1("recv, xmit, via require interface name"
5120 				" or address");
5121 			fill_iface(insntod(cmd, if), av[0], cblen, tstate);
5122 			av++;
5123 			if (F_LEN(cmd) == 0)	/* not a valid address */
5124 				break;
5125 			if (i == TOK_XMIT)
5126 				cmd->opcode = O_XMIT;
5127 			else if (i == TOK_RECV)
5128 				cmd->opcode = O_RECV;
5129 			else if (i == TOK_VIA)
5130 				cmd->opcode = O_VIA;
5131 			break;
5132 
5133 		case TOK_ICMPTYPES:
5134 			NEED1("icmptypes requires list of types");
5135 			fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
5136 			av++;
5137 			break;
5138 
5139 		case TOK_ICMP6TYPES:
5140 			NEED1("icmptypes requires list of types");
5141 			fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
5142 			av++;
5143 			break;
5144 
5145 		case TOK_IPTTL:
5146 			NEED1("ipttl requires TTL");
5147 			if (strpbrk(*av, "-,")) {
5148 			    if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
5149 				errx(EX_DATAERR, "invalid ipttl %s", *av);
5150 			} else
5151 			    fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
5152 			av++;
5153 			break;
5154 
5155 		case TOK_IPID:
5156 			NEED1("ipid requires id");
5157 			if (strpbrk(*av, "-,")) {
5158 			    if (!add_ports(cmd, *av, 0, O_IPID, cblen))
5159 				errx(EX_DATAERR, "invalid ipid %s", *av);
5160 			} else
5161 			    fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
5162 			av++;
5163 			break;
5164 
5165 		case TOK_IPLEN:
5166 			NEED1("iplen requires length");
5167 			if (strpbrk(*av, "-,")) {
5168 			    if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
5169 				errx(EX_DATAERR, "invalid ip len %s", *av);
5170 			} else
5171 			    fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
5172 			av++;
5173 			break;
5174 
5175 		case TOK_IPVER:
5176 			NEED1("ipver requires version");
5177 			fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
5178 			av++;
5179 			break;
5180 
5181 		case TOK_IPPRECEDENCE:
5182 			NEED1("ipprecedence requires value");
5183 			fill_cmd(cmd, O_IPPRECEDENCE, 0,
5184 			    (strtoul(*av, NULL, 0) & 7) << 5);
5185 			av++;
5186 			break;
5187 
5188 		case TOK_DSCP:
5189 			NEED1("missing DSCP code");
5190 			fill_dscp(cmd, *av, cblen);
5191 			av++;
5192 			break;
5193 
5194 		case TOK_IPOPTS:
5195 			NEED1("missing argument for ipoptions");
5196 			fill_flags_cmd(cmd, O_IPOPT, f_ipopts, *av);
5197 			av++;
5198 			break;
5199 
5200 		case TOK_IPTOS:
5201 			NEED1("missing argument for iptos");
5202 			fill_flags_cmd(cmd, O_IPTOS, f_iptos, *av);
5203 			av++;
5204 			break;
5205 
5206 		case TOK_UID:
5207 			NEED1("uid requires argument");
5208 		    {
5209 			char *end;
5210 			uid_t uid;
5211 			struct passwd *pwd;
5212 
5213 			cmd->opcode = O_UID;
5214 			uid = strtoul(*av, &end, 0);
5215 			pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
5216 			if (pwd == NULL)
5217 				errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
5218 			cmd32->d[0] = pwd->pw_uid;
5219 			cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
5220 			av++;
5221 		    }
5222 			break;
5223 
5224 		case TOK_GID:
5225 			NEED1("gid requires argument");
5226 		    {
5227 			char *end;
5228 			gid_t gid;
5229 			struct group *grp;
5230 
5231 			cmd->opcode = O_GID;
5232 			gid = strtoul(*av, &end, 0);
5233 			grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
5234 			if (grp == NULL)
5235 				errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
5236 			cmd32->d[0] = grp->gr_gid;
5237 			cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
5238 			av++;
5239 		    }
5240 			break;
5241 
5242 		case TOK_JAIL:
5243 			NEED1("jail requires argument");
5244 		    {
5245 			char *end;
5246 			int jid;
5247 
5248 			cmd->opcode = O_JAIL;
5249 			/*
5250 			 * If av is a number, then we'll just pass it as-is.  If
5251 			 * it's a name, try to resolve that to a jid.
5252 			 *
5253 			 * We save the jail_getid(3) call for a fallback because
5254 			 * it entails an unconditional trip to the kernel to
5255 			 * either validate a jid or resolve a name to a jid.
5256 			 * This specific token doesn't currently require a
5257 			 * jid to be an active jail, so we save a transition
5258 			 * by simply using a number that we're given.
5259 			 */
5260 			jid = strtoul(*av, &end, 10);
5261 			if (*end != '\0') {
5262 				jid = jail_getid(*av);
5263 				if (jid < 0)
5264 				    errx(EX_DATAERR, "%s", jail_errmsg);
5265 			}
5266 			cmd32->d[0] = (uint32_t)jid;
5267 			cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
5268 			av++;
5269 		    }
5270 			break;
5271 
5272 		case TOK_ESTAB:
5273 			fill_cmd(cmd, O_ESTAB, 0, 0);
5274 			break;
5275 
5276 		case TOK_SETUP:
5277 			fill_cmd(cmd, O_TCPFLAGS, 0,
5278 				(TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
5279 			break;
5280 
5281 		case TOK_TCPDATALEN:
5282 			NEED1("tcpdatalen requires length");
5283 			if (strpbrk(*av, "-,")) {
5284 			    if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
5285 				errx(EX_DATAERR, "invalid tcpdata len %s", *av);
5286 			} else
5287 			    fill_cmd(cmd, O_TCPDATALEN, 0,
5288 				    strtoul(*av, NULL, 0));
5289 			av++;
5290 			break;
5291 
5292 		case TOK_TCPOPTS:
5293 			NEED1("missing argument for tcpoptions");
5294 			fill_flags_cmd(cmd, O_TCPOPTS, f_tcpopts, *av);
5295 			av++;
5296 			break;
5297 
5298 		case TOK_TCPSEQ:
5299 		case TOK_TCPACK:
5300 			NEED1("tcpseq/tcpack requires argument");
5301 			cmd->len = F_INSN_SIZE(ipfw_insn_u32);
5302 			cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
5303 			cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
5304 			av++;
5305 			break;
5306 
5307 		case TOK_TCPMSS:
5308 		case TOK_TCPWIN:
5309 			NEED1("tcpmss/tcpwin requires size");
5310 			if (strpbrk(*av, "-,")) {
5311 				if (add_ports(cmd, *av, 0,
5312 				    i == TOK_TCPWIN ? O_TCPWIN : O_TCPMSS,
5313 				    cblen) == NULL)
5314 					errx(EX_DATAERR, "invalid %s size %s",
5315 					    s, *av);
5316 			} else
5317 				fill_cmd(cmd, i == TOK_TCPWIN ? O_TCPWIN :
5318 				    O_TCPMSS, 0, strtoul(*av, NULL, 0));
5319 			av++;
5320 			break;
5321 
5322 		case TOK_TCPFLAGS:
5323 			NEED1("missing argument for tcpflags");
5324 			cmd->opcode = O_TCPFLAGS;
5325 			fill_flags_cmd(cmd, O_TCPFLAGS, f_tcpflags, *av);
5326 			av++;
5327 			break;
5328 
5329 		case TOK_KEEPSTATE:
5330 		case TOK_RECORDSTATE: {
5331 			uint32_t uidx;
5332 
5333 			if (open_par)
5334 				errx(EX_USAGE, "keep-state or record-state cannot be part "
5335 				    "of an or block");
5336 			if (have_state)
5337 				errx(EX_USAGE, "only one of keep-state, record-state, "
5338 					" limit and set-limit is allowed");
5339 			if (*av != NULL && *av[0] == ':') {
5340 				if (state_check_name(*av + 1) != 0)
5341 					errx(EX_DATAERR,
5342 					    "Invalid state name %s", *av);
5343 				uidx = pack_object(tstate, *av + 1,
5344 				    IPFW_TLV_STATE_NAME);
5345 				av++;
5346 			} else
5347 				uidx = pack_object(tstate, default_state_name,
5348 				    IPFW_TLV_STATE_NAME);
5349 			have_state = cmd;
5350 			have_rstate = i == TOK_RECORDSTATE;
5351 			cmd->opcode = O_KEEP_STATE;
5352 			cmd->len = F_INSN_SIZE(ipfw_insn_kidx);
5353 			CHECK_CMDLEN;
5354 			insntod(have_state, kidx)->kidx = uidx;
5355 			break;
5356 		}
5357 
5358 		case TOK_LIMIT:
5359 		case TOK_SETLIMIT: {
5360 			ipfw_insn_limit *c = insntod(cmd, limit);
5361 			int val;
5362 
5363 			if (open_par)
5364 				errx(EX_USAGE,
5365 				    "limit or set-limit cannot be part of an or block");
5366 			if (have_state)
5367 				errx(EX_USAGE, "only one of keep-state, record-state, "
5368 					" limit and set-limit is allowed");
5369 			have_state = cmd;
5370 			have_rstate = i == TOK_SETLIMIT;
5371 
5372 			cmd->opcode = O_LIMIT;
5373 			cmd->len = F_INSN_SIZE(ipfw_insn_limit);
5374 			CHECK_CMDLEN;
5375 			c->limit_mask = c->conn_limit = c->kidx = 0;
5376 
5377 			while ( av[0] != NULL ) {
5378 				if ((val = match_token(limit_masks, *av)) <= 0)
5379 					break;
5380 				c->limit_mask |= val;
5381 				av++;
5382 			}
5383 
5384 			if (c->limit_mask == 0)
5385 				errx(EX_USAGE, "limit: missing limit mask");
5386 
5387 			GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
5388 			    TOK_LIMIT, rule_options);
5389 			av++;
5390 
5391 			if (*av != NULL && *av[0] == ':') {
5392 				if (state_check_name(*av + 1) != 0)
5393 					errx(EX_DATAERR,
5394 					    "Invalid state name %s", *av);
5395 				c->kidx = pack_object(tstate, *av + 1,
5396 				    IPFW_TLV_STATE_NAME);
5397 				av++;
5398 			} else
5399 				c->kidx = pack_object(tstate,
5400 				    default_state_name, IPFW_TLV_STATE_NAME);
5401 			break;
5402 		}
5403 
5404 		case TOK_PROTO:
5405 			NEED1("missing protocol");
5406 			if (add_proto(cmd, *av, &proto)) {
5407 				av++;
5408 			} else
5409 				errx(EX_DATAERR, "invalid protocol ``%s''",
5410 				    *av);
5411 			break;
5412 
5413 		case TOK_SRCIP:
5414 			NEED1("missing source IP");
5415 			if (add_srcip(cmd, *av, cblen, tstate)) {
5416 				av++;
5417 			}
5418 			break;
5419 
5420 		case TOK_DSTIP:
5421 			NEED1("missing destination IP");
5422 			if (add_dstip(cmd, *av, cblen, tstate)) {
5423 				av++;
5424 			}
5425 			break;
5426 
5427 		case TOK_SRCIP6:
5428 			NEED1("missing source IP6");
5429 			if (add_srcip6(cmd, *av, cblen, tstate)) {
5430 				av++;
5431 			}
5432 			break;
5433 
5434 		case TOK_DSTIP6:
5435 			NEED1("missing destination IP6");
5436 			if (add_dstip6(cmd, *av, cblen, tstate)) {
5437 				av++;
5438 			}
5439 			break;
5440 
5441 
5442 		case TOK_SRCMAC:
5443 			NEED1("missing source MAC");
5444 			if (add_srcmac(cmd, *av, tstate)) {
5445 				av++;
5446 			}
5447 			break;
5448 
5449 		case TOK_DSTMAC:
5450 			NEED1("missing destination MAC");
5451 			if (add_dstmac(cmd, *av, tstate)) {
5452 				av++;
5453 			}
5454 			break;
5455 
5456 		case TOK_SRCPORT:
5457 			NEED1("missing source port");
5458 			if (_substrcmp(*av, "any") == 0 ||
5459 			    add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
5460 				av++;
5461 			} else
5462 				errx(EX_DATAERR, "invalid source port %s", *av);
5463 			break;
5464 
5465 		case TOK_DSTPORT:
5466 			NEED1("missing destination port");
5467 			if (_substrcmp(*av, "any") == 0 ||
5468 			    add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
5469 				av++;
5470 			} else
5471 				errx(EX_DATAERR, "invalid destination port %s",
5472 				    *av);
5473 			break;
5474 
5475 		case TOK_MAC:
5476 			if (add_mac(cmd, av, cblen))
5477 				av += 2;
5478 			break;
5479 
5480 		case TOK_MACTYPE:
5481 			NEED1("missing mac type");
5482 			if (!add_mactype(cmd, *av, cblen))
5483 				errx(EX_DATAERR, "invalid mac type %s", *av);
5484 			av++;
5485 			break;
5486 
5487 		case TOK_VERREVPATH:
5488 			fill_cmd(cmd, O_VERREVPATH, 0, 0);
5489 			break;
5490 
5491 		case TOK_VERSRCREACH:
5492 			fill_cmd(cmd, O_VERSRCREACH, 0, 0);
5493 			break;
5494 
5495 		case TOK_ANTISPOOF:
5496 			fill_cmd(cmd, O_ANTISPOOF, 0, 0);
5497 			break;
5498 
5499 		case TOK_IPSEC:
5500 			fill_cmd(cmd, O_IPSEC, 0, 0);
5501 			break;
5502 
5503 		case TOK_IPV6:
5504 			fill_cmd(cmd, O_IP6, 0, 0);
5505 			break;
5506 
5507 		case TOK_IPV4:
5508 			fill_cmd(cmd, O_IP4, 0, 0);
5509 			break;
5510 
5511 		case TOK_EXT6HDR:
5512 			NEED1("missing extension header");
5513 			fill_ext6hdr( cmd, *av );
5514 			av++;
5515 			break;
5516 
5517 		case TOK_FLOWID:
5518 			if (proto != IPPROTO_IPV6 )
5519 				errx( EX_USAGE, "flow-id filter is active "
5520 				    "only for ipv6 protocol\n");
5521 			fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
5522 			av++;
5523 			break;
5524 
5525 		case TOK_COMMENT:
5526 			fill_comment(cmd, av, cblen);
5527 			av[0]=NULL;
5528 			break;
5529 
5530 		case TOK_TAGGED:
5531 			if (av[0] && strpbrk(*av, "-,")) {
5532 				if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
5533 					errx(EX_DATAERR, "tagged: invalid tag"
5534 					    " list: %s", *av);
5535 			}
5536 			else {
5537 				uint16_t tag;
5538 
5539 				GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
5540 				    TOK_TAGGED, rule_options);
5541 				fill_cmd(cmd, O_TAGGED, 0, tag);
5542 			}
5543 			av++;
5544 			break;
5545 
5546 		case TOK_FIB:
5547 			NEED1("fib requires fib number");
5548 			fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
5549 			av++;
5550 			break;
5551 		case TOK_SOCKARG:
5552 			fill_cmd(cmd, O_SOCKARG, 0, 0);
5553 			break;
5554 
5555 		case TOK_LOOKUP: {
5556 			/* optional mask for some LOOKUP types */
5557 			ipfw_insn_lookup *c = insntod(cmd, lookup);
5558 			char *lkey;
5559 
5560 			if (!av[0] || !av[1])
5561 				errx(EX_USAGE,
5562 				    "format: lookup argument tablenum");
5563 			cmd->opcode = O_TABLE_LOOKUP;
5564 
5565 			lkey = strsep(av, ":");
5566 			i = match_token(lookup_keys, lkey);
5567 			if (i == -1)
5568 				errx(EX_USAGE,
5569 				    "format: cannot lookup on %s", lkey);
5570 			/* masked lookup key */
5571 			if (*av != NULL) {
5572 				switch (i) {
5573 				case LOOKUP_DST_PORT:
5574 				case LOOKUP_SRC_PORT:
5575 				case LOOKUP_UID:
5576 				case LOOKUP_JAIL:
5577 				case LOOKUP_DSCP:
5578 				case LOOKUP_MARK:
5579 				case LOOKUP_RULENUM:
5580 				case LOOKUP_SRC_MAC:
5581 				case LOOKUP_DST_MAC:
5582 				case LOOKUP_SRC_IP6:
5583 				case LOOKUP_DST_IP6:
5584 				case LOOKUP_SRC_IP4:
5585 				case LOOKUP_DST_IP4:
5586 					break;
5587 				default:
5588 					errx(EX_USAGE,
5589 					    "masked lookup is not supported "
5590 					    "for %s", lkey);
5591 				}
5592 				cmd->len |= F_INSN_SIZE(ipfw_insn_lookup);
5593 				IPFW_SET_LOOKUP_MASKING(cmd, 1);
5594 				get_lookup_bitmask(i, c, *av);
5595 			} else {
5596 				cmd->len |= F_INSN_SIZE(ipfw_insn_kidx);
5597 			}
5598 			CHECK_CMDLEN;
5599 
5600 			IPFW_SET_LOOKUP_TYPE(cmd, i);
5601 			av++;
5602 			c->kidx = pack_table(tstate, *av);
5603 			if (c->kidx == 0)
5604 				errx(EX_DATAERR,
5605 				    "Invalid table name: %s", *av);
5606 			av++;
5607 		    }
5608 			break;
5609 		case TOK_FLOW:
5610 			NEED1("missing table name");
5611 			if (strncmp(*av, "table(", 6) != 0)
5612 				errx(EX_DATAERR,
5613 				    "enclose table name into \"table()\"");
5614 			fill_table(cmd, *av, O_IP_FLOW_LOOKUP, tstate);
5615 			av++;
5616 			break;
5617 
5618 		case TOK_SKIPACTION:
5619 			if (have_skipcmd)
5620 				errx(EX_USAGE, "only one defer-action "
5621 					"is allowed");
5622 			have_skipcmd = cmd;
5623 			fill_cmd(cmd, O_SKIP_ACTION, 0, 0);
5624 			break;
5625 
5626 		case TOK_MARK:
5627 			NEED1("missing mark value:mask");
5628 			fill_mark(cmd, *av, cblen);
5629 			av++;
5630 			break;
5631 
5632 		default:
5633 			errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
5634 		}
5635 		if (F_LEN(cmd) > 0) {	/* prepare to advance */
5636 			prev = cmd;
5637 			cmd = next_cmd(cmd, &cblen);
5638 		}
5639 	}
5640 
5641 done:
5642 
5643 	if (!have_state && have_skipcmd)
5644 		warnx("Rule contains \"defer-immediate-action\" "
5645 			"and doesn't contain any state-related options.");
5646 
5647 	/*
5648 	 * Now copy stuff into the rule.
5649 	 * If we have a keep-state option, the first instruction
5650 	 * must be a PROBE_STATE (which is generated here).
5651 	 * If we have a LOG option, it was stored as the first command,
5652 	 * and now must be moved to the top of the action part.
5653 	 */
5654 	dst = (ipfw_insn *)rule->cmd;
5655 
5656 	/*
5657 	 * First thing to write into the command stream is the match probability.
5658 	 */
5659 	if (match_prob != 1) { /* 1 means always match */
5660 		dst->opcode = O_PROB;
5661 		dst->len = 2;
5662 		*((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
5663 		dst += dst->len;
5664 	}
5665 
5666 	/*
5667 	 * generate O_PROBE_STATE if necessary
5668 	 */
5669 	if (have_state && have_state->opcode != O_CHECK_STATE && !have_rstate) {
5670 		dst->opcode = O_PROBE_STATE;
5671 		dst->len = F_INSN_SIZE(ipfw_insn_kidx);
5672 		insntod(dst, kidx)->kidx = insntod(have_state, kidx)->kidx;
5673 		dst = next_cmd(dst, &rblen);
5674 	}
5675 
5676 	/*
5677 	 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG,
5678 	 * O_SKIP_ACTION
5679 	 */
5680 	for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
5681 		i = F_LEN(src);
5682 		CHECK_RBUFLEN(i);
5683 
5684 		switch (src->opcode) {
5685 		case O_LOG:
5686 		case O_KEEP_STATE:
5687 		case O_LIMIT:
5688 		case O_ALTQ:
5689 		case O_TAG:
5690 		case O_SKIP_ACTION:
5691 			break;
5692 		default:
5693 			bcopy(src, dst, i * sizeof(uint32_t));
5694 			dst += i;
5695 		}
5696 	}
5697 
5698 	/*
5699 	 * put back the have_state command as last opcode
5700 	 */
5701 	if (have_state && have_state->opcode != O_CHECK_STATE) {
5702 		i = F_LEN(have_state);
5703 		CHECK_RBUFLEN(i);
5704 		bcopy(have_state, dst, i * sizeof(uint32_t));
5705 		dst += i;
5706 	}
5707 
5708 	/*
5709 	 * put back the have_skipcmd command as very last opcode
5710 	 */
5711 	if (have_skipcmd) {
5712 		i = F_LEN(have_skipcmd);
5713 		CHECK_RBUFLEN(i);
5714 		bcopy(have_skipcmd, dst, i * sizeof(uint32_t));
5715 		dst += i;
5716 	}
5717 
5718 	/*
5719 	 * start action section
5720 	 */
5721 	rule->act_ofs = dst - rule->cmd;
5722 
5723 	/* put back O_LOG, O_ALTQ, O_TAG if necessary */
5724 	if (have_log) {
5725 		i = F_LEN(have_log);
5726 		CHECK_RBUFLEN(i);
5727 		bcopy(have_log, dst, i * sizeof(uint32_t));
5728 		dst += i;
5729 	}
5730 	if (have_altq) {
5731 		i = F_LEN(have_altq);
5732 		CHECK_RBUFLEN(i);
5733 		bcopy(have_altq, dst, i * sizeof(uint32_t));
5734 		dst += i;
5735 	}
5736 	if (have_tag) {
5737 		i = F_LEN(have_tag);
5738 		CHECK_RBUFLEN(i);
5739 		bcopy(have_tag, dst, i * sizeof(uint32_t));
5740 		dst += i;
5741 	}
5742 
5743 	/*
5744 	 * copy all other actions
5745 	 */
5746 	for (src = (ipfw_insn *)actbuf; src != action; src += i) {
5747 		i = F_LEN(src);
5748 		CHECK_RBUFLEN(i);
5749 		bcopy(src, dst, i * sizeof(uint32_t));
5750 		dst += i;
5751 	}
5752 
5753 	rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
5754 	*rbufsize = (char *)dst - (char *)rule;
5755 }
5756 
5757 static int
compare_ntlv(const void * _a,const void * _b)5758 compare_ntlv(const void *_a, const void *_b)
5759 {
5760 	const ipfw_obj_ntlv *a, *b;
5761 
5762 	a = (const ipfw_obj_ntlv *)_a;
5763 	b = (const ipfw_obj_ntlv *)_b;
5764 
5765 	if (a->set < b->set)
5766 		return (-1);
5767 	else if (a->set > b->set)
5768 		return (1);
5769 
5770 	if (a->idx < b->idx)
5771 		return (-1);
5772 	else if (a->idx > b->idx)
5773 		return (1);
5774 
5775 	if (a->head.type < b->head.type)
5776 		return (-1);
5777 	else if (a->head.type > b->head.type)
5778 		return (1);
5779 
5780 	return (0);
5781 }
5782 
5783 /*
5784  * Provide kernel with sorted list of referenced objects
5785  */
5786 static void
object_sort_ctlv(ipfw_obj_ctlv * ctlv)5787 object_sort_ctlv(ipfw_obj_ctlv *ctlv)
5788 {
5789 
5790 	qsort(ctlv + 1, ctlv->count, ctlv->objsize, compare_ntlv);
5791 }
5792 
5793 struct object_kt {
5794 	uint32_t	uidx;
5795 	uint16_t	type;
5796 };
5797 static int
compare_object_kntlv(const void * k,const void * v)5798 compare_object_kntlv(const void *k, const void *v)
5799 {
5800 	const ipfw_obj_ntlv *ntlv;
5801 	struct object_kt key;
5802 
5803 	key = *((const struct object_kt *)k);
5804 	ntlv = (const ipfw_obj_ntlv *)v;
5805 
5806 	if (key.uidx < ntlv->idx)
5807 		return (-1);
5808 	else if (key.uidx > ntlv->idx)
5809 		return (1);
5810 
5811 	if (key.type < ntlv->head.type)
5812 		return (-1);
5813 	else if (key.type > ntlv->head.type)
5814 		return (1);
5815 
5816 	return (0);
5817 }
5818 
5819 /*
5820  * Finds object name in @ctlv by @idx and @type.
5821  * Uses the following facts:
5822  * 1) All TLVs are the same size
5823  * 2) Kernel implementation provides already sorted list.
5824  *
5825  * Returns table name or NULL.
5826  */
5827 static char *
object_search_ctlv(ipfw_obj_ctlv * ctlv,uint32_t idx,uint16_t type)5828 object_search_ctlv(ipfw_obj_ctlv *ctlv, uint32_t idx, uint16_t type)
5829 {
5830 	ipfw_obj_ntlv *ntlv;
5831 	struct object_kt key;
5832 
5833 	key.uidx = idx;
5834 	key.type = type;
5835 
5836 	ntlv = bsearch(&key, (ctlv + 1), ctlv->count, ctlv->objsize,
5837 	    compare_object_kntlv);
5838 
5839 	if (ntlv != NULL)
5840 		return (ntlv->name);
5841 
5842 	return (NULL);
5843 }
5844 
5845 static char *
table_search_ctlv(ipfw_obj_ctlv * ctlv,uint32_t idx)5846 table_search_ctlv(ipfw_obj_ctlv *ctlv, uint32_t idx)
5847 {
5848 
5849 	return (object_search_ctlv(ctlv, idx, IPFW_TLV_TBL_NAME));
5850 }
5851 
5852 /*
5853  * Adds one or more rules to ipfw chain.
5854  * Data layout:
5855  * Request:
5856  * [
5857  *   ip_fw3_opheader
5858  *   [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
5859  *   [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ] (*2) (*3)
5860  * ]
5861  * Reply:
5862  * [
5863  *   ip_fw3_opheader
5864  *   [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
5865  *   [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ]
5866  * ]
5867  *
5868  * Rules in reply are modified to store their actual ruleset number.
5869  *
5870  * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
5871  * according to their idx field and there has to be no duplicates.
5872  * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
5873  * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
5874  */
5875 void
ipfw_add(char * av[])5876 ipfw_add(char *av[])
5877 {
5878 	uint32_t rulebuf[1024];
5879 	int rbufsize, default_off, tlen, rlen;
5880 	size_t sz;
5881 	struct tidx ts;
5882 	struct ip_fw_rule *rule;
5883 	caddr_t tbuf;
5884 	ip_fw3_opheader *op3;
5885 	ipfw_obj_ctlv *ctlv, *tstate;
5886 
5887 	rbufsize = sizeof(rulebuf);
5888 	memset(rulebuf, 0, rbufsize);
5889 	memset(&ts, 0, sizeof(ts));
5890 
5891 	/* Optimize case with no tables */
5892 	default_off = sizeof(ipfw_obj_ctlv) + sizeof(ip_fw3_opheader);
5893 	op3 = (ip_fw3_opheader *)rulebuf;
5894 	ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5895 	rule = (struct ip_fw_rule *)(ctlv + 1);
5896 	rbufsize -= default_off;
5897 
5898 	compile_rule(av, (uint32_t *)rule, &rbufsize, &ts);
5899 	/* Align rule size to u64 boundary */
5900 	rlen = roundup2(rbufsize, sizeof(uint64_t));
5901 
5902 	tbuf = NULL;
5903 	sz = 0;
5904 	tstate = NULL;
5905 	if (ts.count != 0) {
5906 		/* Some tables. We have to alloc more data */
5907 		tlen = ts.count * sizeof(ipfw_obj_ntlv);
5908 		sz = default_off + sizeof(ipfw_obj_ctlv) + tlen + rlen;
5909 
5910 		if ((tbuf = calloc(1, sz)) == NULL)
5911 			err(EX_UNAVAILABLE, "malloc() failed for IP_FW_XADD");
5912 		op3 = (ip_fw3_opheader *)tbuf;
5913 		/* Tables first */
5914 		ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5915 		ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
5916 		ctlv->head.length = sizeof(ipfw_obj_ctlv) + tlen;
5917 		ctlv->count = ts.count;
5918 		ctlv->objsize = sizeof(ipfw_obj_ntlv);
5919 		memcpy(ctlv + 1, ts.idx, tlen);
5920 		object_sort_ctlv(ctlv);
5921 		tstate = ctlv;
5922 		/* Rule next */
5923 		ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
5924 		ctlv->head.type = IPFW_TLV_RULE_LIST;
5925 		ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5926 		ctlv->count = 1;
5927 		memcpy(ctlv + 1, rule, rbufsize);
5928 	} else {
5929 		/* Simply add header */
5930 		sz = rlen + default_off;
5931 		memset(ctlv, 0, sizeof(*ctlv));
5932 		ctlv->head.type = IPFW_TLV_RULE_LIST;
5933 		ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5934 		ctlv->count = 1;
5935 	}
5936 
5937 	if (do_get3(IP_FW_XADD, op3, &sz) != 0)
5938 		err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_XADD");
5939 
5940 	if (!g_co.do_quiet) {
5941 		struct format_opts sfo;
5942 		struct buf_pr bp;
5943 		memset(&sfo, 0, sizeof(sfo));
5944 		sfo.tstate = tstate;
5945 		sfo.set_mask = (uint32_t)(-1);
5946 		bp_alloc(&bp, 4096);
5947 		show_static_rule(&g_co, &sfo, &bp, rule, NULL);
5948 		printf("%s", bp.buf);
5949 		bp_free(&bp);
5950 	}
5951 
5952 	if (tbuf != NULL)
5953 		free(tbuf);
5954 
5955 	if (ts.idx != NULL)
5956 		free(ts.idx);
5957 }
5958 
5959 /*
5960  * clear the counters or the log counters.
5961  * optname has the following values:
5962  *  0 (zero both counters and logging)
5963  *  1 (zero logging only)
5964  */
5965 void
ipfw_zero(int ac,char * av[],int optname)5966 ipfw_zero(int ac, char *av[], int optname)
5967 {
5968 	ipfw_range_tlv rt;
5969 	char const *errstr;
5970 	char const *name = optname ? "RESETLOG" : "ZERO";
5971 	uint32_t arg;
5972 	int failed = EX_OK;
5973 
5974 	optname = optname ? IP_FW_XRESETLOG : IP_FW_XZERO;
5975 	av++; ac--;
5976 
5977 	if (ac == 0) {
5978 		/* clear all entries */
5979 		memset(&rt, 0, sizeof(rt));
5980 		rt.flags = IPFW_RCFLAG_ALL;
5981 		if (do_range_cmd(optname, &rt) < 0)
5982 			err(EX_UNAVAILABLE, "setsockopt(IP_FW_X%s)", name);
5983 		if (!g_co.do_quiet)
5984 			printf("%s.\n", optname == IP_FW_XZERO ?
5985 			    "Accounting cleared":"Logging counts reset");
5986 
5987 		return;
5988 	}
5989 
5990 	while (ac) {
5991 		/* Rule number */
5992 		if (isdigit(**av)) {
5993 			arg = strtonum(*av, 0, 0xffff, &errstr);
5994 			if (errstr)
5995 				errx(EX_DATAERR,
5996 				    "invalid rule number %s\n", *av);
5997 			memset(&rt, 0, sizeof(rt));
5998 			rt.start_rule = arg;
5999 			rt.end_rule = arg;
6000 			rt.flags |= IPFW_RCFLAG_RANGE;
6001 			if (g_co.use_set != 0) {
6002 				rt.set = g_co.use_set - 1;
6003 				rt.flags |= IPFW_RCFLAG_SET;
6004 			}
6005 			if (do_range_cmd(optname, &rt) != 0) {
6006 				warn("rule %u: setsockopt(IP_FW_X%s)",
6007 				    arg, name);
6008 				failed = EX_UNAVAILABLE;
6009 			} else if (rt.new_set == 0) {
6010 				printf("Entry %d not found\n", arg);
6011 				failed = EX_UNAVAILABLE;
6012 			} else if (!g_co.do_quiet)
6013 				printf("Entry %d %s.\n", arg,
6014 				    optname == IP_FW_XZERO ?
6015 					"cleared" : "logging count reset");
6016 		} else {
6017 			errx(EX_USAGE, "invalid rule number ``%s''", *av);
6018 		}
6019 		av++; ac--;
6020 	}
6021 	if (failed != EX_OK)
6022 		exit(failed);
6023 }
6024 
6025 void
ipfw_flush(int force)6026 ipfw_flush(int force)
6027 {
6028 	ipfw_range_tlv rt;
6029 
6030 	if (!force && !g_co.do_quiet) { /* need to ask user */
6031 		int c;
6032 
6033 		printf("Are you sure? [yn] ");
6034 		fflush(stdout);
6035 		do {
6036 			c = toupper(getc(stdin));
6037 			while (c != '\n' && getc(stdin) != '\n')
6038 				if (feof(stdin))
6039 					return; /* and do not flush */
6040 		} while (c != 'Y' && c != 'N');
6041 		printf("\n");
6042 		if (c == 'N')	/* user said no */
6043 			return;
6044 	}
6045 	if (g_co.do_pipe) {
6046 		dummynet_flush();
6047 		return;
6048 	}
6049 	/* `ipfw set N flush` - is the same that `ipfw delete set N` */
6050 	memset(&rt, 0, sizeof(rt));
6051 	if (g_co.use_set != 0) {
6052 		rt.set = g_co.use_set - 1;
6053 		rt.flags = IPFW_RCFLAG_SET;
6054 	} else
6055 		rt.flags = IPFW_RCFLAG_ALL;
6056 	if (do_range_cmd(IP_FW_XDEL, &rt) != 0)
6057 			err(EX_UNAVAILABLE, "setsockopt(IP_FW_XDEL)");
6058 	if (!g_co.do_quiet)
6059 		printf("Flushed all %s.\n", g_co.do_pipe ? "pipes" : "rules");
6060 }
6061 
6062 static struct _s_x intcmds[] = {
6063       { "talist",	TOK_TALIST },
6064       { "iflist",	TOK_IFLIST },
6065       { "olist",	TOK_OLIST },
6066       { "vlist",	TOK_VLIST },
6067       { "monitor",	TOK_MONITOR },
6068       { NULL, 0 }
6069 };
6070 
6071 static struct _s_x otypes[] = {
6072 	{ "EACTION",	IPFW_TLV_EACTION },
6073 	{ "DYNSTATE",	IPFW_TLV_STATE_NAME },
6074 	{ NULL, 0 }
6075 };
6076 
6077 static const char*
lookup_eaction_name(ipfw_obj_ntlv * ntlv,int cnt,uint16_t type)6078 lookup_eaction_name(ipfw_obj_ntlv *ntlv, int cnt, uint16_t type)
6079 {
6080 	const char *name;
6081 	int i;
6082 
6083 	name = NULL;
6084 	for (i = 0; i < cnt; i++) {
6085 		if (ntlv[i].head.type != IPFW_TLV_EACTION)
6086 			continue;
6087 		if (IPFW_TLV_EACTION_NAME(ntlv[i].idx) != type)
6088 			continue;
6089 		name = ntlv[i].name;
6090 		break;
6091 	}
6092 	return (name);
6093 }
6094 
6095 static void
ipfw_list_objects(int ac __unused,char * av[]__unused)6096 ipfw_list_objects(int ac __unused, char *av[] __unused)
6097 {
6098 	ipfw_obj_lheader req, *olh;
6099 	ipfw_obj_ntlv *ntlv;
6100 	const char *name;
6101 	size_t sz;
6102 	uint32_t i;
6103 
6104 	memset(&req, 0, sizeof(req));
6105 	sz = sizeof(req);
6106 	if (do_get3(IP_FW_DUMP_SRVOBJECTS, &req.opheader, &sz) != 0)
6107 		if (errno != ENOMEM)
6108 			return;
6109 
6110 	sz = req.size;
6111 	if ((olh = calloc(1, sz)) == NULL)
6112 		return;
6113 
6114 	olh->size = sz;
6115 	if (do_get3(IP_FW_DUMP_SRVOBJECTS, &olh->opheader, &sz) != 0) {
6116 		free(olh);
6117 		return;
6118 	}
6119 
6120 	if (olh->count > 0)
6121 		printf("Objects list:\n");
6122 	else
6123 		printf("There are no objects\n");
6124 	ntlv = (ipfw_obj_ntlv *)(olh + 1);
6125 	for (i = 0; i < olh->count; i++) {
6126 		name = match_value(otypes, ntlv->head.type);
6127 		if (name == NULL)
6128 			name = lookup_eaction_name(
6129 			    (ipfw_obj_ntlv *)(olh + 1), olh->count,
6130 			    ntlv->head.type);
6131 		if (name == NULL)
6132 			printf(" kidx: %4d\ttype: %10d\tname: %s\n",
6133 			    ntlv->idx, ntlv->head.type, ntlv->name);
6134 		else
6135 			printf(" kidx: %4d\ttype: %10s\tname: %s\n",
6136 			    ntlv->idx, name, ntlv->name);
6137 		ntlv++;
6138 	}
6139 	free(olh);
6140 }
6141 
6142 static void
bprint_sa(struct buf_pr * bp,const struct sockaddr * sa)6143 bprint_sa(struct buf_pr *bp, const struct sockaddr *sa)
6144 {
6145 	struct sockaddr_storage ss;
6146 	char buf[INET6_ADDRSTRLEN];
6147 
6148 	memset(&ss, 0, sizeof(ss));
6149 	if (sa->sa_len == 0)
6150 		ss.ss_family = sa->sa_family;
6151 	else
6152 		memcpy(&ss, sa, sa->sa_len);
6153 
6154 	/* set ss_len in case it was shortened */
6155 	switch (sa->sa_family) {
6156 	case AF_INET:
6157 		ss.ss_len = sizeof(struct sockaddr_in);
6158 		break;
6159 	default:
6160 		ss.ss_len = sizeof(struct sockaddr_in6);
6161 	}
6162 	if (getnameinfo((const struct sockaddr *)&ss, ss.ss_len,
6163 	    buf, sizeof(buf), NULL, 0, NI_NUMERICHOST) != 0) {
6164 		bprintf(bp, "bad-addr");
6165 		return;
6166 	}
6167 	bprintf(bp, "%s", buf);
6168 }
6169 
6170 static void
ipfw_rtsock_monitor(const char * filter)6171 ipfw_rtsock_monitor(const char *filter)
6172 {
6173 	char msg[2048], buf[32];
6174 	struct timespec tp;
6175 	struct tm tm;
6176 	struct buf_pr bp;
6177 	struct rt_msghdr *hdr;
6178 	struct sockaddr *sa;
6179 	struct sockaddr_dl *sdl;
6180 	ipfwlog_rtsock_hdr_v2 *loghdr;
6181 	ssize_t nread;
6182 	size_t msglen;
6183 	int rtsock;
6184 
6185 	rtsock = socket(PF_ROUTE, SOCK_RAW, AF_IPFWLOG);
6186 	if (rtsock < 0)
6187 		err(EX_UNAVAILABLE, "socket(AF_IPFWLOG)");
6188 	bp_alloc(&bp, 4096);
6189 	for (;;) {
6190 		nread = read(rtsock, msg, sizeof(msg));
6191 		if (nread < 0) {
6192 			warn("read()");
6193 			continue;
6194 		}
6195 		msglen = nread;
6196 		if (msglen < sizeof(*hdr))
6197 			continue;
6198 
6199 		hdr = (struct rt_msghdr *)msg;
6200 		if (hdr->rtm_version != RTM_VERSION ||
6201 		    hdr->rtm_type != RTM_IPFWLOG ||
6202 		    (hdr->rtm_addrs & (1 << RTAX_DST)) == 0 ||
6203 		    (hdr->rtm_addrs & (1 << RTAX_GATEWAY)) == 0 ||
6204 		    (hdr->rtm_addrs & (1 << RTAX_NETMASK)) == 0)
6205 			continue;
6206 
6207 		msglen -= sizeof(*hdr);
6208 		sdl = (struct sockaddr_dl *)(hdr + 1);
6209 		if (msglen < sizeof(*sdl) || msglen < SA_SIZE(sdl) ||
6210 		    sdl->sdl_family != AF_IPFWLOG ||
6211 		    sdl->sdl_type != 2 /* version */ ||
6212 		    sdl->sdl_alen != sizeof(*loghdr))
6213 			continue;
6214 
6215 		msglen -= SA_SIZE(sdl);
6216 		loghdr = (ipfwlog_rtsock_hdr_v2 *)sdl->sdl_data;
6217 		/* filter by rule comment. MAX_COMMENT_LEN = 80 */
6218 		if (filter != NULL &&
6219 		    strncmp(filter, loghdr->comment, 80) != 0)
6220 			continue;
6221 
6222 		sa = (struct sockaddr *)((char *)sdl + SA_SIZE(sdl));
6223 		if (msglen < SA_SIZE(sa))
6224 			continue;
6225 
6226 		msglen -= SA_SIZE(sa);
6227 		bp_flush(&bp);
6228 
6229 		clock_gettime(CLOCK_REALTIME, &tp);
6230 		localtime_r(&tp.tv_sec, &tm);
6231 		strftime(buf, sizeof(buf), "%T", &tm);
6232 		bprintf(&bp, "%s.%03ld AF %s", buf, tp.tv_nsec / 1000000,
6233 		    sa->sa_family == AF_INET ? "IPv4" : "IPv6");
6234 
6235 		bprintf(&bp, " %s >",
6236 		    ether_ntoa((const struct ether_addr *)loghdr->ether_shost));
6237 		bprintf(&bp, " %s, ",
6238 		    ether_ntoa((const struct ether_addr *)loghdr->ether_dhost));
6239 		bprint_sa(&bp, sa);
6240 
6241 		sa = (struct sockaddr *)((char *)sa + SA_SIZE(sa));
6242 		if (msglen < SA_SIZE(sa))
6243 			continue;
6244 
6245 		msglen -= SA_SIZE(sa);
6246 		bprintf(&bp, " > ");
6247 		bprint_sa(&bp, sa);
6248 		bprintf(&bp, ", set %u, rulenum %u, targ 0x%08x, "
6249 		    "%scmd[op %d, len %d, arg1 0x%04x], mark 0x%08x",
6250 		    sdl->sdl_index, loghdr->rulenum, loghdr->tablearg,
6251 		    (loghdr->cmd.len & F_NOT) ? "!": "",
6252 		    loghdr->cmd.opcode, F_LEN(&loghdr->cmd),
6253 		    loghdr->cmd.arg1, loghdr->mark);
6254 
6255 		sa = (struct sockaddr *)((char *)sa + SA_SIZE(sa));
6256 		if ((hdr->rtm_addrs & (1 << RTAX_GENMASK)) != 0 &&
6257 		    msglen >= SA_SIZE(sa)) {
6258 			msglen -= SA_SIZE(sa);
6259 			bprintf(&bp, ", nh ");
6260 			bprint_sa(&bp, sa);
6261 		}
6262 		if (sdl->sdl_nlen > 0)
6263 			bprintf(&bp, " // %s", loghdr->comment);
6264 		printf("%s\n", bp.buf);
6265 	}
6266 	bp_free(&bp);
6267 	close(rtsock);
6268 }
6269 
6270 void
ipfw_internal_handler(int ac,char * av[])6271 ipfw_internal_handler(int ac, char *av[])
6272 {
6273 	int tcmd;
6274 
6275 	ac--; av++;
6276 	NEED1("internal cmd required");
6277 
6278 	if ((tcmd = match_token(intcmds, *av)) == -1)
6279 		errx(EX_USAGE, "invalid internal sub-cmd: %s", *av);
6280 
6281 	switch (tcmd) {
6282 	case TOK_IFLIST:
6283 		ipfw_list_tifaces();
6284 		break;
6285 	case TOK_TALIST:
6286 		ipfw_list_ta(ac, av);
6287 		break;
6288 	case TOK_OLIST:
6289 		ipfw_list_objects(ac, av);
6290 		break;
6291 	case TOK_VLIST:
6292 		ipfw_list_values(ac, av);
6293 		break;
6294 	case TOK_MONITOR:
6295 		av++;
6296 		ipfw_rtsock_monitor(*av);
6297 		break;
6298 	}
6299 }
6300 
6301 static int
ipfw_get_tracked_ifaces(ipfw_obj_lheader ** polh)6302 ipfw_get_tracked_ifaces(ipfw_obj_lheader **polh)
6303 {
6304 	ipfw_obj_lheader req, *olh;
6305 	size_t sz;
6306 
6307 	memset(&req, 0, sizeof(req));
6308 	sz = sizeof(req);
6309 
6310 	if (do_get3(IP_FW_XIFLIST, &req.opheader, &sz) != 0) {
6311 		if (errno != ENOMEM)
6312 			return (errno);
6313 	}
6314 
6315 	sz = req.size;
6316 	if ((olh = calloc(1, sz)) == NULL)
6317 		return (ENOMEM);
6318 
6319 	olh->size = sz;
6320 	if (do_get3(IP_FW_XIFLIST, &olh->opheader, &sz) != 0) {
6321 		free(olh);
6322 		return (errno);
6323 	}
6324 
6325 	*polh = olh;
6326 	return (0);
6327 }
6328 
6329 static int
ifinfo_cmp(const void * a,const void * b)6330 ifinfo_cmp(const void *a, const void *b)
6331 {
6332 	const ipfw_iface_info *ia, *ib;
6333 
6334 	ia = (const ipfw_iface_info *)a;
6335 	ib = (const ipfw_iface_info *)b;
6336 
6337 	return (stringnum_cmp(ia->ifname, ib->ifname));
6338 }
6339 
6340 /*
6341  * Retrieves table list from kernel,
6342  * optionally sorts it and calls requested function for each table.
6343  * Returns 0 on success.
6344  */
6345 static void
ipfw_list_tifaces(void)6346 ipfw_list_tifaces(void)
6347 {
6348 	ipfw_obj_lheader *olh = NULL;
6349 	ipfw_iface_info *info;
6350 	uint32_t i;
6351 	int error;
6352 
6353 	if ((error = ipfw_get_tracked_ifaces(&olh)) != 0)
6354 		err(EX_OSERR, "Unable to request ipfw tracked interface list");
6355 
6356 	qsort(olh + 1, olh->count, olh->objsize, ifinfo_cmp);
6357 
6358 	info = (ipfw_iface_info *)(olh + 1);
6359 	for (i = 0; i < olh->count; i++) {
6360 		if (info->flags & IPFW_IFFLAG_RESOLVED)
6361 			printf("%s ifindex: %d refcount: %u changes: %u\n",
6362 			    info->ifname, info->ifindex, info->refcnt,
6363 			    info->gencnt);
6364 		else
6365 			printf("%s ifindex: unresolved refcount: %u changes: %u\n",
6366 			    info->ifname, info->refcnt, info->gencnt);
6367 		info = (ipfw_iface_info *)((caddr_t)info + olh->objsize);
6368 	}
6369 
6370 	free(olh);
6371 }
6372