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