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
6 * Idea and grammar partially left from:
7 * Copyright (c) 1993 Daniel Boulet
9 * Redistribution and use in source forms, with and without modification,
10 * are permitted provided that this entire comment appears intact.
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.
16 * This software is provided ``AS IS'' without any warranties of any kind.
18 * NEW command line interface for IP firewall facility
23 #include <sys/types.h>
24 #include <sys/param.h>
25 #include <sys/socket.h>
26 #include <sys/sockio.h>
27 #include <sys/sysctl.h>
44 #include <time.h> /* ctime */
45 #include <timeconv.h> /* _long_to_time */
48 #include <stddef.h> /* offsetof */
50 #include <net/ethernet.h>
51 #include <net/if.h> /* only IFNAMSIZ */
52 #include <netinet/in.h>
53 #include <netinet/in_systm.h> /* only n_short, n_long */
54 #include <netinet/ip.h>
55 #include <netinet/ip_icmp.h>
56 #include <netinet/ip_fw.h>
57 #include <netinet/tcp.h>
58 #include <arpa/inet.h>
60 struct cmdline_opts g_co; /* global options */
66 int show_time; /* show timestamp */
67 uint32_t set_mask; /* enabled sets mask */
68 uint32_t flags; /* request flags */
69 uint32_t first; /* first rule to request */
70 uint32_t last; /* last rule to request */
71 uint32_t dcnt; /* number of dynamic states */
72 ipfw_obj_ctlv *tstate; /* table state data */
75 int resvd_set_number = RESVD_SET;
77 static int ipfw_socket = -1;
79 #define CHECK_LENGTH(v, len) do { \
81 errx(EX_DATAERR, "Rule too long"); \
84 * Check if we have enough space in cmd buffer. Note that since
85 * first 8? u32 words are reserved by reserved header, full cmd
86 * buffer can't be used, so we need to protect from buffer overrun
87 * only. At the beginning, cblen is less than actual buffer size by
88 * size of ipfw_insn_u32 instruction + 1 u32 work. This eliminates need
89 * for checking small instructions fitting in given range.
90 * We also (ab)use the fact that ipfw_insn is always the first field
91 * for any custom instruction.
93 #define CHECK_CMDLEN CHECK_LENGTH(cblen, F_LEN((ipfw_insn *)cmd))
95 #define GET_UINT_ARG(arg, min, max, tok, s_x) do { \
97 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
98 if (_substrcmp(*av, "tablearg") == 0) { \
107 _xval = strtol(*av, &end, 10); \
109 if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
110 errx(EX_DATAERR, "%s: invalid argument: %s", \
111 match_value(s_x, tok), *av); \
113 if (errno == ERANGE || _xval < min || _xval > max) \
114 errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
115 match_value(s_x, tok), min, max, *av); \
117 if (_xval == IP_FW_TARG) \
118 errx(EX_DATAERR, "%s: illegal argument value: %s", \
119 match_value(s_x, tok), *av); \
124 static struct _s_x f_tcpflags[] = {
135 static struct _s_x f_tcpopts[] = {
136 { "mss", IP_FW_TCPOPT_MSS },
137 { "maxseg", IP_FW_TCPOPT_MSS },
138 { "window", IP_FW_TCPOPT_WINDOW },
139 { "sack", IP_FW_TCPOPT_SACK },
140 { "ts", IP_FW_TCPOPT_TS },
141 { "timestamp", IP_FW_TCPOPT_TS },
142 { "cc", IP_FW_TCPOPT_CC },
148 * IP options span the range 0 to 255 so we need to remap them
149 * (though in fact only the low 5 bits are significant).
151 static struct _s_x f_ipopts[] = {
152 { "ssrr", IP_FW_IPOPT_SSRR},
153 { "lsrr", IP_FW_IPOPT_LSRR},
154 { "rr", IP_FW_IPOPT_RR},
155 { "ts", IP_FW_IPOPT_TS},
160 static struct _s_x f_iptos[] = {
161 { "lowdelay", IPTOS_LOWDELAY},
162 { "throughput", IPTOS_THROUGHPUT},
163 { "reliability", IPTOS_RELIABILITY},
164 { "mincost", IPTOS_MINCOST},
165 { "congestion", IPTOS_ECN_CE},
166 { "ecntransport", IPTOS_ECN_ECT0},
167 { "ip tos option", 0},
171 static struct _s_x f_ipoff[] = {
172 { "rf", IP_RF >> 8 },
173 { "df", IP_DF >> 8 },
174 { "mf", IP_MF >> 8 },
179 struct _s_x f_ipdscp[] = {
180 { "af11", IPTOS_DSCP_AF11 >> 2 }, /* 001010 */
181 { "af12", IPTOS_DSCP_AF12 >> 2 }, /* 001100 */
182 { "af13", IPTOS_DSCP_AF13 >> 2 }, /* 001110 */
183 { "af21", IPTOS_DSCP_AF21 >> 2 }, /* 010010 */
184 { "af22", IPTOS_DSCP_AF22 >> 2 }, /* 010100 */
185 { "af23", IPTOS_DSCP_AF23 >> 2 }, /* 010110 */
186 { "af31", IPTOS_DSCP_AF31 >> 2 }, /* 011010 */
187 { "af32", IPTOS_DSCP_AF32 >> 2 }, /* 011100 */
188 { "af33", IPTOS_DSCP_AF33 >> 2 }, /* 011110 */
189 { "af41", IPTOS_DSCP_AF41 >> 2 }, /* 100010 */
190 { "af42", IPTOS_DSCP_AF42 >> 2 }, /* 100100 */
191 { "af43", IPTOS_DSCP_AF43 >> 2 }, /* 100110 */
192 { "be", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
193 { "va", IPTOS_DSCP_VA >> 2 }, /* 101100 */
194 { "ef", IPTOS_DSCP_EF >> 2 }, /* 101110 */
195 { "cs0", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
196 { "cs1", IPTOS_DSCP_CS1 >> 2 }, /* 001000 */
197 { "cs2", IPTOS_DSCP_CS2 >> 2 }, /* 010000 */
198 { "cs3", IPTOS_DSCP_CS3 >> 2 }, /* 011000 */
199 { "cs4", IPTOS_DSCP_CS4 >> 2 }, /* 100000 */
200 { "cs5", IPTOS_DSCP_CS5 >> 2 }, /* 101000 */
201 { "cs6", IPTOS_DSCP_CS6 >> 2 }, /* 110000 */
202 { "cs7", IPTOS_DSCP_CS7 >> 2 }, /* 100000 */
206 static struct _s_x limit_masks[] = {
207 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
208 {"src-addr", DYN_SRC_ADDR},
209 {"src-port", DYN_SRC_PORT},
210 {"dst-addr", DYN_DST_ADDR},
211 {"dst-port", DYN_DST_PORT},
216 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
217 * This is only used in this code.
219 #define IPPROTO_ETHERTYPE 0x1000
220 static struct _s_x ether_types[] = {
222 * Note, we cannot use "-:&/" in the names because they are field
223 * separators in the type specifications. Also, we use s = NULL as
224 * end-delimiter, because a type of 0 can be legal.
237 { "pppoe_disc", 0x8863 },
238 { "pppoe_sess", 0x8864 },
239 { "ipx_8022", 0x00E0 },
240 { "ipx_8023", 0x0000 },
241 { "ipx_ii", 0x8137 },
242 { "ipx_snap", 0x8137 },
248 static struct _s_x rule_eactions[] = {
249 { "nat64clat", TOK_NAT64CLAT },
250 { "nat64lsn", TOK_NAT64LSN },
251 { "nat64stl", TOK_NAT64STL },
252 { "nptv6", TOK_NPTV6 },
253 { "tcp-setmss", TOK_TCPSETMSS },
254 { NULL, 0 } /* terminator */
257 static struct _s_x rule_actions[] = {
258 { "abort6", TOK_ABORT6 },
259 { "abort", TOK_ABORT },
260 { "accept", TOK_ACCEPT },
261 { "pass", TOK_ACCEPT },
262 { "allow", TOK_ACCEPT },
263 { "permit", TOK_ACCEPT },
264 { "count", TOK_COUNT },
265 { "pipe", TOK_PIPE },
266 { "queue", TOK_QUEUE },
267 { "divert", TOK_DIVERT },
269 { "netgraph", TOK_NETGRAPH },
270 { "ngtee", TOK_NGTEE },
271 { "fwd", TOK_FORWARD },
272 { "forward", TOK_FORWARD },
273 { "skipto", TOK_SKIPTO },
274 { "deny", TOK_DENY },
275 { "drop", TOK_DENY },
276 { "reject", TOK_REJECT },
277 { "reset6", TOK_RESET6 },
278 { "reset", TOK_RESET },
279 { "unreach6", TOK_UNREACH6 },
280 { "unreach", TOK_UNREACH },
281 { "check-state", TOK_CHECKSTATE },
282 { "//", TOK_COMMENT },
284 { "reass", TOK_REASS },
285 { "setfib", TOK_SETFIB },
286 { "setdscp", TOK_SETDSCP },
287 { "call", TOK_CALL },
288 { "return", TOK_RETURN },
289 { "eaction", TOK_EACTION },
290 { "tcp-setmss", TOK_TCPSETMSS },
291 { "setmark", TOK_SETMARK },
292 { NULL, 0 } /* terminator */
295 static struct _s_x rule_action_params[] = {
296 { "altq", TOK_ALTQ },
299 { "untag", TOK_UNTAG },
300 { NULL, 0 } /* terminator */
304 * The 'lookup' instruction accepts one of the following arguments.
305 * Arguments are passed as v[1] in O_DST_LOOKUP options.
307 static struct _s_x lookup_keys[] = {
308 { "dst-ip", LOOKUP_DST_IP },
309 { "src-ip", LOOKUP_SRC_IP },
310 { "dst-port", LOOKUP_DST_PORT },
311 { "src-port", LOOKUP_SRC_PORT },
312 { "dst-mac", LOOKUP_DST_MAC },
313 { "src-mac", LOOKUP_SRC_MAC },
314 { "uid", LOOKUP_UID },
315 { "jail", LOOKUP_JAIL },
316 { "dscp", LOOKUP_DSCP },
317 { "mark", LOOKUP_MARK },
321 static struct _s_x rule_options[] = {
322 { "tagged", TOK_TAGGED },
325 { "jail", TOK_JAIL },
327 { "limit", TOK_LIMIT },
328 { "set-limit", TOK_SETLIMIT },
329 { "keep-state", TOK_KEEPSTATE },
330 { "record-state", TOK_RECORDSTATE },
331 { "bridged", TOK_LAYER2 },
332 { "layer2", TOK_LAYER2 },
334 { "diverted", TOK_DIVERTED },
335 { "diverted-loopback", TOK_DIVERTEDLOOPBACK },
336 { "diverted-output", TOK_DIVERTEDOUTPUT },
337 { "xmit", TOK_XMIT },
338 { "recv", TOK_RECV },
340 { "fragment", TOK_FRAG },
341 { "frag", TOK_FRAG },
343 { "ipoptions", TOK_IPOPTS },
344 { "ipopts", TOK_IPOPTS },
345 { "iplen", TOK_IPLEN },
346 { "ipid", TOK_IPID },
347 { "ipprecedence", TOK_IPPRECEDENCE },
348 { "dscp", TOK_DSCP },
349 { "iptos", TOK_IPTOS },
350 { "ipttl", TOK_IPTTL },
351 { "ipversion", TOK_IPVER },
352 { "ipver", TOK_IPVER },
353 { "estab", TOK_ESTAB },
354 { "established", TOK_ESTAB },
355 { "setup", TOK_SETUP },
356 { "sockarg", TOK_SOCKARG },
357 { "tcpdatalen", TOK_TCPDATALEN },
358 { "tcpflags", TOK_TCPFLAGS },
359 { "tcpflgs", TOK_TCPFLAGS },
360 { "tcpmss", TOK_TCPMSS },
361 { "tcpoptions", TOK_TCPOPTS },
362 { "tcpopts", TOK_TCPOPTS },
363 { "tcpseq", TOK_TCPSEQ },
364 { "tcpack", TOK_TCPACK },
365 { "tcpwin", TOK_TCPWIN },
366 { "icmptype", TOK_ICMPTYPES },
367 { "icmptypes", TOK_ICMPTYPES },
368 { "dst-ip", TOK_DSTIP },
369 { "src-ip", TOK_SRCIP },
370 { "dst-port", TOK_DSTPORT },
371 { "src-port", TOK_SRCPORT },
372 { "dst-mac", TOK_DSTMAC },
373 { "src-mac", TOK_SRCMAC },
374 { "proto", TOK_PROTO },
377 { "mac-type", TOK_MACTYPE },
378 { "verrevpath", TOK_VERREVPATH },
379 { "versrcreach", TOK_VERSRCREACH },
380 { "antispoof", TOK_ANTISPOOF },
381 { "ipsec", TOK_IPSEC },
382 { "icmp6type", TOK_ICMP6TYPES },
383 { "icmp6types", TOK_ICMP6TYPES },
384 { "ext6hdr", TOK_EXT6HDR },
385 { "flow-id", TOK_FLOWID },
386 { "ipv6", TOK_IPV6 },
388 { "ipv4", TOK_IPV4 },
390 { "dst-ipv6", TOK_DSTIP6 },
391 { "dst-ip6", TOK_DSTIP6 },
392 { "src-ipv6", TOK_SRCIP6 },
393 { "src-ip6", TOK_SRCIP6 },
394 { "lookup", TOK_LOOKUP },
395 { "flow", TOK_FLOW },
396 { "mark", TOK_MARK },
397 { "defer-action", TOK_SKIPACTION },
398 { "defer-immediate-action", TOK_SKIPACTION },
399 { "//", TOK_COMMENT },
401 { "not", TOK_NOT }, /* pseudo option */
402 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
403 { "or", TOK_OR }, /* pseudo option */
404 { "|", /* escape */ TOK_OR }, /* pseudo option */
405 { "{", TOK_STARTBRACE }, /* pseudo option */
406 { "(", TOK_STARTBRACE }, /* pseudo option */
407 { "}", TOK_ENDBRACE }, /* pseudo option */
408 { ")", TOK_ENDBRACE }, /* pseudo option */
409 { NULL, 0 } /* terminator */
412 void bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg);
413 static int ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
414 ipfw_cfg_lheader **pcfg, size_t *psize);
415 static int ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
416 ipfw_cfg_lheader *cfg, size_t sz, int ac, char **av);
417 static void ipfw_list_tifaces(void);
420 static uint16_t pack_object(struct tidx *tstate, const char *name, int otype);
421 static uint16_t pack_table(struct tidx *tstate, const char *name);
423 static char *table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx);
424 static void object_sort_ctlv(ipfw_obj_ctlv *ctlv);
425 static char *object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx,
431 return (g_co.prog == cmdline_prog_ipfw);
435 * Simple string buffer API.
436 * Used to simplify buffer passing between function and for
437 * transparent overrun handling.
441 * Allocates new buffer of given size @sz.
443 * Returns 0 on success.
446 bp_alloc(struct buf_pr *b, size_t size)
448 memset(b, 0, sizeof(struct buf_pr));
450 if ((b->buf = calloc(1, size)) == NULL)
461 bp_free(struct buf_pr *b)
468 * Flushes buffer so new writer start from beginning.
471 bp_flush(struct buf_pr *b)
480 * Print message specified by @format and args.
481 * Automatically manage buffer space and transparently handle
484 * Returns number of bytes that should have been printed.
487 bprintf(struct buf_pr *b, const char *format, ...)
492 va_start(args, format);
494 i = vsnprintf(b->ptr, b->avail, format, args);
497 if (i < 0 || (size_t)i > b->avail) {
498 /* Overflow or print error */
511 * Special values printer for tablearg-aware opcodes.
514 bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg)
518 bprintf(bp, "%s", str);
519 if (arg == IP_FW_TARG)
520 bprintf(bp, "tablearg");
522 bprintf(bp, "%u", arg);
526 * Helper routine to print a possibly unaligned uint64_t on
527 * various platform. If width > 0, print the value with
528 * the desired width, followed by a space;
529 * otherwise, return the required width.
532 pr_u64(struct buf_pr *b, void *pd, int width)
535 #define U64_FMT "I64"
537 #define U64_FMT "llu"
540 unsigned long long d;
542 bcopy (pd, &u, sizeof(u));
545 bprintf(b, "%*" U64_FMT " ", width, d) :
546 snprintf(NULL, 0, "%" U64_FMT, d) ;
552 safe_calloc(size_t number, size_t size)
554 void *ret = calloc(number, size);
557 err(EX_OSERR, "calloc");
562 safe_realloc(void *ptr, size_t size)
564 void *ret = realloc(ptr, size);
567 err(EX_OSERR, "realloc");
572 * Compare things like interface or table names.
575 stringnum_cmp(const char *a, const char *b)
587 return (strcmp(a, b));
590 struct debug_header {
599 * conditionally runs the command.
600 * Selected options or negative -> getsockopt
603 do_cmd(int optname, void *optval, uintptr_t optlen)
607 if (g_co.debug_only) {
608 struct debug_header dbg = {
611 .total_len = optlen + sizeof(struct debug_header),
613 write(1, &dbg, sizeof(dbg));
614 write(1, optval, optlen);
620 if (ipfw_socket == -1)
621 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
623 err(EX_UNAVAILABLE, "socket");
625 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
626 optname == IP_FW_ADD || optname == IP_FW3 ||
627 optname == IP_FW_NAT_GET_CONFIG ||
629 optname == IP_FW_NAT_GET_LOG) {
632 i = getsockopt(ipfw_socket, IPPROTO_IP, optname, optval,
633 (socklen_t *)optlen);
635 i = setsockopt(ipfw_socket, IPPROTO_IP, optname, optval, optlen);
641 * do_set3 - pass ipfw control cmd to kernel
642 * @optname: option name
643 * @optval: pointer to option data
644 * @optlen: option length
646 * Assumes op3 header is already embedded.
647 * Calls setsockopt() with IP_FW3 as kernel-visible opcode.
648 * Returns 0 on success or errno otherwise.
651 do_set3(int optname, ip_fw3_opheader *op3, size_t optlen)
654 op3->opcode = optname;
656 if (g_co.debug_only) {
657 struct debug_header dbg = {
660 .total_len = optlen, sizeof(struct debug_header),
662 write(1, &dbg, sizeof(dbg));
663 write(1, op3, optlen);
669 if (ipfw_socket == -1)
670 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
672 err(EX_UNAVAILABLE, "socket");
675 return (setsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, optlen));
679 * do_get3 - pass ipfw control cmd to kernel
680 * @optname: option name
681 * @optval: pointer to option data
682 * @optlen: pointer to option length
684 * Assumes op3 header is already embedded.
685 * Calls getsockopt() with IP_FW3 as kernel-visible opcode.
686 * Returns 0 on success or errno otherwise.
689 do_get3(int optname, ip_fw3_opheader *op3, size_t *optlen)
694 op3->opcode = optname;
696 if (g_co.debug_only) {
697 struct debug_header dbg = {
700 .total_len = *optlen + sizeof(struct debug_header),
702 write(1, &dbg, sizeof(dbg));
703 write(1, op3, *optlen);
709 if (ipfw_socket == -1)
710 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
712 err(EX_UNAVAILABLE, "socket");
716 error = getsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, &len);
723 * match_token takes a table and a string, returns the value associated
724 * with the string (-1 in case of failure).
727 match_token(struct _s_x *table, const char *string)
730 uint i = strlen(string);
732 for (pt = table ; i && pt->s != NULL ; pt++)
733 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
739 * match_token_relaxed takes a table and a string, returns the value associated
740 * with the string for the best match.
743 * value from @table for matched records
744 * -1 for non-matched records
745 * -2 if more than one records match @string.
748 match_token_relaxed(struct _s_x *table, const char *string)
756 for (pt = table ; i != 0 && pt->s != NULL ; pt++) {
757 if (strncmp(pt->s, string, i) != 0)
766 return (c > 0 ? -2: -1);
770 get_token(struct _s_x *table, const char *string, const char *errbase)
774 if ((tcmd = match_token_relaxed(table, string)) < 0)
775 errx(EX_USAGE, "%s %s %s",
776 (tcmd == 0) ? "invalid" : "ambiguous", errbase, string);
782 * match_value takes a table and a value, returns the string associated
783 * with the value (NULL in case of failure).
786 match_value(struct _s_x *p, int value)
788 for (; p->s != NULL; p++)
795 concat_tokens(char *buf, size_t bufsize, struct _s_x *table,
796 const char *delimiter)
802 for (sz = 0, pt = table ; pt->s != NULL; pt++) {
803 l = snprintf(buf + sz, bufsize - sz, "%s%s",
804 (sz == 0) ? "" : delimiter, pt->s);
815 * helper function to process a set of flags and set bits in the
819 fill_flags(struct _s_x *flags, char *p, char **e, uint32_t *set,
822 char *q; /* points to the separator */
824 uint32_t *which; /* mask we are working on */
835 val = match_token(flags, p);
841 *which |= (uint32_t)val;
848 print_flags_buffer(char *buf, size_t sz, struct _s_x *list, uint32_t set)
850 char const *comma = "";
853 for (i = 0; list[i].x != 0; i++) {
854 if ((set & list[i].x) == 0)
858 l = snprintf(buf, sz, "%s%s", comma, list[i].s);
859 if (l < 0 || (size_t)l >= sz)
868 * _substrcmp takes two strings and returns 1 if they do not match,
869 * and 0 if they match exactly or the first string is a sub-string
870 * of the second. A warning is printed to stderr in the case that the
871 * first string is a sub-string of the second.
873 * This function will be removed in the future through the usual
874 * deprecation process.
877 _substrcmp(const char *str1, const char* str2)
880 if (strncmp(str1, str2, strlen(str1)) != 0)
883 if (strlen(str1) != strlen(str2))
884 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
890 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
891 * and 0 if they match exactly or the second string is a sub-string
892 * of the first. A warning is printed to stderr in the case that the
893 * first string does not match the third.
895 * This function exists to warn about the bizarre construction
896 * strncmp(str, "by", 2) which is used to allow people to use a shortcut
897 * for "bytes". The problem is that in addition to accepting "by",
898 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
899 * other string beginning with "by".
901 * This function will be removed in the future through the usual
902 * deprecation process.
905 _substrcmp2(const char *str1, const char* str2, const char* str3)
908 if (strncmp(str1, str2, strlen(str2)) != 0)
911 if (strcmp(str1, str3) != 0)
912 warnx("DEPRECATED: '%s' matched '%s'",
918 * prints one port, symbolic or numeric
921 print_port(struct buf_pr *bp, int proto, uint16_t port)
924 if (proto == IPPROTO_ETHERTYPE) {
927 if (g_co.do_resolv && (s = match_value(ether_types, port)) )
928 bprintf(bp, "%s", s);
930 bprintf(bp, "0x%04x", port);
932 struct servent *se = NULL;
933 if (g_co.do_resolv) {
934 struct protoent *pe = getprotobynumber(proto);
936 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
939 bprintf(bp, "%s", se->s_name);
941 bprintf(bp, "%d", port);
945 static struct _s_x _port_name[] = {
946 {"dst-port", O_IP_DSTPORT},
947 {"src-port", O_IP_SRCPORT},
951 {"mac-type", O_MAC_TYPE},
952 {"tcpdatalen", O_TCPDATALEN},
953 {"tcpmss", O_TCPMSS},
954 {"tcpwin", O_TCPWIN},
955 {"tagged", O_TAGGED},
960 * Print the values in a list 16-bit items of the types above.
961 * XXX todo: add support for mask.
964 print_newports(struct buf_pr *bp, const ipfw_insn_u16 *cmd, int proto, int opcode)
966 const uint16_t *p = cmd->ports;
971 sep = match_value(_port_name, opcode);
974 bprintf(bp, " %s", sep);
977 for (i = F_LEN((const ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
978 bprintf(bp, "%s", sep);
979 print_port(bp, proto, p[0]);
982 print_port(bp, proto, p[1]);
989 * Like strtol, but also translates service names into port numbers
990 * for some protocols.
992 * proto == -1 disables the protocol check;
993 * proto == IPPROTO_ETHERTYPE looks up an internal table
994 * proto == <some value in /etc/protocols> matches the values there.
995 * Returns *end == s in case the parameter is not found.
998 strtoport(char *s, char **end, int base, int proto)
1004 *end = s; /* default - not found */
1006 return 0; /* not found */
1009 return strtol(s, end, base);
1012 * find separator. '\\' escapes the next char.
1014 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\' ||
1015 *s1 == '_' || *s1 == '.') ; s1++)
1016 if (*s1 == '\\' && s1[1] != '\0')
1019 buf = safe_calloc(s1 - s + 1, 1);
1022 * copy into a buffer skipping backslashes
1024 for (p = s, i = 0; p != s1 ; p++)
1029 if (proto == IPPROTO_ETHERTYPE) {
1030 i = match_token(ether_types, buf);
1032 if (i != -1) { /* found */
1037 struct protoent *pe = NULL;
1041 pe = getprotobynumber(proto);
1043 se = getservbyname(buf, pe ? pe->p_name : NULL);
1047 return ntohs(se->s_port);
1050 return 0; /* not found */
1054 * Fill the body of the command with the list of port ranges.
1057 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
1059 uint16_t a, b, *p = cmd->ports;
1064 a = strtoport(av, &s, 0, proto);
1065 if (s == av) /* empty or invalid argument */
1068 CHECK_LENGTH(cblen, i + 2);
1071 case '-': /* a range */
1073 b = strtoport(av, &s, 0, proto);
1074 /* Reject expressions like '1-abc' or '1-2-3'. */
1075 if (s == av || (*s != ',' && *s != '\0'))
1080 case ',': /* comma separated list */
1085 warnx("port list: invalid separator <%c> in <%s>",
1095 if (i + 1 > F_LEN_MASK)
1096 errx(EX_DATAERR, "too many ports/ranges\n");
1097 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
1103 * Fill the body of the command with the list of DiffServ codepoints.
1106 fill_dscp(ipfw_insn *cmd, char *av, int cblen)
1108 uint32_t *low, *high;
1112 cmd->opcode = O_DSCP;
1113 cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
1117 low = (uint32_t *)(cmd + 1);
1130 if ((code = match_token(f_ipdscp, s)) == -1)
1131 errx(EX_DATAERR, "Unknown DSCP code");
1133 code = strtoul(s, NULL, 10);
1134 if (code < 0 || code > 63)
1135 errx(EX_DATAERR, "Invalid DSCP value");
1139 *high |= 1 << (code - 32);
1148 * Fill the body of the command with mark value and mask.
1151 fill_mark(ipfw_insn *cmd, char *av, int cblen)
1153 uint32_t *value, *mask;
1156 cmd->opcode = O_MARK;
1157 cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
1161 value = (uint32_t *)(cmd + 1);
1164 value_str = strsep(&av, ":");
1166 if (strcmp(value_str, "tablearg") == 0) {
1167 cmd->arg1 = IP_FW_TARG;
1170 /* This is not a tablearg */
1171 cmd->arg1 |= 0x8000;
1172 *value = strtoul(value_str, NULL, 0);
1175 *mask = strtoul(av, NULL, 0);
1179 if ((*value & *mask) != *value)
1180 errx(EX_DATAERR, "Static mark value: some bits in value are"
1181 " set that will be masked out by mask "
1182 "(%#x & %#x) = %#x != %#x",
1183 *value, *mask, (*value & *mask), *value);
1186 static struct _s_x icmpcodes[] = {
1187 { "net", ICMP_UNREACH_NET },
1188 { "host", ICMP_UNREACH_HOST },
1189 { "protocol", ICMP_UNREACH_PROTOCOL },
1190 { "port", ICMP_UNREACH_PORT },
1191 { "needfrag", ICMP_UNREACH_NEEDFRAG },
1192 { "srcfail", ICMP_UNREACH_SRCFAIL },
1193 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
1194 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
1195 { "isolated", ICMP_UNREACH_ISOLATED },
1196 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
1197 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
1198 { "tosnet", ICMP_UNREACH_TOSNET },
1199 { "toshost", ICMP_UNREACH_TOSHOST },
1200 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
1201 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
1202 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
1207 get_reject_code(const char *str)
1212 val = strtoul(str, &s, 0);
1213 if (s == str || *s != '\0' || val >= 0x100)
1214 val = match_token(icmpcodes, str);
1216 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
1221 print_reject_code(struct buf_pr *bp, uint16_t code)
1225 if ((s = match_value(icmpcodes, code)) != NULL)
1226 bprintf(bp, "unreach %s", s);
1228 bprintf(bp, "unreach %u", code);
1232 * Returns the number of bits set (from left) in a contiguous bitmask,
1233 * or -1 if the mask is not contiguous.
1234 * XXX this needs a proper fix.
1235 * This effectively works on masks in big-endian (network) format.
1236 * when compiled on little endian architectures.
1238 * First bit is bit 7 of the first byte -- note, for MAC addresses,
1239 * the first bit on the wire is bit 0 of the first byte.
1240 * len is the max length in bits.
1243 contigmask(const uint8_t *p, int len)
1247 for (i=0; i<len ; i++)
1248 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
1250 for (n=i+1; n < len; n++)
1251 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
1252 return -1; /* mask not contiguous */
1257 * print flags set/clear in the two bitmasks passed as parameters.
1258 * There is a specialized check for f_tcpflags.
1261 print_flags(struct buf_pr *bp, char const *name, const ipfw_insn *cmd,
1264 char const *comma = "";
1266 uint8_t set = cmd->arg1 & 0xff;
1267 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
1269 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
1270 bprintf(bp, " setup");
1274 bprintf(bp, " %s ", name);
1275 for (i=0; list[i].x != 0; i++) {
1276 if (set & list[i].x) {
1278 bprintf(bp, "%s%s", comma, list[i].s);
1281 if (clear & list[i].x) {
1282 clear &= ~list[i].x;
1283 bprintf(bp, "%s!%s", comma, list[i].s);
1291 * Print the ip address contained in a command.
1294 print_ip(struct buf_pr *bp, const struct format_opts *fo,
1295 const ipfw_insn_ip *cmd)
1297 struct hostent *he = NULL;
1298 const struct in_addr *ia;
1299 const uint32_t *a = ((const ipfw_insn_u32 *)cmd)->d;
1300 uint32_t len = F_LEN((const ipfw_insn *)cmd);
1304 if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
1307 arg = match_value(lookup_keys, a[1]);
1308 t = table_search_ctlv(fo->tstate,
1309 ((const ipfw_insn *)cmd)->arg1);
1310 bprintf(bp, "lookup %s %s", arg, t);
1313 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
1317 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
1318 cmd->o.opcode == O_IP_DST_LOOKUP) {
1319 t = table_search_ctlv(fo->tstate,
1320 ((const ipfw_insn *)cmd)->arg1);
1321 bprintf(bp, "table(%s", t);
1322 if (len == F_INSN_SIZE(ipfw_insn_u32))
1323 bprintf(bp, ",%u", *a);
1327 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
1328 const uint32_t *map = (const uint32_t *)&cmd->mask;
1329 struct in_addr addr;
1334 x = cmd->o.arg1 - 1;
1336 addr.s_addr = htonl(cmd->addr.s_addr);
1337 bprintf(bp, "%s/%d", inet_ntoa(addr),
1338 contigmask((uint8_t *)&x, 32));
1339 x = cmd->addr.s_addr;
1340 x &= 0xff; /* base */
1342 * Print bits and ranges.
1343 * Locate first bit set (i), then locate first bit unset (j).
1344 * If we have 3+ consecutive bits set, then print them as a
1345 * range, otherwise only print the initial bit and rescan.
1347 for (i=0; i < cmd->o.arg1; i++)
1348 if (map[i/32] & (1<<(i & 31))) {
1349 for (j=i+1; j < cmd->o.arg1; j++)
1350 if (!(map[ j/32] & (1<<(j & 31))))
1352 bprintf(bp, "%c%d", comma, i+x);
1353 if (j>i+2) { /* range has at least 3 elements */
1354 bprintf(bp, "-%d", j-1+x);
1363 * len == 2 indicates a single IP, whereas lists of 1 or more
1364 * addr/mask pairs have len = (2n+1). We convert len to n so we
1365 * use that to count the number of entries.
1367 for (len = len / 2; len > 0; len--, a += 2) {
1368 int mb = /* mask length */
1369 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1370 32 : contigmask((const uint8_t *)&(a[1]), 32);
1371 if (mb == 32 && g_co.do_resolv)
1372 he = gethostbyaddr((const char *)&(a[0]), sizeof(in_addr_t),
1374 if (he != NULL) /* resolved to name */
1375 bprintf(bp, "%s", he->h_name);
1376 else if (mb == 0) /* any */
1378 else { /* numeric IP followed by some kind of mask */
1379 ia = (const struct in_addr *)&a[0];
1380 bprintf(bp, "%s", inet_ntoa(*ia));
1382 ia = (const struct in_addr *)&a[1];
1383 bprintf(bp, ":%s", inet_ntoa(*ia));
1385 bprintf(bp, "/%d", mb);
1393 * prints a MAC address/mask pair
1396 format_mac(struct buf_pr *bp, const uint8_t *addr, const uint8_t *mask)
1398 int l = contigmask(mask, 48);
1401 bprintf(bp, " any");
1403 bprintf(bp, " %02x:%02x:%02x:%02x:%02x:%02x",
1404 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1406 bprintf(bp, "&%02x:%02x:%02x:%02x:%02x:%02x",
1407 mask[0], mask[1], mask[2],
1408 mask[3], mask[4], mask[5]);
1410 bprintf(bp, "/%d", l);
1415 print_mac(struct buf_pr *bp, const ipfw_insn_mac *mac)
1418 bprintf(bp, " MAC");
1419 format_mac(bp, mac->addr, mac->mask);
1420 format_mac(bp, mac->addr + 6, mac->mask + 6);
1424 print_mac_lookup(struct buf_pr *bp, const struct format_opts *fo,
1425 const ipfw_insn *cmd)
1427 uint32_t len = F_LEN(cmd);
1432 t = table_search_ctlv(fo->tstate, cmd->arg1);
1433 bprintf(bp, "table(%s", t);
1434 if (len == F_INSN_SIZE(ipfw_insn_u32))
1435 bprintf(bp, ",%u", ((const ipfw_insn_u32 *)cmd)->d[0]);
1440 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1449 type = strtoul(av, &av, 0);
1451 if (*av != ',' && *av != '\0')
1452 errx(EX_DATAERR, "invalid ICMP type");
1455 errx(EX_DATAERR, "ICMP type out of range");
1457 cmd->d[0] |= 1 << type;
1459 cmd->o.opcode = O_ICMPTYPE;
1460 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1464 print_icmptypes(struct buf_pr *bp, const ipfw_insn_u32 *cmd)
1469 bprintf(bp, " icmptypes");
1470 for (i = 0; i < 32; i++) {
1471 if ( (cmd->d[0] & (1 << (i))) == 0)
1473 bprintf(bp, "%c%d", sep, i);
1479 print_dscp(struct buf_pr *bp, const ipfw_insn_u32 *cmd)
1486 bprintf(bp, " dscp");
1489 if (*v & (1 << i)) {
1490 if ((code = match_value(f_ipdscp, i)) != NULL)
1491 bprintf(bp, "%c%s", sep, code);
1493 bprintf(bp, "%c%d", sep, i);
1497 if ((++i % 32) == 0)
1502 #define insntod(cmd, type) ((const ipfw_insn_ ## type *)(cmd))
1504 struct ip_fw_rule *rule;
1505 const ipfw_insn *eaction;
1508 #define HAVE_PROTO 0x0001
1509 #define HAVE_SRCIP 0x0002
1510 #define HAVE_DSTIP 0x0004
1511 #define HAVE_PROBE_STATE 0x0008
1517 init_show_state(struct show_state *state, struct ip_fw_rule *rule)
1520 state->printed = calloc(rule->cmd_len, sizeof(uint8_t));
1521 if (state->printed == NULL)
1524 state->eaction = NULL;
1527 state->or_block = 0;
1532 free_show_state(struct show_state *state)
1535 free(state->printed);
1539 is_printed_opcode(struct show_state *state, const ipfw_insn *cmd)
1542 return (state->printed[cmd - state->rule->cmd]);
1546 mark_printed(struct show_state *state, const ipfw_insn *cmd)
1549 state->printed[cmd - state->rule->cmd] = 1;
1553 print_limit_mask(struct buf_pr *bp, const ipfw_insn_limit *limit)
1555 struct _s_x *p = limit_masks;
1556 char const *comma = " ";
1559 for (x = limit->limit_mask; p->x != 0; p++) {
1560 if ((x & p->x) == p->x) {
1562 bprintf(bp, "%s%s", comma, p->s);
1566 bprint_uint_arg(bp, " ", limit->conn_limit);
1570 print_instruction(struct buf_pr *bp, const struct format_opts *fo,
1571 struct show_state *state, const ipfw_insn *cmd)
1573 struct protoent *pe;
1579 if (is_printed_opcode(state, cmd))
1581 if ((cmd->len & F_OR) != 0 && state->or_block == 0)
1583 if (cmd->opcode != O_IN && (cmd->len & F_NOT) != 0)
1584 bprintf(bp, " not");
1586 switch (cmd->opcode) {
1588 d = 1.0 * insntod(cmd, u32)->d[0] / 0x7fffffff;
1589 bprintf(bp, "prob %f ", d);
1591 case O_PROBE_STATE: /* no need to print anything here */
1592 state->flags |= HAVE_PROBE_STATE;
1595 case O_IP_SRC_LOOKUP:
1599 if (state->flags & HAVE_SRCIP)
1600 bprintf(bp, " src-ip");
1601 print_ip(bp, fo, insntod(cmd, ip));
1604 case O_IP_DST_LOOKUP:
1608 if (state->flags & HAVE_DSTIP)
1609 bprintf(bp, " dst-ip");
1610 print_ip(bp, fo, insntod(cmd, ip));
1613 case O_IP6_SRC_MASK:
1615 if (state->flags & HAVE_SRCIP)
1616 bprintf(bp, " src-ip6");
1617 print_ip6(bp, insntod(cmd, ip6));
1620 case O_IP6_DST_MASK:
1622 if (state->flags & HAVE_DSTIP)
1623 bprintf(bp, " dst-ip6");
1624 print_ip6(bp, insntod(cmd, ip6));
1626 case O_MAC_SRC_LOOKUP:
1627 bprintf(bp, " src-mac");
1628 print_mac_lookup(bp, fo, cmd);
1630 case O_MAC_DST_LOOKUP:
1631 bprintf(bp, " dst-mac");
1632 print_mac_lookup(bp, fo, cmd);
1635 print_flow6id(bp, insntod(cmd, u32));
1639 print_newports(bp, insntod(cmd, u16), state->proto,
1640 (state->flags & (HAVE_SRCIP | HAVE_DSTIP)) ==
1641 (HAVE_SRCIP | HAVE_DSTIP) ? cmd->opcode: 0);
1644 pe = getprotobynumber(cmd->arg1);
1645 if (state->flags & HAVE_PROTO)
1646 bprintf(bp, " proto");
1648 bprintf(bp, " %s", pe->p_name);
1650 bprintf(bp, " %u", cmd->arg1);
1651 state->proto = cmd->arg1;
1654 print_mac(bp, insntod(cmd, mac));
1657 print_newports(bp, insntod(cmd, u16),
1658 IPPROTO_ETHERTYPE, cmd->opcode);
1661 print_flags(bp, "frag", cmd, f_ipoff);
1664 bprintf(bp, " fib %u", cmd->arg1);
1667 bprintf(bp, " sockarg");
1670 bprintf(bp, cmd->len & F_NOT ? " out" : " in");
1673 switch (cmd->arg1) {
1675 bprintf(bp, " diverted");
1678 bprintf(bp, " diverted-output");
1681 bprintf(bp, " diverted-loopback");
1684 bprintf(bp, " diverted-?<%u>", cmd->arg1);
1689 bprintf(bp, " layer2");
1694 if (cmd->opcode == O_XMIT)
1696 else if (cmd->opcode == O_RECV)
1698 else /* if (cmd->opcode == O_VIA) */
1700 switch (insntod(cmd, if)->name[0]) {
1702 bprintf(bp, " %s %s", s,
1703 inet_ntoa(insntod(cmd, if)->p.ip));
1706 bprintf(bp, " %s table(%s)", s,
1707 table_search_ctlv(fo->tstate,
1708 insntod(cmd, if)->p.kidx));
1711 bprintf(bp, " %s %s", s,
1712 insntod(cmd, if)->name);
1715 case O_IP_FLOW_LOOKUP:
1716 s = table_search_ctlv(fo->tstate, cmd->arg1);
1717 bprintf(bp, " flow table(%s", s);
1718 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))
1719 bprintf(bp, ",%u", insntod(cmd, u32)->d[0]);
1728 if (F_LEN(cmd) == 1) {
1729 switch (cmd->opcode) {
1752 bprintf(bp, " %s %u", s, cmd->arg1);
1754 print_newports(bp, insntod(cmd, u16), 0,
1758 bprintf(bp, " ipver %u", cmd->arg1);
1760 case O_IPPRECEDENCE:
1761 bprintf(bp, " ipprecedence %u", cmd->arg1 >> 5);
1764 print_dscp(bp, insntod(cmd, u32));
1767 print_flags(bp, "ipoptions", cmd, f_ipopts);
1770 print_flags(bp, "iptos", cmd, f_iptos);
1773 print_icmptypes(bp, insntod(cmd, u32));
1776 bprintf(bp, " established");
1779 print_flags(bp, "tcpflags", cmd, f_tcpflags);
1782 print_flags(bp, "tcpoptions", cmd, f_tcpopts);
1785 bprintf(bp, " tcpack %d",
1786 ntohl(insntod(cmd, u32)->d[0]));
1789 bprintf(bp, " tcpseq %d",
1790 ntohl(insntod(cmd, u32)->d[0]));
1793 pwd = getpwuid(insntod(cmd, u32)->d[0]);
1795 bprintf(bp, " uid %s", pwd->pw_name);
1797 bprintf(bp, " uid %u",
1798 insntod(cmd, u32)->d[0]);
1801 grp = getgrgid(insntod(cmd, u32)->d[0]);
1803 bprintf(bp, " gid %s", grp->gr_name);
1805 bprintf(bp, " gid %u",
1806 insntod(cmd, u32)->d[0]);
1809 bprintf(bp, " jail %d", insntod(cmd, u32)->d[0]);
1812 bprintf(bp, " verrevpath");
1815 bprintf(bp, " versrcreach");
1818 bprintf(bp, " antispoof");
1821 bprintf(bp, " ipsec");
1824 bprintf(bp, " // %s", (const char *)(cmd + 1));
1827 if (state->flags & HAVE_PROBE_STATE)
1828 bprintf(bp, " keep-state");
1830 bprintf(bp, " record-state");
1832 object_search_ctlv(fo->tstate, cmd->arg1,
1833 IPFW_TLV_STATE_NAME));
1836 if (state->flags & HAVE_PROBE_STATE)
1837 bprintf(bp, " limit");
1839 bprintf(bp, " set-limit");
1840 print_limit_mask(bp, insntod(cmd, limit));
1842 object_search_ctlv(fo->tstate, cmd->arg1,
1843 IPFW_TLV_STATE_NAME));
1846 if (state->flags & HAVE_PROTO)
1847 bprintf(bp, " proto");
1848 bprintf(bp, " ip6");
1851 if (state->flags & HAVE_PROTO)
1852 bprintf(bp, " proto");
1853 bprintf(bp, " ip4");
1856 print_icmp6types(bp, insntod(cmd, u32));
1859 print_ext6hdr(bp, cmd);
1862 if (F_LEN(cmd) == 1)
1863 bprint_uint_arg(bp, " tagged ", cmd->arg1);
1865 print_newports(bp, insntod(cmd, u16),
1869 bprintf(bp, " defer-immediate-action");
1872 bprintf(bp, " mark");
1873 if (cmd->arg1 == IP_FW_TARG)
1874 bprintf(bp, " tablearg");
1877 ((const ipfw_insn_u32 *)cmd)->d[0]);
1879 if (((const ipfw_insn_u32 *)cmd)->d[1] != 0xFFFFFFFF)
1881 ((const ipfw_insn_u32 *)cmd)->d[1]);
1885 bprintf(bp, " [opcode %d len %d]", cmd->opcode,
1888 if (cmd->len & F_OR) {
1890 state->or_block = 1;
1891 } else if (state->or_block != 0) {
1893 state->or_block = 0;
1895 mark_printed(state, cmd);
1901 print_opcode(struct buf_pr *bp, struct format_opts *fo,
1902 struct show_state *state, int opcode)
1907 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
1908 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1909 /* We use zero opcode to print the rest of options */
1910 if (opcode >= 0 && cmd->opcode != opcode)
1913 * Skip O_NOP, when we printing the rest
1914 * of options, it will be handled separately.
1916 if (cmd->opcode == O_NOP && opcode != O_NOP)
1918 if (!print_instruction(bp, fo, state, cmd))
1926 print_fwd(struct buf_pr *bp, const ipfw_insn *cmd)
1928 char buf[INET6_ADDRSTRLEN + IF_NAMESIZE + 2];
1929 const ipfw_insn_sa6 *sa6;
1930 const ipfw_insn_sa *sa;
1933 if (cmd->opcode == O_FORWARD_IP) {
1934 sa = insntod(cmd, sa);
1935 port = sa->sa.sin_port;
1936 if (sa->sa.sin_addr.s_addr == INADDR_ANY)
1937 bprintf(bp, "fwd tablearg");
1939 bprintf(bp, "fwd %s", inet_ntoa(sa->sa.sin_addr));
1941 sa6 = insntod(cmd, sa6);
1942 port = sa6->sa.sin6_port;
1943 bprintf(bp, "fwd ");
1944 if (getnameinfo((const struct sockaddr *)&sa6->sa,
1945 sizeof(struct sockaddr_in6), buf, sizeof(buf), NULL, 0,
1946 NI_NUMERICHOST) == 0)
1947 bprintf(bp, "%s", buf);
1950 bprintf(bp, ",%u", port);
1954 print_action_instruction(struct buf_pr *bp, const struct format_opts *fo,
1955 struct show_state *state, const ipfw_insn *cmd)
1959 if (is_printed_opcode(state, cmd))
1961 switch (cmd->opcode) {
1963 bprintf(bp, "check-state");
1965 s = object_search_ctlv(fo->tstate, cmd->arg1,
1966 IPFW_TLV_STATE_NAME);
1969 bprintf(bp, " :%s", s ? s: "any");
1972 bprintf(bp, "allow");
1975 bprintf(bp, "count");
1978 bprintf(bp, "deny");
1981 if (cmd->arg1 == ICMP_REJECT_RST)
1982 bprintf(bp, "reset");
1983 else if (cmd->arg1 == ICMP_REJECT_ABORT)
1984 bprintf(bp, "abort");
1985 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1986 bprintf(bp, "reject");
1987 else if (cmd->arg1 == ICMP_UNREACH_NEEDFRAG &&
1988 cmd->len == F_INSN_SIZE(ipfw_insn_u16))
1989 bprintf(bp, "needfrag %u",
1990 ((const ipfw_insn_u16 *)cmd)->ports[0]);
1992 print_reject_code(bp, cmd->arg1);
1995 if (cmd->arg1 == ICMP6_UNREACH_RST)
1996 bprintf(bp, "reset6");
1997 else if (cmd->arg1 == ICMP6_UNREACH_ABORT)
1998 bprintf(bp, "abort6");
2000 print_unreach6_code(bp, cmd->arg1);
2003 bprint_uint_arg(bp, "skipto ", cmd->arg1);
2006 bprint_uint_arg(bp, "pipe ", cmd->arg1);
2009 bprint_uint_arg(bp, "queue ", cmd->arg1);
2012 bprint_uint_arg(bp, "divert ", cmd->arg1);
2015 bprint_uint_arg(bp, "tee ", cmd->arg1);
2018 bprint_uint_arg(bp, "netgraph ", cmd->arg1);
2021 bprint_uint_arg(bp, "ngtee ", cmd->arg1);
2028 if (insntod(cmd, log)->max_log > 0)
2029 bprintf(bp, " log logamount %d",
2030 insntod(cmd, log)->max_log);
2032 bprintf(bp, " log");
2036 print_altq_cmd(bp, insntod(cmd, altq));
2040 bprint_uint_arg(bp, cmd->len & F_NOT ? " untag ":
2041 " tag ", cmd->arg1);
2044 if (cmd->arg1 != IP_FW_NAT44_GLOBAL)
2045 bprint_uint_arg(bp, "nat ", cmd->arg1);
2047 bprintf(bp, "nat global");
2050 if (cmd->arg1 == IP_FW_TARG)
2051 bprint_uint_arg(bp, "setfib ", cmd->arg1);
2053 bprintf(bp, "setfib %u", cmd->arg1 & 0x7FFF);
2055 case O_EXTERNAL_ACTION:
2057 * The external action can consists of two following
2058 * each other opcodes - O_EXTERNAL_ACTION and
2059 * O_EXTERNAL_INSTANCE. The first contains the ID of
2060 * name of external action. The second contains the ID
2061 * of name of external action instance.
2062 * NOTE: in case when external action has no named
2063 * instances support, the second opcode isn't needed.
2065 state->eaction = cmd;
2066 s = object_search_ctlv(fo->tstate, cmd->arg1,
2068 if (match_token(rule_eactions, s) != -1)
2069 bprintf(bp, "%s", s);
2071 bprintf(bp, "eaction %s", s);
2073 case O_EXTERNAL_INSTANCE:
2074 if (state->eaction == NULL)
2077 * XXX: we need to teach ipfw(9) to rewrite opcodes
2078 * in the user buffer on rule addition. When we add
2079 * the rule, we specify zero TLV type for
2080 * O_EXTERNAL_INSTANCE object. To show correct
2081 * rule after `ipfw add` we need to search instance
2082 * name with zero type. But when we do `ipfw show`
2083 * we calculate TLV type using IPFW_TLV_EACTION_NAME()
2086 s = object_search_ctlv(fo->tstate, cmd->arg1, 0);
2088 s = object_search_ctlv(fo->tstate,
2089 cmd->arg1, IPFW_TLV_EACTION_NAME(
2090 state->eaction->arg1));
2091 bprintf(bp, " %s", s);
2093 case O_EXTERNAL_DATA:
2094 if (state->eaction == NULL)
2097 * Currently we support data formatting only for
2098 * external data with datalen u16. For unknown data
2099 * print its size in bytes.
2101 if (cmd->len == F_INSN_SIZE(ipfw_insn))
2102 bprintf(bp, " %u", cmd->arg1);
2104 bprintf(bp, " %ubytes",
2105 cmd->len * sizeof(uint32_t));
2108 if (cmd->arg1 == IP_FW_TARG) {
2109 bprintf(bp, "setdscp tablearg");
2112 s = match_value(f_ipdscp, cmd->arg1 & 0x3F);
2114 bprintf(bp, "setdscp %s", s);
2116 bprintf(bp, "setdscp %u", cmd->arg1 & 0x3F);
2119 bprintf(bp, "reass");
2122 if (cmd->len & F_NOT)
2123 bprintf(bp, "return");
2125 bprint_uint_arg(bp, "call ", cmd->arg1);
2128 if (cmd->arg1 == IP_FW_TARG) {
2129 bprintf(bp, "setmark tablearg");
2132 bprintf(bp, "setmark %#x", ((const ipfw_insn_u32 *)cmd)->d[0]);
2135 bprintf(bp, "** unrecognized action %d len %d ",
2136 cmd->opcode, cmd->len);
2138 mark_printed(state, cmd);
2145 print_action(struct buf_pr *bp, struct format_opts *fo,
2146 struct show_state *state, uint8_t opcode)
2151 for (l = state->rule->cmd_len - state->rule->act_ofs,
2152 cmd = ACTION_PTR(state->rule); l > 0;
2153 l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2154 if (cmd->opcode != opcode)
2156 if (!print_action_instruction(bp, fo, state, cmd))
2164 print_proto(struct buf_pr *bp, struct format_opts *fo,
2165 struct show_state *state)
2168 int l, proto, ip4, ip6;
2170 /* Count all O_PROTO, O_IP4, O_IP6 instructions. */
2171 proto = ip4 = ip6 = 0;
2172 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2173 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2174 switch (cmd->opcode) {
2180 if (cmd->len & F_OR)
2185 if (cmd->len & F_OR)
2192 if (proto == 0 && ip4 == 0 && ip6 == 0) {
2193 state->proto = IPPROTO_IP;
2194 state->flags |= HAVE_PROTO;
2198 /* To handle the case { ip4 or ip6 }, print opcode with F_OR first */
2201 cmd = print_opcode(bp, fo, state, ip4 > ip6 ? O_IP4: O_IP6);
2202 if (cmd != NULL && (cmd->len & F_OR))
2203 cmd = print_opcode(bp, fo, state, ip4 > ip6 ? O_IP6: O_IP4);
2204 if (cmd == NULL || (cmd->len & F_OR))
2205 for (l = proto; l > 0; l--) {
2206 cmd = print_opcode(bp, fo, state, O_PROTO);
2207 if (cmd == NULL || (cmd->len & F_OR) == 0)
2210 /* Initialize proto, it is used by print_newports() */
2211 state->flags |= HAVE_PROTO;
2212 if (state->proto == 0 && ip6 != 0)
2213 state->proto = IPPROTO_IPV6;
2217 match_opcode(int opcode, const int opcodes[], size_t nops)
2221 for (i = 0; i < nops; i++)
2222 if (opcode == opcodes[i])
2228 print_address(struct buf_pr *bp, struct format_opts *fo,
2229 struct show_state *state, const int opcodes[], size_t nops, int portop,
2233 int count, l, portcnt, pf;
2235 count = portcnt = 0;
2236 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2237 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2238 if (match_opcode(cmd->opcode, opcodes, nops))
2240 else if (cmd->opcode == portop)
2244 bprintf(bp, " any");
2245 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2246 l > 0 && count > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2247 if (!match_opcode(cmd->opcode, opcodes, nops))
2249 print_instruction(bp, fo, state, cmd);
2250 if ((cmd->len & F_OR) == 0)
2255 * If several O_IP_?PORT opcodes specified, leave them to the
2259 for (l = state->rule->act_ofs, cmd = state->rule->cmd, pf = 0;
2260 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2261 if (cmd->opcode != portop) {
2262 pf = (cmd->len & F_OR);
2265 /* Print opcode iff it is not in OR block. */
2266 if (pf == 0 && (cmd->len & F_OR) == 0)
2267 print_instruction(bp, fo, state, cmd);
2271 state->flags |= flag;
2274 static const int action_opcodes[] = {
2275 O_CHECK_STATE, O_ACCEPT, O_COUNT, O_DENY, O_REJECT,
2276 O_UNREACH6, O_SKIPTO, O_PIPE, O_QUEUE, O_DIVERT, O_TEE,
2277 O_NETGRAPH, O_NGTEE, O_FORWARD_IP, O_FORWARD_IP6, O_NAT,
2278 O_SETFIB, O_SETDSCP, O_REASS, O_CALLRETURN, O_SETMARK,
2279 /* keep the following opcodes at the end of the list */
2280 O_EXTERNAL_ACTION, O_EXTERNAL_INSTANCE, O_EXTERNAL_DATA
2283 static const int modifier_opcodes[] = {
2284 O_LOG, O_ALTQ, O_TAG
2287 static const int src_opcodes[] = {
2288 O_IP_SRC, O_IP_SRC_LOOKUP, O_IP_SRC_MASK, O_IP_SRC_ME,
2289 O_IP_SRC_SET, O_IP6_SRC, O_IP6_SRC_MASK, O_IP6_SRC_ME
2292 static const int dst_opcodes[] = {
2293 O_IP_DST, O_IP_DST_LOOKUP, O_IP_DST_MASK, O_IP_DST_ME,
2294 O_IP_DST_SET, O_IP6_DST, O_IP6_DST_MASK, O_IP6_DST_ME
2298 show_static_rule(struct cmdline_opts *co, struct format_opts *fo,
2299 struct buf_pr *bp, struct ip_fw_rule *rule, struct ip_fw_bcounter *cntr)
2301 static int twidth = 0;
2302 struct show_state state;
2306 /* Print # DISABLED or skip the rule */
2307 if ((fo->set_mask & (1 << rule->set)) == 0) {
2312 bprintf(bp, "# DISABLED ");
2314 if (init_show_state(&state, rule) != 0) {
2315 warn("init_show_state() failed");
2318 bprintf(bp, "%05u ", rule->rulenum);
2320 /* only if counters are available */
2322 /* Print counters if enabled */
2323 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2324 pr_u64(bp, &cntr->pcnt, fo->pcwidth);
2325 pr_u64(bp, &cntr->bcnt, fo->bcwidth);
2328 /* Print timestamp */
2329 if (co->do_time == TIMESTAMP_NUMERIC)
2330 bprintf(bp, "%10u ", cntr->timestamp);
2331 else if (co->do_time == TIMESTAMP_STRING) {
2333 time_t t = (time_t)0;
2336 strcpy(timestr, ctime(&t));
2337 *strchr(timestr, '\n') = '\0';
2338 twidth = strlen(timestr);
2340 if (cntr->timestamp > 0) {
2341 t = _long_to_time(cntr->timestamp);
2343 strcpy(timestr, ctime(&t));
2344 *strchr(timestr, '\n') = '\0';
2345 bprintf(bp, "%s ", timestr);
2347 bprintf(bp, "%*s ", twidth, "");
2352 /* Print set number */
2354 bprintf(bp, "set %d ", rule->set);
2356 /* Print the optional "match probability" */
2357 cmd = print_opcode(bp, fo, &state, O_PROB);
2358 /* Print rule action */
2359 for (i = 0; i < nitems(action_opcodes); i++) {
2360 cmd = print_action(bp, fo, &state, action_opcodes[i]);
2363 /* Handle special cases */
2364 switch (cmd->opcode) {
2367 case O_EXTERNAL_ACTION:
2368 case O_EXTERNAL_INSTANCE:
2369 /* External action can have several instructions */
2374 /* Print rule modifiers */
2375 for (i = 0; i < nitems(modifier_opcodes); i++)
2376 print_action(bp, fo, &state, modifier_opcodes[i]);
2380 if (co->comment_only != 0)
2383 if (rule->flags & IPFW_RULE_JUSTOPTS) {
2384 state.flags |= HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP;
2388 print_proto(bp, fo, &state);
2389 if (co->do_compact != 0 && (rule->flags & IPFW_RULE_NOOPT))
2393 bprintf(bp, " from");
2394 print_address(bp, fo, &state, src_opcodes, nitems(src_opcodes),
2395 O_IP_SRCPORT, HAVE_SRCIP);
2397 /* Print destination */
2399 print_address(bp, fo, &state, dst_opcodes, nitems(dst_opcodes),
2400 O_IP_DSTPORT, HAVE_DSTIP);
2403 /* Print the rest of options */
2404 while (print_opcode(bp, fo, &state, -1))
2407 /* Print comment at the end */
2408 cmd = print_opcode(bp, fo, &state, O_NOP);
2409 if (co->comment_only != 0 && cmd == NULL)
2410 bprintf(bp, " // ...");
2412 free_show_state(&state);
2416 show_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2417 struct buf_pr *bp, ipfw_dyn_rule *d)
2419 struct protoent *pe;
2422 char buf[INET6_ADDRSTRLEN];
2424 if (d->expire == 0 && d->dyn_type != O_LIMIT_PARENT)
2427 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2428 bprintf(bp, "%05d", rulenum);
2429 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2431 pr_u64(bp, &d->pcnt, fo->pcwidth);
2432 pr_u64(bp, &d->bcnt, fo->bcwidth);
2433 bprintf(bp, "(%ds)", d->expire);
2435 switch (d->dyn_type) {
2436 case O_LIMIT_PARENT:
2437 bprintf(bp, " PARENT %d", d->count);
2440 bprintf(bp, " LIMIT");
2442 case O_KEEP_STATE: /* bidir, no mask */
2443 bprintf(bp, " STATE");
2447 if ((pe = getprotobynumber(d->id.proto)) != NULL)
2448 bprintf(bp, " %s", pe->p_name);
2450 bprintf(bp, " proto %u", d->id.proto);
2452 if (d->id.addr_type == 4) {
2453 a.s_addr = htonl(d->id.src_ip);
2454 bprintf(bp, " %s %d", inet_ntoa(a), d->id.src_port);
2456 a.s_addr = htonl(d->id.dst_ip);
2457 bprintf(bp, " <-> %s %d", inet_ntoa(a), d->id.dst_port);
2458 } else if (d->id.addr_type == 6) {
2459 bprintf(bp, " %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
2460 sizeof(buf)), d->id.src_port);
2461 bprintf(bp, " <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6,
2462 buf, sizeof(buf)), d->id.dst_port);
2464 bprintf(bp, " UNKNOWN <-> UNKNOWN");
2466 bprintf(bp, " :%s", object_search_ctlv(fo->tstate,
2467 d->kidx, IPFW_TLV_STATE_NAME));
2469 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
2470 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
2472 bprintf(bp, " state 0x%08x%s", d->state,
2473 d->state ? " ": ",");
2474 if (d->state & IPFW_DYN_ORPHANED)
2475 bprintf(bp, "ORPHANED,");
2476 if ((d->state & BOTH_SYN) == BOTH_SYN)
2477 bprintf(bp, "BOTH_SYN,");
2479 if (d->state & TH_SYN)
2480 bprintf(bp, "F_SYN,");
2481 if (d->state & (TH_SYN << 8))
2482 bprintf(bp, "R_SYN,");
2484 if ((d->state & BOTH_FIN) == BOTH_FIN)
2485 bprintf(bp, "BOTH_FIN,");
2487 if (d->state & TH_FIN)
2488 bprintf(bp, "F_FIN,");
2489 if (d->state & (TH_FIN << 8))
2490 bprintf(bp, "R_FIN,");
2492 bprintf(bp, " f_ack 0x%x, r_ack 0x%x", d->ack_fwd,
2498 do_range_cmd(int cmd, ipfw_range_tlv *rt)
2500 ipfw_range_header rh;
2503 memset(&rh, 0, sizeof(rh));
2504 memcpy(&rh.range, rt, sizeof(*rt));
2505 rh.range.head.length = sizeof(*rt);
2506 rh.range.head.type = IPFW_TLV_RANGE;
2509 if (do_get3(cmd, &rh.opheader, &sz) != 0)
2511 /* Save number of matched objects */
2512 rt->new_set = rh.range.new_set;
2517 * This one handles all set-related commands
2518 * ipfw set { show | enable | disable }
2520 * ipfw set move X to Y
2521 * ipfw set move rule X to Y
2524 ipfw_sets_handler(char *av[])
2535 memset(&rt, 0, sizeof(rt));
2538 errx(EX_USAGE, "set needs command");
2539 if (_substrcmp(*av, "show") == 0) {
2540 struct format_opts fo;
2541 ipfw_cfg_lheader *cfg;
2543 memset(&fo, 0, sizeof(fo));
2544 if (ipfw_get_config(&g_co, &fo, &cfg, &size) != 0)
2545 err(EX_OSERR, "requesting config failed");
2547 for (i = 0, msg = "disable"; i < RESVD_SET; i++)
2548 if ((cfg->set_mask & (1<<i)) == 0) {
2549 printf("%s %d", msg, i);
2552 msg = (cfg->set_mask != (uint32_t)-1) ? " enable" : "enable";
2553 for (i = 0; i < RESVD_SET; i++)
2554 if ((cfg->set_mask & (1<<i)) != 0) {
2555 printf("%s %d", msg, i);
2560 } else if (_substrcmp(*av, "swap") == 0) {
2562 if ( av[0] == NULL || av[1] == NULL )
2563 errx(EX_USAGE, "set swap needs 2 set numbers\n");
2564 rt.set = atoi(av[0]);
2565 rt.new_set = atoi(av[1]);
2566 if (!isdigit(*(av[0])) || rt.set > RESVD_SET)
2567 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2568 if (!isdigit(*(av[1])) || rt.new_set > RESVD_SET)
2569 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2570 i = do_range_cmd(IP_FW_SET_SWAP, &rt);
2571 } else if (_substrcmp(*av, "move") == 0) {
2573 if (av[0] && _substrcmp(*av, "rule") == 0) {
2574 rt.flags = IPFW_RCFLAG_RANGE; /* move rules to new set */
2578 cmd = IP_FW_SET_MOVE; /* Move set to new one */
2579 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
2580 av[3] != NULL || _substrcmp(av[1], "to") != 0)
2581 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2582 rulenum = atoi(av[0]);
2583 rt.new_set = atoi(av[2]);
2584 if (cmd == IP_FW_XMOVE) {
2585 rt.start_rule = rulenum;
2586 rt.end_rule = rulenum;
2589 rt.new_set = atoi(av[2]);
2590 if (!isdigit(*(av[0])) || (cmd == 3 && rt.set > RESVD_SET) ||
2591 (cmd == 2 && rt.start_rule == IPFW_DEFAULT_RULE) )
2592 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2593 if (!isdigit(*(av[2])) || rt.new_set > RESVD_SET)
2594 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2595 i = do_range_cmd(cmd, &rt);
2597 err(EX_OSERR, "failed to move %s",
2598 cmd == IP_FW_SET_MOVE ? "set": "rule");
2599 } else if (_substrcmp(*av, "disable") == 0 ||
2600 _substrcmp(*av, "enable") == 0 ) {
2601 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2604 masks[0] = masks[1] = 0;
2607 if (isdigit(**av)) {
2609 if (i < 0 || i > RESVD_SET)
2611 "invalid set number %d\n", i);
2612 masks[which] |= (1<<i);
2613 } else if (_substrcmp(*av, "disable") == 0)
2615 else if (_substrcmp(*av, "enable") == 0)
2619 "invalid set command %s\n", *av);
2622 if ( (masks[0] & masks[1]) != 0 )
2624 "cannot enable and disable the same set\n");
2627 rt.new_set = masks[1];
2628 i = do_range_cmd(IP_FW_SET_ENABLE, &rt);
2630 warn("set enable/disable: setsockopt(IP_FW_SET_ENABLE)");
2632 errx(EX_USAGE, "invalid set command %s\n", *av);
2636 ipfw_sysctl_handler(char *av[], int which)
2640 if (av[0] == NULL) {
2641 warnx("missing keyword to enable/disable\n");
2642 } else if (_substrcmp(*av, "firewall") == 0) {
2643 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2644 &which, sizeof(which));
2645 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
2646 &which, sizeof(which));
2647 } else if (_substrcmp(*av, "one_pass") == 0) {
2648 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2649 &which, sizeof(which));
2650 } else if (_substrcmp(*av, "debug") == 0) {
2651 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2652 &which, sizeof(which));
2653 } else if (_substrcmp(*av, "verbose") == 0) {
2654 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2655 &which, sizeof(which));
2656 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2657 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2658 &which, sizeof(which));
2660 } else if (_substrcmp(*av, "altq") == 0) {
2661 altq_set_enabled(which);
2664 warnx("unrecognize enable/disable keyword: %s\n", *av);
2668 typedef void state_cb(struct cmdline_opts *co, struct format_opts *fo,
2669 void *arg, void *state);
2672 prepare_format_dyn(struct cmdline_opts *co, struct format_opts *fo,
2673 void *arg __unused, void *_state)
2679 d = (ipfw_dyn_rule *)_state;
2680 /* Count _ALL_ states */
2683 if (fo->show_counters == 0)
2687 /* skip states from another set */
2688 bcopy((char *)&d->rule + sizeof(uint16_t), &set,
2690 if (set != co->use_set - 1)
2694 width = pr_u64(NULL, &d->pcnt, 0);
2695 if (width > fo->pcwidth)
2696 fo->pcwidth = width;
2698 width = pr_u64(NULL, &d->bcnt, 0);
2699 if (width > fo->bcwidth)
2700 fo->bcwidth = width;
2704 foreach_state(struct cmdline_opts *co, struct format_opts *fo,
2705 caddr_t base, size_t sz, state_cb dyn_bc, void *dyn_arg)
2711 ipfw_obj_ctlv *ctlv;
2717 ctlv = (ipfw_obj_ctlv *)base;
2718 switch (ctlv->head.type) {
2719 case IPFW_TLV_DYNSTATE_LIST:
2720 base += sizeof(*ctlv);
2721 sz -= sizeof(*ctlv);
2722 ttype = IPFW_TLV_DYN_ENT;
2731 tlv = (ipfw_obj_tlv *)base;
2732 if (tlv->type != ttype)
2735 fptr(co, fo, farg, tlv + 1);
2737 base += tlv->length;
2745 prepare_format_opts(struct cmdline_opts *co, struct format_opts *fo,
2746 ipfw_obj_tlv *rtlv, int rcnt, caddr_t dynbase, size_t dynsz)
2748 int bcwidth, pcwidth, width;
2750 struct ip_fw_bcounter *cntr;
2751 struct ip_fw_rule *r;
2755 if (fo->show_counters != 0) {
2756 for (n = 0; n < rcnt; n++,
2757 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2758 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2759 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2760 /* skip rules from another set */
2761 if (co->use_set && r->set != co->use_set - 1)
2764 /* packet counter */
2765 width = pr_u64(NULL, &cntr->pcnt, 0);
2766 if (width > pcwidth)
2770 width = pr_u64(NULL, &cntr->bcnt, 0);
2771 if (width > bcwidth)
2775 fo->bcwidth = bcwidth;
2776 fo->pcwidth = pcwidth;
2779 if (co->do_dynamic && dynsz > 0)
2780 foreach_state(co, fo, dynbase, dynsz, prepare_format_dyn, NULL);
2784 list_static_range(struct cmdline_opts *co, struct format_opts *fo,
2785 struct buf_pr *bp, ipfw_obj_tlv *rtlv, int rcnt)
2788 struct ip_fw_rule *r;
2789 struct ip_fw_bcounter *cntr;
2791 for (n = seen = 0; n < rcnt; n++,
2792 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2794 if ((fo->show_counters | fo->show_time) != 0) {
2795 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2796 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2799 r = (struct ip_fw_rule *)(rtlv + 1);
2801 if (r->rulenum > fo->last)
2803 if (co->use_set && r->set != co->use_set - 1)
2805 if (r->rulenum >= fo->first && r->rulenum <= fo->last) {
2806 show_static_rule(co, fo, bp, r, cntr);
2807 printf("%s", bp->buf);
2817 list_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2818 void *_arg, void *_state)
2825 d = (ipfw_dyn_rule *)_state;
2826 bp = (struct buf_pr *)_arg;
2828 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2829 if (rulenum > fo->last)
2832 bcopy((char *)&d->rule + sizeof(uint16_t),
2833 &set, sizeof(uint8_t));
2834 if (set != co->use_set - 1)
2837 if (rulenum >= fo->first) {
2838 show_dyn_state(co, fo, bp, d);
2839 printf("%s\n", bp->buf);
2845 list_dyn_range(struct cmdline_opts *co, struct format_opts *fo,
2846 struct buf_pr *bp, caddr_t base, size_t sz)
2849 sz = foreach_state(co, fo, base, sz, list_dyn_state, bp);
2854 ipfw_list(int ac, char *av[], int show_counters)
2856 ipfw_cfg_lheader *cfg;
2857 struct format_opts sfo;
2865 if (g_co.test_only) {
2866 fprintf(stderr, "Testing only, list disabled\n");
2870 dummynet_list(ac, av, show_counters);
2876 memset(&sfo, 0, sizeof(sfo));
2878 /* Determine rule range to request */
2880 for (lac = ac, lav = av; lac != 0; lac--) {
2881 rnum = strtoul(*lav++, &endptr, 10);
2882 if (sfo.first == 0 || rnum < sfo.first)
2886 rnum = strtoul(endptr + 1, &endptr, 10);
2887 if (sfo.last == 0 || rnum > sfo.last)
2892 /* get configuration from kernel */
2894 sfo.show_counters = show_counters;
2895 sfo.show_time = g_co.do_time;
2896 if (g_co.do_dynamic != 2)
2897 sfo.flags |= IPFW_CFG_GET_STATIC;
2898 if (g_co.do_dynamic != 0)
2899 sfo.flags |= IPFW_CFG_GET_STATES;
2900 if ((sfo.show_counters | sfo.show_time) != 0)
2901 sfo.flags |= IPFW_CFG_GET_COUNTERS;
2902 if (ipfw_get_config(&g_co, &sfo, &cfg, &sz) != 0)
2903 err(EX_OSERR, "retrieving config failed");
2905 error = ipfw_show_config(&g_co, &sfo, cfg, sz, ac, av);
2914 ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
2915 ipfw_cfg_lheader *cfg, size_t sz, int ac, char *av[])
2920 int exitval = EX_OK;
2926 ipfw_obj_ctlv *ctlv;
2927 ipfw_obj_tlv *rbase;
2930 * Handle tablenames TLV first, if any
2935 readsz = sizeof(*cfg);
2938 fo->set_mask = cfg->set_mask;
2940 ctlv = (ipfw_obj_ctlv *)(cfg + 1);
2941 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2942 object_sort_ctlv(ctlv);
2944 readsz += ctlv->head.length;
2945 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2948 if (cfg->flags & IPFW_CFG_GET_STATIC) {
2949 /* We've requested static rules */
2950 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2951 rbase = (ipfw_obj_tlv *)(ctlv + 1);
2953 readsz += ctlv->head.length;
2954 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2959 if ((cfg->flags & IPFW_CFG_GET_STATES) && (readsz != sz)) {
2960 /* We may have some dynamic states */
2961 dynsz = sz - readsz;
2962 /* Skip empty header */
2963 if (dynsz != sizeof(ipfw_obj_ctlv))
2964 dynbase = (caddr_t)ctlv;
2969 prepare_format_opts(co, fo, rbase, rcnt, dynbase, dynsz);
2970 bp_alloc(&bp, 4096);
2972 /* if no rule numbers were specified, list all rules */
2975 fo->last = IPFW_DEFAULT_RULE;
2976 if (cfg->flags & IPFW_CFG_GET_STATIC)
2977 list_static_range(co, fo, &bp, rbase, rcnt);
2979 if (co->do_dynamic && dynsz > 0) {
2980 printf("## Dynamic rules (%d %zu):\n", fo->dcnt,
2982 list_dyn_range(co, fo, &bp, dynbase, dynsz);
2989 /* display specific rules requested on command line */
2990 for (lac = ac, lav = av; lac != 0; lac--) {
2991 /* convert command line rule # */
2992 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2994 fo->last = strtoul(endptr + 1, &endptr, 10);
2997 warnx("invalid rule number: %s", *(lav - 1));
3001 if ((cfg->flags & IPFW_CFG_GET_STATIC) == 0)
3004 if (list_static_range(co, fo, &bp, rbase, rcnt) == 0) {
3005 /* give precedence to other error(s) */
3006 if (exitval == EX_OK)
3007 exitval = EX_UNAVAILABLE;
3008 if (fo->first == fo->last)
3009 warnx("rule %u does not exist", fo->first);
3011 warnx("no rules in range %u-%u",
3012 fo->first, fo->last);
3016 if (co->do_dynamic && dynsz > 0) {
3017 printf("## Dynamic rules:\n");
3018 for (lac = ac, lav = av; lac != 0; lac--) {
3019 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
3021 fo->last = strtoul(endptr+1, &endptr, 10);
3023 /* already warned */
3025 list_dyn_range(co, fo, &bp, dynbase, dynsz);
3035 * Retrieves current ipfw configuration of given type
3036 * and stores its pointer to @pcfg.
3038 * Caller is responsible for freeing @pcfg.
3040 * Returns 0 on success.
3044 ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
3045 ipfw_cfg_lheader **pcfg, size_t *psize)
3047 ipfw_cfg_lheader *cfg;
3052 if (co->test_only != 0) {
3053 fprintf(stderr, "Testing only, list disabled\n");
3057 /* Start with some data size */
3061 for (i = 0; i < 16; i++) {
3064 if ((cfg = calloc(1, sz)) == NULL)
3067 cfg->flags = fo->flags;
3068 cfg->start_rule = fo->first;
3069 cfg->end_rule = fo->last;
3071 if (do_get3(IP_FW_XGET, &cfg->opheader, &sz) != 0) {
3072 if (errno != ENOMEM) {
3077 /* Buffer size is not enough. Try to increase */
3094 lookup_host (char *host, struct in_addr *ipaddr)
3098 if (!inet_aton(host, ipaddr)) {
3099 if ((he = gethostbyname(host)) == NULL)
3101 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
3115 ipfw_check_object_name(const char *name)
3120 * Check that name is null-terminated and contains
3121 * valid symbols only. Valid mask is:
3122 * [a-zA-Z0-9\-_\.]{1,63}
3125 if (l == 0 || l >= 64)
3127 for (i = 0; i < l; i++) {
3129 if (isalpha(c) || isdigit(c) || c == '_' ||
3130 c == '-' || c == '.')
3137 static const char *default_state_name = "default";
3140 state_check_name(const char *name)
3143 if (ipfw_check_object_name(name) != 0)
3145 if (strcmp(name, "any") == 0)
3151 eaction_check_name(const char *name)
3154 if (ipfw_check_object_name(name) != 0)
3156 /* Restrict some 'special' names */
3157 if (match_token(rule_actions, name) != -1 &&
3158 match_token(rule_action_params, name) != -1)
3164 pack_object(struct tidx *tstate, const char *name, int otype)
3166 ipfw_obj_ntlv *ntlv;
3169 for (i = 0; i < tstate->count; i++) {
3170 if (strcmp(tstate->idx[i].name, name) != 0)
3172 if (tstate->idx[i].set != tstate->set)
3174 if (tstate->idx[i].head.type != otype)
3177 return (tstate->idx[i].idx);
3180 if (tstate->count + 1 > tstate->size) {
3182 tstate->idx = realloc(tstate->idx, tstate->size *
3183 sizeof(ipfw_obj_ntlv));
3184 if (tstate->idx == NULL)
3188 ntlv = &tstate->idx[i];
3189 memset(ntlv, 0, sizeof(ipfw_obj_ntlv));
3190 strlcpy(ntlv->name, name, sizeof(ntlv->name));
3191 ntlv->head.type = otype;
3192 ntlv->head.length = sizeof(ipfw_obj_ntlv);
3193 ntlv->set = tstate->set;
3194 ntlv->idx = ++tstate->counter;
3201 pack_table(struct tidx *tstate, const char *name)
3204 if (table_check_name(name) != 0)
3207 return (pack_object(tstate, name, IPFW_TLV_TBL_NAME));
3211 fill_table(struct _ipfw_insn *cmd, char *av, uint8_t opcode,
3212 struct tidx *tstate)
3214 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
3218 if ((p = strchr(av + 6, ')')) == NULL)
3219 errx(EX_DATAERR, "forgotten parenthesis: '%s'", av);
3221 p = strchr(av + 6, ',');
3225 if ((uidx = pack_table(tstate, av + 6)) == 0)
3226 errx(EX_DATAERR, "Invalid table name: %s", av + 6);
3228 cmd->opcode = opcode;
3231 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3232 d[0] = strtoul(p, NULL, 0);
3234 cmd->len |= F_INSN_SIZE(ipfw_insn);
3239 * fills the addr and mask fields in the instruction as appropriate from av.
3240 * Update length as appropriate.
3241 * The following formats are allowed:
3242 * me returns O_IP_*_ME
3243 * 1.2.3.4 single IP address
3244 * 1.2.3.4:5.6.7.8 address:mask
3245 * 1.2.3.4/24 address/mask
3246 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
3247 * We can have multiple comma-separated address/mask entries.
3250 fill_ip(ipfw_insn_ip *cmd, char *av, int cblen, struct tidx *tstate)
3253 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
3255 cmd->o.len &= ~F_LEN_MASK; /* zero len */
3257 if (_substrcmp(av, "any") == 0)
3260 if (_substrcmp(av, "me") == 0) {
3261 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
3265 if (strncmp(av, "table(", 6) == 0) {
3266 fill_table(&cmd->o, av, O_IP_DST_LOOKUP, tstate);
3272 * After the address we can have '/' or ':' indicating a mask,
3273 * ',' indicating another address follows, '{' indicating a
3274 * set of addresses of unspecified size.
3276 char *t = NULL, *p = strpbrk(av, "/:,{");
3280 CHECK_LENGTH(cblen, (int)F_INSN_SIZE(ipfw_insn) + 2 + len);
3285 if ((t = strpbrk(p, ",{")) != NULL) {
3292 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
3293 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
3296 if (!inet_aton(p, (struct in_addr *)&d[1]))
3297 errx(EX_DATAERR, "bad netmask ``%s''", p);
3302 d[1] = htonl(0U); /* mask */
3303 else if (masklen > 32)
3304 errx(EX_DATAERR, "bad width ``%s''", p);
3306 d[1] = htonl(~0U << (32 - masklen));
3308 case '{': /* no mask, assume /24 and put back the '{' */
3309 d[1] = htonl(~0U << (32 - 24));
3313 case ',': /* single address plus continuation */
3316 case 0: /* initialization value */
3318 d[1] = htonl(~0U); /* force /32 */
3321 d[0] &= d[1]; /* mask base address with mask */
3324 /* find next separator */
3326 p = strpbrk(p, ",{");
3327 if (p && *p == '{') {
3329 * We have a set of addresses. They are stored as follows:
3330 * arg1 is the set size (powers of 2, 2..256)
3331 * addr is the base address IN HOST FORMAT
3332 * mask.. is an array of arg1 bits (rounded up to
3333 * the next multiple of 32) with bits set
3334 * for each host in the map.
3336 uint32_t *map = (uint32_t *)&cmd->mask;
3338 int i = contigmask((uint8_t *)&(d[1]), 32);
3341 errx(EX_DATAERR, "address set cannot be in a list");
3342 if (i < 24 || i > 31)
3343 errx(EX_DATAERR, "invalid set with mask %d\n", i);
3344 cmd->o.arg1 = 1<<(32-i); /* map length */
3345 d[0] = ntohl(d[0]); /* base addr in host format */
3346 cmd->o.opcode = O_IP_DST_SET; /* default */
3347 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
3348 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
3349 map[i] = 0; /* clear map */
3353 high = low + cmd->o.arg1 - 1;
3355 * Here, i stores the previous value when we specify a range
3356 * of addresses within a mask, e.g. 45-63. i = -1 means we
3357 * have no previous value.
3359 i = -1; /* previous value in a range */
3360 while (isdigit(*av)) {
3362 int a = strtol(av, &s, 0);
3364 if (s == av) { /* no parameter */
3366 errx(EX_DATAERR, "set not closed\n");
3368 errx(EX_DATAERR, "incomplete range %d-", i);
3371 if (a < low || a > high)
3372 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
3375 if (i == -1) /* no previous in range */
3377 else { /* check that range is valid */
3379 errx(EX_DATAERR, "invalid range %d-%d",
3382 errx(EX_DATAERR, "double '-' in range");
3385 map[i/32] |= 1<<(i & 31);
3396 if (av) /* then *av must be a ',' */
3399 /* Check this entry */
3400 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
3402 * 'any' turns the entire list into a NOP.
3403 * 'not any' never matches, so it is removed from the
3404 * list unless it is the only item, in which case we
3407 if (cmd->o.len & F_NOT) { /* "not any" never matches */
3408 if (av == NULL && len == 0) /* only this entry */
3409 errx(EX_DATAERR, "not any never matches");
3411 /* else do nothing and skip this entry */
3414 /* A single IP can be stored in an optimized format */
3415 if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
3416 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
3419 len += 2; /* two words... */
3422 if (len + 1 > F_LEN_MASK)
3423 errx(EX_DATAERR, "address list too long");
3424 cmd->o.len |= len+1;
3428 /* n2mask sets n bits of the mask */
3430 n2mask(struct in6_addr *mask, int n)
3432 static int minimask[9] =
3433 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
3436 memset(mask, 0, sizeof(struct in6_addr));
3437 p = (u_char *) mask;
3438 for (; n > 0; p++, n -= 8) {
3448 fill_flags_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3449 struct _s_x *flags, char *p)
3452 uint32_t set = 0, clear = 0;
3454 if (fill_flags(flags, p, &e, &set, &clear) != 0)
3455 errx(EX_DATAERR, "invalid flag %s", e);
3457 cmd->opcode = opcode;
3458 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
3459 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3464 ipfw_delete(char *av[])
3469 int exitval = EX_OK;
3473 NEED1("missing rule specification");
3474 if ( *av && _substrcmp(*av, "set") == 0) {
3475 /* Do not allow using the following syntax:
3476 * ipfw set N delete set M
3479 errx(EX_DATAERR, "invalid syntax");
3480 do_set = 1; /* delete set */
3485 while (*av && isdigit(**av)) {
3486 i = strtol(*av, &sep, 10);
3489 j = strtol(sep + 1, NULL, 10);
3492 exitval = ipfw_delete_nat(i);
3493 } else if (g_co.do_pipe) {
3494 exitval = ipfw_delete_pipe(g_co.do_pipe, i);
3496 memset(&rt, 0, sizeof(rt));
3499 rt.flags = IPFW_RCFLAG_SET;
3501 rt.start_rule = i & 0xffff;
3502 rt.end_rule = j & 0xffff;
3503 if (rt.start_rule == 0 && rt.end_rule == 0)
3504 rt.flags |= IPFW_RCFLAG_ALL;
3506 rt.flags |= IPFW_RCFLAG_RANGE;
3507 if (g_co.use_set != 0) {
3508 rt.set = g_co.use_set - 1;
3509 rt.flags |= IPFW_RCFLAG_SET;
3512 if (g_co.do_dynamic == 2)
3513 rt.flags |= IPFW_RCFLAG_DYNAMIC;
3514 i = do_range_cmd(IP_FW_XDEL, &rt);
3516 exitval = EX_UNAVAILABLE;
3519 warn("rule %u: setsockopt(IP_FW_XDEL)",
3521 } else if (rt.new_set == 0 && do_set == 0 &&
3522 g_co.do_dynamic != 2) {
3523 exitval = EX_UNAVAILABLE;
3526 if (rt.start_rule != rt.end_rule)
3527 warnx("no rules rules in %u-%u range",
3528 rt.start_rule, rt.end_rule);
3530 warnx("rule %u not found",
3535 if (exitval != EX_OK && g_co.do_force == 0)
3541 * fill the interface structure. We do not check the name as we can
3542 * create interfaces dynamically, so checking them at insert time
3543 * makes relatively little sense.
3544 * Interface names containing '*', '?', or '[' are assumed to be shell
3545 * patterns which match interfaces.
3548 fill_iface(ipfw_insn_if *cmd, char *arg, int cblen, struct tidx *tstate)
3553 cmd->name[0] = '\0';
3554 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3558 /* Parse the interface or address */
3559 if (strcmp(arg, "any") == 0)
3560 cmd->o.len = 0; /* effectively ignore this command */
3561 else if (strncmp(arg, "table(", 6) == 0) {
3562 if ((p = strchr(arg + 6, ')')) == NULL)
3563 errx(EX_DATAERR, "forgotten parenthesis: '%s'", arg);
3565 p = strchr(arg + 6, ',');
3568 if ((uidx = pack_table(tstate, arg + 6)) == 0)
3569 errx(EX_DATAERR, "Invalid table name: %s", arg + 6);
3571 cmd->name[0] = '\1'; /* Special value indicating table */
3573 } else if (!isdigit(*arg)) {
3574 strlcpy(cmd->name, arg, sizeof(cmd->name));
3575 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3576 } else if (!inet_aton(arg, &cmd->p.ip))
3577 errx(EX_DATAERR, "bad ip address ``%s''", arg);
3581 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
3585 char *ap, *ptr, *optr;
3586 struct ether_addr *mac;
3587 const char *macset = "0123456789abcdefABCDEF:";
3589 if (strcmp(p, "any") == 0) {
3590 for (i = 0; i < ETHER_ADDR_LEN; i++)
3591 addr[i] = mask[i] = 0;
3595 optr = ptr = strdup(p);
3596 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
3598 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
3599 errx(EX_DATAERR, "Incorrect MAC address");
3600 bcopy(mac, addr, ETHER_ADDR_LEN);
3602 errx(EX_DATAERR, "Incorrect MAC address");
3604 if (ptr != NULL) { /* we have mask? */
3605 if (p[ptr - optr - 1] == '/') { /* mask len */
3606 long ml = strtol(ptr, &ap, 10);
3607 if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
3608 errx(EX_DATAERR, "Incorrect mask length");
3609 for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
3610 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
3613 if (strspn(ptr, macset) != l ||
3614 (mac = ether_aton(ptr)) == NULL)
3615 errx(EX_DATAERR, "Incorrect mask");
3616 bcopy(mac, mask, ETHER_ADDR_LEN);
3618 } else { /* default mask: ff:ff:ff:ff:ff:ff */
3619 for (i = 0; i < ETHER_ADDR_LEN; i++)
3622 for (i = 0; i < ETHER_ADDR_LEN; i++)
3629 * helper function, updates the pointer to cmd with the length
3630 * of the current command, and also cleans up the first word of
3631 * the new command in case it has been clobbered before.
3634 next_cmd(ipfw_insn *cmd, int *len)
3637 CHECK_LENGTH(*len, 0);
3639 bzero(cmd, sizeof(*cmd));
3644 * Takes arguments and copies them into a comment
3647 fill_comment(ipfw_insn *cmd, char **av, int cblen)
3650 char *p = (char *)(cmd + 1);
3652 cmd->opcode = O_NOP;
3653 cmd->len = (cmd->len & (F_NOT | F_OR));
3655 /* Compute length of comment string. */
3656 for (i = 0, l = 0; av[i] != NULL; i++)
3657 l += strlen(av[i]) + 1;
3662 "comment too long (max 80 chars)");
3664 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
3667 for (i = 0; av[i] != NULL; i++) {
3676 * A function to fill simple commands of size 1.
3677 * Existing flags are preserved.
3680 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3682 cmd->opcode = opcode;
3683 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3688 * Fetch and add the MAC address and type, with masks. This generates one or
3689 * two microinstructions, and returns the pointer to the last one.
3692 add_mac(ipfw_insn *cmd, char *av[], int cblen)
3696 if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
3697 errx(EX_DATAERR, "MAC dst src");
3699 cmd->opcode = O_MACADDR2;
3700 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3703 mac = (ipfw_insn_mac *)cmd;
3704 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
3705 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
3706 &(mac->mask[ETHER_ADDR_LEN])); /* src */
3711 add_mactype(ipfw_insn *cmd, char *av, int cblen)
3714 errx(EX_DATAERR, "missing MAC type");
3715 if (strcmp(av, "any") != 0) { /* we have a non-null type */
3716 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
3718 cmd->opcode = O_MAC_TYPE;
3725 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
3727 struct protoent *pe;
3731 proto = strtol(av, &ep, 10);
3732 if (*ep != '\0' || proto <= 0) {
3733 if ((pe = getprotobyname(av)) == NULL)
3735 proto = pe->p_proto;
3738 fill_cmd(cmd, O_PROTO, 0, proto);
3744 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
3746 u_char proto = IPPROTO_IP;
3748 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3749 ; /* do not set O_IP4 nor O_IP6 */
3750 else if (strcmp(av, "ip4") == 0)
3751 /* explicit "just IPv4" rule */
3752 fill_cmd(cmd, O_IP4, 0, 0);
3753 else if (strcmp(av, "ip6") == 0) {
3754 /* explicit "just IPv6" rule */
3755 proto = IPPROTO_IPV6;
3756 fill_cmd(cmd, O_IP6, 0, 0);
3758 return add_proto0(cmd, av, protop);
3765 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
3767 u_char proto = IPPROTO_IP;
3769 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3770 ; /* do not set O_IP4 nor O_IP6 */
3771 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3772 /* explicit "just IPv4" rule */
3773 fill_cmd(cmd, O_IP4, 0, 0);
3774 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3775 /* explicit "just IPv6" rule */
3776 proto = IPPROTO_IPV6;
3777 fill_cmd(cmd, O_IP6, 0, 0);
3779 return add_proto0(cmd, av, protop);
3786 add_srcip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3788 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3789 if (cmd->opcode == O_IP_DST_SET) /* set */
3790 cmd->opcode = O_IP_SRC_SET;
3791 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3792 cmd->opcode = O_IP_SRC_LOOKUP;
3793 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3794 cmd->opcode = O_IP_SRC_ME;
3795 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3796 cmd->opcode = O_IP_SRC;
3797 else /* addr/mask */
3798 cmd->opcode = O_IP_SRC_MASK;
3803 add_dstip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3805 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3806 if (cmd->opcode == O_IP_DST_SET) /* set */
3808 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3810 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3811 cmd->opcode = O_IP_DST_ME;
3812 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3813 cmd->opcode = O_IP_DST;
3814 else /* addr/mask */
3815 cmd->opcode = O_IP_DST_MASK;
3820 add_srcmac(ipfw_insn *cmd, char *av, struct tidx *tstate)
3823 if (strncmp(av, "table(", 6) == 0)
3824 fill_table(cmd, av, O_MAC_SRC_LOOKUP, tstate);
3826 errx(EX_DATAERR, "only mac table lookup is supported %s", av);
3831 add_dstmac(ipfw_insn *cmd, char *av, struct tidx *tstate)
3834 if (strncmp(av, "table(", 6) == 0)
3835 fill_table(cmd, av, O_MAC_DST_LOOKUP, tstate);
3837 errx(EX_DATAERR, "only mac table lookup is supported %s", av);
3842 static struct _s_x f_reserved_keywords[] = {
3845 { "diverted", TOK_OR },
3846 { "dst-port", TOK_OR },
3847 { "src-port", TOK_OR },
3848 { "established", TOK_OR },
3849 { "keep-state", TOK_OR },
3851 { "icmptypes", TOK_OR },
3859 { NULL, 0 } /* terminator */
3863 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
3866 if (match_token(f_reserved_keywords, av) != -1)
3869 if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
3870 /* XXX todo: check that we have a protocol with ports */
3871 cmd->opcode = opcode;
3878 add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3881 char *host, *ch, buf[INET6_ADDRSTRLEN];
3882 ipfw_insn *ret = NULL;
3885 /* Copy first address in set if needed */
3886 if ((ch = strpbrk(av, "/,")) != NULL) {
3888 strlcpy(buf, av, sizeof(buf));
3889 if (len < sizeof(buf))
3895 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3896 inet_pton(AF_INET6, host, &a) == 1)
3897 ret = add_srcip6(cmd, av, cblen, tstate);
3898 /* XXX: should check for IPv4, not !IPv6 */
3899 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3900 inet_pton(AF_INET6, host, &a) != 1))
3901 ret = add_srcip(cmd, av, cblen, tstate);
3902 if (ret == NULL && strcmp(av, "any") != 0)
3909 add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3912 char *host, *ch, buf[INET6_ADDRSTRLEN];
3913 ipfw_insn *ret = NULL;
3916 /* Copy first address in set if needed */
3917 if ((ch = strpbrk(av, "/,")) != NULL) {
3919 strlcpy(buf, av, sizeof(buf));
3920 if (len < sizeof(buf))
3926 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3927 inet_pton(AF_INET6, host, &a) == 1)
3928 ret = add_dstip6(cmd, av, cblen, tstate);
3929 /* XXX: should check for IPv4, not !IPv6 */
3930 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3931 inet_pton(AF_INET6, host, &a) != 1))
3932 ret = add_dstip(cmd, av, cblen, tstate);
3933 if (ret == NULL && strcmp(av, "any") != 0)
3940 arg_or_targ_relaxed(const char *arg, const char *action)
3942 uint32_t arg1 = (uint32_t)(-1);
3945 errx(EX_USAGE, "missing argument for %s", action);
3946 if (isdigit(arg[0])) {
3947 arg1 = strtoul(arg, NULL, 10);
3948 if (arg1 <= 0 || arg1 >= IP_FW_TABLEARG)
3949 errx(EX_DATAERR, "illegal argument %s(%u) for %s",
3951 } else if (_substrcmp(arg, "tablearg") == 0)
3956 static inline uint16_t
3957 arg_or_targ(const char *arg, const char *action)
3959 uint32_t arg1 = arg_or_targ_relaxed(arg, action);
3961 if (arg1 == (uint32_t)(-1))
3962 errx(EX_DATAERR, "illegal argument %s(%u) for %s",
3968 get_divert_port(const char *arg, const char *action)
3970 uint32_t arg1 = arg_or_targ_relaxed(arg, action);
3972 if (arg1 != (uint32_t)(-1))
3977 s = getservbyname(arg, "divert");
3979 errx(EX_DATAERR, "illegal divert/tee port");
3980 return (ntohs(s->s_port));
3984 * Parse arguments and assemble the microinstructions which make up a rule.
3985 * Rules are added into the 'rulebuf' and then copied in the correct order
3986 * into the actual rule.
3988 * The syntax for a rule starts with the action, followed by
3989 * optional action parameters, and the various match patterns.
3990 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
3991 * (generated if the rule includes a keep-state option), then the
3992 * various match patterns, log/altq actions, and the actual action.
3996 compile_rule(char *av[], uint32_t *rbuf, int *rbufsize, struct tidx *tstate)
3999 * rules are added into the 'rulebuf' and then copied in
4000 * the correct order into the actual rule.
4001 * Some things that need to go out of order (prob, action etc.)
4004 static uint32_t actbuf[255], cmdbuf[255];
4005 int rblen, ablen, cblen;
4007 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
4008 ipfw_insn *first_cmd; /* first match pattern */
4010 struct ip_fw_rule *rule;
4013 * various flags used to record that we entered some fields.
4015 ipfw_insn *have_state = NULL; /* any state-related option */
4016 int have_rstate = 0;
4017 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
4018 ipfw_insn *have_skipcmd = NULL;
4023 int open_par = 0; /* open parenthesis ( */
4025 /* proto is here because it is used to fetch ports */
4026 u_char proto = IPPROTO_IP; /* default protocol */
4028 double match_prob = 1; /* match probability, default is always match */
4030 bzero(actbuf, sizeof(actbuf)); /* actions go here */
4031 bzero(cmdbuf, sizeof(cmdbuf));
4032 bzero(rbuf, *rbufsize);
4034 rule = (struct ip_fw_rule *)rbuf;
4035 cmd = (ipfw_insn *)cmdbuf;
4036 action = (ipfw_insn *)actbuf;
4038 rblen = *rbufsize / sizeof(uint32_t);
4039 rblen -= sizeof(struct ip_fw_rule) / sizeof(uint32_t);
4040 ablen = sizeof(actbuf) / sizeof(actbuf[0]);
4041 cblen = sizeof(cmdbuf) / sizeof(cmdbuf[0]);
4042 cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
4044 #define CHECK_RBUFLEN(len) { CHECK_LENGTH(rblen, len); rblen -= len; }
4045 #define CHECK_ACTLEN CHECK_LENGTH(ablen, action->len)
4049 /* [rule N] -- Rule number optional */
4050 if (av[0] && isdigit(**av)) {
4051 rule->rulenum = atoi(*av);
4055 /* [set N] -- set number (0..RESVD_SET), optional */
4056 if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
4057 int set = strtoul(av[1], NULL, 10);
4058 if (set < 0 || set > RESVD_SET)
4059 errx(EX_DATAERR, "illegal set %s", av[1]);
4065 /* [prob D] -- match probability, optional */
4066 if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
4067 match_prob = strtod(av[1], NULL);
4069 if (match_prob <= 0 || match_prob > 1)
4070 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
4074 /* action -- mandatory */
4075 NEED1("missing action");
4076 i = match_token(rule_actions, *av);
4078 action->len = 1; /* default */
4081 case TOK_CHECKSTATE:
4082 have_state = action;
4083 action->opcode = O_CHECK_STATE;
4085 match_token(rule_options, *av) == TOK_COMMENT) {
4086 action->arg1 = pack_object(tstate,
4087 default_state_name, IPFW_TLV_STATE_NAME);
4090 if (*av[0] == ':') {
4091 if (strcmp(*av + 1, "any") == 0)
4093 else if (state_check_name(*av + 1) == 0)
4094 action->arg1 = pack_object(tstate, *av + 1,
4095 IPFW_TLV_STATE_NAME);
4097 errx(EX_DATAERR, "Invalid state name %s",
4102 errx(EX_DATAERR, "Invalid state name %s", *av);
4106 action->opcode = O_REJECT;
4107 action->arg1 = ICMP_REJECT_ABORT;
4111 action->opcode = O_UNREACH6;
4112 action->arg1 = ICMP6_UNREACH_ABORT;
4116 action->opcode = O_ACCEPT;
4120 action->opcode = O_DENY;
4125 action->opcode = O_REJECT;
4126 action->arg1 = ICMP_UNREACH_HOST;
4130 action->opcode = O_REJECT;
4131 action->arg1 = ICMP_REJECT_RST;
4135 action->opcode = O_UNREACH6;
4136 action->arg1 = ICMP6_UNREACH_RST;
4140 action->opcode = O_REJECT;
4141 NEED1("missing reject code");
4142 action->arg1 = get_reject_code(*av);
4144 if (action->arg1 == ICMP_UNREACH_NEEDFRAG && isdigit(**av)) {
4147 mtu = strtoul(*av, NULL, 10);
4148 if (mtu < 68 || mtu >= IP_MAXPACKET)
4149 errx(EX_DATAERR, "illegal argument for %s",
4151 action->len = F_INSN_SIZE(ipfw_insn_u16);
4152 ((ipfw_insn_u16 *)action)->ports[0] = mtu;
4158 action->opcode = O_UNREACH6;
4159 NEED1("missing unreach code");
4160 action->arg1 = get_unreach6_code(*av);
4165 action->opcode = O_COUNT;
4169 action->opcode = O_NAT;
4170 action->len = F_INSN_SIZE(ipfw_insn_nat);
4172 if (*av != NULL && _substrcmp(*av, "global") == 0)
4173 action->arg1 = IP_FW_NAT44_GLOBAL;
4175 action->arg1 = arg_or_targ(av[0], *(av - 1));
4179 action->opcode = O_QUEUE;
4180 action->arg1 = arg_or_targ(av[0], *(av - 1));
4184 action->opcode = O_PIPE;
4185 action->arg1 = arg_or_targ(av[0], *(av - 1));
4189 action->opcode = O_SKIPTO;
4190 action->arg1 = arg_or_targ(av[0], *(av - 1));
4194 action->opcode = O_NETGRAPH;
4195 action->arg1 = arg_or_targ(av[0], *(av - 1));
4199 action->opcode = O_NGTEE;
4200 action->arg1 = arg_or_targ(av[0], *(av - 1));
4204 action->opcode = O_DIVERT;
4205 action->arg1 = get_divert_port(av[0], *(av - 1));
4209 action->opcode = O_TEE;
4210 action->arg1 = get_divert_port(av[0], *(av - 1));
4214 action->opcode = O_CALLRETURN;
4215 action->arg1 = arg_or_targ(av[0], *(av - 1));
4221 * Locate the address-port separator (':' or ',').
4222 * Could be one of the following:
4226 * IPv6 w:x:y::z,port
4227 * IPv6 [w:x:y::z]:port
4229 struct sockaddr_storage result;
4230 struct addrinfo *res;
4233 u_short port_number = 0;
4235 NEED1("missing forward address[:port]");
4237 if (strncmp(*av, "tablearg", 8) == 0 &&
4238 ((*av)[8] == '\0' || (*av)[8] == ',' || (*av)[8] == ':'))
4239 memcpy(++(*av), "0.0.0.0", 7);
4242 * Are we an bracket-enclosed IPv6 address?
4244 if (strchr(*av, '['))
4248 * locate the address-port separator (':' or ',')
4250 s = strchr(*av, ',');
4252 s = strchr(*av, ']');
4253 /* Prevent erroneous parsing on brackets. */
4259 /* Distinguish between IPv4:port and IPv6 cases. */
4261 if (s && strchr(s+1, ':'))
4262 s = NULL; /* no port */
4266 /* Terminate host portion and set s to start of port. */
4268 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
4271 "illegal forwarding port ``%s''", s);
4272 port_number = (u_short)i;
4276 * Resolve the host name or address to a family and a
4277 * network representation of the address.
4279 if (getaddrinfo(*av, NULL, NULL, &res))
4280 errx(EX_DATAERR, NULL);
4281 /* Just use the first host in the answer. */
4282 family = res->ai_family;
4283 memcpy(&result, res->ai_addr, res->ai_addrlen);
4286 if (family == PF_INET) {
4287 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
4289 action->opcode = O_FORWARD_IP;
4290 action->len = F_INSN_SIZE(ipfw_insn_sa);
4294 * In the kernel we assume AF_INET and use only
4295 * sin_port and sin_addr. Remember to set sin_len as
4296 * the routing code seems to use it too.
4298 p->sa.sin_len = sizeof(struct sockaddr_in);
4299 p->sa.sin_family = AF_INET;
4300 p->sa.sin_port = port_number;
4301 p->sa.sin_addr.s_addr =
4302 ((struct sockaddr_in *)&result)->sin_addr.s_addr;
4303 } else if (family == PF_INET6) {
4304 ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
4306 action->opcode = O_FORWARD_IP6;
4307 action->len = F_INSN_SIZE(ipfw_insn_sa6);
4310 p->sa.sin6_len = sizeof(struct sockaddr_in6);
4311 p->sa.sin6_family = AF_INET6;
4312 p->sa.sin6_port = port_number;
4313 p->sa.sin6_flowinfo = 0;
4314 p->sa.sin6_scope_id =
4315 ((struct sockaddr_in6 *)&result)->sin6_scope_id;
4316 bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
4317 &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
4319 errx(EX_DATAERR, "Invalid address family in forward action");
4325 /* pretend it is a 'count' rule followed by the comment */
4326 action->opcode = O_COUNT;
4327 av--; /* go back... */
4333 size_t intsize = sizeof(int);
4335 action->opcode = O_SETFIB;
4336 NEED1("missing fib number");
4337 if (_substrcmp(*av, "tablearg") == 0) {
4338 action->arg1 = IP_FW_TARG;
4340 action->arg1 = strtoul(*av, NULL, 10);
4341 if (sysctlbyname("net.fibs", &numfibs, &intsize,
4343 errx(EX_DATAERR, "fibs not supported.\n");
4344 if (action->arg1 >= numfibs) /* Temporary */
4345 errx(EX_DATAERR, "fib too large.\n");
4346 /* Add high-order bit to fib to make room for tablearg*/
4347 action->arg1 |= 0x8000;
4357 action->opcode = O_SETDSCP;
4358 NEED1("missing DSCP code");
4359 if (_substrcmp(*av, "tablearg") == 0) {
4360 action->arg1 = IP_FW_TARG;
4362 if (isalpha(*av[0])) {
4363 if ((code = match_token(f_ipdscp, *av)) == -1)
4364 errx(EX_DATAERR, "Unknown DSCP code");
4365 action->arg1 = code;
4367 action->arg1 = strtoul(*av, NULL, 10);
4369 * Add high-order bit to DSCP to make room
4372 action->arg1 |= 0x8000;
4379 action->opcode = O_REASS;
4383 fill_cmd(action, O_CALLRETURN, F_NOT, 0);
4387 action->opcode = O_SETMARK;
4388 action->len = F_INSN_SIZE(ipfw_insn_u32);
4389 NEED1("missing mark");
4390 if (strcmp(*av, "tablearg") == 0) {
4391 action->arg1 = IP_FW_TARG;
4393 ((ipfw_insn_u32 *)action)->d[0] =
4394 strtoul(*av, NULL, 0);
4395 /* This is not a tablearg */
4396 action->arg1 |= 0x8000;
4403 case TOK_TCPSETMSS: {
4407 idx = pack_object(tstate, "tcp-setmss", IPFW_TLV_EACTION);
4409 errx(EX_DATAERR, "pack_object failed");
4410 fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4411 NEED1("Missing MSS value");
4412 action = next_cmd(action, &ablen);
4415 mss = strtoul(*av, NULL, 10);
4416 if (mss == 0 || mss > UINT16_MAX)
4417 errx(EX_USAGE, "invalid MSS value %s", *av);
4418 fill_cmd(action, O_EXTERNAL_DATA, 0, (uint16_t)mss);
4425 if (match_token(rule_eactions, *av) == -1)
4426 errx(EX_DATAERR, "invalid action %s\n", *av);
4428 * External actions support.
4429 * XXX: we support only syntax with instance name.
4430 * For known external actions (from rule_eactions list)
4431 * we can handle syntax directly. But with `eaction'
4432 * keyword we can use only `eaction <name> <instance>'
4438 NEED1("Missing eaction name");
4439 if (eaction_check_name(*av) != 0)
4440 errx(EX_DATAERR, "Invalid eaction name %s", *av);
4441 idx = pack_object(tstate, *av, IPFW_TLV_EACTION);
4443 errx(EX_DATAERR, "pack_object failed");
4444 fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4446 NEED1("Missing eaction instance name");
4447 action = next_cmd(action, &ablen);
4450 if (eaction_check_name(*av) != 0)
4451 errx(EX_DATAERR, "Invalid eaction instance name %s",
4454 * External action instance object has TLV type depended
4455 * from the external action name object index. Since we
4456 * currently don't know this index, use zero as TLV type.
4458 idx = pack_object(tstate, *av, 0);
4460 errx(EX_DATAERR, "pack_object failed");
4461 fill_cmd(action, O_EXTERNAL_INSTANCE, 0, idx);
4465 action = next_cmd(action, &ablen);
4468 * [altq queuename] -- altq tag, optional
4469 * [log [logamount N]] -- log, optional
4471 * If they exist, it go first in the cmdbuf, but then it is
4472 * skipped in the copy section to the end of the buffer.
4474 while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
4479 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
4484 "log cannot be specified more than once");
4485 have_log = (ipfw_insn *)c;
4486 cmd->len = F_INSN_SIZE(ipfw_insn_log);
4488 cmd->opcode = O_LOG;
4489 if (av[0] && _substrcmp(*av, "logamount") == 0) {
4491 NEED1("logamount requires argument");
4495 "logamount must be positive");
4499 len = sizeof(c->max_log);
4500 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
4501 &c->max_log, &len, NULL, 0) == -1) {
4502 if (g_co.test_only) {
4506 errx(1, "sysctlbyname(\"%s\")",
4507 "net.inet.ip.fw.verbose_limit");
4516 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
4518 NEED1("missing altq queue name");
4521 "altq cannot be specified more than once");
4522 have_altq = (ipfw_insn *)a;
4523 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
4525 cmd->opcode = O_ALTQ;
4526 a->qid = altq_name_to_qid(*av);
4537 errx(EX_USAGE, "tag and untag cannot be "
4538 "specified more than once");
4539 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
4540 rule_action_params);
4542 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
4550 cmd = next_cmd(cmd, &cblen);
4553 if (have_state) { /* must be a check-state, we are done */
4555 match_token(rule_options, *av) == TOK_COMMENT) {
4556 /* check-state has a comment */
4558 fill_comment(cmd, av, cblen);
4559 cmd = next_cmd(cmd, &cblen);
4565 #define OR_START(target) \
4566 if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
4568 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
4571 if ( (av[0])[1] == '\0') { \
4582 strcmp(*av, ")") == 0 || \
4583 strcmp(*av, "}") == 0)) { \
4588 errx(EX_USAGE, "missing \")\"\n"); \
4592 if (av[0] && _substrcmp(*av, "not") == 0) { \
4593 if (cmd->len & F_NOT) \
4594 errx(EX_USAGE, "double \"not\" not allowed\n"); \
4595 cmd->len |= F_NOT; \
4599 #define OR_BLOCK(target) \
4600 if (av[0] && _substrcmp(*av, "or") == 0) { \
4601 if (prev == NULL || open_par == 0) \
4602 errx(EX_DATAERR, "invalid OR block"); \
4603 prev->len |= F_OR; \
4613 * MAC addresses, optional.
4614 * If we have this, we skip the part "proto from src to dst"
4615 * and jump straight to the option parsing.
4618 NEED1("missing protocol");
4619 if (_substrcmp(*av, "MAC") == 0 ||
4620 _substrcmp(*av, "mac") == 0) {
4621 av++; /* the "MAC" keyword */
4622 add_mac(cmd, av); /* exits in case of errors */
4623 cmd = next_cmd(cmd);
4624 av += 2; /* dst-mac and src-mac */
4626 NEED1("missing mac type");
4627 if (add_mactype(cmd, av[0]))
4628 cmd = next_cmd(cmd);
4629 av++; /* any or mac-type */
4635 * protocol, mandatory
4637 OR_START(get_proto);
4639 NEED1("missing protocol");
4640 if (add_proto_compat(cmd, *av, &proto)) {
4642 if (F_LEN(cmd) != 0) {
4644 cmd = next_cmd(cmd, &cblen);
4646 } else if (first_cmd != cmd) {
4647 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
4649 rule->flags |= IPFW_RULE_JUSTOPTS;
4652 OR_BLOCK(get_proto);
4654 first_cmd = cmd; /* update pointer to use in compact form */
4659 if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
4660 errx(EX_USAGE, "missing ``from''");
4664 * source IP, mandatory
4666 OR_START(source_ip);
4667 NOT_BLOCK; /* optional "not" */
4668 NEED1("missing source address");
4669 if (add_src(cmd, *av, proto, cblen, tstate)) {
4671 if (F_LEN(cmd) != 0) { /* ! any */
4673 cmd = next_cmd(cmd, &cblen);
4676 errx(EX_USAGE, "bad source address %s", *av);
4677 OR_BLOCK(source_ip);
4680 * source ports, optional
4682 NOT_BLOCK; /* optional "not" */
4683 if ( av[0] != NULL ) {
4684 if (_substrcmp(*av, "any") == 0 ||
4685 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4687 if (F_LEN(cmd) != 0)
4688 cmd = next_cmd(cmd, &cblen);
4695 if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
4696 errx(EX_USAGE, "missing ``to''");
4700 * destination, mandatory
4703 NOT_BLOCK; /* optional "not" */
4704 NEED1("missing dst address");
4705 if (add_dst(cmd, *av, proto, cblen, tstate)) {
4707 if (F_LEN(cmd) != 0) { /* ! any */
4709 cmd = next_cmd(cmd, &cblen);
4712 errx( EX_USAGE, "bad destination address %s", *av);
4716 * dest. ports, optional
4718 NOT_BLOCK; /* optional "not" */
4720 if (_substrcmp(*av, "any") == 0 ||
4721 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4723 if (F_LEN(cmd) != 0)
4724 cmd = next_cmd(cmd, &cblen);
4727 if (first_cmd == cmd)
4728 rule->flags |= IPFW_RULE_NOOPT;
4732 while ( av[0] != NULL ) {
4734 ipfw_insn_u32 *cmd32; /* alias for cmd */
4737 cmd32 = (ipfw_insn_u32 *)cmd;
4739 if (*s == '!') { /* alternate syntax for NOT */
4740 if (cmd->len & F_NOT)
4741 errx(EX_USAGE, "double \"not\" not allowed\n");
4745 i = match_token(rule_options, s);
4749 if (cmd->len & F_NOT)
4750 errx(EX_USAGE, "double \"not\" not allowed\n");
4755 if (open_par == 0 || prev == NULL)
4756 errx(EX_USAGE, "invalid \"or\" block\n");
4760 case TOK_STARTBRACE:
4762 errx(EX_USAGE, "+nested \"(\" not allowed\n");
4768 errx(EX_USAGE, "+missing \")\"\n");
4774 fill_cmd(cmd, O_IN, 0, 0);
4778 cmd->len ^= F_NOT; /* toggle F_NOT */
4779 fill_cmd(cmd, O_IN, 0, 0);
4783 fill_cmd(cmd, O_DIVERTED, 0, 3);
4786 case TOK_DIVERTEDLOOPBACK:
4787 fill_cmd(cmd, O_DIVERTED, 0, 1);
4790 case TOK_DIVERTEDOUTPUT:
4791 fill_cmd(cmd, O_DIVERTED, 0, 2);
4795 uint32_t set = 0, clear = 0;
4797 if (*av != NULL && fill_flags(f_ipoff, *av, NULL,
4802 * Compatibility: no argument after "frag"
4803 * keyword equals to "frag offset".
4808 fill_cmd(cmd, O_FRAG, 0,
4809 (set & 0xff) | ( (clear & 0xff) << 8));
4814 fill_cmd(cmd, O_LAYER2, 0, 0);
4820 NEED1("recv, xmit, via require interface name"
4822 fill_iface((ipfw_insn_if *)cmd, av[0], cblen, tstate);
4824 if (F_LEN(cmd) == 0) /* not a valid address */
4827 cmd->opcode = O_XMIT;
4828 else if (i == TOK_RECV)
4829 cmd->opcode = O_RECV;
4830 else if (i == TOK_VIA)
4831 cmd->opcode = O_VIA;
4835 NEED1("icmptypes requires list of types");
4836 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
4840 case TOK_ICMP6TYPES:
4841 NEED1("icmptypes requires list of types");
4842 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
4847 NEED1("ipttl requires TTL");
4848 if (strpbrk(*av, "-,")) {
4849 if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
4850 errx(EX_DATAERR, "invalid ipttl %s", *av);
4852 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
4857 NEED1("ipid requires id");
4858 if (strpbrk(*av, "-,")) {
4859 if (!add_ports(cmd, *av, 0, O_IPID, cblen))
4860 errx(EX_DATAERR, "invalid ipid %s", *av);
4862 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
4867 NEED1("iplen requires length");
4868 if (strpbrk(*av, "-,")) {
4869 if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
4870 errx(EX_DATAERR, "invalid ip len %s", *av);
4872 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
4877 NEED1("ipver requires version");
4878 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
4882 case TOK_IPPRECEDENCE:
4883 NEED1("ipprecedence requires value");
4884 fill_cmd(cmd, O_IPPRECEDENCE, 0,
4885 (strtoul(*av, NULL, 0) & 7) << 5);
4890 NEED1("missing DSCP code");
4891 fill_dscp(cmd, *av, cblen);
4896 NEED1("missing argument for ipoptions");
4897 fill_flags_cmd(cmd, O_IPOPT, f_ipopts, *av);
4902 NEED1("missing argument for iptos");
4903 fill_flags_cmd(cmd, O_IPTOS, f_iptos, *av);
4908 NEED1("uid requires argument");
4914 cmd->opcode = O_UID;
4915 uid = strtoul(*av, &end, 0);
4916 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
4918 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
4919 cmd32->d[0] = pwd->pw_uid;
4920 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4926 NEED1("gid requires argument");
4932 cmd->opcode = O_GID;
4933 gid = strtoul(*av, &end, 0);
4934 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
4936 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
4937 cmd32->d[0] = grp->gr_gid;
4938 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4944 NEED1("jail requires argument");
4949 cmd->opcode = O_JAIL;
4951 * If av is a number, then we'll just pass it as-is. If
4952 * it's a name, try to resolve that to a jid.
4954 * We save the jail_getid(3) call for a fallback because
4955 * it entails an unconditional trip to the kernel to
4956 * either validate a jid or resolve a name to a jid.
4957 * This specific token doesn't currently require a
4958 * jid to be an active jail, so we save a transition
4959 * by simply using a number that we're given.
4961 jid = strtoul(*av, &end, 10);
4963 jid = jail_getid(*av);
4965 errx(EX_DATAERR, "%s", jail_errmsg);
4967 cmd32->d[0] = (uint32_t)jid;
4968 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4974 fill_cmd(cmd, O_ESTAB, 0, 0);
4978 fill_cmd(cmd, O_TCPFLAGS, 0,
4979 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
4982 case TOK_TCPDATALEN:
4983 NEED1("tcpdatalen requires length");
4984 if (strpbrk(*av, "-,")) {
4985 if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
4986 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
4988 fill_cmd(cmd, O_TCPDATALEN, 0,
4989 strtoul(*av, NULL, 0));
4994 NEED1("missing argument for tcpoptions");
4995 fill_flags_cmd(cmd, O_TCPOPTS, f_tcpopts, *av);
5001 NEED1("tcpseq/tcpack requires argument");
5002 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
5003 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
5004 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
5010 NEED1("tcpmss/tcpwin requires size");
5011 if (strpbrk(*av, "-,")) {
5012 if (add_ports(cmd, *av, 0,
5013 i == TOK_TCPWIN ? O_TCPWIN : O_TCPMSS,
5015 errx(EX_DATAERR, "invalid %s size %s",
5018 fill_cmd(cmd, i == TOK_TCPWIN ? O_TCPWIN :
5019 O_TCPMSS, 0, strtoul(*av, NULL, 0));
5024 NEED1("missing argument for tcpflags");
5025 cmd->opcode = O_TCPFLAGS;
5026 fill_flags_cmd(cmd, O_TCPFLAGS, f_tcpflags, *av);
5031 case TOK_RECORDSTATE: {
5035 errx(EX_USAGE, "keep-state or record-state cannot be part "
5038 errx(EX_USAGE, "only one of keep-state, record-state, "
5039 " limit and set-limit is allowed");
5040 if (*av != NULL && *av[0] == ':') {
5041 if (state_check_name(*av + 1) != 0)
5043 "Invalid state name %s", *av);
5044 uidx = pack_object(tstate, *av + 1,
5045 IPFW_TLV_STATE_NAME);
5048 uidx = pack_object(tstate, default_state_name,
5049 IPFW_TLV_STATE_NAME);
5051 have_rstate = i == TOK_RECORDSTATE;
5052 fill_cmd(cmd, O_KEEP_STATE, 0, uidx);
5057 case TOK_SETLIMIT: {
5058 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
5063 "limit or set-limit cannot be part of an or block");
5065 errx(EX_USAGE, "only one of keep-state, record-state, "
5066 " limit and set-limit is allowed");
5068 have_rstate = i == TOK_SETLIMIT;
5070 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
5072 cmd->opcode = O_LIMIT;
5073 c->limit_mask = c->conn_limit = 0;
5075 while ( av[0] != NULL ) {
5076 if ((val = match_token(limit_masks, *av)) <= 0)
5078 c->limit_mask |= val;
5082 if (c->limit_mask == 0)
5083 errx(EX_USAGE, "limit: missing limit mask");
5085 GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
5086 TOK_LIMIT, rule_options);
5089 if (*av != NULL && *av[0] == ':') {
5090 if (state_check_name(*av + 1) != 0)
5092 "Invalid state name %s", *av);
5093 cmd->arg1 = pack_object(tstate, *av + 1,
5094 IPFW_TLV_STATE_NAME);
5097 cmd->arg1 = pack_object(tstate,
5098 default_state_name, IPFW_TLV_STATE_NAME);
5103 NEED1("missing protocol");
5104 if (add_proto(cmd, *av, &proto)) {
5107 errx(EX_DATAERR, "invalid protocol ``%s''",
5112 NEED1("missing source IP");
5113 if (add_srcip(cmd, *av, cblen, tstate)) {
5119 NEED1("missing destination IP");
5120 if (add_dstip(cmd, *av, cblen, tstate)) {
5126 NEED1("missing source IP6");
5127 if (add_srcip6(cmd, *av, cblen, tstate)) {
5133 NEED1("missing destination IP6");
5134 if (add_dstip6(cmd, *av, cblen, tstate)) {
5141 NEED1("missing source MAC");
5142 if (add_srcmac(cmd, *av, tstate)) {
5148 NEED1("missing destination MAC");
5149 if (add_dstmac(cmd, *av, tstate)) {
5155 NEED1("missing source port");
5156 if (_substrcmp(*av, "any") == 0 ||
5157 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
5160 errx(EX_DATAERR, "invalid source port %s", *av);
5164 NEED1("missing destination port");
5165 if (_substrcmp(*av, "any") == 0 ||
5166 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
5169 errx(EX_DATAERR, "invalid destination port %s",
5174 if (add_mac(cmd, av, cblen))
5179 NEED1("missing mac type");
5180 if (!add_mactype(cmd, *av, cblen))
5181 errx(EX_DATAERR, "invalid mac type %s", *av);
5185 case TOK_VERREVPATH:
5186 fill_cmd(cmd, O_VERREVPATH, 0, 0);
5189 case TOK_VERSRCREACH:
5190 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
5194 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
5198 fill_cmd(cmd, O_IPSEC, 0, 0);
5202 fill_cmd(cmd, O_IP6, 0, 0);
5206 fill_cmd(cmd, O_IP4, 0, 0);
5210 NEED1("missing extension header");
5211 fill_ext6hdr( cmd, *av );
5216 if (proto != IPPROTO_IPV6 )
5217 errx( EX_USAGE, "flow-id filter is active "
5218 "only for ipv6 protocol\n");
5219 fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
5224 fill_comment(cmd, av, cblen);
5229 if (av[0] && strpbrk(*av, "-,")) {
5230 if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
5231 errx(EX_DATAERR, "tagged: invalid tag"
5237 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
5238 TOK_TAGGED, rule_options);
5239 fill_cmd(cmd, O_TAGGED, 0, tag);
5245 NEED1("fib requires fib number");
5246 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
5250 fill_cmd(cmd, O_SOCKARG, 0, 0);
5254 ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
5256 if (!av[0] || !av[1])
5257 errx(EX_USAGE, "format: lookup argument tablenum");
5258 cmd->opcode = O_IP_DST_LOOKUP;
5259 cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
5260 i = match_token(lookup_keys, *av);
5262 errx(EX_USAGE, "format: cannot lookup on %s", *av);
5263 __PAST_END(c->d, 1) = i;
5266 if ((i = pack_table(tstate, *av)) == 0)
5267 errx(EX_DATAERR, "Invalid table name: %s", *av);
5274 NEED1("missing table name");
5275 if (strncmp(*av, "table(", 6) != 0)
5277 "enclose table name into \"table()\"");
5278 fill_table(cmd, *av, O_IP_FLOW_LOOKUP, tstate);
5282 case TOK_SKIPACTION:
5284 errx(EX_USAGE, "only one defer-action "
5287 fill_cmd(cmd, O_SKIP_ACTION, 0, 0);
5291 NEED1("missing mark value:mask");
5292 fill_mark(cmd, *av, cblen);
5297 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
5299 if (F_LEN(cmd) > 0) { /* prepare to advance */
5301 cmd = next_cmd(cmd, &cblen);
5307 if (!have_state && have_skipcmd)
5308 warnx("Rule contains \"defer-immediate-action\" "
5309 "and doesn't contain any state-related options.");
5312 * Now copy stuff into the rule.
5313 * If we have a keep-state option, the first instruction
5314 * must be a PROBE_STATE (which is generated here).
5315 * If we have a LOG option, it was stored as the first command,
5316 * and now must be moved to the top of the action part.
5318 dst = (ipfw_insn *)rule->cmd;
5321 * First thing to write into the command stream is the match probability.
5323 if (match_prob != 1) { /* 1 means always match */
5324 dst->opcode = O_PROB;
5326 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
5331 * generate O_PROBE_STATE if necessary
5333 if (have_state && have_state->opcode != O_CHECK_STATE && !have_rstate) {
5334 fill_cmd(dst, O_PROBE_STATE, 0, have_state->arg1);
5335 dst = next_cmd(dst, &rblen);
5339 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG,
5342 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
5346 switch (src->opcode) {
5355 bcopy(src, dst, i * sizeof(uint32_t));
5361 * put back the have_state command as last opcode
5363 if (have_state && have_state->opcode != O_CHECK_STATE) {
5364 i = F_LEN(have_state);
5366 bcopy(have_state, dst, i * sizeof(uint32_t));
5371 * put back the have_skipcmd command as very last opcode
5374 i = F_LEN(have_skipcmd);
5376 bcopy(have_skipcmd, dst, i * sizeof(uint32_t));
5381 * start action section
5383 rule->act_ofs = dst - rule->cmd;
5385 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
5387 i = F_LEN(have_log);
5389 bcopy(have_log, dst, i * sizeof(uint32_t));
5393 i = F_LEN(have_altq);
5395 bcopy(have_altq, dst, i * sizeof(uint32_t));
5399 i = F_LEN(have_tag);
5401 bcopy(have_tag, dst, i * sizeof(uint32_t));
5406 * copy all other actions
5408 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
5411 bcopy(src, dst, i * sizeof(uint32_t));
5415 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
5416 *rbufsize = (char *)dst - (char *)rule;
5420 compare_ntlv(const void *_a, const void *_b)
5422 const ipfw_obj_ntlv *a, *b;
5424 a = (const ipfw_obj_ntlv *)_a;
5425 b = (const ipfw_obj_ntlv *)_b;
5427 if (a->set < b->set)
5429 else if (a->set > b->set)
5432 if (a->idx < b->idx)
5434 else if (a->idx > b->idx)
5437 if (a->head.type < b->head.type)
5439 else if (a->head.type > b->head.type)
5446 * Provide kernel with sorted list of referenced objects
5449 object_sort_ctlv(ipfw_obj_ctlv *ctlv)
5452 qsort(ctlv + 1, ctlv->count, ctlv->objsize, compare_ntlv);
5460 compare_object_kntlv(const void *k, const void *v)
5462 const ipfw_obj_ntlv *ntlv;
5463 struct object_kt key;
5465 key = *((const struct object_kt *)k);
5466 ntlv = (const ipfw_obj_ntlv *)v;
5468 if (key.uidx < ntlv->idx)
5470 else if (key.uidx > ntlv->idx)
5473 if (key.type < ntlv->head.type)
5475 else if (key.type > ntlv->head.type)
5482 * Finds object name in @ctlv by @idx and @type.
5483 * Uses the following facts:
5484 * 1) All TLVs are the same size
5485 * 2) Kernel implementation provides already sorted list.
5487 * Returns table name or NULL.
5490 object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx, uint16_t type)
5492 ipfw_obj_ntlv *ntlv;
5493 struct object_kt key;
5498 ntlv = bsearch(&key, (ctlv + 1), ctlv->count, ctlv->objsize,
5499 compare_object_kntlv);
5502 return (ntlv->name);
5508 table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx)
5511 return (object_search_ctlv(ctlv, idx, IPFW_TLV_TBL_NAME));
5515 * Adds one or more rules to ipfw chain.
5520 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
5521 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ] (*2) (*3)
5526 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
5527 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ]
5530 * Rules in reply are modified to store their actual ruleset number.
5532 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
5533 * according to their idx field and there has to be no duplicates.
5534 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
5535 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
5538 ipfw_add(char *av[])
5540 uint32_t rulebuf[1024];
5541 int rbufsize, default_off, tlen, rlen;
5544 struct ip_fw_rule *rule;
5546 ip_fw3_opheader *op3;
5547 ipfw_obj_ctlv *ctlv, *tstate;
5549 rbufsize = sizeof(rulebuf);
5550 memset(rulebuf, 0, rbufsize);
5551 memset(&ts, 0, sizeof(ts));
5553 /* Optimize case with no tables */
5554 default_off = sizeof(ipfw_obj_ctlv) + sizeof(ip_fw3_opheader);
5555 op3 = (ip_fw3_opheader *)rulebuf;
5556 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5557 rule = (struct ip_fw_rule *)(ctlv + 1);
5558 rbufsize -= default_off;
5560 compile_rule(av, (uint32_t *)rule, &rbufsize, &ts);
5561 /* Align rule size to u64 boundary */
5562 rlen = roundup2(rbufsize, sizeof(uint64_t));
5567 if (ts.count != 0) {
5568 /* Some tables. We have to alloc more data */
5569 tlen = ts.count * sizeof(ipfw_obj_ntlv);
5570 sz = default_off + sizeof(ipfw_obj_ctlv) + tlen + rlen;
5572 if ((tbuf = calloc(1, sz)) == NULL)
5573 err(EX_UNAVAILABLE, "malloc() failed for IP_FW_ADD");
5574 op3 = (ip_fw3_opheader *)tbuf;
5576 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5577 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
5578 ctlv->head.length = sizeof(ipfw_obj_ctlv) + tlen;
5579 ctlv->count = ts.count;
5580 ctlv->objsize = sizeof(ipfw_obj_ntlv);
5581 memcpy(ctlv + 1, ts.idx, tlen);
5582 object_sort_ctlv(ctlv);
5585 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
5586 ctlv->head.type = IPFW_TLV_RULE_LIST;
5587 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5589 memcpy(ctlv + 1, rule, rbufsize);
5591 /* Simply add header */
5592 sz = rlen + default_off;
5593 memset(ctlv, 0, sizeof(*ctlv));
5594 ctlv->head.type = IPFW_TLV_RULE_LIST;
5595 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5599 if (do_get3(IP_FW_XADD, op3, &sz) != 0)
5600 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_XADD");
5602 if (!g_co.do_quiet) {
5603 struct format_opts sfo;
5605 memset(&sfo, 0, sizeof(sfo));
5606 sfo.tstate = tstate;
5607 sfo.set_mask = (uint32_t)(-1);
5608 bp_alloc(&bp, 4096);
5609 show_static_rule(&g_co, &sfo, &bp, rule, NULL);
5610 printf("%s", bp.buf);
5622 * clear the counters or the log counters.
5623 * optname has the following values:
5624 * 0 (zero both counters and logging)
5625 * 1 (zero logging only)
5628 ipfw_zero(int ac, char *av[], int optname)
5632 char const *name = optname ? "RESETLOG" : "ZERO";
5636 optname = optname ? IP_FW_XRESETLOG : IP_FW_XZERO;
5640 /* clear all entries */
5641 memset(&rt, 0, sizeof(rt));
5642 rt.flags = IPFW_RCFLAG_ALL;
5643 if (do_range_cmd(optname, &rt) < 0)
5644 err(EX_UNAVAILABLE, "setsockopt(IP_FW_X%s)", name);
5646 printf("%s.\n", optname == IP_FW_XZERO ?
5647 "Accounting cleared":"Logging counts reset");
5654 if (isdigit(**av)) {
5655 arg = strtonum(*av, 0, 0xffff, &errstr);
5658 "invalid rule number %s\n", *av);
5659 memset(&rt, 0, sizeof(rt));
5660 rt.start_rule = arg;
5662 rt.flags |= IPFW_RCFLAG_RANGE;
5663 if (g_co.use_set != 0) {
5664 rt.set = g_co.use_set - 1;
5665 rt.flags |= IPFW_RCFLAG_SET;
5667 if (do_range_cmd(optname, &rt) != 0) {
5668 warn("rule %u: setsockopt(IP_FW_X%s)",
5670 failed = EX_UNAVAILABLE;
5671 } else if (rt.new_set == 0) {
5672 printf("Entry %d not found\n", arg);
5673 failed = EX_UNAVAILABLE;
5674 } else if (!g_co.do_quiet)
5675 printf("Entry %d %s.\n", arg,
5676 optname == IP_FW_XZERO ?
5677 "cleared" : "logging count reset");
5679 errx(EX_USAGE, "invalid rule number ``%s''", *av);
5683 if (failed != EX_OK)
5688 ipfw_flush(int force)
5692 if (!force && !g_co.do_quiet) { /* need to ask user */
5695 printf("Are you sure? [yn] ");
5698 c = toupper(getc(stdin));
5699 while (c != '\n' && getc(stdin) != '\n')
5701 return; /* and do not flush */
5702 } while (c != 'Y' && c != 'N');
5704 if (c == 'N') /* user said no */
5711 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
5712 memset(&rt, 0, sizeof(rt));
5713 if (g_co.use_set != 0) {
5714 rt.set = g_co.use_set - 1;
5715 rt.flags = IPFW_RCFLAG_SET;
5717 rt.flags = IPFW_RCFLAG_ALL;
5718 if (do_range_cmd(IP_FW_XDEL, &rt) != 0)
5719 err(EX_UNAVAILABLE, "setsockopt(IP_FW_XDEL)");
5721 printf("Flushed all %s.\n", g_co.do_pipe ? "pipes" : "rules");
5724 static struct _s_x intcmds[] = {
5725 { "talist", TOK_TALIST },
5726 { "iflist", TOK_IFLIST },
5727 { "olist", TOK_OLIST },
5728 { "vlist", TOK_VLIST },
5732 static struct _s_x otypes[] = {
5733 { "EACTION", IPFW_TLV_EACTION },
5734 { "DYNSTATE", IPFW_TLV_STATE_NAME },
5739 lookup_eaction_name(ipfw_obj_ntlv *ntlv, int cnt, uint16_t type)
5745 for (i = 0; i < cnt; i++) {
5746 if (ntlv[i].head.type != IPFW_TLV_EACTION)
5748 if (IPFW_TLV_EACTION_NAME(ntlv[i].idx) != type)
5750 name = ntlv[i].name;
5757 ipfw_list_objects(int ac __unused, char *av[] __unused)
5759 ipfw_obj_lheader req, *olh;
5760 ipfw_obj_ntlv *ntlv;
5765 memset(&req, 0, sizeof(req));
5767 if (do_get3(IP_FW_DUMP_SRVOBJECTS, &req.opheader, &sz) != 0)
5768 if (errno != ENOMEM)
5772 if ((olh = calloc(1, sz)) == NULL)
5776 if (do_get3(IP_FW_DUMP_SRVOBJECTS, &olh->opheader, &sz) != 0) {
5782 printf("Objects list:\n");
5784 printf("There are no objects\n");
5785 ntlv = (ipfw_obj_ntlv *)(olh + 1);
5786 for (i = 0; i < olh->count; i++) {
5787 name = match_value(otypes, ntlv->head.type);
5789 name = lookup_eaction_name(
5790 (ipfw_obj_ntlv *)(olh + 1), olh->count,
5793 printf(" kidx: %4d\ttype: %10d\tname: %s\n",
5794 ntlv->idx, ntlv->head.type, ntlv->name);
5796 printf(" kidx: %4d\ttype: %10s\tname: %s\n",
5797 ntlv->idx, name, ntlv->name);
5804 ipfw_internal_handler(int ac, char *av[])
5809 NEED1("internal cmd required");
5811 if ((tcmd = match_token(intcmds, *av)) == -1)
5812 errx(EX_USAGE, "invalid internal sub-cmd: %s", *av);
5816 ipfw_list_tifaces();
5819 ipfw_list_ta(ac, av);
5822 ipfw_list_objects(ac, av);
5825 ipfw_list_values(ac, av);
5831 ipfw_get_tracked_ifaces(ipfw_obj_lheader **polh)
5833 ipfw_obj_lheader req, *olh;
5836 memset(&req, 0, sizeof(req));
5839 if (do_get3(IP_FW_XIFLIST, &req.opheader, &sz) != 0) {
5840 if (errno != ENOMEM)
5845 if ((olh = calloc(1, sz)) == NULL)
5849 if (do_get3(IP_FW_XIFLIST, &olh->opheader, &sz) != 0) {
5859 ifinfo_cmp(const void *a, const void *b)
5861 const ipfw_iface_info *ia, *ib;
5863 ia = (const ipfw_iface_info *)a;
5864 ib = (const ipfw_iface_info *)b;
5866 return (stringnum_cmp(ia->ifname, ib->ifname));
5870 * Retrieves table list from kernel,
5871 * optionally sorts it and calls requested function for each table.
5872 * Returns 0 on success.
5875 ipfw_list_tifaces(void)
5877 ipfw_obj_lheader *olh = NULL;
5878 ipfw_iface_info *info;
5882 if ((error = ipfw_get_tracked_ifaces(&olh)) != 0)
5883 err(EX_OSERR, "Unable to request ipfw tracked interface list");
5885 qsort(olh + 1, olh->count, olh->objsize, ifinfo_cmp);
5887 info = (ipfw_iface_info *)(olh + 1);
5888 for (i = 0; i < olh->count; i++) {
5889 if (info->flags & IPFW_IFFLAG_RESOLVED)
5890 printf("%s ifindex: %d refcount: %u changes: %u\n",
5891 info->ifname, info->ifindex, info->refcnt,
5894 printf("%s ifindex: unresolved refcount: %u changes: %u\n",
5895 info->ifname, info->refcnt, info->gencnt);
5896 info = (ipfw_iface_info *)((caddr_t)info + olh->objsize);