xref: /freebsd/sbin/ipfw/ipfw2.c (revision 2872268c7f6d473aae9b02ebb5d2c24fc2cff9b1)
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 (av == NULL && len == 0) {
3599 			if (cmd->o.len & F_NOT) /* "not any" never matches */
3600 				errx(EX_DATAERR, "not any never matches");
3601 			return;
3602 		}
3603 		/* else do nothing and skip this entry */
3604 		continue;
3605 	}
3606 	/* A single IP can be stored in an optimized format */
3607 	if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
3608 		cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
3609 		return;
3610 	}
3611 	len += 2;	/* two words... */
3612 	d += 2;
3613     } /* end while */
3614     if (len + 1 > F_LEN_MASK)
3615 	errx(EX_DATAERR, "address list too long");
3616     cmd->o.len |= len+1;
3617 }
3618 
3619 
3620 /* n2mask sets n bits of the mask */
3621 void
n2mask(struct in6_addr * mask,int n)3622 n2mask(struct in6_addr *mask, int n)
3623 {
3624 	static int	minimask[9] =
3625 	    { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
3626 	u_char		*p;
3627 
3628 	memset(mask, 0, sizeof(struct in6_addr));
3629 	p = (u_char *) mask;
3630 	for (; n > 0; p++, n -= 8) {
3631 		if (n >= 8)
3632 			*p = 0xff;
3633 		else
3634 			*p = minimask[n];
3635 	}
3636 	return;
3637 }
3638 
3639 static void
fill_flags_cmd(ipfw_insn * cmd,enum ipfw_opcodes opcode,struct _s_x * flags,char * p)3640 fill_flags_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3641 	struct _s_x *flags, char *p)
3642 {
3643 	char *e;
3644 	uint32_t set = 0, clear = 0;
3645 
3646 	if (fill_flags(flags, p, &e, &set, &clear) != 0)
3647 		errx(EX_DATAERR, "invalid flag %s", e);
3648 
3649 	cmd->opcode = opcode;
3650 	cmd->len =  (cmd->len & (F_NOT | F_OR)) | 1;
3651 	cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3652 }
3653 
3654 
3655 void
ipfw_delete(char * av[])3656 ipfw_delete(char *av[])
3657 {
3658 	ipfw_range_tlv rt;
3659 	char *sep;
3660 	uint32_t i, j;
3661 	int exitval = EX_OK;
3662 	int do_set = 0;
3663 
3664 	av++;
3665 	NEED1("missing rule specification");
3666 	if ( *av && _substrcmp(*av, "set") == 0) {
3667 		/* Do not allow using the following syntax:
3668 		 *	ipfw set N delete set M
3669 		 */
3670 		if (g_co.use_set)
3671 			errx(EX_DATAERR, "invalid syntax");
3672 		do_set = 1;	/* delete set */
3673 		av++;
3674 	}
3675 
3676 	/* Rule number */
3677 	while (*av && isdigit(**av)) {
3678 		i = strtol(*av, &sep, 10);
3679 		j = i;
3680 		if (*sep== '-')
3681 			j = strtol(sep + 1, NULL, 10);
3682 		av++;
3683 		if (g_co.do_nat) {
3684 			exitval = ipfw_delete_nat(i);
3685 		} else if (g_co.do_pipe) {
3686 			exitval = ipfw_delete_pipe(g_co.do_pipe, i);
3687 		} else {
3688 			memset(&rt, 0, sizeof(rt));
3689 			if (do_set != 0) {
3690 				rt.set = i & 31;
3691 				rt.flags = IPFW_RCFLAG_SET;
3692 			} else {
3693 				rt.start_rule = i;
3694 				rt.end_rule = j;
3695 				if (rt.start_rule == 0 && rt.end_rule == 0)
3696 					rt.flags |= IPFW_RCFLAG_ALL;
3697 				else
3698 					rt.flags |= IPFW_RCFLAG_RANGE;
3699 				if (g_co.use_set != 0) {
3700 					rt.set = g_co.use_set - 1;
3701 					rt.flags |= IPFW_RCFLAG_SET;
3702 				}
3703 			}
3704 			if (g_co.do_dynamic == 2)
3705 				rt.flags |= IPFW_RCFLAG_DYNAMIC;
3706 			i = do_range_cmd(IP_FW_XDEL, &rt);
3707 			if (i != 0) {
3708 				exitval = EX_UNAVAILABLE;
3709 				if (g_co.do_quiet)
3710 					continue;
3711 				warn("rule %u: setsockopt(IP_FW_XDEL)",
3712 				    rt.start_rule);
3713 			} else if (rt.new_set == 0 && do_set == 0 &&
3714 			    g_co.do_dynamic != 2) {
3715 				exitval = EX_UNAVAILABLE;
3716 				if (g_co.do_quiet)
3717 					continue;
3718 				if (rt.start_rule != rt.end_rule)
3719 					warnx("no rules in %u-%u range",
3720 					    rt.start_rule, rt.end_rule);
3721 				else
3722 					warnx("rule %u not found",
3723 					    rt.start_rule);
3724 			}
3725 		}
3726 	}
3727 	if (exitval != EX_OK && g_co.do_force == 0)
3728 		exit(exitval);
3729 }
3730 
3731 /*
3732  * fill the interface structure. We do not check the name as we can
3733  * create interfaces dynamically, so checking them at insert time
3734  * makes relatively little sense.
3735  * Interface names containing '*', '?', or '[' are assumed to be shell
3736  * patterns which match interfaces.
3737  */
3738 static void
fill_iface(ipfw_insn_if * cmd,char * arg,int cblen,struct tidx * tstate)3739 fill_iface(ipfw_insn_if *cmd, char *arg, int cblen, struct tidx *tstate)
3740 {
3741 	char *p;
3742 	uint32_t uidx;
3743 
3744 	cmd->name[0] = '\0';
3745 	cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3746 
3747 	CHECK_CMDLEN;
3748 
3749 	/* Parse the interface or address */
3750 	if (strcmp(arg, "any") == 0)
3751 		cmd->o.len = 0;		/* effectively ignore this command */
3752 	else if (strncmp(arg, "table(", 6) == 0) {
3753 		if ((p = strchr(arg + 6, ')')) == NULL)
3754 			errx(EX_DATAERR, "forgotten parenthesis: '%s'", arg);
3755 		*p = '\0';
3756 		p = strchr(arg + 6, ',');
3757 		if (p)
3758 			*p++ = '\0';
3759 		if ((uidx = pack_table(tstate, arg + 6)) == 0)
3760 			errx(EX_DATAERR, "Invalid table name: %s", arg + 6);
3761 
3762 		cmd->name[0] = '\1'; /* Special value indicating table */
3763 		cmd->p.kidx = uidx;
3764 	} else if (!isdigit(*arg)) {
3765 		strlcpy(cmd->name, arg, sizeof(cmd->name));
3766 		cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3767 	} else if (!inet_aton(arg, &cmd->p.ip))
3768 		errx(EX_DATAERR, "bad ip address ``%s''", arg);
3769 }
3770 
3771 static void
get_mac_addr_mask(const char * p,uint8_t * addr,uint8_t * mask)3772 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
3773 {
3774 	int i;
3775 	size_t l;
3776 	char *ap, *ptr, *optr;
3777 	struct ether_addr *mac;
3778 	const char *macset = "0123456789abcdefABCDEF:";
3779 
3780 	if (strcmp(p, "any") == 0) {
3781 		for (i = 0; i < ETHER_ADDR_LEN; i++)
3782 			addr[i] = mask[i] = 0;
3783 		return;
3784 	}
3785 
3786 	optr = ptr = strdup(p);
3787 	if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
3788 		l = strlen(ap);
3789 		if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
3790 			errx(EX_DATAERR, "Incorrect MAC address");
3791 		bcopy(mac, addr, ETHER_ADDR_LEN);
3792 	} else
3793 		errx(EX_DATAERR, "Incorrect MAC address");
3794 
3795 	if (ptr != NULL) { /* we have mask? */
3796 		if (p[ptr - optr - 1] == '/') { /* mask len */
3797 			long ml = strtol(ptr, &ap, 10);
3798 			if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
3799 				errx(EX_DATAERR, "Incorrect mask length");
3800 			for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
3801 				mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
3802 		} else { /* mask */
3803 			l = strlen(ptr);
3804 			if (strspn(ptr, macset) != l ||
3805 			    (mac = ether_aton(ptr)) == NULL)
3806 				errx(EX_DATAERR, "Incorrect mask");
3807 			bcopy(mac, mask, ETHER_ADDR_LEN);
3808 		}
3809 	} else { /* default mask: ff:ff:ff:ff:ff:ff */
3810 		for (i = 0; i < ETHER_ADDR_LEN; i++)
3811 			mask[i] = 0xff;
3812 	}
3813 	for (i = 0; i < ETHER_ADDR_LEN; i++)
3814 		addr[i] &= mask[i];
3815 
3816 	free(optr);
3817 }
3818 
3819 /*
3820  * helper function, updates the pointer to cmd with the length
3821  * of the current command, and also cleans up the first word of
3822  * the new command in case it has been clobbered before.
3823  */
3824 static ipfw_insn *
next_cmd(ipfw_insn * cmd,int * len)3825 next_cmd(ipfw_insn *cmd, int *len)
3826 {
3827 	*len -= F_LEN(cmd);
3828 	CHECK_LENGTH(*len, 0);
3829 	cmd += F_LEN(cmd);
3830 	bzero(cmd, sizeof(*cmd));
3831 	return cmd;
3832 }
3833 
3834 /*
3835  * Takes arguments and copies them into a comment
3836  */
3837 static void
fill_comment(ipfw_insn * cmd,char ** av,int cblen)3838 fill_comment(ipfw_insn *cmd, char **av, int cblen)
3839 {
3840 	int i, l;
3841 	char *p = (char *)(cmd + 1);
3842 
3843 	cmd->opcode = O_NOP;
3844 	cmd->len =  (cmd->len & (F_NOT | F_OR));
3845 
3846 	/* Compute length of comment string. */
3847 	for (i = 0, l = 0; av[i] != NULL; i++)
3848 		l += strlen(av[i]) + 1;
3849 	if (l == 0)
3850 		return;
3851 	if (l > 84)
3852 		errx(EX_DATAERR,
3853 		    "comment too long (max 80 chars)");
3854 	l = 1 + (l+3)/4;
3855 	cmd->len =  (cmd->len & (F_NOT | F_OR)) | l;
3856 	CHECK_CMDLEN;
3857 
3858 	for (i = 0; av[i] != NULL; i++) {
3859 		strcpy(p, av[i]);
3860 		p += strlen(av[i]);
3861 		*p++ = ' ';
3862 	}
3863 	*(--p) = '\0';
3864 }
3865 
3866 /*
3867  * A function to fill simple commands of size 1.
3868  * Existing flags are preserved.
3869  */
3870 static void
fill_cmd(ipfw_insn * cmd,enum ipfw_opcodes opcode,int flags,uint16_t arg)3871 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3872 {
3873 	cmd->opcode = opcode;
3874 	cmd->len =  ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3875 	cmd->arg1 = arg;
3876 }
3877 
3878 /*
3879  * Fetch and add the MAC address and type, with masks. This generates one or
3880  * two microinstructions, and returns the pointer to the last one.
3881  */
3882 static ipfw_insn *
add_mac(ipfw_insn * cmd,char * av[],int cblen)3883 add_mac(ipfw_insn *cmd, char *av[], int cblen)
3884 {
3885 	ipfw_insn_mac *mac;
3886 
3887 	if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
3888 		errx(EX_DATAERR, "MAC dst src");
3889 
3890 	cmd->opcode = O_MACADDR2;
3891 	cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3892 	CHECK_CMDLEN;
3893 
3894 	mac = (ipfw_insn_mac *)cmd;
3895 	get_mac_addr_mask(av[0], mac->addr, mac->mask);	/* dst */
3896 	get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
3897 	    &(mac->mask[ETHER_ADDR_LEN])); /* src */
3898 	return cmd;
3899 }
3900 
3901 static ipfw_insn *
add_mactype(ipfw_insn * cmd,char * av,int cblen)3902 add_mactype(ipfw_insn *cmd, char *av, int cblen)
3903 {
3904 	if (!av)
3905 		errx(EX_DATAERR, "missing MAC type");
3906 	if (strcmp(av, "any") != 0) { /* we have a non-null type */
3907 		fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
3908 		    cblen);
3909 		cmd->opcode = O_MAC_TYPE;
3910 		return cmd;
3911 	} else
3912 		return NULL;
3913 }
3914 
3915 static ipfw_insn *
add_proto0(ipfw_insn * cmd,char * av,u_char * protop)3916 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
3917 {
3918 	struct protoent *pe;
3919 	char *ep;
3920 	int proto;
3921 
3922 	proto = strtol(av, &ep, 10);
3923 	if (*ep != '\0' || proto <= 0) {
3924 		if ((pe = getprotobyname(av)) == NULL)
3925 			return NULL;
3926 		proto = pe->p_proto;
3927 	}
3928 
3929 	fill_cmd(cmd, O_PROTO, 0, proto);
3930 	*protop = proto;
3931 	return cmd;
3932 }
3933 
3934 static ipfw_insn *
add_proto(ipfw_insn * cmd,char * av,u_char * protop)3935 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
3936 {
3937 	u_char proto = IPPROTO_IP;
3938 
3939 	if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3940 		; /* do not set O_IP4 nor O_IP6 */
3941 	else if (strcmp(av, "ip4") == 0)
3942 		/* explicit "just IPv4" rule */
3943 		fill_cmd(cmd, O_IP4, 0, 0);
3944 	else if (strcmp(av, "ip6") == 0) {
3945 		/* explicit "just IPv6" rule */
3946 		proto = IPPROTO_IPV6;
3947 		fill_cmd(cmd, O_IP6, 0, 0);
3948 	} else
3949 		return add_proto0(cmd, av, protop);
3950 
3951 	*protop = proto;
3952 	return cmd;
3953 }
3954 
3955 static ipfw_insn *
add_proto_compat(ipfw_insn * cmd,char * av,u_char * protop)3956 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
3957 {
3958 	u_char proto = IPPROTO_IP;
3959 
3960 	if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3961 		; /* do not set O_IP4 nor O_IP6 */
3962 	else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3963 		/* explicit "just IPv4" rule */
3964 		fill_cmd(cmd, O_IP4, 0, 0);
3965 	else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3966 		/* explicit "just IPv6" rule */
3967 		proto = IPPROTO_IPV6;
3968 		fill_cmd(cmd, O_IP6, 0, 0);
3969 	} else
3970 		return add_proto0(cmd, av, protop);
3971 
3972 	*protop = proto;
3973 	return cmd;
3974 }
3975 
3976 static ipfw_insn *
add_srcip(ipfw_insn * cmd,char * av,int cblen,struct tidx * tstate)3977 add_srcip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3978 {
3979 	fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3980 	if (cmd->opcode == O_IP_DST_SET)			/* set */
3981 		cmd->opcode = O_IP_SRC_SET;
3982 	else if (cmd->opcode == O_IP_DST_LOOKUP)		/* table */
3983 		cmd->opcode = O_IP_SRC_LOOKUP;
3984 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))		/* me */
3985 		cmd->opcode = O_IP_SRC_ME;
3986 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))	/* one IP */
3987 		cmd->opcode = O_IP_SRC;
3988 	else							/* addr/mask */
3989 		cmd->opcode = O_IP_SRC_MASK;
3990 	return cmd;
3991 }
3992 
3993 static ipfw_insn *
add_dstip(ipfw_insn * cmd,char * av,int cblen,struct tidx * tstate)3994 add_dstip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3995 {
3996 	fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3997 	if (cmd->opcode == O_IP_DST_SET)			/* set */
3998 		;
3999 	else if (cmd->opcode == O_IP_DST_LOOKUP)		/* table */
4000 		;
4001 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn))		/* me */
4002 		cmd->opcode = O_IP_DST_ME;
4003 	else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))	/* one IP */
4004 		cmd->opcode = O_IP_DST;
4005 	else							/* addr/mask */
4006 		cmd->opcode = O_IP_DST_MASK;
4007 	return cmd;
4008 }
4009 
4010 static ipfw_insn *
add_srcmac(ipfw_insn * cmd,char * av,struct tidx * tstate)4011 add_srcmac(ipfw_insn *cmd, char *av, struct tidx *tstate)
4012 {
4013 
4014 	if (strncmp(av, "table(", 6) == 0)
4015 		fill_table(cmd, av, O_MAC_SRC_LOOKUP, tstate);
4016 	else
4017 		errx(EX_DATAERR, "only mac table lookup is supported %s", av);
4018 	return cmd;
4019 }
4020 
4021 static ipfw_insn *
add_dstmac(ipfw_insn * cmd,char * av,struct tidx * tstate)4022 add_dstmac(ipfw_insn *cmd, char *av, struct tidx *tstate)
4023 {
4024 
4025 	if (strncmp(av, "table(", 6) == 0)
4026 		fill_table(cmd, av, O_MAC_DST_LOOKUP, tstate);
4027 	else
4028 		errx(EX_DATAERR, "only mac table lookup is supported %s", av);
4029 	return cmd;
4030 }
4031 
4032 
4033 static struct _s_x f_reserved_keywords[] = {
4034 	{ "altq",	TOK_OR },
4035 	{ "//",		TOK_OR },
4036 	{ "diverted",	TOK_OR },
4037 	{ "dst-port",	TOK_OR },
4038 	{ "src-port",	TOK_OR },
4039 	{ "established",	TOK_OR },
4040 	{ "keep-state",	TOK_OR },
4041 	{ "frag",	TOK_OR },
4042 	{ "icmptypes",	TOK_OR },
4043 	{ "in",		TOK_OR },
4044 	{ "out",	TOK_OR },
4045 	{ "ip6",	TOK_OR },
4046 	{ "any",	TOK_OR },
4047 	{ "to",		TOK_OR },
4048 	{ "via",	TOK_OR },
4049 	{ "{",		TOK_OR },
4050 	{ "lookup",	TOK_OR },
4051 	{ "tagged",	TOK_OR },
4052 	{ NULL, 0 }	/* terminator */
4053 };
4054 
4055 static ipfw_insn *
add_ports(ipfw_insn * cmd,char * av,u_char proto,int opcode,int cblen)4056 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
4057 {
4058 
4059 	if (match_token(f_reserved_keywords, av) != -1)
4060 		return (NULL);
4061 
4062 	if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
4063 		/* XXX todo: check that we have a protocol with ports */
4064 		cmd->opcode = opcode;
4065 		return cmd;
4066 	}
4067 	return NULL;
4068 }
4069 
4070 static ipfw_insn *
add_src(ipfw_insn * cmd,char * av,u_char proto,int cblen,struct tidx * tstate)4071 add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
4072 {
4073 	struct in6_addr a;
4074 	char *host, *ch, buf[INET6_ADDRSTRLEN];
4075 	ipfw_insn *ret = NULL;
4076 	size_t len;
4077 
4078 	/* Copy first address in set if needed */
4079 	if ((ch = strpbrk(av, "/,")) != NULL) {
4080 		len = ch - av;
4081 		strlcpy(buf, av, sizeof(buf));
4082 		if (len < sizeof(buf))
4083 			buf[len] = '\0';
4084 		host = buf;
4085 	} else
4086 		host = av;
4087 
4088 	if (proto == IPPROTO_IPV6  || strcmp(av, "me6") == 0 ||
4089 	    inet_pton(AF_INET6, host, &a) == 1)
4090 		ret = add_srcip6(cmd, av, cblen, tstate);
4091 	/* XXX: should check for IPv4, not !IPv6 */
4092 	if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
4093 	    inet_pton(AF_INET6, host, &a) != 1))
4094 		ret = add_srcip(cmd, av, cblen, tstate);
4095 	if (ret == NULL && strcmp(av, "any") != 0)
4096 		ret = cmd;
4097 
4098 	return ret;
4099 }
4100 
4101 static ipfw_insn *
add_dst(ipfw_insn * cmd,char * av,u_char proto,int cblen,struct tidx * tstate)4102 add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
4103 {
4104 	struct in6_addr a;
4105 	char *host, *ch, buf[INET6_ADDRSTRLEN];
4106 	ipfw_insn *ret = NULL;
4107 	size_t len;
4108 
4109 	/* Copy first address in set if needed */
4110 	if ((ch = strpbrk(av, "/,")) != NULL) {
4111 		len = ch - av;
4112 		strlcpy(buf, av, sizeof(buf));
4113 		if (len < sizeof(buf))
4114 			buf[len] = '\0';
4115 		host = buf;
4116 	} else
4117 		host = av;
4118 
4119 	if (proto == IPPROTO_IPV6  || strcmp(av, "me6") == 0 ||
4120 	    inet_pton(AF_INET6, host, &a) == 1)
4121 		ret = add_dstip6(cmd, av, cblen, tstate);
4122 	/* XXX: should check for IPv4, not !IPv6 */
4123 	if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
4124 	    inet_pton(AF_INET6, host, &a) != 1))
4125 		ret = add_dstip(cmd, av, cblen, tstate);
4126 	if (ret == NULL && strcmp(av, "any") != 0)
4127 		ret = cmd;
4128 
4129 	return ret;
4130 }
4131 
4132 static uint16_t
parse_logdst(char * logdst_iter)4133 parse_logdst(char *logdst_iter)
4134 {
4135 	char *token;
4136 	uint16_t ret;
4137 
4138 	ret = IPFW_LOG_DEFAULT;
4139 	while ((token = strsep(&logdst_iter, ",")) != NULL) {
4140 		if (_substrcmp(token, "syslog") == 0) {
4141 			ret |= IPFW_LOG_SYSLOG;
4142 			continue;
4143 		}
4144 		/* ipfw0 is compatibility keyword. */
4145 		if (_substrcmp(token, "bpf") == 0 ||
4146 		    _substrcmp(token, "ipfw0") == 0) {
4147 			ret |= IPFW_LOG_IPFW0;
4148 			continue;
4149 		}
4150 		if (_substrcmp(token, "rtsock") == 0) {
4151 			ret |= IPFW_LOG_RTSOCK;
4152 			continue;
4153 		}
4154 		errx(EX_DATAERR,
4155 		    "unsupported logdst token");
4156 	}
4157 	return (ret);
4158 }
4159 
4160 static inline uint32_t
arg_or_targ_relaxed(const char * arg,const char * action,uint32_t maxarg)4161 arg_or_targ_relaxed(const char *arg, const char *action, uint32_t maxarg)
4162 {
4163 	uint32_t arg1 = (uint32_t)(-1);
4164 
4165 	if (arg == NULL)
4166 		errx(EX_USAGE, "missing argument for %s", action);
4167 	if (isdigit(arg[0])) {
4168 		arg1 = strtoul(arg, NULL, 10);
4169 		if (arg1 < IPFW_ARG_MIN || arg1 > maxarg)
4170 			errx(EX_DATAERR, "illegal argument %s(%u) for %s",
4171 			    arg, arg1, action);
4172 	} else if (_substrcmp(arg, "tablearg") == 0)
4173 		arg1 = IP_FW_TARG;
4174 	return (arg1);
4175 }
4176 
4177 static inline uint32_t
arg_or_targ(const char * arg,const char * action)4178 arg_or_targ(const char *arg, const char *action)
4179 {
4180 	uint32_t arg1 = arg_or_targ_relaxed(arg, action, IPFW_ARG_MAX);
4181 
4182 	if (arg1 == (uint32_t)(-1))
4183 		errx(EX_DATAERR, "illegal argument %s(%u) for %s",
4184 		    arg, arg1, action);
4185 	return (arg1);
4186 }
4187 
4188 static uint16_t
get_divert_port(const char * arg,const char * action)4189 get_divert_port(const char *arg, const char *action)
4190 {
4191 	uint32_t arg1 = arg_or_targ_relaxed(arg, action, IPFW_ARG_MAX);
4192 
4193 	if (arg1 != (uint32_t)(-1))
4194 		return (arg1);
4195 
4196 	struct servent *s;
4197 	setservent(1);
4198 	s = getservbyname(arg, "divert");
4199 	if (s == NULL)
4200 		errx(EX_DATAERR, "illegal divert/tee port");
4201 	return (ntohs(s->s_port));
4202 }
4203 
4204 static void
get_lookup_bitmask(int ltype,ipfw_insn_lookup * cmd,const char * src)4205 get_lookup_bitmask(int ltype, ipfw_insn_lookup *cmd, const char *src)
4206 {
4207 	struct ether_addr *mac;
4208 	const char *macset = "0123456789abcdefABCDEF:";
4209 
4210 	if (ltype == LOOKUP_SRC_IP6 || ltype == LOOKUP_DST_IP6) {
4211 		if (inet_pton(AF_INET6, src, &cmd->ip6) != 1)
4212 			errx(EX_USAGE, "invalid IPv6 mask provided");
4213 		return;
4214 	} else if (ltype == LOOKUP_SRC_MAC || ltype == LOOKUP_DST_MAC) {
4215 		if (strspn(src, macset) != strlen(src) ||
4216 		    (mac = ether_aton(src)) == NULL)
4217 			errx(EX_DATAERR, "Incorrect MAC address");
4218 
4219 		bcopy(mac, cmd->mac, ETHER_ADDR_LEN);
4220 		return;
4221 	/* mask in a dotted-quad notation */
4222 	} else if (strchr(src, '.') != NULL) {
4223 		if (inet_aton(src, &cmd->ip4) != 1)
4224 			errx(EX_USAGE, "invalid dotted-quad mask provided");
4225 		switch (ltype) {
4226 		case LOOKUP_SRC_IP4:
4227 		case LOOKUP_DST_IP4:
4228 			return;
4229 		}
4230 		cmd->u32 = ntohl(cmd->u32);
4231 		return;
4232 	}
4233 	cmd->u32 = strtoul(src, NULL, 0);
4234 }
4235 
4236 /*
4237  * Parse arguments and assemble the microinstructions which make up a rule.
4238  * Rules are added into the 'rulebuf' and then copied in the correct order
4239  * into the actual rule.
4240  *
4241  * The syntax for a rule starts with the action, followed by
4242  * optional action parameters, and the various match patterns.
4243  * In the assembled microcode, the first opcode must be an O_PROBE_STATE
4244  * (generated if the rule includes a keep-state option), then the
4245  * various match patterns, log/altq actions, and the actual action.
4246  *
4247  */
4248 static void
compile_rule(char * av[],uint32_t * rbuf,int * rbufsize,struct tidx * tstate)4249 compile_rule(char *av[], uint32_t *rbuf, int *rbufsize, struct tidx *tstate)
4250 {
4251 	/*
4252 	 * rules are added into the 'rulebuf' and then copied in
4253 	 * the correct order into the actual rule.
4254 	 * Some things that need to go out of order (prob, action etc.)
4255 	 * go into actbuf[].
4256 	 */
4257 	static uint32_t actbuf[255], cmdbuf[255];
4258 	int rblen, ablen, cblen;
4259 
4260 	ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
4261 	ipfw_insn *first_cmd;	/* first match pattern */
4262 
4263 	struct ip_fw_rule *rule;
4264 
4265 	/*
4266 	 * various flags used to record that we entered some fields.
4267 	 */
4268 	ipfw_insn *have_state = NULL;	/* any state-related option */
4269 	int have_rstate = 0;
4270 	ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
4271 	ipfw_insn *have_skipcmd = NULL;
4272 	size_t len;
4273 
4274 	int i;
4275 
4276 	int open_par = 0;	/* open parenthesis ( */
4277 
4278 	/* proto is here because it is used to fetch ports */
4279 	u_char proto = IPPROTO_IP;	/* default protocol */
4280 
4281 	double match_prob = 1; /* match probability, default is always match */
4282 
4283 	bzero(actbuf, sizeof(actbuf));		/* actions go here */
4284 	bzero(cmdbuf, sizeof(cmdbuf));
4285 	bzero(rbuf, *rbufsize);
4286 
4287 	rule = (struct ip_fw_rule *)rbuf;
4288 	cmd = (ipfw_insn *)cmdbuf;
4289 	action = (ipfw_insn *)actbuf;
4290 
4291 	rblen = *rbufsize / sizeof(uint32_t);
4292 	rblen -= sizeof(struct ip_fw_rule) / sizeof(uint32_t);
4293 	ablen = nitems(actbuf);
4294 	cblen = nitems(cmdbuf);
4295 	cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
4296 
4297 #define	CHECK_RBUFLEN(len)	{ CHECK_LENGTH(rblen, len); rblen -= len; }
4298 #define	CHECK_ACTLEN		CHECK_LENGTH(ablen, action->len)
4299 
4300 	av++;
4301 
4302 	/* [rule N]	-- Rule number optional */
4303 	if (av[0] && isdigit(**av)) {
4304 		rule->rulenum = atoi(*av);
4305 		av++;
4306 	}
4307 
4308 	/* [set N]	-- set number (0..RESVD_SET), optional */
4309 	if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
4310 		int set = strtoul(av[1], NULL, 10);
4311 		if (set < 0 || set > RESVD_SET)
4312 			errx(EX_DATAERR, "illegal set %s", av[1]);
4313 		rule->set = set;
4314 		tstate->set = set;
4315 		av += 2;
4316 	}
4317 
4318 	/* [prob D]	-- match probability, optional */
4319 	if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
4320 		match_prob = strtod(av[1], NULL);
4321 
4322 		if (match_prob <= 0 || match_prob > 1)
4323 			errx(EX_DATAERR, "illegal match prob. %s", av[1]);
4324 		av += 2;
4325 	}
4326 
4327 	/* action	-- mandatory */
4328 	NEED1("missing action");
4329 	i = match_token(rule_actions, *av);
4330 	av++;
4331 	action->len = 1;	/* default */
4332 	CHECK_ACTLEN;
4333 	switch(i) {
4334 	case TOK_CHECKSTATE:
4335 		have_state = action;
4336 		action->opcode = O_CHECK_STATE;
4337 		action->len = F_INSN_SIZE(ipfw_insn_kidx);
4338 		CHECK_ACTLEN;
4339 		if (*av == NULL ||
4340 		    match_token(rule_options, *av) == TOK_COMMENT) {
4341 			insntod(have_state, kidx)->kidx = pack_object(tstate,
4342 			    default_state_name, IPFW_TLV_STATE_NAME);
4343 			break;
4344 		}
4345 		if (*av[0] == ':') {
4346 			if (strcmp(*av + 1, "any") == 0)
4347 				insntod(have_state, kidx)->kidx = 0;
4348 			else if (state_check_name(*av + 1) == 0)
4349 				insntod(have_state, kidx)->kidx = pack_object(
4350 				    tstate, *av + 1, IPFW_TLV_STATE_NAME);
4351 			else
4352 				errx(EX_DATAERR, "Invalid state name %s",
4353 				    *av);
4354 			av++;
4355 			break;
4356 		}
4357 		errx(EX_DATAERR, "Invalid state name %s", *av);
4358 		break;
4359 
4360 	case TOK_ABORT:
4361 		action->opcode = O_REJECT;
4362 		action->arg1 = ICMP_REJECT_ABORT;
4363 		break;
4364 
4365 	case TOK_ABORT6:
4366 		action->opcode = O_UNREACH6;
4367 		action->arg1 = ICMP6_UNREACH_ABORT;
4368 		break;
4369 
4370 	case TOK_ACCEPT:
4371 		action->opcode = O_ACCEPT;
4372 		break;
4373 
4374 	case TOK_DENY:
4375 		action->opcode = O_DENY;
4376 		action->arg1 = 0;
4377 		break;
4378 
4379 	case TOK_REJECT:
4380 		action->opcode = O_REJECT;
4381 		action->arg1 = ICMP_UNREACH_HOST;
4382 		break;
4383 
4384 	case TOK_RESET:
4385 		action->opcode = O_REJECT;
4386 		action->arg1 = ICMP_REJECT_RST;
4387 		break;
4388 
4389 	case TOK_RESET6:
4390 		action->opcode = O_UNREACH6;
4391 		action->arg1 = ICMP6_UNREACH_RST;
4392 		break;
4393 
4394 	case TOK_UNREACH:
4395 		action->opcode = O_REJECT;
4396 		NEED1("missing reject code");
4397 		action->arg1 = get_reject_code(*av);
4398 		av++;
4399 		if (action->arg1 == ICMP_UNREACH_NEEDFRAG && isdigit(**av)) {
4400 			uint16_t mtu;
4401 
4402 			mtu = strtoul(*av, NULL, 10);
4403 			if (mtu < 68 || mtu >= IP_MAXPACKET)
4404 				errx(EX_DATAERR, "illegal argument for %s",
4405 				    *(av - 1));
4406 			action->len = F_INSN_SIZE(ipfw_insn_u16);
4407 			insntod(action, u16)->ports[0] = mtu;
4408 			av++;
4409 		}
4410 		break;
4411 
4412 	case TOK_UNREACH6:
4413 		action->opcode = O_UNREACH6;
4414 		NEED1("missing unreach code");
4415 		action->arg1 = get_unreach6_code(*av);
4416 		av++;
4417 		break;
4418 
4419 	case TOK_COUNT:
4420 		action->opcode = O_COUNT;
4421 		break;
4422 
4423 	case TOK_NAT:
4424 		action->opcode = O_NAT;
4425 		action->len = F_INSN_SIZE(ipfw_insn_nat);
4426 		CHECK_ACTLEN;
4427 		if (*av != NULL && _substrcmp(*av, "global") == 0)
4428 			action->arg1 = IP_FW_NAT44_GLOBAL;
4429 		else
4430 			action->arg1 = arg_or_targ(av[0], *(av - 1));
4431 		av++;
4432 		break;
4433 	case TOK_QUEUE:
4434 		action->opcode = O_QUEUE;
4435 		action->arg1 = arg_or_targ(av[0], *(av - 1));
4436 		av++;
4437 		break;
4438 	case TOK_PIPE:
4439 		action->opcode = O_PIPE;
4440 		action->arg1 = arg_or_targ(av[0], *(av - 1));
4441 		av++;
4442 		break;
4443 	case TOK_SKIPTO:
4444 		action->opcode = O_SKIPTO;
4445 		action->len = F_INSN_SIZE(ipfw_insn_u32);
4446 		CHECK_ACTLEN;
4447 		insntod(action, u32)->d[0] =
4448 		    arg_or_targ_relaxed(av[0], *(av - 1), IPFW_DEFAULT_RULE);
4449 		av++;
4450 		break;
4451 	case TOK_NETGRAPH:
4452 		action->opcode = O_NETGRAPH;
4453 		action->arg1 = arg_or_targ(av[0], *(av - 1));
4454 		av++;
4455 		break;
4456 	case TOK_NGTEE:
4457 		action->opcode = O_NGTEE;
4458 		action->arg1 = arg_or_targ(av[0], *(av - 1));
4459 		av++;
4460 		break;
4461 	case TOK_DIVERT:
4462 		action->opcode = O_DIVERT;
4463 		action->arg1 = get_divert_port(av[0], *(av - 1));
4464 		av++;
4465 		break;
4466 	case TOK_TEE:
4467 		action->opcode = O_TEE;
4468 		action->arg1 = get_divert_port(av[0], *(av - 1));
4469 		av++;
4470 		break;
4471 	case TOK_CALL:
4472 		action->opcode = O_CALLRETURN;
4473 		action->len = F_INSN_SIZE(ipfw_insn_u32);
4474 		CHECK_ACTLEN;
4475 		insntod(action, u32)->d[0] =
4476 		    arg_or_targ_relaxed(av[0], *(av - 1), IPFW_DEFAULT_RULE);
4477 		av++;
4478 		break;
4479 
4480 	case TOK_FORWARD: {
4481 		/*
4482 		 * Locate the address-port separator (':' or ',').
4483 		 * Could be one of the following:
4484 		 *	hostname:port
4485 		 *	IPv4 a.b.c.d,port
4486 		 *	IPv4 a.b.c.d:port
4487 		 *	IPv6 w:x:y::z,port
4488 		 *	IPv6 [w:x:y::z]:port
4489 		 */
4490 		struct sockaddr_storage result;
4491 		struct addrinfo *res;
4492 		char *s, *end;
4493 		int family;
4494 		u_short port_number = 0;
4495 
4496 		NEED1("missing forward address[:port]");
4497 
4498 		if (strncmp(*av, "tablearg", 8) == 0 &&
4499 		    ((*av)[8] == '\0' || (*av)[8] == ',' || (*av)[8] == ':'))
4500 			memcpy(++(*av), "0.0.0.0", 7);
4501 
4502 		/*
4503 		 * Are we an bracket-enclosed IPv6 address?
4504 		 */
4505 		if (strchr(*av, '['))
4506 			(*av)++;
4507 
4508 		/*
4509 		 * locate the address-port separator (':' or ',')
4510 		 */
4511 		s = strchr(*av, ',');
4512 		if (s == NULL) {
4513 			s = strchr(*av, ']');
4514 			/* Prevent erroneous parsing on brackets. */
4515 			if (s != NULL)
4516 				*(s++) = '\0';
4517 			else
4518 				s = *av;
4519 
4520 			/* Distinguish between IPv4:port and IPv6 cases. */
4521 			s = strchr(s, ':');
4522 			if (s && strchr(s+1, ':'))
4523 				s = NULL; /* no port */
4524 		}
4525 
4526 		if (s != NULL) {
4527 			/* Terminate host portion and set s to start of port. */
4528 			*(s++) = '\0';
4529 			i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
4530 			if (s == end)
4531 				errx(EX_DATAERR,
4532 				    "illegal forwarding port ``%s''", s);
4533 			port_number = (u_short)i;
4534 		}
4535 
4536 		/*
4537 		 * Resolve the host name or address to a family and a
4538 		 * network representation of the address.
4539 		 */
4540 		if (getaddrinfo(*av, NULL, NULL, &res))
4541 			errx(EX_DATAERR, NULL);
4542 		/* Just use the first host in the answer. */
4543 		family = res->ai_family;
4544 		memcpy(&result, res->ai_addr, res->ai_addrlen);
4545 		freeaddrinfo(res);
4546 
4547  		if (family == PF_INET) {
4548 			ipfw_insn_sa *p = (ipfw_insn_sa *)action;
4549 
4550 			action->opcode = O_FORWARD_IP;
4551 			action->len = F_INSN_SIZE(ipfw_insn_sa);
4552 			CHECK_ACTLEN;
4553 
4554 			/*
4555 			 * In the kernel we assume AF_INET and use only
4556 			 * sin_port and sin_addr. Remember to set sin_len as
4557 			 * the routing code seems to use it too.
4558 			 */
4559 			p->sa.sin_len = sizeof(struct sockaddr_in);
4560 			p->sa.sin_family = AF_INET;
4561 			p->sa.sin_port = port_number;
4562 			p->sa.sin_addr.s_addr =
4563 			     ((struct sockaddr_in *)&result)->sin_addr.s_addr;
4564 		} else if (family == PF_INET6) {
4565 			ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
4566 
4567 			action->opcode = O_FORWARD_IP6;
4568 			action->len = F_INSN_SIZE(ipfw_insn_sa6);
4569 			CHECK_ACTLEN;
4570 
4571 			p->sa.sin6_len = sizeof(struct sockaddr_in6);
4572 			p->sa.sin6_family = AF_INET6;
4573 			p->sa.sin6_port = port_number;
4574 			p->sa.sin6_flowinfo = 0;
4575 			p->sa.sin6_scope_id =
4576 			    ((struct sockaddr_in6 *)&result)->sin6_scope_id;
4577 			bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
4578 			    &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
4579 		} else {
4580 			errx(EX_DATAERR, "Invalid address family in forward action");
4581 		}
4582 		av++;
4583 		break;
4584 	    }
4585 	case TOK_COMMENT:
4586 		/* pretend it is a 'count' rule followed by the comment */
4587 		action->opcode = O_COUNT;
4588 		av--;		/* go back... */
4589 		break;
4590 
4591 	case TOK_SETFIB:
4592 	    {
4593 		int numfibs;
4594 		size_t intsize = sizeof(int);
4595 
4596 		action->opcode = O_SETFIB;
4597 		NEED1("missing fib number");
4598 		if (_substrcmp(*av, "tablearg") == 0) {
4599 			action->arg1 = IP_FW_TARG;
4600 		} else {
4601 		        action->arg1 = strtoul(*av, NULL, 10);
4602 			if (sysctlbyname("net.fibs", &numfibs, &intsize,
4603 			    NULL, 0) == -1)
4604 				errx(EX_DATAERR, "fibs not supported.\n");
4605 			if (action->arg1 >= numfibs)  /* Temporary */
4606 				errx(EX_DATAERR, "fib too large.\n");
4607 			/* Add high-order bit to fib to make room for tablearg*/
4608 			action->arg1 |= 0x8000;
4609 		}
4610 		av++;
4611 		break;
4612 	    }
4613 
4614 	case TOK_SETDSCP:
4615 	    {
4616 		int code;
4617 
4618 		action->opcode = O_SETDSCP;
4619 		NEED1("missing DSCP code");
4620 		if (_substrcmp(*av, "tablearg") == 0) {
4621 			action->arg1 = IP_FW_TARG;
4622 		} else {
4623 			if (isalpha(*av[0])) {
4624 				if ((code = match_token(f_ipdscp, *av)) == -1)
4625 					errx(EX_DATAERR, "Unknown DSCP code");
4626 				action->arg1 = code;
4627 			} else
4628 			        action->arg1 = strtoul(*av, NULL, 10);
4629 			/*
4630 			 * Add high-order bit to DSCP to make room
4631 			 * for tablearg
4632 			 */
4633 			action->arg1 |= 0x8000;
4634 		}
4635 		av++;
4636 		break;
4637 	    }
4638 
4639 	case TOK_REASS:
4640 		action->opcode = O_REASS;
4641 		break;
4642 
4643 	case TOK_RETURN:
4644 		action->opcode = O_CALLRETURN;
4645 		action->len = F_INSN_SIZE(ipfw_insn_u32) | F_NOT;
4646 		CHECK_ACTLEN;
4647 		if (*av != NULL) {
4648 			/*
4649 			 * Return type is optional.
4650 			 * By default we use RETURN_NEXT_RULENUM.
4651 			 */
4652 			i = match_token(return_types, *av);
4653 			if (i >= 0) {
4654 				action->arg1 = i;
4655 				av++;
4656 			} else
4657 				action->arg1 = RETURN_NEXT_RULENUM;
4658 		}
4659 		break;
4660 
4661 	case TOK_SETMARK: {
4662 		action->opcode = O_SETMARK;
4663 		action->len = F_INSN_SIZE(ipfw_insn_u32);
4664 		NEED1("missing mark");
4665 		if (strcmp(*av, "tablearg") == 0) {
4666 			action->arg1 = IP_FW_TARG;
4667 		} else {
4668 		        insntod(action, u32)->d[0] = strtoul(*av, NULL, 0);
4669 			/* This is not a tablearg */
4670 			action->arg1 |= 0x8000;
4671 		}
4672 		av++;
4673 		CHECK_CMDLEN;
4674 		break;
4675 	}
4676 
4677 	case TOK_TCPSETMSS: {
4678 		u_long mss;
4679 		uint32_t idx;
4680 
4681 		idx = pack_object(tstate, "tcp-setmss", IPFW_TLV_EACTION);
4682 		if (idx == 0)
4683 			errx(EX_DATAERR, "pack_object failed");
4684 		action->opcode = O_EXTERNAL_ACTION;
4685 		action->len = F_INSN_SIZE(ipfw_insn_kidx);
4686 		CHECK_ACTLEN;
4687 		insntod(action, kidx)->kidx = idx;
4688 
4689 		NEED1("Missing MSS value");
4690 		action = next_cmd(action, &ablen);
4691 		action->len = 1;
4692 		CHECK_ACTLEN;
4693 		mss = strtoul(*av, NULL, 10);
4694 		if (mss == 0 || mss > UINT16_MAX)
4695 			errx(EX_USAGE, "invalid MSS value %s", *av);
4696 		fill_cmd(action, O_EXTERNAL_DATA, 0, (uint16_t)mss);
4697 		av++;
4698 		break;
4699 	}
4700 
4701 	default:
4702 		av--;
4703 		if (match_token(rule_eactions, *av) == -1)
4704 			errx(EX_DATAERR, "invalid action %s\n", *av);
4705 		/*
4706 		 * External actions support.
4707 		 * XXX: we support only syntax with instance name.
4708 		 *	For known external actions (from rule_eactions list)
4709 		 *	we can handle syntax directly. But with `eaction'
4710 		 *	keyword we can use only `eaction <name> <instance>'
4711 		 *	syntax.
4712 		 */
4713 	case TOK_EACTION: {
4714 		uint32_t idx;
4715 
4716 		NEED1("Missing eaction name");
4717 		if (eaction_check_name(*av) != 0)
4718 			errx(EX_DATAERR, "Invalid eaction name %s", *av);
4719 		idx = pack_object(tstate, *av, IPFW_TLV_EACTION);
4720 		if (idx == 0)
4721 			errx(EX_DATAERR, "pack_object failed");
4722 		action->opcode = O_EXTERNAL_ACTION;
4723 		action->len = F_INSN_SIZE(ipfw_insn_kidx);
4724 		CHECK_ACTLEN;
4725 		insntod(action, kidx)->kidx = idx;
4726 
4727 		av++;
4728 		NEED1("Missing eaction instance name");
4729 		if (eaction_check_name(*av) != 0)
4730 			errx(EX_DATAERR, "Invalid eaction instance name %s",
4731 			    *av);
4732 		/*
4733 		 * External action instance object has TLV type depended
4734 		 * from the external action name object index. Since we
4735 		 * currently don't know this index, use zero as TLV type.
4736 		 */
4737 		idx = pack_object(tstate, *av, 0);
4738 		if (idx == 0)
4739 			errx(EX_DATAERR, "pack_object failed");
4740 		action = next_cmd(action, &ablen);
4741 		action->opcode = O_EXTERNAL_INSTANCE;
4742 		action->len = F_INSN_SIZE(ipfw_insn_kidx);
4743 		CHECK_ACTLEN;
4744 		insntod(action, kidx)->kidx = idx;
4745 		av++;
4746 		}
4747 	}
4748 	action = next_cmd(action, &ablen);
4749 
4750 	/*
4751 	 * [altq queuename] -- altq tag, optional
4752 	 * [log [logamount N]]	-- log, optional
4753 	 *
4754 	 * If they exist, it go first in the cmdbuf, but then it is
4755 	 * skipped in the copy section to the end of the buffer.
4756 	 */
4757 	while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
4758 		av++;
4759 		switch (i) {
4760 		case TOK_LOG:
4761 		    {
4762 			ipfw_insn_log *c = (ipfw_insn_log *)cmd;
4763 			int l;
4764 
4765 			if (have_log)
4766 				errx(EX_DATAERR,
4767 				    "log cannot be specified more than once");
4768 			have_log = (ipfw_insn *)c;
4769 			cmd->len = F_INSN_SIZE(ipfw_insn_log);
4770 			CHECK_CMDLEN;
4771 			cmd->opcode = O_LOG;
4772 			cmd->arg1 = IPFW_LOG_DEFAULT;
4773 			/* logdst before logamount */
4774 			if (av[0] && _substrcmp(*av, "logdst") == 0) {
4775 				av++;
4776 				NEED1("logdst requires argument");
4777 				cmd->arg1 = parse_logdst(*av);
4778 				av++;
4779 			}
4780 
4781 			if (av[0] && _substrcmp(*av, "logamount") == 0) {
4782 				av++;
4783 				NEED1("logamount requires argument");
4784 				l = atoi(*av);
4785 				if (l < 0)
4786 					errx(EX_DATAERR,
4787 					    "logamount must be positive");
4788 				c->max_log = l;
4789 				av++;
4790 			} else {
4791 				len = sizeof(c->max_log);
4792 				if (sysctlbyname("net.inet.ip.fw.verbose_limit",
4793 				    &c->max_log, &len, NULL, 0) == -1) {
4794 					if (g_co.test_only) {
4795 						c->max_log = 0;
4796 						break;
4797 					}
4798 					errx(1, "sysctlbyname(\"%s\")",
4799 					    "net.inet.ip.fw.verbose_limit");
4800 				}
4801 			}
4802 
4803 			/* logdst after logamount */
4804 			if (av[0] && _substrcmp(*av, "logdst") == 0) {
4805 				av++;
4806 				NEED1("logdst requires argument");
4807 				cmd->arg1 = parse_logdst(*av);
4808 				av++;
4809 			}
4810 		    }
4811 			break;
4812 
4813 #ifndef NO_ALTQ
4814 		case TOK_ALTQ:
4815 		    {
4816 			ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
4817 
4818 			NEED1("missing altq queue name");
4819 			if (have_altq)
4820 				errx(EX_DATAERR,
4821 				    "altq cannot be specified more than once");
4822 			have_altq = (ipfw_insn *)a;
4823 			cmd->len = F_INSN_SIZE(ipfw_insn_altq);
4824 			CHECK_CMDLEN;
4825 			cmd->opcode = O_ALTQ;
4826 			a->qid = altq_name_to_qid(*av);
4827 			av++;
4828 		    }
4829 			break;
4830 #endif
4831 
4832 		case TOK_TAG:
4833 		case TOK_UNTAG: {
4834 			uint16_t tag;
4835 
4836 			if (have_tag)
4837 				errx(EX_USAGE, "tag and untag cannot be "
4838 				    "specified more than once");
4839 			GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
4840 			   rule_action_params);
4841 			have_tag = cmd;
4842 			fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
4843 			av++;
4844 			break;
4845 		}
4846 
4847 		default:
4848 			abort();
4849 		}
4850 		cmd = next_cmd(cmd, &cblen);
4851 	}
4852 
4853 	if (have_state)	{ /* must be a check-state, we are done */
4854 		if (*av != NULL &&
4855 		    match_token(rule_options, *av) == TOK_COMMENT) {
4856 			/* check-state has a comment */
4857 			av++;
4858 			fill_comment(cmd, av, cblen);
4859 			cmd = next_cmd(cmd, &cblen);
4860 			av[0] = NULL;
4861 		}
4862 		goto done;
4863 	}
4864 
4865 #define OR_START(target)					\
4866 	if (av[0] && (*av[0] == '(' || *av[0] == '{')) { 	\
4867 		if (open_par)					\
4868 			errx(EX_USAGE, "nested \"(\" not allowed\n"); \
4869 		prev = NULL;					\
4870 		open_par = 1;					\
4871 		if ( (av[0])[1] == '\0') {			\
4872 			av++;					\
4873 		} else						\
4874 			(*av)++;				\
4875 	}							\
4876 	target:							\
4877 
4878 
4879 #define	CLOSE_PAR						\
4880 	if (open_par) {						\
4881 		if (av[0] && (					\
4882 		    strcmp(*av, ")") == 0 ||			\
4883 		    strcmp(*av, "}") == 0)) {			\
4884 			prev = NULL;				\
4885 			open_par = 0;				\
4886 			av++;					\
4887 		} else						\
4888 			errx(EX_USAGE, "missing \")\"\n");	\
4889 	}
4890 
4891 #define NOT_BLOCK						\
4892 	if (av[0] && _substrcmp(*av, "not") == 0) {		\
4893 		if (cmd->len & F_NOT)				\
4894 			errx(EX_USAGE, "double \"not\" not allowed\n"); \
4895 		cmd->len |= F_NOT;				\
4896 		av++;						\
4897 	}
4898 
4899 #define OR_BLOCK(target)					\
4900 	if (av[0] && _substrcmp(*av, "or") == 0) {		\
4901 		if (prev == NULL || open_par == 0)		\
4902 			errx(EX_DATAERR, "invalid OR block");	\
4903 		prev->len |= F_OR;				\
4904 		av++;					\
4905 		goto target;					\
4906 	}							\
4907 	CLOSE_PAR;
4908 
4909 	first_cmd = cmd;
4910 
4911 #if 0
4912 	/*
4913 	 * MAC addresses, optional.
4914 	 * If we have this, we skip the part "proto from src to dst"
4915 	 * and jump straight to the option parsing.
4916 	 */
4917 	NOT_BLOCK;
4918 	NEED1("missing protocol");
4919 	if (_substrcmp(*av, "MAC") == 0 ||
4920 	    _substrcmp(*av, "mac") == 0) {
4921 		av++;			/* the "MAC" keyword */
4922 		add_mac(cmd, av);	/* exits in case of errors */
4923 		cmd = next_cmd(cmd);
4924 		av += 2;		/* dst-mac and src-mac */
4925 		NOT_BLOCK;
4926 		NEED1("missing mac type");
4927 		if (add_mactype(cmd, av[0]))
4928 			cmd = next_cmd(cmd);
4929 		av++;			/* any or mac-type */
4930 		goto read_options;
4931 	}
4932 #endif
4933 
4934 	/*
4935 	 * protocol, mandatory
4936 	 */
4937     OR_START(get_proto);
4938 	NOT_BLOCK;
4939 	NEED1("missing protocol");
4940 	if (add_proto_compat(cmd, *av, &proto)) {
4941 		av++;
4942 		if (F_LEN(cmd) != 0) {
4943 			prev = cmd;
4944 			cmd = next_cmd(cmd, &cblen);
4945 		}
4946 	} else if (first_cmd != cmd) {
4947 		errx(EX_DATAERR, "invalid protocol ``%s''", *av);
4948 	} else {
4949 		rule->flags |= IPFW_RULE_JUSTOPTS;
4950 		goto read_options;
4951 	}
4952     OR_BLOCK(get_proto);
4953 
4954 	first_cmd = cmd; /* update pointer to use in compact form */
4955 
4956 	/*
4957 	 * "from", mandatory
4958 	 */
4959 	if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
4960 		errx(EX_USAGE, "missing ``from''");
4961 	av++;
4962 
4963 	/*
4964 	 * source IP, mandatory
4965 	 */
4966     OR_START(source_ip);
4967 	NOT_BLOCK;	/* optional "not" */
4968 	NEED1("missing source address");
4969 	if (add_src(cmd, *av, proto, cblen, tstate)) {
4970 		av++;
4971 		if (F_LEN(cmd) != 0) {	/* ! any */
4972 			prev = cmd;
4973 			cmd = next_cmd(cmd, &cblen);
4974 		}
4975 	} else
4976 		errx(EX_USAGE, "bad source address %s", *av);
4977     OR_BLOCK(source_ip);
4978 
4979 	/*
4980 	 * source ports, optional
4981 	 */
4982 	NOT_BLOCK;	/* optional "not" */
4983 	if ( av[0] != NULL ) {
4984 		if (_substrcmp(*av, "any") == 0 ||
4985 		    add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4986 			av++;
4987 			if (F_LEN(cmd) != 0)
4988 				cmd = next_cmd(cmd, &cblen);
4989 		}
4990 	}
4991 
4992 	/*
4993 	 * "to", mandatory
4994 	 */
4995 	if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
4996 		errx(EX_USAGE, "missing ``to''");
4997 	av++;
4998 
4999 	/*
5000 	 * destination, mandatory
5001 	 */
5002     OR_START(dest_ip);
5003 	NOT_BLOCK;	/* optional "not" */
5004 	NEED1("missing dst address");
5005 	if (add_dst(cmd, *av, proto, cblen, tstate)) {
5006 		av++;
5007 		if (F_LEN(cmd) != 0) {	/* ! any */
5008 			prev = cmd;
5009 			cmd = next_cmd(cmd, &cblen);
5010 		}
5011 	} else
5012 		errx( EX_USAGE, "bad destination address %s", *av);
5013     OR_BLOCK(dest_ip);
5014 
5015 	/*
5016 	 * dest. ports, optional
5017 	 */
5018 	NOT_BLOCK;	/* optional "not" */
5019 	if (av[0]) {
5020 		if (_substrcmp(*av, "any") == 0 ||
5021 		    add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
5022 			av++;
5023 			if (F_LEN(cmd) != 0)
5024 				cmd = next_cmd(cmd, &cblen);
5025 		}
5026 	}
5027 	if (first_cmd == cmd)
5028 		rule->flags |= IPFW_RULE_NOOPT;
5029 
5030 read_options:
5031 	prev = NULL;
5032 	while ( av[0] != NULL ) {
5033 		char *s;
5034 		ipfw_insn_u32 *cmd32;	/* alias for cmd */
5035 
5036 		s = *av;
5037 		cmd32 = (ipfw_insn_u32 *)cmd;
5038 
5039 		if (*s == '!') {	/* alternate syntax for NOT */
5040 			if (cmd->len & F_NOT)
5041 				errx(EX_USAGE, "double \"not\" not allowed\n");
5042 			cmd->len = F_NOT;
5043 			s++;
5044 		}
5045 		i = match_token(rule_options, s);
5046 		av++;
5047 		switch(i) {
5048 		case TOK_NOT:
5049 			if (cmd->len & F_NOT)
5050 				errx(EX_USAGE, "double \"not\" not allowed\n");
5051 			cmd->len = F_NOT;
5052 			break;
5053 
5054 		case TOK_OR:
5055 			if (open_par == 0 || prev == NULL)
5056 				errx(EX_USAGE, "invalid \"or\" block\n");
5057 			prev->len |= F_OR;
5058 			break;
5059 
5060 		case TOK_STARTBRACE:
5061 			if (open_par)
5062 				errx(EX_USAGE, "+nested \"(\" not allowed\n");
5063 			open_par = 1;
5064 			break;
5065 
5066 		case TOK_ENDBRACE:
5067 			if (!open_par)
5068 				errx(EX_USAGE, "+missing \")\"\n");
5069 			open_par = 0;
5070 			prev = NULL;
5071 			break;
5072 
5073 		case TOK_IN:
5074 			fill_cmd(cmd, O_IN, 0, 0);
5075 			break;
5076 
5077 		case TOK_OUT:
5078 			cmd->len ^= F_NOT; /* toggle F_NOT */
5079 			fill_cmd(cmd, O_IN, 0, 0);
5080 			break;
5081 
5082 		case TOK_DIVERTED:
5083 			fill_cmd(cmd, O_DIVERTED, 0, 3);
5084 			break;
5085 
5086 		case TOK_DIVERTEDLOOPBACK:
5087 			fill_cmd(cmd, O_DIVERTED, 0, 1);
5088 			break;
5089 
5090 		case TOK_DIVERTEDOUTPUT:
5091 			fill_cmd(cmd, O_DIVERTED, 0, 2);
5092 			break;
5093 
5094 		case TOK_FRAG: {
5095 			uint32_t set = 0, clear = 0;
5096 
5097 			if (*av != NULL && fill_flags(f_ipoff, *av, NULL,
5098 			    &set, &clear) == 0)
5099 				av++;
5100 			else {
5101 				/*
5102 				 * Compatibility: no argument after "frag"
5103 				 * keyword equals to "frag offset".
5104 				 */
5105 				set = 0x01;
5106 				clear = 0;
5107 			}
5108 			fill_cmd(cmd, O_FRAG, 0,
5109 			    (set & 0xff) | ( (clear & 0xff) << 8));
5110 			break;
5111 		}
5112 
5113 		case TOK_LAYER2:
5114 			fill_cmd(cmd, O_LAYER2, 0, 0);
5115 			break;
5116 
5117 		case TOK_XMIT:
5118 		case TOK_RECV:
5119 		case TOK_VIA:
5120 			NEED1("recv, xmit, via require interface name"
5121 				" or address");
5122 			fill_iface(insntod(cmd, if), av[0], cblen, tstate);
5123 			av++;
5124 			if (F_LEN(cmd) == 0)	/* not a valid address */
5125 				break;
5126 			if (i == TOK_XMIT)
5127 				cmd->opcode = O_XMIT;
5128 			else if (i == TOK_RECV)
5129 				cmd->opcode = O_RECV;
5130 			else if (i == TOK_VIA)
5131 				cmd->opcode = O_VIA;
5132 			break;
5133 
5134 		case TOK_ICMPTYPES:
5135 			NEED1("icmptypes requires list of types");
5136 			fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
5137 			av++;
5138 			break;
5139 
5140 		case TOK_ICMP6TYPES:
5141 			NEED1("icmptypes requires list of types");
5142 			fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
5143 			av++;
5144 			break;
5145 
5146 		case TOK_IPTTL:
5147 			NEED1("ipttl requires TTL");
5148 			if (strpbrk(*av, "-,")) {
5149 			    if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
5150 				errx(EX_DATAERR, "invalid ipttl %s", *av);
5151 			} else
5152 			    fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
5153 			av++;
5154 			break;
5155 
5156 		case TOK_IPID:
5157 			NEED1("ipid requires id");
5158 			if (strpbrk(*av, "-,")) {
5159 			    if (!add_ports(cmd, *av, 0, O_IPID, cblen))
5160 				errx(EX_DATAERR, "invalid ipid %s", *av);
5161 			} else
5162 			    fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
5163 			av++;
5164 			break;
5165 
5166 		case TOK_IPLEN:
5167 			NEED1("iplen requires length");
5168 			if (strpbrk(*av, "-,")) {
5169 			    if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
5170 				errx(EX_DATAERR, "invalid ip len %s", *av);
5171 			} else
5172 			    fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
5173 			av++;
5174 			break;
5175 
5176 		case TOK_IPVER:
5177 			NEED1("ipver requires version");
5178 			fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
5179 			av++;
5180 			break;
5181 
5182 		case TOK_IPPRECEDENCE:
5183 			NEED1("ipprecedence requires value");
5184 			fill_cmd(cmd, O_IPPRECEDENCE, 0,
5185 			    (strtoul(*av, NULL, 0) & 7) << 5);
5186 			av++;
5187 			break;
5188 
5189 		case TOK_DSCP:
5190 			NEED1("missing DSCP code");
5191 			fill_dscp(cmd, *av, cblen);
5192 			av++;
5193 			break;
5194 
5195 		case TOK_IPOPTS:
5196 			NEED1("missing argument for ipoptions");
5197 			fill_flags_cmd(cmd, O_IPOPT, f_ipopts, *av);
5198 			av++;
5199 			break;
5200 
5201 		case TOK_IPTOS:
5202 			NEED1("missing argument for iptos");
5203 			fill_flags_cmd(cmd, O_IPTOS, f_iptos, *av);
5204 			av++;
5205 			break;
5206 
5207 		case TOK_UID:
5208 			NEED1("uid requires argument");
5209 		    {
5210 			char *end;
5211 			uid_t uid;
5212 			struct passwd *pwd;
5213 
5214 			cmd->opcode = O_UID;
5215 			uid = strtoul(*av, &end, 0);
5216 			pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
5217 			if (pwd == NULL)
5218 				errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
5219 			cmd32->d[0] = pwd->pw_uid;
5220 			cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
5221 			av++;
5222 		    }
5223 			break;
5224 
5225 		case TOK_GID:
5226 			NEED1("gid requires argument");
5227 		    {
5228 			char *end;
5229 			gid_t gid;
5230 			struct group *grp;
5231 
5232 			cmd->opcode = O_GID;
5233 			gid = strtoul(*av, &end, 0);
5234 			grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
5235 			if (grp == NULL)
5236 				errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
5237 			cmd32->d[0] = grp->gr_gid;
5238 			cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
5239 			av++;
5240 		    }
5241 			break;
5242 
5243 		case TOK_JAIL:
5244 			NEED1("jail requires argument");
5245 		    {
5246 			char *end;
5247 			int jid;
5248 
5249 			cmd->opcode = O_JAIL;
5250 			/*
5251 			 * If av is a number, then we'll just pass it as-is.  If
5252 			 * it's a name, try to resolve that to a jid.
5253 			 *
5254 			 * We save the jail_getid(3) call for a fallback because
5255 			 * it entails an unconditional trip to the kernel to
5256 			 * either validate a jid or resolve a name to a jid.
5257 			 * This specific token doesn't currently require a
5258 			 * jid to be an active jail, so we save a transition
5259 			 * by simply using a number that we're given.
5260 			 */
5261 			jid = strtoul(*av, &end, 10);
5262 			if (*end != '\0') {
5263 				jid = jail_getid(*av);
5264 				if (jid < 0)
5265 				    errx(EX_DATAERR, "%s", jail_errmsg);
5266 			}
5267 			cmd32->d[0] = (uint32_t)jid;
5268 			cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
5269 			av++;
5270 		    }
5271 			break;
5272 
5273 		case TOK_ESTAB:
5274 			fill_cmd(cmd, O_ESTAB, 0, 0);
5275 			break;
5276 
5277 		case TOK_SETUP:
5278 			fill_cmd(cmd, O_TCPFLAGS, 0,
5279 				(TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
5280 			break;
5281 
5282 		case TOK_TCPDATALEN:
5283 			NEED1("tcpdatalen requires length");
5284 			if (strpbrk(*av, "-,")) {
5285 			    if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
5286 				errx(EX_DATAERR, "invalid tcpdata len %s", *av);
5287 			} else
5288 			    fill_cmd(cmd, O_TCPDATALEN, 0,
5289 				    strtoul(*av, NULL, 0));
5290 			av++;
5291 			break;
5292 
5293 		case TOK_TCPOPTS:
5294 			NEED1("missing argument for tcpoptions");
5295 			fill_flags_cmd(cmd, O_TCPOPTS, f_tcpopts, *av);
5296 			av++;
5297 			break;
5298 
5299 		case TOK_TCPSEQ:
5300 		case TOK_TCPACK:
5301 			NEED1("tcpseq/tcpack requires argument");
5302 			cmd->len = F_INSN_SIZE(ipfw_insn_u32);
5303 			cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
5304 			cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
5305 			av++;
5306 			break;
5307 
5308 		case TOK_TCPMSS:
5309 		case TOK_TCPWIN:
5310 			NEED1("tcpmss/tcpwin requires size");
5311 			if (strpbrk(*av, "-,")) {
5312 				if (add_ports(cmd, *av, 0,
5313 				    i == TOK_TCPWIN ? O_TCPWIN : O_TCPMSS,
5314 				    cblen) == NULL)
5315 					errx(EX_DATAERR, "invalid %s size %s",
5316 					    s, *av);
5317 			} else
5318 				fill_cmd(cmd, i == TOK_TCPWIN ? O_TCPWIN :
5319 				    O_TCPMSS, 0, strtoul(*av, NULL, 0));
5320 			av++;
5321 			break;
5322 
5323 		case TOK_TCPFLAGS:
5324 			NEED1("missing argument for tcpflags");
5325 			cmd->opcode = O_TCPFLAGS;
5326 			fill_flags_cmd(cmd, O_TCPFLAGS, f_tcpflags, *av);
5327 			av++;
5328 			break;
5329 
5330 		case TOK_KEEPSTATE:
5331 		case TOK_RECORDSTATE: {
5332 			uint32_t uidx;
5333 
5334 			if (open_par)
5335 				errx(EX_USAGE, "keep-state or record-state cannot be part "
5336 				    "of an or block");
5337 			if (have_state)
5338 				errx(EX_USAGE, "only one of keep-state, record-state, "
5339 					" limit and set-limit is allowed");
5340 			if (*av != NULL && *av[0] == ':') {
5341 				if (state_check_name(*av + 1) != 0)
5342 					errx(EX_DATAERR,
5343 					    "Invalid state name %s", *av);
5344 				uidx = pack_object(tstate, *av + 1,
5345 				    IPFW_TLV_STATE_NAME);
5346 				av++;
5347 			} else
5348 				uidx = pack_object(tstate, default_state_name,
5349 				    IPFW_TLV_STATE_NAME);
5350 			have_state = cmd;
5351 			have_rstate = i == TOK_RECORDSTATE;
5352 			cmd->opcode = O_KEEP_STATE;
5353 			cmd->len = F_INSN_SIZE(ipfw_insn_kidx);
5354 			CHECK_CMDLEN;
5355 			insntod(have_state, kidx)->kidx = uidx;
5356 			break;
5357 		}
5358 
5359 		case TOK_LIMIT:
5360 		case TOK_SETLIMIT: {
5361 			ipfw_insn_limit *c = insntod(cmd, limit);
5362 			int val;
5363 
5364 			if (open_par)
5365 				errx(EX_USAGE,
5366 				    "limit or set-limit cannot be part of an or block");
5367 			if (have_state)
5368 				errx(EX_USAGE, "only one of keep-state, record-state, "
5369 					" limit and set-limit is allowed");
5370 			have_state = cmd;
5371 			have_rstate = i == TOK_SETLIMIT;
5372 
5373 			cmd->opcode = O_LIMIT;
5374 			cmd->len = F_INSN_SIZE(ipfw_insn_limit);
5375 			CHECK_CMDLEN;
5376 			c->limit_mask = c->conn_limit = c->kidx = 0;
5377 
5378 			while ( av[0] != NULL ) {
5379 				if ((val = match_token(limit_masks, *av)) <= 0)
5380 					break;
5381 				c->limit_mask |= val;
5382 				av++;
5383 			}
5384 
5385 			if (c->limit_mask == 0)
5386 				errx(EX_USAGE, "limit: missing limit mask");
5387 
5388 			GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
5389 			    TOK_LIMIT, rule_options);
5390 			av++;
5391 
5392 			if (*av != NULL && *av[0] == ':') {
5393 				if (state_check_name(*av + 1) != 0)
5394 					errx(EX_DATAERR,
5395 					    "Invalid state name %s", *av);
5396 				c->kidx = pack_object(tstate, *av + 1,
5397 				    IPFW_TLV_STATE_NAME);
5398 				av++;
5399 			} else
5400 				c->kidx = pack_object(tstate,
5401 				    default_state_name, IPFW_TLV_STATE_NAME);
5402 			break;
5403 		}
5404 
5405 		case TOK_PROTO:
5406 			NEED1("missing protocol");
5407 			if (add_proto(cmd, *av, &proto)) {
5408 				av++;
5409 			} else
5410 				errx(EX_DATAERR, "invalid protocol ``%s''",
5411 				    *av);
5412 			break;
5413 
5414 		case TOK_SRCIP:
5415 			NEED1("missing source IP");
5416 			if (add_srcip(cmd, *av, cblen, tstate)) {
5417 				av++;
5418 			}
5419 			break;
5420 
5421 		case TOK_DSTIP:
5422 			NEED1("missing destination IP");
5423 			if (add_dstip(cmd, *av, cblen, tstate)) {
5424 				av++;
5425 			}
5426 			break;
5427 
5428 		case TOK_SRCIP6:
5429 			NEED1("missing source IP6");
5430 			if (add_srcip6(cmd, *av, cblen, tstate)) {
5431 				av++;
5432 			}
5433 			break;
5434 
5435 		case TOK_DSTIP6:
5436 			NEED1("missing destination IP6");
5437 			if (add_dstip6(cmd, *av, cblen, tstate)) {
5438 				av++;
5439 			}
5440 			break;
5441 
5442 
5443 		case TOK_SRCMAC:
5444 			NEED1("missing source MAC");
5445 			if (add_srcmac(cmd, *av, tstate)) {
5446 				av++;
5447 			}
5448 			break;
5449 
5450 		case TOK_DSTMAC:
5451 			NEED1("missing destination MAC");
5452 			if (add_dstmac(cmd, *av, tstate)) {
5453 				av++;
5454 			}
5455 			break;
5456 
5457 		case TOK_SRCPORT:
5458 			NEED1("missing source port");
5459 			if (_substrcmp(*av, "any") == 0 ||
5460 			    add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
5461 				av++;
5462 			} else
5463 				errx(EX_DATAERR, "invalid source port %s", *av);
5464 			break;
5465 
5466 		case TOK_DSTPORT:
5467 			NEED1("missing destination port");
5468 			if (_substrcmp(*av, "any") == 0 ||
5469 			    add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
5470 				av++;
5471 			} else
5472 				errx(EX_DATAERR, "invalid destination port %s",
5473 				    *av);
5474 			break;
5475 
5476 		case TOK_MAC:
5477 			if (add_mac(cmd, av, cblen))
5478 				av += 2;
5479 			break;
5480 
5481 		case TOK_MACTYPE:
5482 			NEED1("missing mac type");
5483 			if (!add_mactype(cmd, *av, cblen))
5484 				errx(EX_DATAERR, "invalid mac type %s", *av);
5485 			av++;
5486 			break;
5487 
5488 		case TOK_VERREVPATH:
5489 			fill_cmd(cmd, O_VERREVPATH, 0, 0);
5490 			break;
5491 
5492 		case TOK_VERSRCREACH:
5493 			fill_cmd(cmd, O_VERSRCREACH, 0, 0);
5494 			break;
5495 
5496 		case TOK_ANTISPOOF:
5497 			fill_cmd(cmd, O_ANTISPOOF, 0, 0);
5498 			break;
5499 
5500 		case TOK_IPSEC:
5501 			fill_cmd(cmd, O_IPSEC, 0, 0);
5502 			break;
5503 
5504 		case TOK_IPV6:
5505 			fill_cmd(cmd, O_IP6, 0, 0);
5506 			break;
5507 
5508 		case TOK_IPV4:
5509 			fill_cmd(cmd, O_IP4, 0, 0);
5510 			break;
5511 
5512 		case TOK_EXT6HDR:
5513 			NEED1("missing extension header");
5514 			fill_ext6hdr( cmd, *av );
5515 			av++;
5516 			break;
5517 
5518 		case TOK_FLOWID:
5519 			fill_flow6(insntod(cmd, u32), *av, cblen);
5520 			av++;
5521 			break;
5522 
5523 		case TOK_COMMENT:
5524 			fill_comment(cmd, av, cblen);
5525 			av[0]=NULL;
5526 			break;
5527 
5528 		case TOK_TAGGED:
5529 			if (av[0] && strpbrk(*av, "-,")) {
5530 				if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
5531 					errx(EX_DATAERR, "tagged: invalid tag"
5532 					    " list: %s", *av);
5533 			}
5534 			else {
5535 				uint16_t tag;
5536 
5537 				GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
5538 				    TOK_TAGGED, rule_options);
5539 				fill_cmd(cmd, O_TAGGED, 0, tag);
5540 			}
5541 			av++;
5542 			break;
5543 
5544 		case TOK_FIB:
5545 			NEED1("fib requires fib number");
5546 			fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
5547 			av++;
5548 			break;
5549 		case TOK_SOCKARG:
5550 			fill_cmd(cmd, O_SOCKARG, 0, 0);
5551 			break;
5552 
5553 		case TOK_LOOKUP: {
5554 			/* optional mask for some LOOKUP types */
5555 			ipfw_insn_lookup *c = insntod(cmd, lookup);
5556 			char *lkey;
5557 
5558 			if (!av[0] || !av[1])
5559 				errx(EX_USAGE,
5560 				    "format: lookup argument tablenum");
5561 			cmd->opcode = O_TABLE_LOOKUP;
5562 
5563 			lkey = strsep(av, ":");
5564 			i = match_token(lookup_keys, lkey);
5565 			if (i == -1)
5566 				errx(EX_USAGE,
5567 				    "format: cannot lookup on %s", lkey);
5568 			/* masked lookup key */
5569 			if (*av != NULL) {
5570 				switch (i) {
5571 				case LOOKUP_DST_PORT:
5572 				case LOOKUP_SRC_PORT:
5573 				case LOOKUP_UID:
5574 				case LOOKUP_JAIL:
5575 				case LOOKUP_DSCP:
5576 				case LOOKUP_MARK:
5577 				case LOOKUP_RULENUM:
5578 				case LOOKUP_SRC_MAC:
5579 				case LOOKUP_DST_MAC:
5580 				case LOOKUP_SRC_IP6:
5581 				case LOOKUP_DST_IP6:
5582 				case LOOKUP_SRC_IP4:
5583 				case LOOKUP_DST_IP4:
5584 					break;
5585 				default:
5586 					errx(EX_USAGE,
5587 					    "masked lookup is not supported "
5588 					    "for %s", lkey);
5589 				}
5590 				cmd->len |= F_INSN_SIZE(ipfw_insn_lookup);
5591 				IPFW_SET_LOOKUP_MASKING(cmd, 1);
5592 				get_lookup_bitmask(i, c, *av);
5593 			} else {
5594 				cmd->len |= F_INSN_SIZE(ipfw_insn_kidx);
5595 			}
5596 			CHECK_CMDLEN;
5597 
5598 			IPFW_SET_LOOKUP_TYPE(cmd, i);
5599 			av++;
5600 			c->kidx = pack_table(tstate, *av);
5601 			if (c->kidx == 0)
5602 				errx(EX_DATAERR,
5603 				    "Invalid table name: %s", *av);
5604 			av++;
5605 		    }
5606 			break;
5607 		case TOK_FLOW:
5608 			NEED1("missing table name");
5609 			if (strncmp(*av, "table(", 6) != 0)
5610 				errx(EX_DATAERR,
5611 				    "enclose table name into \"table()\"");
5612 			fill_table(cmd, *av, O_IP_FLOW_LOOKUP, tstate);
5613 			av++;
5614 			break;
5615 
5616 		case TOK_SKIPACTION:
5617 			if (have_skipcmd)
5618 				errx(EX_USAGE, "only one defer-action "
5619 					"is allowed");
5620 			have_skipcmd = cmd;
5621 			fill_cmd(cmd, O_SKIP_ACTION, 0, 0);
5622 			break;
5623 
5624 		case TOK_MARK:
5625 			NEED1("missing mark value:mask");
5626 			fill_mark(cmd, *av, cblen);
5627 			av++;
5628 			break;
5629 
5630 		default:
5631 			errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
5632 		}
5633 		if (F_LEN(cmd) > 0) {	/* prepare to advance */
5634 			prev = cmd;
5635 			cmd = next_cmd(cmd, &cblen);
5636 		}
5637 	}
5638 
5639 done:
5640 
5641 	if (!have_state && have_skipcmd)
5642 		warnx("Rule contains \"defer-immediate-action\" "
5643 			"and doesn't contain any state-related options.");
5644 
5645 	/*
5646 	 * Now copy stuff into the rule.
5647 	 * If we have a keep-state option, the first instruction
5648 	 * must be a PROBE_STATE (which is generated here).
5649 	 * If we have a LOG option, it was stored as the first command,
5650 	 * and now must be moved to the top of the action part.
5651 	 */
5652 	dst = (ipfw_insn *)rule->cmd;
5653 
5654 	/*
5655 	 * First thing to write into the command stream is the match probability.
5656 	 */
5657 	if (match_prob != 1) { /* 1 means always match */
5658 		dst->opcode = O_PROB;
5659 		dst->len = 2;
5660 		*((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
5661 		dst += dst->len;
5662 	}
5663 
5664 	/*
5665 	 * generate O_PROBE_STATE if necessary
5666 	 */
5667 	if (have_state && have_state->opcode != O_CHECK_STATE && !have_rstate) {
5668 		dst->opcode = O_PROBE_STATE;
5669 		dst->len = F_INSN_SIZE(ipfw_insn_kidx);
5670 		insntod(dst, kidx)->kidx = insntod(have_state, kidx)->kidx;
5671 		dst = next_cmd(dst, &rblen);
5672 	}
5673 
5674 	/*
5675 	 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG,
5676 	 * O_SKIP_ACTION
5677 	 */
5678 	for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
5679 		i = F_LEN(src);
5680 		CHECK_RBUFLEN(i);
5681 
5682 		switch (src->opcode) {
5683 		case O_LOG:
5684 		case O_KEEP_STATE:
5685 		case O_LIMIT:
5686 		case O_ALTQ:
5687 		case O_TAG:
5688 		case O_SKIP_ACTION:
5689 			break;
5690 		default:
5691 			bcopy(src, dst, i * sizeof(uint32_t));
5692 			dst += i;
5693 		}
5694 	}
5695 
5696 	/*
5697 	 * put back the have_state command as last opcode
5698 	 */
5699 	if (have_state && have_state->opcode != O_CHECK_STATE) {
5700 		i = F_LEN(have_state);
5701 		CHECK_RBUFLEN(i);
5702 		bcopy(have_state, dst, i * sizeof(uint32_t));
5703 		dst += i;
5704 	}
5705 
5706 	/*
5707 	 * put back the have_skipcmd command as very last opcode
5708 	 */
5709 	if (have_skipcmd) {
5710 		i = F_LEN(have_skipcmd);
5711 		CHECK_RBUFLEN(i);
5712 		bcopy(have_skipcmd, dst, i * sizeof(uint32_t));
5713 		dst += i;
5714 	}
5715 
5716 	/*
5717 	 * start action section
5718 	 */
5719 	rule->act_ofs = dst - rule->cmd;
5720 
5721 	/* put back O_LOG, O_ALTQ, O_TAG if necessary */
5722 	if (have_log) {
5723 		i = F_LEN(have_log);
5724 		CHECK_RBUFLEN(i);
5725 		bcopy(have_log, dst, i * sizeof(uint32_t));
5726 		dst += i;
5727 	}
5728 	if (have_altq) {
5729 		i = F_LEN(have_altq);
5730 		CHECK_RBUFLEN(i);
5731 		bcopy(have_altq, dst, i * sizeof(uint32_t));
5732 		dst += i;
5733 	}
5734 	if (have_tag) {
5735 		i = F_LEN(have_tag);
5736 		CHECK_RBUFLEN(i);
5737 		bcopy(have_tag, dst, i * sizeof(uint32_t));
5738 		dst += i;
5739 	}
5740 
5741 	/*
5742 	 * copy all other actions
5743 	 */
5744 	for (src = (ipfw_insn *)actbuf; src != action; src += i) {
5745 		i = F_LEN(src);
5746 		CHECK_RBUFLEN(i);
5747 		bcopy(src, dst, i * sizeof(uint32_t));
5748 		dst += i;
5749 	}
5750 
5751 	rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
5752 	*rbufsize = (char *)dst - (char *)rule;
5753 }
5754 
5755 static int
compare_ntlv(const void * _a,const void * _b)5756 compare_ntlv(const void *_a, const void *_b)
5757 {
5758 	const ipfw_obj_ntlv *a, *b;
5759 
5760 	a = (const ipfw_obj_ntlv *)_a;
5761 	b = (const ipfw_obj_ntlv *)_b;
5762 
5763 	if (a->set < b->set)
5764 		return (-1);
5765 	else if (a->set > b->set)
5766 		return (1);
5767 
5768 	if (a->idx < b->idx)
5769 		return (-1);
5770 	else if (a->idx > b->idx)
5771 		return (1);
5772 
5773 	if (a->head.type < b->head.type)
5774 		return (-1);
5775 	else if (a->head.type > b->head.type)
5776 		return (1);
5777 
5778 	return (0);
5779 }
5780 
5781 /*
5782  * Provide kernel with sorted list of referenced objects
5783  */
5784 static void
object_sort_ctlv(ipfw_obj_ctlv * ctlv)5785 object_sort_ctlv(ipfw_obj_ctlv *ctlv)
5786 {
5787 
5788 	qsort(ctlv + 1, ctlv->count, ctlv->objsize, compare_ntlv);
5789 }
5790 
5791 struct object_kt {
5792 	uint32_t	uidx;
5793 	uint16_t	type;
5794 };
5795 static int
compare_object_kntlv(const void * k,const void * v)5796 compare_object_kntlv(const void *k, const void *v)
5797 {
5798 	const ipfw_obj_ntlv *ntlv;
5799 	struct object_kt key;
5800 
5801 	key = *((const struct object_kt *)k);
5802 	ntlv = (const ipfw_obj_ntlv *)v;
5803 
5804 	if (key.uidx < ntlv->idx)
5805 		return (-1);
5806 	else if (key.uidx > ntlv->idx)
5807 		return (1);
5808 
5809 	if (key.type < ntlv->head.type)
5810 		return (-1);
5811 	else if (key.type > ntlv->head.type)
5812 		return (1);
5813 
5814 	return (0);
5815 }
5816 
5817 /*
5818  * Finds object name in @ctlv by @idx and @type.
5819  * Uses the following facts:
5820  * 1) All TLVs are the same size
5821  * 2) Kernel implementation provides already sorted list.
5822  *
5823  * Returns table name or NULL.
5824  */
5825 static char *
object_search_ctlv(ipfw_obj_ctlv * ctlv,uint32_t idx,uint16_t type)5826 object_search_ctlv(ipfw_obj_ctlv *ctlv, uint32_t idx, uint16_t type)
5827 {
5828 	ipfw_obj_ntlv *ntlv;
5829 	struct object_kt key;
5830 
5831 	key.uidx = idx;
5832 	key.type = type;
5833 
5834 	ntlv = bsearch(&key, (ctlv + 1), ctlv->count, ctlv->objsize,
5835 	    compare_object_kntlv);
5836 
5837 	if (ntlv != NULL)
5838 		return (ntlv->name);
5839 
5840 	return (NULL);
5841 }
5842 
5843 static char *
table_search_ctlv(ipfw_obj_ctlv * ctlv,uint32_t idx)5844 table_search_ctlv(ipfw_obj_ctlv *ctlv, uint32_t idx)
5845 {
5846 
5847 	return (object_search_ctlv(ctlv, idx, IPFW_TLV_TBL_NAME));
5848 }
5849 
5850 /*
5851  * Adds one or more rules to ipfw chain.
5852  * Data layout:
5853  * Request:
5854  * [
5855  *   ip_fw3_opheader
5856  *   [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
5857  *   [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ] (*2) (*3)
5858  * ]
5859  * Reply:
5860  * [
5861  *   ip_fw3_opheader
5862  *   [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
5863  *   [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ]
5864  * ]
5865  *
5866  * Rules in reply are modified to store their actual ruleset number.
5867  *
5868  * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
5869  * according to their idx field and there has to be no duplicates.
5870  * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
5871  * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
5872  */
5873 void
ipfw_add(char * av[])5874 ipfw_add(char *av[])
5875 {
5876 	uint32_t rulebuf[1024];
5877 	int rbufsize, default_off, tlen, rlen;
5878 	size_t sz;
5879 	struct tidx ts;
5880 	struct ip_fw_rule *rule;
5881 	caddr_t tbuf;
5882 	ip_fw3_opheader *op3;
5883 	ipfw_obj_ctlv *ctlv, *tstate;
5884 
5885 	rbufsize = sizeof(rulebuf);
5886 	memset(rulebuf, 0, rbufsize);
5887 	memset(&ts, 0, sizeof(ts));
5888 
5889 	/* Optimize case with no tables */
5890 	default_off = sizeof(ipfw_obj_ctlv) + sizeof(ip_fw3_opheader);
5891 	op3 = (ip_fw3_opheader *)rulebuf;
5892 	ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5893 	rule = (struct ip_fw_rule *)(ctlv + 1);
5894 	rbufsize -= default_off;
5895 
5896 	compile_rule(av, (uint32_t *)rule, &rbufsize, &ts);
5897 	/* Align rule size to u64 boundary */
5898 	rlen = roundup2(rbufsize, sizeof(uint64_t));
5899 
5900 	tbuf = NULL;
5901 	sz = 0;
5902 	tstate = NULL;
5903 	if (ts.count != 0) {
5904 		/* Some tables. We have to alloc more data */
5905 		tlen = ts.count * sizeof(ipfw_obj_ntlv);
5906 		sz = default_off + sizeof(ipfw_obj_ctlv) + tlen + rlen;
5907 
5908 		if ((tbuf = calloc(1, sz)) == NULL)
5909 			err(EX_UNAVAILABLE, "malloc() failed for IP_FW_XADD");
5910 		op3 = (ip_fw3_opheader *)tbuf;
5911 		/* Tables first */
5912 		ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5913 		ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
5914 		ctlv->head.length = sizeof(ipfw_obj_ctlv) + tlen;
5915 		ctlv->count = ts.count;
5916 		ctlv->objsize = sizeof(ipfw_obj_ntlv);
5917 		memcpy(ctlv + 1, ts.idx, tlen);
5918 		object_sort_ctlv(ctlv);
5919 		tstate = ctlv;
5920 		/* Rule next */
5921 		ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
5922 		ctlv->head.type = IPFW_TLV_RULE_LIST;
5923 		ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5924 		ctlv->count = 1;
5925 		memcpy(ctlv + 1, rule, rbufsize);
5926 	} else {
5927 		/* Simply add header */
5928 		sz = rlen + default_off;
5929 		memset(ctlv, 0, sizeof(*ctlv));
5930 		ctlv->head.type = IPFW_TLV_RULE_LIST;
5931 		ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5932 		ctlv->count = 1;
5933 	}
5934 
5935 	if (do_get3(IP_FW_XADD, op3, &sz) != 0)
5936 		err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_XADD");
5937 
5938 	if (!g_co.do_quiet) {
5939 		struct format_opts sfo;
5940 		struct buf_pr bp;
5941 		memset(&sfo, 0, sizeof(sfo));
5942 		sfo.tstate = tstate;
5943 		sfo.set_mask = (uint32_t)(-1);
5944 		bp_alloc(&bp, 4096);
5945 		show_static_rule(&g_co, &sfo, &bp, rule, NULL);
5946 		printf("%s", bp.buf);
5947 		bp_free(&bp);
5948 	}
5949 
5950 	if (tbuf != NULL)
5951 		free(tbuf);
5952 
5953 	if (ts.idx != NULL)
5954 		free(ts.idx);
5955 }
5956 
5957 /*
5958  * clear the counters or the log counters.
5959  * optname has the following values:
5960  *  0 (zero both counters and logging)
5961  *  1 (zero logging only)
5962  */
5963 void
ipfw_zero(int ac,char * av[],int optname)5964 ipfw_zero(int ac, char *av[], int optname)
5965 {
5966 	ipfw_range_tlv rt;
5967 	char const *errstr;
5968 	char const *name = optname ? "RESETLOG" : "ZERO";
5969 	uint32_t arg;
5970 	int failed = EX_OK;
5971 
5972 	optname = optname ? IP_FW_XRESETLOG : IP_FW_XZERO;
5973 	av++; ac--;
5974 
5975 	if (ac == 0) {
5976 		/* clear all entries */
5977 		memset(&rt, 0, sizeof(rt));
5978 		rt.flags = IPFW_RCFLAG_ALL;
5979 		if (do_range_cmd(optname, &rt) < 0)
5980 			err(EX_UNAVAILABLE, "setsockopt(IP_FW_X%s)", name);
5981 		if (!g_co.do_quiet)
5982 			printf("%s.\n", optname == IP_FW_XZERO ?
5983 			    "Accounting cleared":"Logging counts reset");
5984 
5985 		return;
5986 	}
5987 
5988 	while (ac) {
5989 		/* Rule number */
5990 		if (isdigit(**av)) {
5991 			arg = strtonum(*av, 0, 0xffff, &errstr);
5992 			if (errstr)
5993 				errx(EX_DATAERR,
5994 				    "invalid rule number %s\n", *av);
5995 			memset(&rt, 0, sizeof(rt));
5996 			rt.start_rule = arg;
5997 			rt.end_rule = arg;
5998 			rt.flags |= IPFW_RCFLAG_RANGE;
5999 			if (g_co.use_set != 0) {
6000 				rt.set = g_co.use_set - 1;
6001 				rt.flags |= IPFW_RCFLAG_SET;
6002 			}
6003 			if (do_range_cmd(optname, &rt) != 0) {
6004 				warn("rule %u: setsockopt(IP_FW_X%s)",
6005 				    arg, name);
6006 				failed = EX_UNAVAILABLE;
6007 			} else if (rt.new_set == 0) {
6008 				printf("Entry %d not found\n", arg);
6009 				failed = EX_UNAVAILABLE;
6010 			} else if (!g_co.do_quiet)
6011 				printf("Entry %d %s.\n", arg,
6012 				    optname == IP_FW_XZERO ?
6013 					"cleared" : "logging count reset");
6014 		} else {
6015 			errx(EX_USAGE, "invalid rule number ``%s''", *av);
6016 		}
6017 		av++; ac--;
6018 	}
6019 	if (failed != EX_OK)
6020 		exit(failed);
6021 }
6022 
6023 void
ipfw_flush(int force)6024 ipfw_flush(int force)
6025 {
6026 	ipfw_range_tlv rt;
6027 
6028 	if (!force && !g_co.do_quiet) { /* need to ask user */
6029 		int c;
6030 
6031 		printf("Are you sure? [yn] ");
6032 		fflush(stdout);
6033 		do {
6034 			c = toupper(getc(stdin));
6035 			while (c != '\n' && getc(stdin) != '\n')
6036 				if (feof(stdin))
6037 					return; /* and do not flush */
6038 		} while (c != 'Y' && c != 'N');
6039 		printf("\n");
6040 		if (c == 'N')	/* user said no */
6041 			return;
6042 	}
6043 	if (g_co.do_pipe) {
6044 		dummynet_flush();
6045 		return;
6046 	}
6047 	/* `ipfw set N flush` - is the same that `ipfw delete set N` */
6048 	memset(&rt, 0, sizeof(rt));
6049 	if (g_co.use_set != 0) {
6050 		rt.set = g_co.use_set - 1;
6051 		rt.flags = IPFW_RCFLAG_SET;
6052 	} else
6053 		rt.flags = IPFW_RCFLAG_ALL;
6054 	if (do_range_cmd(IP_FW_XDEL, &rt) != 0)
6055 			err(EX_UNAVAILABLE, "setsockopt(IP_FW_XDEL)");
6056 	if (!g_co.do_quiet)
6057 		printf("Flushed all %s.\n", g_co.do_pipe ? "pipes" : "rules");
6058 }
6059 
6060 static struct _s_x intcmds[] = {
6061       { "talist",	TOK_TALIST },
6062       { "iflist",	TOK_IFLIST },
6063       { "olist",	TOK_OLIST },
6064       { "vlist",	TOK_VLIST },
6065       { "monitor",	TOK_MONITOR },
6066       { NULL, 0 }
6067 };
6068 
6069 static struct _s_x otypes[] = {
6070 	{ "EACTION",	IPFW_TLV_EACTION },
6071 	{ "DYNSTATE",	IPFW_TLV_STATE_NAME },
6072 	{ NULL, 0 }
6073 };
6074 
6075 static const char*
lookup_eaction_name(ipfw_obj_ntlv * ntlv,int cnt,uint16_t type)6076 lookup_eaction_name(ipfw_obj_ntlv *ntlv, int cnt, uint16_t type)
6077 {
6078 	const char *name;
6079 	int i;
6080 
6081 	name = NULL;
6082 	for (i = 0; i < cnt; i++) {
6083 		if (ntlv[i].head.type != IPFW_TLV_EACTION)
6084 			continue;
6085 		if (IPFW_TLV_EACTION_NAME(ntlv[i].idx) != type)
6086 			continue;
6087 		name = ntlv[i].name;
6088 		break;
6089 	}
6090 	return (name);
6091 }
6092 
6093 static void
ipfw_list_objects(int ac __unused,char * av[]__unused)6094 ipfw_list_objects(int ac __unused, char *av[] __unused)
6095 {
6096 	ipfw_obj_lheader req, *olh;
6097 	ipfw_obj_ntlv *ntlv;
6098 	const char *name;
6099 	size_t sz;
6100 	uint32_t i;
6101 
6102 	memset(&req, 0, sizeof(req));
6103 	sz = sizeof(req);
6104 	if (do_get3(IP_FW_DUMP_SRVOBJECTS, &req.opheader, &sz) != 0)
6105 		if (errno != ENOMEM)
6106 			return;
6107 
6108 	sz = req.size;
6109 	if ((olh = calloc(1, sz)) == NULL)
6110 		return;
6111 
6112 	olh->size = sz;
6113 	if (do_get3(IP_FW_DUMP_SRVOBJECTS, &olh->opheader, &sz) != 0) {
6114 		free(olh);
6115 		return;
6116 	}
6117 
6118 	if (olh->count > 0)
6119 		printf("Objects list:\n");
6120 	else
6121 		printf("There are no objects\n");
6122 	ntlv = (ipfw_obj_ntlv *)(olh + 1);
6123 	for (i = 0; i < olh->count; i++) {
6124 		name = match_value(otypes, ntlv->head.type);
6125 		if (name == NULL)
6126 			name = lookup_eaction_name(
6127 			    (ipfw_obj_ntlv *)(olh + 1), olh->count,
6128 			    ntlv->head.type);
6129 		if (name == NULL)
6130 			printf(" kidx: %4d\ttype: %10d\tname: %s\n",
6131 			    ntlv->idx, ntlv->head.type, ntlv->name);
6132 		else
6133 			printf(" kidx: %4d\ttype: %10s\tname: %s\n",
6134 			    ntlv->idx, name, ntlv->name);
6135 		ntlv++;
6136 	}
6137 	free(olh);
6138 }
6139 
6140 static void
bprint_sa(struct buf_pr * bp,const struct sockaddr * sa)6141 bprint_sa(struct buf_pr *bp, const struct sockaddr *sa)
6142 {
6143 	struct sockaddr_storage ss;
6144 	char buf[INET6_ADDRSTRLEN];
6145 
6146 	memset(&ss, 0, sizeof(ss));
6147 	if (sa->sa_len == 0)
6148 		ss.ss_family = sa->sa_family;
6149 	else
6150 		memcpy(&ss, sa, sa->sa_len);
6151 
6152 	/* set ss_len in case it was shortened */
6153 	switch (sa->sa_family) {
6154 	case AF_INET:
6155 		ss.ss_len = sizeof(struct sockaddr_in);
6156 		break;
6157 	default:
6158 		ss.ss_len = sizeof(struct sockaddr_in6);
6159 	}
6160 	if (getnameinfo((const struct sockaddr *)&ss, ss.ss_len,
6161 	    buf, sizeof(buf), NULL, 0, NI_NUMERICHOST) != 0) {
6162 		bprintf(bp, "bad-addr");
6163 		return;
6164 	}
6165 	bprintf(bp, "%s", buf);
6166 }
6167 
6168 static void
ipfw_rtsock_monitor(const char * filter)6169 ipfw_rtsock_monitor(const char *filter)
6170 {
6171 	char msg[2048], buf[32];
6172 	struct timespec tp;
6173 	struct tm tm;
6174 	struct buf_pr bp;
6175 	struct rt_msghdr *hdr;
6176 	struct sockaddr *sa;
6177 	struct sockaddr_dl *sdl;
6178 	ipfwlog_rtsock_hdr_v2 *loghdr;
6179 	ssize_t nread;
6180 	size_t msglen;
6181 	int rtsock;
6182 
6183 	rtsock = socket(PF_ROUTE, SOCK_RAW, AF_IPFWLOG);
6184 	if (rtsock < 0)
6185 		err(EX_UNAVAILABLE, "socket(AF_IPFWLOG)");
6186 	bp_alloc(&bp, 4096);
6187 	for (;;) {
6188 		nread = read(rtsock, msg, sizeof(msg));
6189 		if (nread < 0) {
6190 			warn("read()");
6191 			continue;
6192 		}
6193 		msglen = nread;
6194 		if (msglen < sizeof(*hdr))
6195 			continue;
6196 
6197 		hdr = (struct rt_msghdr *)msg;
6198 		if (hdr->rtm_version != RTM_VERSION ||
6199 		    hdr->rtm_type != RTM_IPFWLOG ||
6200 		    (hdr->rtm_addrs & (1 << RTAX_DST)) == 0 ||
6201 		    (hdr->rtm_addrs & (1 << RTAX_GATEWAY)) == 0 ||
6202 		    (hdr->rtm_addrs & (1 << RTAX_NETMASK)) == 0)
6203 			continue;
6204 
6205 		msglen -= sizeof(*hdr);
6206 		sdl = (struct sockaddr_dl *)(hdr + 1);
6207 		if (msglen < sizeof(*sdl) || msglen < SA_SIZE(sdl) ||
6208 		    sdl->sdl_family != AF_IPFWLOG ||
6209 		    sdl->sdl_type != 2 /* version */ ||
6210 		    sdl->sdl_alen != sizeof(*loghdr))
6211 			continue;
6212 
6213 		msglen -= SA_SIZE(sdl);
6214 		loghdr = (ipfwlog_rtsock_hdr_v2 *)sdl->sdl_data;
6215 		/* filter by rule comment. MAX_COMMENT_LEN = 80 */
6216 		if (filter != NULL &&
6217 		    strncmp(filter, loghdr->comment, 80) != 0)
6218 			continue;
6219 
6220 		sa = (struct sockaddr *)((char *)sdl + SA_SIZE(sdl));
6221 		if (msglen < SA_SIZE(sa))
6222 			continue;
6223 
6224 		msglen -= SA_SIZE(sa);
6225 		bp_flush(&bp);
6226 
6227 		clock_gettime(CLOCK_REALTIME, &tp);
6228 		localtime_r(&tp.tv_sec, &tm);
6229 		strftime(buf, sizeof(buf), "%T", &tm);
6230 		bprintf(&bp, "%s.%03ld AF %s", buf, tp.tv_nsec / 1000000,
6231 		    sa->sa_family == AF_INET ? "IPv4" : "IPv6");
6232 
6233 		bprintf(&bp, " %s >",
6234 		    ether_ntoa((const struct ether_addr *)loghdr->ether_shost));
6235 		bprintf(&bp, " %s, ",
6236 		    ether_ntoa((const struct ether_addr *)loghdr->ether_dhost));
6237 		bprint_sa(&bp, sa);
6238 
6239 		sa = (struct sockaddr *)((char *)sa + SA_SIZE(sa));
6240 		if (msglen < SA_SIZE(sa))
6241 			continue;
6242 
6243 		msglen -= SA_SIZE(sa);
6244 		bprintf(&bp, " > ");
6245 		bprint_sa(&bp, sa);
6246 		bprintf(&bp, ", set %u, rulenum %u, targ 0x%08x, "
6247 		    "%scmd[op %d, len %d, arg1 0x%04x], mark 0x%08x",
6248 		    sdl->sdl_index, loghdr->rulenum, loghdr->tablearg,
6249 		    (loghdr->cmd.len & F_NOT) ? "!": "",
6250 		    loghdr->cmd.opcode, F_LEN(&loghdr->cmd),
6251 		    loghdr->cmd.arg1, loghdr->mark);
6252 
6253 		sa = (struct sockaddr *)((char *)sa + SA_SIZE(sa));
6254 		if ((hdr->rtm_addrs & (1 << RTAX_GENMASK)) != 0 &&
6255 		    msglen >= SA_SIZE(sa)) {
6256 			msglen -= SA_SIZE(sa);
6257 			bprintf(&bp, ", nh ");
6258 			bprint_sa(&bp, sa);
6259 		}
6260 		if (sdl->sdl_nlen > 0)
6261 			bprintf(&bp, " // %s", loghdr->comment);
6262 		printf("%s\n", bp.buf);
6263 	}
6264 	bp_free(&bp);
6265 	close(rtsock);
6266 }
6267 
6268 void
ipfw_internal_handler(int ac,char * av[])6269 ipfw_internal_handler(int ac, char *av[])
6270 {
6271 	int tcmd;
6272 
6273 	ac--; av++;
6274 	NEED1("internal cmd required");
6275 
6276 	if ((tcmd = match_token(intcmds, *av)) == -1)
6277 		errx(EX_USAGE, "invalid internal sub-cmd: %s", *av);
6278 
6279 	switch (tcmd) {
6280 	case TOK_IFLIST:
6281 		ipfw_list_tifaces();
6282 		break;
6283 	case TOK_TALIST:
6284 		ipfw_list_ta(ac, av);
6285 		break;
6286 	case TOK_OLIST:
6287 		ipfw_list_objects(ac, av);
6288 		break;
6289 	case TOK_VLIST:
6290 		ipfw_list_values(ac, av);
6291 		break;
6292 	case TOK_MONITOR:
6293 		av++;
6294 		ipfw_rtsock_monitor(*av);
6295 		break;
6296 	}
6297 }
6298 
6299 static int
ipfw_get_tracked_ifaces(ipfw_obj_lheader ** polh)6300 ipfw_get_tracked_ifaces(ipfw_obj_lheader **polh)
6301 {
6302 	ipfw_obj_lheader req, *olh;
6303 	size_t sz;
6304 
6305 	memset(&req, 0, sizeof(req));
6306 	sz = sizeof(req);
6307 
6308 	if (do_get3(IP_FW_XIFLIST, &req.opheader, &sz) != 0) {
6309 		if (errno != ENOMEM)
6310 			return (errno);
6311 	}
6312 
6313 	sz = req.size;
6314 	if ((olh = calloc(1, sz)) == NULL)
6315 		return (ENOMEM);
6316 
6317 	olh->size = sz;
6318 	if (do_get3(IP_FW_XIFLIST, &olh->opheader, &sz) != 0) {
6319 		free(olh);
6320 		return (errno);
6321 	}
6322 
6323 	*polh = olh;
6324 	return (0);
6325 }
6326 
6327 static int
ifinfo_cmp(const void * a,const void * b)6328 ifinfo_cmp(const void *a, const void *b)
6329 {
6330 	const ipfw_iface_info *ia, *ib;
6331 
6332 	ia = (const ipfw_iface_info *)a;
6333 	ib = (const ipfw_iface_info *)b;
6334 
6335 	return (stringnum_cmp(ia->ifname, ib->ifname));
6336 }
6337 
6338 /*
6339  * Retrieves table list from kernel,
6340  * optionally sorts it and calls requested function for each table.
6341  * Returns 0 on success.
6342  */
6343 static void
ipfw_list_tifaces(void)6344 ipfw_list_tifaces(void)
6345 {
6346 	ipfw_obj_lheader *olh = NULL;
6347 	ipfw_iface_info *info;
6348 	uint32_t i;
6349 	int error;
6350 
6351 	if ((error = ipfw_get_tracked_ifaces(&olh)) != 0)
6352 		err(EX_OSERR, "Unable to request ipfw tracked interface list");
6353 
6354 	qsort(olh + 1, olh->count, olh->objsize, ifinfo_cmp);
6355 
6356 	info = (ipfw_iface_info *)(olh + 1);
6357 	for (i = 0; i < olh->count; i++) {
6358 		if (info->flags & IPFW_IFFLAG_RESOLVED)
6359 			printf("%s ifindex: %d refcount: %u changes: %u\n",
6360 			    info->ifname, info->ifindex, info->refcnt,
6361 			    info->gencnt);
6362 		else
6363 			printf("%s ifindex: unresolved refcount: %u changes: %u\n",
6364 			    info->ifname, info->refcnt, info->gencnt);
6365 		info = (ipfw_iface_info *)((caddr_t)info + olh->objsize);
6366 	}
6367 
6368 	free(olh);
6369 }
6370