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
21 #include <sys/types.h>
22 #include <sys/param.h>
23 #include <sys/socket.h>
24 #include <sys/sockio.h>
25 #include <sys/sysctl.h>
42 #include <time.h> /* ctime */
43 #include <timeconv.h> /* _long_to_time */
46 #include <stddef.h> /* offsetof */
48 #include <net/ethernet.h>
49 #include <net/if.h> /* only IFNAMSIZ */
50 #include <netinet/in.h>
51 #include <netinet/in_systm.h> /* only n_short, n_long */
52 #include <netinet/ip.h>
53 #include <netinet/ip_icmp.h>
54 #include <netinet/ip_fw.h>
55 #include <netinet/tcp.h>
56 #include <arpa/inet.h>
58 struct cmdline_opts g_co; /* global options */
64 int show_time; /* show timestamp */
65 uint32_t set_mask; /* enabled sets mask */
66 uint32_t flags; /* request flags */
67 uint32_t first; /* first rule to request */
68 uint32_t last; /* last rule to request */
69 uint32_t dcnt; /* number of dynamic states */
70 ipfw_obj_ctlv *tstate; /* table state data */
73 int resvd_set_number = RESVD_SET;
75 static int ipfw_socket = -1;
77 #define CHECK_LENGTH(v, len) do { \
79 errx(EX_DATAERR, "Rule too long"); \
82 * Check if we have enough space in cmd buffer. Note that since
83 * first 8? u32 words are reserved by reserved header, full cmd
84 * buffer can't be used, so we need to protect from buffer overrun
85 * only. At the beginning, cblen is less than actual buffer size by
86 * size of ipfw_insn_u32 instruction + 1 u32 work. This eliminates need
87 * for checking small instructions fitting in given range.
88 * We also (ab)use the fact that ipfw_insn is always the first field
89 * for any custom instruction.
91 #define CHECK_CMDLEN CHECK_LENGTH(cblen, F_LEN((ipfw_insn *)cmd))
93 #define GET_UINT_ARG(arg, min, max, tok, s_x) do { \
95 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
96 if (_substrcmp(*av, "tablearg") == 0) { \
105 _xval = strtol(*av, &end, 10); \
107 if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
108 errx(EX_DATAERR, "%s: invalid argument: %s", \
109 match_value(s_x, tok), *av); \
111 if (errno == ERANGE || _xval < min || _xval > max) \
112 errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
113 match_value(s_x, tok), min, max, *av); \
115 if (_xval == IP_FW_TARG) \
116 errx(EX_DATAERR, "%s: illegal argument value: %s", \
117 match_value(s_x, tok), *av); \
122 static struct _s_x f_tcpflags[] = {
133 static struct _s_x f_tcpopts[] = {
134 { "mss", IP_FW_TCPOPT_MSS },
135 { "maxseg", IP_FW_TCPOPT_MSS },
136 { "window", IP_FW_TCPOPT_WINDOW },
137 { "sack", IP_FW_TCPOPT_SACK },
138 { "ts", IP_FW_TCPOPT_TS },
139 { "timestamp", IP_FW_TCPOPT_TS },
140 { "cc", IP_FW_TCPOPT_CC },
146 * IP options span the range 0 to 255 so we need to remap them
147 * (though in fact only the low 5 bits are significant).
149 static struct _s_x f_ipopts[] = {
150 { "ssrr", IP_FW_IPOPT_SSRR},
151 { "lsrr", IP_FW_IPOPT_LSRR},
152 { "rr", IP_FW_IPOPT_RR},
153 { "ts", IP_FW_IPOPT_TS},
158 static struct _s_x f_iptos[] = {
159 { "lowdelay", IPTOS_LOWDELAY},
160 { "throughput", IPTOS_THROUGHPUT},
161 { "reliability", IPTOS_RELIABILITY},
162 { "mincost", IPTOS_MINCOST},
163 { "congestion", IPTOS_ECN_CE},
164 { "ecntransport", IPTOS_ECN_ECT0},
165 { "ip tos option", 0},
169 static struct _s_x f_ipoff[] = {
170 { "rf", IP_RF >> 8 },
171 { "df", IP_DF >> 8 },
172 { "mf", IP_MF >> 8 },
177 struct _s_x f_ipdscp[] = {
178 { "af11", IPTOS_DSCP_AF11 >> 2 }, /* 001010 */
179 { "af12", IPTOS_DSCP_AF12 >> 2 }, /* 001100 */
180 { "af13", IPTOS_DSCP_AF13 >> 2 }, /* 001110 */
181 { "af21", IPTOS_DSCP_AF21 >> 2 }, /* 010010 */
182 { "af22", IPTOS_DSCP_AF22 >> 2 }, /* 010100 */
183 { "af23", IPTOS_DSCP_AF23 >> 2 }, /* 010110 */
184 { "af31", IPTOS_DSCP_AF31 >> 2 }, /* 011010 */
185 { "af32", IPTOS_DSCP_AF32 >> 2 }, /* 011100 */
186 { "af33", IPTOS_DSCP_AF33 >> 2 }, /* 011110 */
187 { "af41", IPTOS_DSCP_AF41 >> 2 }, /* 100010 */
188 { "af42", IPTOS_DSCP_AF42 >> 2 }, /* 100100 */
189 { "af43", IPTOS_DSCP_AF43 >> 2 }, /* 100110 */
190 { "be", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
191 { "va", IPTOS_DSCP_VA >> 2 }, /* 101100 */
192 { "ef", IPTOS_DSCP_EF >> 2 }, /* 101110 */
193 { "cs0", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
194 { "cs1", IPTOS_DSCP_CS1 >> 2 }, /* 001000 */
195 { "cs2", IPTOS_DSCP_CS2 >> 2 }, /* 010000 */
196 { "cs3", IPTOS_DSCP_CS3 >> 2 }, /* 011000 */
197 { "cs4", IPTOS_DSCP_CS4 >> 2 }, /* 100000 */
198 { "cs5", IPTOS_DSCP_CS5 >> 2 }, /* 101000 */
199 { "cs6", IPTOS_DSCP_CS6 >> 2 }, /* 110000 */
200 { "cs7", IPTOS_DSCP_CS7 >> 2 }, /* 100000 */
204 static struct _s_x limit_masks[] = {
205 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
206 {"src-addr", DYN_SRC_ADDR},
207 {"src-port", DYN_SRC_PORT},
208 {"dst-addr", DYN_DST_ADDR},
209 {"dst-port", DYN_DST_PORT},
214 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
215 * This is only used in this code.
217 #define IPPROTO_ETHERTYPE 0x1000
218 static struct _s_x ether_types[] = {
220 * Note, we cannot use "-:&/" in the names because they are field
221 * separators in the type specifications. Also, we use s = NULL as
222 * end-delimiter, because a type of 0 can be legal.
235 { "pppoe_disc", 0x8863 },
236 { "pppoe_sess", 0x8864 },
237 { "ipx_8022", 0x00E0 },
238 { "ipx_8023", 0x0000 },
239 { "ipx_ii", 0x8137 },
240 { "ipx_snap", 0x8137 },
246 static struct _s_x rule_eactions[] = {
247 { "nat64clat", TOK_NAT64CLAT },
248 { "nat64lsn", TOK_NAT64LSN },
249 { "nat64stl", TOK_NAT64STL },
250 { "nptv6", TOK_NPTV6 },
251 { "tcp-setmss", TOK_TCPSETMSS },
252 { NULL, 0 } /* terminator */
255 static struct _s_x rule_actions[] = {
256 { "abort6", TOK_ABORT6 },
257 { "abort", TOK_ABORT },
258 { "accept", TOK_ACCEPT },
259 { "pass", TOK_ACCEPT },
260 { "allow", TOK_ACCEPT },
261 { "permit", TOK_ACCEPT },
262 { "count", TOK_COUNT },
263 { "pipe", TOK_PIPE },
264 { "queue", TOK_QUEUE },
265 { "divert", TOK_DIVERT },
267 { "netgraph", TOK_NETGRAPH },
268 { "ngtee", TOK_NGTEE },
269 { "fwd", TOK_FORWARD },
270 { "forward", TOK_FORWARD },
271 { "skipto", TOK_SKIPTO },
272 { "deny", TOK_DENY },
273 { "drop", TOK_DENY },
274 { "reject", TOK_REJECT },
275 { "reset6", TOK_RESET6 },
276 { "reset", TOK_RESET },
277 { "unreach6", TOK_UNREACH6 },
278 { "unreach", TOK_UNREACH },
279 { "check-state", TOK_CHECKSTATE },
280 { "//", TOK_COMMENT },
282 { "reass", TOK_REASS },
283 { "setfib", TOK_SETFIB },
284 { "setdscp", TOK_SETDSCP },
285 { "call", TOK_CALL },
286 { "return", TOK_RETURN },
287 { "eaction", TOK_EACTION },
288 { "tcp-setmss", TOK_TCPSETMSS },
289 { "setmark", TOK_SETMARK },
290 { NULL, 0 } /* terminator */
293 static struct _s_x rule_action_params[] = {
294 { "altq", TOK_ALTQ },
297 { "untag", TOK_UNTAG },
298 { NULL, 0 } /* terminator */
302 * The 'lookup' instruction accepts one of the following arguments.
303 * Arguments are passed as v[1] in O_DST_LOOKUP options.
305 static struct _s_x lookup_keys[] = {
306 { "dst-ip", LOOKUP_DST_IP },
307 { "src-ip", LOOKUP_SRC_IP },
308 { "dst-port", LOOKUP_DST_PORT },
309 { "src-port", LOOKUP_SRC_PORT },
310 { "dst-mac", LOOKUP_DST_MAC },
311 { "src-mac", LOOKUP_SRC_MAC },
312 { "uid", LOOKUP_UID },
313 { "jail", LOOKUP_JAIL },
314 { "dscp", LOOKUP_DSCP },
315 { "mark", LOOKUP_MARK },
319 static struct _s_x rule_options[] = {
320 { "tagged", TOK_TAGGED },
323 { "jail", TOK_JAIL },
325 { "limit", TOK_LIMIT },
326 { "set-limit", TOK_SETLIMIT },
327 { "keep-state", TOK_KEEPSTATE },
328 { "record-state", TOK_RECORDSTATE },
329 { "bridged", TOK_LAYER2 },
330 { "layer2", TOK_LAYER2 },
332 { "diverted", TOK_DIVERTED },
333 { "diverted-loopback", TOK_DIVERTEDLOOPBACK },
334 { "diverted-output", TOK_DIVERTEDOUTPUT },
335 { "xmit", TOK_XMIT },
336 { "recv", TOK_RECV },
338 { "fragment", TOK_FRAG },
339 { "frag", TOK_FRAG },
341 { "ipoptions", TOK_IPOPTS },
342 { "ipopts", TOK_IPOPTS },
343 { "iplen", TOK_IPLEN },
344 { "ipid", TOK_IPID },
345 { "ipprecedence", TOK_IPPRECEDENCE },
346 { "dscp", TOK_DSCP },
347 { "iptos", TOK_IPTOS },
348 { "ipttl", TOK_IPTTL },
349 { "ipversion", TOK_IPVER },
350 { "ipver", TOK_IPVER },
351 { "estab", TOK_ESTAB },
352 { "established", TOK_ESTAB },
353 { "setup", TOK_SETUP },
354 { "sockarg", TOK_SOCKARG },
355 { "tcpdatalen", TOK_TCPDATALEN },
356 { "tcpflags", TOK_TCPFLAGS },
357 { "tcpflgs", TOK_TCPFLAGS },
358 { "tcpmss", TOK_TCPMSS },
359 { "tcpoptions", TOK_TCPOPTS },
360 { "tcpopts", TOK_TCPOPTS },
361 { "tcpseq", TOK_TCPSEQ },
362 { "tcpack", TOK_TCPACK },
363 { "tcpwin", TOK_TCPWIN },
364 { "icmptype", TOK_ICMPTYPES },
365 { "icmptypes", TOK_ICMPTYPES },
366 { "dst-ip", TOK_DSTIP },
367 { "src-ip", TOK_SRCIP },
368 { "dst-port", TOK_DSTPORT },
369 { "src-port", TOK_SRCPORT },
370 { "dst-mac", TOK_DSTMAC },
371 { "src-mac", TOK_SRCMAC },
372 { "proto", TOK_PROTO },
375 { "mac-type", TOK_MACTYPE },
376 { "verrevpath", TOK_VERREVPATH },
377 { "versrcreach", TOK_VERSRCREACH },
378 { "antispoof", TOK_ANTISPOOF },
379 { "ipsec", TOK_IPSEC },
380 { "icmp6type", TOK_ICMP6TYPES },
381 { "icmp6types", TOK_ICMP6TYPES },
382 { "ext6hdr", TOK_EXT6HDR },
383 { "flow-id", TOK_FLOWID },
384 { "ipv6", TOK_IPV6 },
386 { "ipv4", TOK_IPV4 },
388 { "dst-ipv6", TOK_DSTIP6 },
389 { "dst-ip6", TOK_DSTIP6 },
390 { "src-ipv6", TOK_SRCIP6 },
391 { "src-ip6", TOK_SRCIP6 },
392 { "lookup", TOK_LOOKUP },
393 { "flow", TOK_FLOW },
394 { "mark", TOK_MARK },
395 { "defer-action", TOK_SKIPACTION },
396 { "defer-immediate-action", TOK_SKIPACTION },
397 { "//", TOK_COMMENT },
399 { "not", TOK_NOT }, /* pseudo option */
400 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
401 { "or", TOK_OR }, /* pseudo option */
402 { "|", /* escape */ TOK_OR }, /* pseudo option */
403 { "{", TOK_STARTBRACE }, /* pseudo option */
404 { "(", TOK_STARTBRACE }, /* pseudo option */
405 { "}", TOK_ENDBRACE }, /* pseudo option */
406 { ")", TOK_ENDBRACE }, /* pseudo option */
407 { NULL, 0 } /* terminator */
410 void bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg);
411 static int ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
412 ipfw_cfg_lheader **pcfg, size_t *psize);
413 static int ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
414 ipfw_cfg_lheader *cfg, size_t sz, int ac, char **av);
415 static void ipfw_list_tifaces(void);
418 static uint16_t pack_object(struct tidx *tstate, const char *name, int otype);
419 static uint16_t pack_table(struct tidx *tstate, const char *name);
421 static char *table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx);
422 static void object_sort_ctlv(ipfw_obj_ctlv *ctlv);
423 static char *object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx,
429 return (g_co.prog == cmdline_prog_ipfw);
433 * Simple string buffer API.
434 * Used to simplify buffer passing between function and for
435 * transparent overrun handling.
439 * Allocates new buffer of given size @sz.
441 * Returns 0 on success.
444 bp_alloc(struct buf_pr *b, size_t size)
446 memset(b, 0, sizeof(struct buf_pr));
448 if ((b->buf = calloc(1, size)) == NULL)
459 bp_free(struct buf_pr *b)
466 * Flushes buffer so new writer start from beginning.
469 bp_flush(struct buf_pr *b)
478 * Print message specified by @format and args.
479 * Automatically manage buffer space and transparently handle
482 * Returns number of bytes that should have been printed.
485 bprintf(struct buf_pr *b, const char *format, ...)
490 va_start(args, format);
492 i = vsnprintf(b->ptr, b->avail, format, args);
495 if (i < 0 || (size_t)i > b->avail) {
496 /* Overflow or print error */
509 * Special values printer for tablearg-aware opcodes.
512 bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg)
516 bprintf(bp, "%s", str);
517 if (arg == IP_FW_TARG)
518 bprintf(bp, "tablearg");
520 bprintf(bp, "%u", arg);
524 * Helper routine to print a possibly unaligned uint64_t on
525 * various platform. If width > 0, print the value with
526 * the desired width, followed by a space;
527 * otherwise, return the required width.
530 pr_u64(struct buf_pr *b, void *pd, int width)
533 #define U64_FMT "I64"
535 #define U64_FMT "llu"
538 unsigned long long d;
540 bcopy (pd, &u, sizeof(u));
543 bprintf(b, "%*" U64_FMT " ", width, d) :
544 snprintf(NULL, 0, "%" U64_FMT, d) ;
550 safe_calloc(size_t number, size_t size)
552 void *ret = calloc(number, size);
555 err(EX_OSERR, "calloc");
560 safe_realloc(void *ptr, size_t size)
562 void *ret = realloc(ptr, size);
565 err(EX_OSERR, "realloc");
570 * Compare things like interface or table names.
573 stringnum_cmp(const char *a, const char *b)
585 return (strcmp(a, b));
588 struct debug_header {
597 * conditionally runs the command.
598 * Selected options or negative -> getsockopt
601 do_cmd(int optname, void *optval, uintptr_t optlen)
605 if (g_co.debug_only) {
606 struct debug_header dbg = {
609 .total_len = optlen + sizeof(struct debug_header),
611 write(1, &dbg, sizeof(dbg));
612 write(1, optval, optlen);
618 if (ipfw_socket == -1)
619 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
621 err(EX_UNAVAILABLE, "socket");
623 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
624 optname == IP_FW_ADD || optname == IP_FW3 ||
625 optname == IP_FW_NAT_GET_CONFIG ||
627 optname == IP_FW_NAT_GET_LOG) {
630 i = getsockopt(ipfw_socket, IPPROTO_IP, optname, optval,
631 (socklen_t *)optlen);
633 i = setsockopt(ipfw_socket, IPPROTO_IP, optname, optval, optlen);
639 * do_set3 - pass ipfw control cmd to kernel
640 * @optname: option name
641 * @optval: pointer to option data
642 * @optlen: option length
644 * Assumes op3 header is already embedded.
645 * Calls setsockopt() with IP_FW3 as kernel-visible opcode.
646 * Returns 0 on success or errno otherwise.
649 do_set3(int optname, ip_fw3_opheader *op3, size_t optlen)
652 op3->opcode = optname;
654 if (g_co.debug_only) {
655 struct debug_header dbg = {
658 .total_len = optlen, sizeof(struct debug_header),
660 write(1, &dbg, sizeof(dbg));
661 write(1, op3, optlen);
667 if (ipfw_socket == -1)
668 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
670 err(EX_UNAVAILABLE, "socket");
673 return (setsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, optlen));
677 * do_get3 - pass ipfw control cmd to kernel
678 * @optname: option name
679 * @optval: pointer to option data
680 * @optlen: pointer to option length
682 * Assumes op3 header is already embedded.
683 * Calls getsockopt() with IP_FW3 as kernel-visible opcode.
684 * Returns 0 on success or errno otherwise.
687 do_get3(int optname, ip_fw3_opheader *op3, size_t *optlen)
692 op3->opcode = optname;
694 if (g_co.debug_only) {
695 struct debug_header dbg = {
698 .total_len = *optlen + sizeof(struct debug_header),
700 write(1, &dbg, sizeof(dbg));
701 write(1, op3, *optlen);
707 if (ipfw_socket == -1)
708 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
710 err(EX_UNAVAILABLE, "socket");
714 error = getsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, &len);
721 * match_token takes a table and a string, returns the value associated
722 * with the string (-1 in case of failure).
725 match_token(struct _s_x *table, const char *string)
728 uint i = strlen(string);
730 for (pt = table ; i && pt->s != NULL ; pt++)
731 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
737 * match_token_relaxed takes a table and a string, returns the value associated
738 * with the string for the best match.
741 * value from @table for matched records
742 * -1 for non-matched records
743 * -2 if more than one records match @string.
746 match_token_relaxed(struct _s_x *table, const char *string)
754 for (pt = table ; i != 0 && pt->s != NULL ; pt++) {
755 if (strncmp(pt->s, string, i) != 0)
764 return (c > 0 ? -2: -1);
768 get_token(struct _s_x *table, const char *string, const char *errbase)
772 if ((tcmd = match_token_relaxed(table, string)) < 0)
773 errx(EX_USAGE, "%s %s %s",
774 (tcmd == 0) ? "invalid" : "ambiguous", errbase, string);
780 * match_value takes a table and a value, returns the string associated
781 * with the value (NULL in case of failure).
784 match_value(struct _s_x *p, int value)
786 for (; p->s != NULL; p++)
793 concat_tokens(char *buf, size_t bufsize, struct _s_x *table,
794 const char *delimiter)
800 for (sz = 0, pt = table ; pt->s != NULL; pt++) {
801 l = snprintf(buf + sz, bufsize - sz, "%s%s",
802 (sz == 0) ? "" : delimiter, pt->s);
813 * helper function to process a set of flags and set bits in the
817 fill_flags(struct _s_x *flags, char *p, char **e, uint32_t *set,
820 char *q; /* points to the separator */
822 uint32_t *which; /* mask we are working on */
833 val = match_token(flags, p);
839 *which |= (uint32_t)val;
846 print_flags_buffer(char *buf, size_t sz, struct _s_x *list, uint32_t set)
848 char const *comma = "";
851 for (i = 0; list[i].x != 0; i++) {
852 if ((set & list[i].x) == 0)
856 l = snprintf(buf, sz, "%s%s", comma, list[i].s);
857 if (l < 0 || (size_t)l >= sz)
866 * _substrcmp takes two strings and returns 1 if they do not match,
867 * and 0 if they match exactly or the first string is a sub-string
868 * of the second. A warning is printed to stderr in the case that the
869 * first string is a sub-string of the second.
871 * This function will be removed in the future through the usual
872 * deprecation process.
875 _substrcmp(const char *str1, const char* str2)
878 if (strncmp(str1, str2, strlen(str1)) != 0)
881 if (strlen(str1) != strlen(str2))
882 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
888 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
889 * and 0 if they match exactly or the second string is a sub-string
890 * of the first. A warning is printed to stderr in the case that the
891 * first string does not match the third.
893 * This function exists to warn about the bizarre construction
894 * strncmp(str, "by", 2) which is used to allow people to use a shortcut
895 * for "bytes". The problem is that in addition to accepting "by",
896 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
897 * other string beginning with "by".
899 * This function will be removed in the future through the usual
900 * deprecation process.
903 _substrcmp2(const char *str1, const char* str2, const char* str3)
906 if (strncmp(str1, str2, strlen(str2)) != 0)
909 if (strcmp(str1, str3) != 0)
910 warnx("DEPRECATED: '%s' matched '%s'",
916 * prints one port, symbolic or numeric
919 print_port(struct buf_pr *bp, int proto, uint16_t port)
922 if (proto == IPPROTO_ETHERTYPE) {
925 if (g_co.do_resolv && (s = match_value(ether_types, port)) )
926 bprintf(bp, "%s", s);
928 bprintf(bp, "0x%04x", port);
930 struct servent *se = NULL;
931 if (g_co.do_resolv) {
932 struct protoent *pe = getprotobynumber(proto);
934 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
937 bprintf(bp, "%s", se->s_name);
939 bprintf(bp, "%d", port);
943 static struct _s_x _port_name[] = {
944 {"dst-port", O_IP_DSTPORT},
945 {"src-port", O_IP_SRCPORT},
949 {"mac-type", O_MAC_TYPE},
950 {"tcpdatalen", O_TCPDATALEN},
951 {"tcpmss", O_TCPMSS},
952 {"tcpwin", O_TCPWIN},
953 {"tagged", O_TAGGED},
958 * Print the values in a list 16-bit items of the types above.
959 * XXX todo: add support for mask.
962 print_newports(struct buf_pr *bp, const ipfw_insn_u16 *cmd, int proto, int opcode)
964 const uint16_t *p = cmd->ports;
969 sep = match_value(_port_name, opcode);
972 bprintf(bp, " %s", sep);
975 for (i = F_LEN((const ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
976 bprintf(bp, "%s", sep);
977 print_port(bp, proto, p[0]);
980 print_port(bp, proto, p[1]);
987 * Like strtol, but also translates service names into port numbers
988 * for some protocols.
990 * proto == -1 disables the protocol check;
991 * proto == IPPROTO_ETHERTYPE looks up an internal table
992 * proto == <some value in /etc/protocols> matches the values there.
993 * Returns *end == s in case the parameter is not found.
996 strtoport(char *s, char **end, int base, int proto)
1002 *end = s; /* default - not found */
1004 return 0; /* not found */
1007 return strtol(s, end, base);
1010 * find separator. '\\' escapes the next char.
1012 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\' ||
1013 *s1 == '_' || *s1 == '.') ; s1++)
1014 if (*s1 == '\\' && s1[1] != '\0')
1017 buf = safe_calloc(s1 - s + 1, 1);
1020 * copy into a buffer skipping backslashes
1022 for (p = s, i = 0; p != s1 ; p++)
1027 if (proto == IPPROTO_ETHERTYPE) {
1028 i = match_token(ether_types, buf);
1030 if (i != -1) { /* found */
1035 struct protoent *pe = NULL;
1039 pe = getprotobynumber(proto);
1041 se = getservbyname(buf, pe ? pe->p_name : NULL);
1045 return ntohs(se->s_port);
1048 return 0; /* not found */
1052 * Fill the body of the command with the list of port ranges.
1055 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
1057 uint16_t a, b, *p = cmd->ports;
1062 a = strtoport(av, &s, 0, proto);
1063 if (s == av) /* empty or invalid argument */
1066 CHECK_LENGTH(cblen, i + 2);
1069 case '-': /* a range */
1071 b = strtoport(av, &s, 0, proto);
1072 /* Reject expressions like '1-abc' or '1-2-3'. */
1073 if (s == av || (*s != ',' && *s != '\0'))
1078 case ',': /* comma separated list */
1083 warnx("port list: invalid separator <%c> in <%s>",
1093 if (i + 1 > F_LEN_MASK)
1094 errx(EX_DATAERR, "too many ports/ranges\n");
1095 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
1101 * Fill the body of the command with the list of DiffServ codepoints.
1104 fill_dscp(ipfw_insn *cmd, char *av, int cblen)
1106 uint32_t *low, *high;
1110 cmd->opcode = O_DSCP;
1111 cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
1115 low = (uint32_t *)(cmd + 1);
1128 if ((code = match_token(f_ipdscp, s)) == -1)
1129 errx(EX_DATAERR, "Unknown DSCP code");
1131 code = strtoul(s, NULL, 10);
1132 if (code < 0 || code > 63)
1133 errx(EX_DATAERR, "Invalid DSCP value");
1137 *high |= 1 << (code - 32);
1146 * Fill the body of the command with mark value and mask.
1149 fill_mark(ipfw_insn *cmd, char *av, int cblen)
1151 uint32_t *value, *mask;
1154 cmd->opcode = O_MARK;
1155 cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
1159 value = (uint32_t *)(cmd + 1);
1162 value_str = strsep(&av, ":");
1164 if (strcmp(value_str, "tablearg") == 0) {
1165 cmd->arg1 = IP_FW_TARG;
1168 /* This is not a tablearg */
1169 cmd->arg1 |= 0x8000;
1170 *value = strtoul(value_str, NULL, 0);
1173 *mask = strtoul(av, NULL, 0);
1177 if ((*value & *mask) != *value)
1178 errx(EX_DATAERR, "Static mark value: some bits in value are"
1179 " set that will be masked out by mask "
1180 "(%#x & %#x) = %#x != %#x",
1181 *value, *mask, (*value & *mask), *value);
1184 static struct _s_x icmpcodes[] = {
1185 { "net", ICMP_UNREACH_NET },
1186 { "host", ICMP_UNREACH_HOST },
1187 { "protocol", ICMP_UNREACH_PROTOCOL },
1188 { "port", ICMP_UNREACH_PORT },
1189 { "needfrag", ICMP_UNREACH_NEEDFRAG },
1190 { "srcfail", ICMP_UNREACH_SRCFAIL },
1191 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
1192 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
1193 { "isolated", ICMP_UNREACH_ISOLATED },
1194 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
1195 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
1196 { "tosnet", ICMP_UNREACH_TOSNET },
1197 { "toshost", ICMP_UNREACH_TOSHOST },
1198 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
1199 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
1200 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
1205 get_reject_code(const char *str)
1210 val = strtoul(str, &s, 0);
1211 if (s == str || *s != '\0' || val >= 0x100)
1212 val = match_token(icmpcodes, str);
1214 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
1219 print_reject_code(struct buf_pr *bp, uint16_t code)
1223 if ((s = match_value(icmpcodes, code)) != NULL)
1224 bprintf(bp, "unreach %s", s);
1226 bprintf(bp, "unreach %u", code);
1230 * Returns the number of bits set (from left) in a contiguous bitmask,
1231 * or -1 if the mask is not contiguous.
1232 * XXX this needs a proper fix.
1233 * This effectively works on masks in big-endian (network) format.
1234 * when compiled on little endian architectures.
1236 * First bit is bit 7 of the first byte -- note, for MAC addresses,
1237 * the first bit on the wire is bit 0 of the first byte.
1238 * len is the max length in bits.
1241 contigmask(const uint8_t *p, int len)
1245 for (i=0; i<len ; i++)
1246 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
1248 for (n=i+1; n < len; n++)
1249 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
1250 return -1; /* mask not contiguous */
1255 * print flags set/clear in the two bitmasks passed as parameters.
1256 * There is a specialized check for f_tcpflags.
1259 print_flags(struct buf_pr *bp, char const *name, const ipfw_insn *cmd,
1262 char const *comma = "";
1264 uint8_t set = cmd->arg1 & 0xff;
1265 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
1267 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
1268 bprintf(bp, " setup");
1272 bprintf(bp, " %s ", name);
1273 for (i=0; list[i].x != 0; i++) {
1274 if (set & list[i].x) {
1276 bprintf(bp, "%s%s", comma, list[i].s);
1279 if (clear & list[i].x) {
1280 clear &= ~list[i].x;
1281 bprintf(bp, "%s!%s", comma, list[i].s);
1289 * Print the ip address contained in a command.
1292 print_ip(struct buf_pr *bp, const struct format_opts *fo,
1293 const ipfw_insn_ip *cmd)
1295 struct hostent *he = NULL;
1296 const struct in_addr *ia;
1297 const uint32_t *a = ((const ipfw_insn_u32 *)cmd)->d;
1298 uint32_t len = F_LEN((const ipfw_insn *)cmd);
1302 if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
1305 arg = match_value(lookup_keys, a[1]);
1306 t = table_search_ctlv(fo->tstate,
1307 ((const ipfw_insn *)cmd)->arg1);
1308 bprintf(bp, "lookup %s %s", arg, t);
1311 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
1315 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
1316 cmd->o.opcode == O_IP_DST_LOOKUP) {
1317 t = table_search_ctlv(fo->tstate,
1318 ((const ipfw_insn *)cmd)->arg1);
1319 bprintf(bp, "table(%s", t);
1320 if (len == F_INSN_SIZE(ipfw_insn_u32))
1321 bprintf(bp, ",%u", *a);
1325 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
1326 const uint32_t *map = (const uint32_t *)&cmd->mask;
1327 struct in_addr addr;
1332 x = cmd->o.arg1 - 1;
1334 addr.s_addr = htonl(cmd->addr.s_addr);
1335 bprintf(bp, "%s/%d", inet_ntoa(addr),
1336 contigmask((uint8_t *)&x, 32));
1337 x = cmd->addr.s_addr;
1338 x &= 0xff; /* base */
1340 * Print bits and ranges.
1341 * Locate first bit set (i), then locate first bit unset (j).
1342 * If we have 3+ consecutive bits set, then print them as a
1343 * range, otherwise only print the initial bit and rescan.
1345 for (i=0; i < cmd->o.arg1; i++)
1346 if (map[i/32] & (1<<(i & 31))) {
1347 for (j=i+1; j < cmd->o.arg1; j++)
1348 if (!(map[ j/32] & (1<<(j & 31))))
1350 bprintf(bp, "%c%d", comma, i+x);
1351 if (j>i+2) { /* range has at least 3 elements */
1352 bprintf(bp, "-%d", j-1+x);
1361 * len == 2 indicates a single IP, whereas lists of 1 or more
1362 * addr/mask pairs have len = (2n+1). We convert len to n so we
1363 * use that to count the number of entries.
1365 for (len = len / 2; len > 0; len--, a += 2) {
1366 int mb = /* mask length */
1367 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1368 32 : contigmask((const uint8_t *)&(a[1]), 32);
1369 if (mb == 32 && g_co.do_resolv)
1370 he = gethostbyaddr((const char *)&(a[0]), sizeof(in_addr_t),
1372 if (he != NULL) /* resolved to name */
1373 bprintf(bp, "%s", he->h_name);
1374 else if (mb == 0) /* any */
1376 else { /* numeric IP followed by some kind of mask */
1377 ia = (const struct in_addr *)&a[0];
1378 bprintf(bp, "%s", inet_ntoa(*ia));
1380 ia = (const struct in_addr *)&a[1];
1381 bprintf(bp, ":%s", inet_ntoa(*ia));
1383 bprintf(bp, "/%d", mb);
1391 * prints a MAC address/mask pair
1394 format_mac(struct buf_pr *bp, const uint8_t *addr, const uint8_t *mask)
1396 int l = contigmask(mask, 48);
1399 bprintf(bp, " any");
1401 bprintf(bp, " %02x:%02x:%02x:%02x:%02x:%02x",
1402 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1404 bprintf(bp, "&%02x:%02x:%02x:%02x:%02x:%02x",
1405 mask[0], mask[1], mask[2],
1406 mask[3], mask[4], mask[5]);
1408 bprintf(bp, "/%d", l);
1413 print_mac(struct buf_pr *bp, const ipfw_insn_mac *mac)
1416 bprintf(bp, " MAC");
1417 format_mac(bp, mac->addr, mac->mask);
1418 format_mac(bp, mac->addr + 6, mac->mask + 6);
1422 print_mac_lookup(struct buf_pr *bp, const struct format_opts *fo,
1423 const ipfw_insn *cmd)
1425 uint32_t len = F_LEN(cmd);
1430 t = table_search_ctlv(fo->tstate, cmd->arg1);
1431 bprintf(bp, "table(%s", t);
1432 if (len == F_INSN_SIZE(ipfw_insn_u32))
1433 bprintf(bp, ",%u", ((const ipfw_insn_u32 *)cmd)->d[0]);
1438 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1447 type = strtoul(av, &av, 0);
1449 if (*av != ',' && *av != '\0')
1450 errx(EX_DATAERR, "invalid ICMP type");
1453 errx(EX_DATAERR, "ICMP type out of range");
1455 cmd->d[0] |= 1 << type;
1457 cmd->o.opcode = O_ICMPTYPE;
1458 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1462 print_icmptypes(struct buf_pr *bp, const ipfw_insn_u32 *cmd)
1467 bprintf(bp, " icmptypes");
1468 for (i = 0; i < 32; i++) {
1469 if ( (cmd->d[0] & (1 << (i))) == 0)
1471 bprintf(bp, "%c%d", sep, i);
1477 print_dscp(struct buf_pr *bp, const ipfw_insn_u32 *cmd)
1484 bprintf(bp, " dscp");
1487 if (*v & (1 << i)) {
1488 if ((code = match_value(f_ipdscp, i)) != NULL)
1489 bprintf(bp, "%c%s", sep, code);
1491 bprintf(bp, "%c%d", sep, i);
1495 if ((++i % 32) == 0)
1500 #define insntod(cmd, type) ((const ipfw_insn_ ## type *)(cmd))
1502 struct ip_fw_rule *rule;
1503 const ipfw_insn *eaction;
1506 #define HAVE_PROTO 0x0001
1507 #define HAVE_SRCIP 0x0002
1508 #define HAVE_DSTIP 0x0004
1509 #define HAVE_PROBE_STATE 0x0008
1515 init_show_state(struct show_state *state, struct ip_fw_rule *rule)
1518 state->printed = calloc(rule->cmd_len, sizeof(uint8_t));
1519 if (state->printed == NULL)
1522 state->eaction = NULL;
1525 state->or_block = 0;
1530 free_show_state(struct show_state *state)
1533 free(state->printed);
1537 is_printed_opcode(struct show_state *state, const ipfw_insn *cmd)
1540 return (state->printed[cmd - state->rule->cmd]);
1544 mark_printed(struct show_state *state, const ipfw_insn *cmd)
1547 state->printed[cmd - state->rule->cmd] = 1;
1551 print_limit_mask(struct buf_pr *bp, const ipfw_insn_limit *limit)
1553 struct _s_x *p = limit_masks;
1554 char const *comma = " ";
1557 for (x = limit->limit_mask; p->x != 0; p++) {
1558 if ((x & p->x) == p->x) {
1560 bprintf(bp, "%s%s", comma, p->s);
1564 bprint_uint_arg(bp, " ", limit->conn_limit);
1568 print_instruction(struct buf_pr *bp, const struct format_opts *fo,
1569 struct show_state *state, const ipfw_insn *cmd)
1571 struct protoent *pe;
1577 if (is_printed_opcode(state, cmd))
1579 if ((cmd->len & F_OR) != 0 && state->or_block == 0)
1581 if (cmd->opcode != O_IN && (cmd->len & F_NOT) != 0)
1582 bprintf(bp, " not");
1584 switch (cmd->opcode) {
1586 d = 1.0 * insntod(cmd, u32)->d[0] / 0x7fffffff;
1587 bprintf(bp, "prob %f ", d);
1589 case O_PROBE_STATE: /* no need to print anything here */
1590 state->flags |= HAVE_PROBE_STATE;
1593 case O_IP_SRC_LOOKUP:
1597 if (state->flags & HAVE_SRCIP)
1598 bprintf(bp, " src-ip");
1599 print_ip(bp, fo, insntod(cmd, ip));
1602 case O_IP_DST_LOOKUP:
1606 if (state->flags & HAVE_DSTIP)
1607 bprintf(bp, " dst-ip");
1608 print_ip(bp, fo, insntod(cmd, ip));
1611 case O_IP6_SRC_MASK:
1613 if (state->flags & HAVE_SRCIP)
1614 bprintf(bp, " src-ip6");
1615 print_ip6(bp, insntod(cmd, ip6));
1618 case O_IP6_DST_MASK:
1620 if (state->flags & HAVE_DSTIP)
1621 bprintf(bp, " dst-ip6");
1622 print_ip6(bp, insntod(cmd, ip6));
1624 case O_MAC_SRC_LOOKUP:
1625 bprintf(bp, " src-mac");
1626 print_mac_lookup(bp, fo, cmd);
1628 case O_MAC_DST_LOOKUP:
1629 bprintf(bp, " dst-mac");
1630 print_mac_lookup(bp, fo, cmd);
1633 print_flow6id(bp, insntod(cmd, u32));
1637 print_newports(bp, insntod(cmd, u16), state->proto,
1638 (state->flags & (HAVE_SRCIP | HAVE_DSTIP)) ==
1639 (HAVE_SRCIP | HAVE_DSTIP) ? cmd->opcode: 0);
1642 pe = getprotobynumber(cmd->arg1);
1643 if (state->flags & HAVE_PROTO)
1644 bprintf(bp, " proto");
1646 bprintf(bp, " %s", pe->p_name);
1648 bprintf(bp, " %u", cmd->arg1);
1649 state->proto = cmd->arg1;
1652 print_mac(bp, insntod(cmd, mac));
1655 print_newports(bp, insntod(cmd, u16),
1656 IPPROTO_ETHERTYPE, cmd->opcode);
1659 print_flags(bp, "frag", cmd, f_ipoff);
1662 bprintf(bp, " fib %u", cmd->arg1);
1665 bprintf(bp, " sockarg");
1668 bprintf(bp, cmd->len & F_NOT ? " out" : " in");
1671 switch (cmd->arg1) {
1673 bprintf(bp, " diverted");
1676 bprintf(bp, " diverted-output");
1679 bprintf(bp, " diverted-loopback");
1682 bprintf(bp, " diverted-?<%u>", cmd->arg1);
1687 bprintf(bp, " layer2");
1692 if (cmd->opcode == O_XMIT)
1694 else if (cmd->opcode == O_RECV)
1696 else /* if (cmd->opcode == O_VIA) */
1698 switch (insntod(cmd, if)->name[0]) {
1700 bprintf(bp, " %s %s", s,
1701 inet_ntoa(insntod(cmd, if)->p.ip));
1704 bprintf(bp, " %s table(%s)", s,
1705 table_search_ctlv(fo->tstate,
1706 insntod(cmd, if)->p.kidx));
1709 bprintf(bp, " %s %s", s,
1710 insntod(cmd, if)->name);
1713 case O_IP_FLOW_LOOKUP:
1714 s = table_search_ctlv(fo->tstate, cmd->arg1);
1715 bprintf(bp, " flow table(%s", s);
1716 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))
1717 bprintf(bp, ",%u", insntod(cmd, u32)->d[0]);
1726 if (F_LEN(cmd) == 1) {
1727 switch (cmd->opcode) {
1750 bprintf(bp, " %s %u", s, cmd->arg1);
1752 print_newports(bp, insntod(cmd, u16), 0,
1756 bprintf(bp, " ipver %u", cmd->arg1);
1758 case O_IPPRECEDENCE:
1759 bprintf(bp, " ipprecedence %u", cmd->arg1 >> 5);
1762 print_dscp(bp, insntod(cmd, u32));
1765 print_flags(bp, "ipoptions", cmd, f_ipopts);
1768 print_flags(bp, "iptos", cmd, f_iptos);
1771 print_icmptypes(bp, insntod(cmd, u32));
1774 bprintf(bp, " established");
1777 print_flags(bp, "tcpflags", cmd, f_tcpflags);
1780 print_flags(bp, "tcpoptions", cmd, f_tcpopts);
1783 bprintf(bp, " tcpack %d",
1784 ntohl(insntod(cmd, u32)->d[0]));
1787 bprintf(bp, " tcpseq %d",
1788 ntohl(insntod(cmd, u32)->d[0]));
1791 pwd = getpwuid(insntod(cmd, u32)->d[0]);
1793 bprintf(bp, " uid %s", pwd->pw_name);
1795 bprintf(bp, " uid %u",
1796 insntod(cmd, u32)->d[0]);
1799 grp = getgrgid(insntod(cmd, u32)->d[0]);
1801 bprintf(bp, " gid %s", grp->gr_name);
1803 bprintf(bp, " gid %u",
1804 insntod(cmd, u32)->d[0]);
1807 bprintf(bp, " jail %d", insntod(cmd, u32)->d[0]);
1810 bprintf(bp, " verrevpath");
1813 bprintf(bp, " versrcreach");
1816 bprintf(bp, " antispoof");
1819 bprintf(bp, " ipsec");
1822 bprintf(bp, " // %s", (const char *)(cmd + 1));
1825 if (state->flags & HAVE_PROBE_STATE)
1826 bprintf(bp, " keep-state");
1828 bprintf(bp, " record-state");
1830 object_search_ctlv(fo->tstate, cmd->arg1,
1831 IPFW_TLV_STATE_NAME));
1834 if (state->flags & HAVE_PROBE_STATE)
1835 bprintf(bp, " limit");
1837 bprintf(bp, " set-limit");
1838 print_limit_mask(bp, insntod(cmd, limit));
1840 object_search_ctlv(fo->tstate, cmd->arg1,
1841 IPFW_TLV_STATE_NAME));
1844 if (state->flags & HAVE_PROTO)
1845 bprintf(bp, " proto");
1846 bprintf(bp, " ip6");
1849 if (state->flags & HAVE_PROTO)
1850 bprintf(bp, " proto");
1851 bprintf(bp, " ip4");
1854 print_icmp6types(bp, insntod(cmd, u32));
1857 print_ext6hdr(bp, cmd);
1860 if (F_LEN(cmd) == 1)
1861 bprint_uint_arg(bp, " tagged ", cmd->arg1);
1863 print_newports(bp, insntod(cmd, u16),
1867 bprintf(bp, " defer-immediate-action");
1870 bprintf(bp, " mark");
1871 if (cmd->arg1 == IP_FW_TARG)
1872 bprintf(bp, " tablearg");
1875 ((const ipfw_insn_u32 *)cmd)->d[0]);
1877 if (((const ipfw_insn_u32 *)cmd)->d[1] != 0xFFFFFFFF)
1879 ((const ipfw_insn_u32 *)cmd)->d[1]);
1883 bprintf(bp, " [opcode %d len %d]", cmd->opcode,
1886 if (cmd->len & F_OR) {
1888 state->or_block = 1;
1889 } else if (state->or_block != 0) {
1891 state->or_block = 0;
1893 mark_printed(state, cmd);
1899 print_opcode(struct buf_pr *bp, struct format_opts *fo,
1900 struct show_state *state, int opcode)
1905 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
1906 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1907 /* We use zero opcode to print the rest of options */
1908 if (opcode >= 0 && cmd->opcode != opcode)
1911 * Skip O_NOP, when we printing the rest
1912 * of options, it will be handled separately.
1914 if (cmd->opcode == O_NOP && opcode != O_NOP)
1916 if (!print_instruction(bp, fo, state, cmd))
1924 print_fwd(struct buf_pr *bp, const ipfw_insn *cmd)
1926 char buf[INET6_ADDRSTRLEN + IF_NAMESIZE + 2];
1927 const ipfw_insn_sa6 *sa6;
1928 const ipfw_insn_sa *sa;
1931 if (cmd->opcode == O_FORWARD_IP) {
1932 sa = insntod(cmd, sa);
1933 port = sa->sa.sin_port;
1934 if (sa->sa.sin_addr.s_addr == INADDR_ANY)
1935 bprintf(bp, "fwd tablearg");
1937 bprintf(bp, "fwd %s", inet_ntoa(sa->sa.sin_addr));
1939 sa6 = insntod(cmd, sa6);
1940 port = sa6->sa.sin6_port;
1941 bprintf(bp, "fwd ");
1942 if (getnameinfo((const struct sockaddr *)&sa6->sa,
1943 sizeof(struct sockaddr_in6), buf, sizeof(buf), NULL, 0,
1944 NI_NUMERICHOST) == 0)
1945 bprintf(bp, "%s", buf);
1948 bprintf(bp, ",%u", port);
1952 print_action_instruction(struct buf_pr *bp, const struct format_opts *fo,
1953 struct show_state *state, const ipfw_insn *cmd)
1957 if (is_printed_opcode(state, cmd))
1959 switch (cmd->opcode) {
1961 bprintf(bp, "check-state");
1963 s = object_search_ctlv(fo->tstate, cmd->arg1,
1964 IPFW_TLV_STATE_NAME);
1967 bprintf(bp, " :%s", s ? s: "any");
1970 bprintf(bp, "allow");
1973 bprintf(bp, "count");
1976 bprintf(bp, "deny");
1979 if (cmd->arg1 == ICMP_REJECT_RST)
1980 bprintf(bp, "reset");
1981 else if (cmd->arg1 == ICMP_REJECT_ABORT)
1982 bprintf(bp, "abort");
1983 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1984 bprintf(bp, "reject");
1985 else if (cmd->arg1 == ICMP_UNREACH_NEEDFRAG &&
1986 cmd->len == F_INSN_SIZE(ipfw_insn_u16))
1987 bprintf(bp, "needfrag %u",
1988 ((const ipfw_insn_u16 *)cmd)->ports[0]);
1990 print_reject_code(bp, cmd->arg1);
1993 if (cmd->arg1 == ICMP6_UNREACH_RST)
1994 bprintf(bp, "reset6");
1995 else if (cmd->arg1 == ICMP6_UNREACH_ABORT)
1996 bprintf(bp, "abort6");
1998 print_unreach6_code(bp, cmd->arg1);
2001 bprint_uint_arg(bp, "skipto ", cmd->arg1);
2004 bprint_uint_arg(bp, "pipe ", cmd->arg1);
2007 bprint_uint_arg(bp, "queue ", cmd->arg1);
2010 bprint_uint_arg(bp, "divert ", cmd->arg1);
2013 bprint_uint_arg(bp, "tee ", cmd->arg1);
2016 bprint_uint_arg(bp, "netgraph ", cmd->arg1);
2019 bprint_uint_arg(bp, "ngtee ", cmd->arg1);
2026 if (insntod(cmd, log)->max_log > 0)
2027 bprintf(bp, " log logamount %d",
2028 insntod(cmd, log)->max_log);
2030 bprintf(bp, " log");
2034 print_altq_cmd(bp, insntod(cmd, altq));
2038 bprint_uint_arg(bp, cmd->len & F_NOT ? " untag ":
2039 " tag ", cmd->arg1);
2042 if (cmd->arg1 != IP_FW_NAT44_GLOBAL)
2043 bprint_uint_arg(bp, "nat ", cmd->arg1);
2045 bprintf(bp, "nat global");
2048 if (cmd->arg1 == IP_FW_TARG)
2049 bprint_uint_arg(bp, "setfib ", cmd->arg1);
2051 bprintf(bp, "setfib %u", cmd->arg1 & 0x7FFF);
2053 case O_EXTERNAL_ACTION:
2055 * The external action can consists of two following
2056 * each other opcodes - O_EXTERNAL_ACTION and
2057 * O_EXTERNAL_INSTANCE. The first contains the ID of
2058 * name of external action. The second contains the ID
2059 * of name of external action instance.
2060 * NOTE: in case when external action has no named
2061 * instances support, the second opcode isn't needed.
2063 state->eaction = cmd;
2064 s = object_search_ctlv(fo->tstate, cmd->arg1,
2066 if (match_token(rule_eactions, s) != -1)
2067 bprintf(bp, "%s", s);
2069 bprintf(bp, "eaction %s", s);
2071 case O_EXTERNAL_INSTANCE:
2072 if (state->eaction == NULL)
2075 * XXX: we need to teach ipfw(9) to rewrite opcodes
2076 * in the user buffer on rule addition. When we add
2077 * the rule, we specify zero TLV type for
2078 * O_EXTERNAL_INSTANCE object. To show correct
2079 * rule after `ipfw add` we need to search instance
2080 * name with zero type. But when we do `ipfw show`
2081 * we calculate TLV type using IPFW_TLV_EACTION_NAME()
2084 s = object_search_ctlv(fo->tstate, cmd->arg1, 0);
2086 s = object_search_ctlv(fo->tstate,
2087 cmd->arg1, IPFW_TLV_EACTION_NAME(
2088 state->eaction->arg1));
2089 bprintf(bp, " %s", s);
2091 case O_EXTERNAL_DATA:
2092 if (state->eaction == NULL)
2095 * Currently we support data formatting only for
2096 * external data with datalen u16. For unknown data
2097 * print its size in bytes.
2099 if (cmd->len == F_INSN_SIZE(ipfw_insn))
2100 bprintf(bp, " %u", cmd->arg1);
2102 bprintf(bp, " %ubytes",
2103 cmd->len * sizeof(uint32_t));
2106 if (cmd->arg1 == IP_FW_TARG) {
2107 bprintf(bp, "setdscp tablearg");
2110 s = match_value(f_ipdscp, cmd->arg1 & 0x3F);
2112 bprintf(bp, "setdscp %s", s);
2114 bprintf(bp, "setdscp %u", cmd->arg1 & 0x3F);
2117 bprintf(bp, "reass");
2120 if (cmd->len & F_NOT)
2121 bprintf(bp, "return");
2123 bprint_uint_arg(bp, "call ", cmd->arg1);
2126 if (cmd->arg1 == IP_FW_TARG) {
2127 bprintf(bp, "setmark tablearg");
2130 bprintf(bp, "setmark %#x", ((const ipfw_insn_u32 *)cmd)->d[0]);
2133 bprintf(bp, "** unrecognized action %d len %d ",
2134 cmd->opcode, cmd->len);
2136 mark_printed(state, cmd);
2143 print_action(struct buf_pr *bp, struct format_opts *fo,
2144 struct show_state *state, uint8_t opcode)
2149 for (l = state->rule->cmd_len - state->rule->act_ofs,
2150 cmd = ACTION_PTR(state->rule); l > 0;
2151 l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2152 if (cmd->opcode != opcode)
2154 if (!print_action_instruction(bp, fo, state, cmd))
2162 print_proto(struct buf_pr *bp, struct format_opts *fo,
2163 struct show_state *state)
2166 int l, proto, ip4, ip6;
2168 /* Count all O_PROTO, O_IP4, O_IP6 instructions. */
2169 proto = ip4 = ip6 = 0;
2170 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2171 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2172 switch (cmd->opcode) {
2178 if (cmd->len & F_OR)
2183 if (cmd->len & F_OR)
2190 if (proto == 0 && ip4 == 0 && ip6 == 0) {
2191 state->proto = IPPROTO_IP;
2192 state->flags |= HAVE_PROTO;
2196 /* To handle the case { ip4 or ip6 }, print opcode with F_OR first */
2199 cmd = print_opcode(bp, fo, state, ip4 > ip6 ? O_IP4: O_IP6);
2200 if (cmd != NULL && (cmd->len & F_OR))
2201 cmd = print_opcode(bp, fo, state, ip4 > ip6 ? O_IP6: O_IP4);
2202 if (cmd == NULL || (cmd->len & F_OR))
2203 for (l = proto; l > 0; l--) {
2204 cmd = print_opcode(bp, fo, state, O_PROTO);
2205 if (cmd == NULL || (cmd->len & F_OR) == 0)
2208 /* Initialize proto, it is used by print_newports() */
2209 state->flags |= HAVE_PROTO;
2210 if (state->proto == 0 && ip6 != 0)
2211 state->proto = IPPROTO_IPV6;
2215 match_opcode(int opcode, const int opcodes[], size_t nops)
2219 for (i = 0; i < nops; i++)
2220 if (opcode == opcodes[i])
2226 print_address(struct buf_pr *bp, struct format_opts *fo,
2227 struct show_state *state, const int opcodes[], size_t nops, int portop,
2231 int count, l, portcnt, pf;
2233 count = portcnt = 0;
2234 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2235 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2236 if (match_opcode(cmd->opcode, opcodes, nops))
2238 else if (cmd->opcode == portop)
2242 bprintf(bp, " any");
2243 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2244 l > 0 && count > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2245 if (!match_opcode(cmd->opcode, opcodes, nops))
2247 print_instruction(bp, fo, state, cmd);
2248 if ((cmd->len & F_OR) == 0)
2253 * If several O_IP_?PORT opcodes specified, leave them to the
2257 for (l = state->rule->act_ofs, cmd = state->rule->cmd, pf = 0;
2258 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2259 if (cmd->opcode != portop) {
2260 pf = (cmd->len & F_OR);
2263 /* Print opcode iff it is not in OR block. */
2264 if (pf == 0 && (cmd->len & F_OR) == 0)
2265 print_instruction(bp, fo, state, cmd);
2269 state->flags |= flag;
2272 static const int action_opcodes[] = {
2273 O_CHECK_STATE, O_ACCEPT, O_COUNT, O_DENY, O_REJECT,
2274 O_UNREACH6, O_SKIPTO, O_PIPE, O_QUEUE, O_DIVERT, O_TEE,
2275 O_NETGRAPH, O_NGTEE, O_FORWARD_IP, O_FORWARD_IP6, O_NAT,
2276 O_SETFIB, O_SETDSCP, O_REASS, O_CALLRETURN, O_SETMARK,
2277 /* keep the following opcodes at the end of the list */
2278 O_EXTERNAL_ACTION, O_EXTERNAL_INSTANCE, O_EXTERNAL_DATA
2281 static const int modifier_opcodes[] = {
2282 O_LOG, O_ALTQ, O_TAG
2285 static const int src_opcodes[] = {
2286 O_IP_SRC, O_IP_SRC_LOOKUP, O_IP_SRC_MASK, O_IP_SRC_ME,
2287 O_IP_SRC_SET, O_IP6_SRC, O_IP6_SRC_MASK, O_IP6_SRC_ME
2290 static const int dst_opcodes[] = {
2291 O_IP_DST, O_IP_DST_LOOKUP, O_IP_DST_MASK, O_IP_DST_ME,
2292 O_IP_DST_SET, O_IP6_DST, O_IP6_DST_MASK, O_IP6_DST_ME
2296 show_static_rule(struct cmdline_opts *co, struct format_opts *fo,
2297 struct buf_pr *bp, struct ip_fw_rule *rule, struct ip_fw_bcounter *cntr)
2299 static int twidth = 0;
2300 struct show_state state;
2304 /* Print # DISABLED or skip the rule */
2305 if ((fo->set_mask & (1 << rule->set)) == 0) {
2310 bprintf(bp, "# DISABLED ");
2312 if (init_show_state(&state, rule) != 0) {
2313 warn("init_show_state() failed");
2316 bprintf(bp, "%05u ", rule->rulenum);
2318 /* only if counters are available */
2320 /* Print counters if enabled */
2321 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2322 pr_u64(bp, &cntr->pcnt, fo->pcwidth);
2323 pr_u64(bp, &cntr->bcnt, fo->bcwidth);
2326 /* Print timestamp */
2327 if (co->do_time == TIMESTAMP_NUMERIC)
2328 bprintf(bp, "%10u ", cntr->timestamp);
2329 else if (co->do_time == TIMESTAMP_STRING) {
2331 time_t t = (time_t)0;
2334 strcpy(timestr, ctime(&t));
2335 *strchr(timestr, '\n') = '\0';
2336 twidth = strlen(timestr);
2338 if (cntr->timestamp > 0) {
2339 t = _long_to_time(cntr->timestamp);
2341 strcpy(timestr, ctime(&t));
2342 *strchr(timestr, '\n') = '\0';
2343 bprintf(bp, "%s ", timestr);
2345 bprintf(bp, "%*s ", twidth, "");
2350 /* Print set number */
2352 bprintf(bp, "set %d ", rule->set);
2354 /* Print the optional "match probability" */
2355 cmd = print_opcode(bp, fo, &state, O_PROB);
2356 /* Print rule action */
2357 for (i = 0; i < nitems(action_opcodes); i++) {
2358 cmd = print_action(bp, fo, &state, action_opcodes[i]);
2361 /* Handle special cases */
2362 switch (cmd->opcode) {
2365 case O_EXTERNAL_ACTION:
2366 case O_EXTERNAL_INSTANCE:
2367 /* External action can have several instructions */
2372 /* Print rule modifiers */
2373 for (i = 0; i < nitems(modifier_opcodes); i++)
2374 print_action(bp, fo, &state, modifier_opcodes[i]);
2378 if (co->comment_only != 0)
2381 if (rule->flags & IPFW_RULE_JUSTOPTS) {
2382 state.flags |= HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP;
2386 print_proto(bp, fo, &state);
2387 if (co->do_compact != 0 && (rule->flags & IPFW_RULE_NOOPT))
2391 bprintf(bp, " from");
2392 print_address(bp, fo, &state, src_opcodes, nitems(src_opcodes),
2393 O_IP_SRCPORT, HAVE_SRCIP);
2395 /* Print destination */
2397 print_address(bp, fo, &state, dst_opcodes, nitems(dst_opcodes),
2398 O_IP_DSTPORT, HAVE_DSTIP);
2401 /* Print the rest of options */
2402 while (print_opcode(bp, fo, &state, -1))
2405 /* Print comment at the end */
2406 cmd = print_opcode(bp, fo, &state, O_NOP);
2407 if (co->comment_only != 0 && cmd == NULL)
2408 bprintf(bp, " // ...");
2410 free_show_state(&state);
2414 show_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2415 struct buf_pr *bp, ipfw_dyn_rule *d)
2417 struct protoent *pe;
2420 char buf[INET6_ADDRSTRLEN];
2422 if (d->expire == 0 && d->dyn_type != O_LIMIT_PARENT)
2425 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2426 bprintf(bp, "%05d", rulenum);
2427 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2429 pr_u64(bp, &d->pcnt, fo->pcwidth);
2430 pr_u64(bp, &d->bcnt, fo->bcwidth);
2431 bprintf(bp, "(%ds)", d->expire);
2433 switch (d->dyn_type) {
2434 case O_LIMIT_PARENT:
2435 bprintf(bp, " PARENT %d", d->count);
2438 bprintf(bp, " LIMIT");
2440 case O_KEEP_STATE: /* bidir, no mask */
2441 bprintf(bp, " STATE");
2445 if ((pe = getprotobynumber(d->id.proto)) != NULL)
2446 bprintf(bp, " %s", pe->p_name);
2448 bprintf(bp, " proto %u", d->id.proto);
2450 if (d->id.addr_type == 4) {
2451 a.s_addr = htonl(d->id.src_ip);
2452 bprintf(bp, " %s %d", inet_ntoa(a), d->id.src_port);
2454 a.s_addr = htonl(d->id.dst_ip);
2455 bprintf(bp, " <-> %s %d", inet_ntoa(a), d->id.dst_port);
2456 } else if (d->id.addr_type == 6) {
2457 bprintf(bp, " %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
2458 sizeof(buf)), d->id.src_port);
2459 bprintf(bp, " <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6,
2460 buf, sizeof(buf)), d->id.dst_port);
2462 bprintf(bp, " UNKNOWN <-> UNKNOWN");
2464 bprintf(bp, " :%s", object_search_ctlv(fo->tstate,
2465 d->kidx, IPFW_TLV_STATE_NAME));
2467 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
2468 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
2470 bprintf(bp, " state 0x%08x%s", d->state,
2471 d->state ? " ": ",");
2472 if (d->state & IPFW_DYN_ORPHANED)
2473 bprintf(bp, "ORPHANED,");
2474 if ((d->state & BOTH_SYN) == BOTH_SYN)
2475 bprintf(bp, "BOTH_SYN,");
2477 if (d->state & TH_SYN)
2478 bprintf(bp, "F_SYN,");
2479 if (d->state & (TH_SYN << 8))
2480 bprintf(bp, "R_SYN,");
2482 if ((d->state & BOTH_FIN) == BOTH_FIN)
2483 bprintf(bp, "BOTH_FIN,");
2485 if (d->state & TH_FIN)
2486 bprintf(bp, "F_FIN,");
2487 if (d->state & (TH_FIN << 8))
2488 bprintf(bp, "R_FIN,");
2490 bprintf(bp, " f_ack 0x%x, r_ack 0x%x", d->ack_fwd,
2496 do_range_cmd(int cmd, ipfw_range_tlv *rt)
2498 ipfw_range_header rh;
2501 memset(&rh, 0, sizeof(rh));
2502 memcpy(&rh.range, rt, sizeof(*rt));
2503 rh.range.head.length = sizeof(*rt);
2504 rh.range.head.type = IPFW_TLV_RANGE;
2507 if (do_get3(cmd, &rh.opheader, &sz) != 0)
2509 /* Save number of matched objects */
2510 rt->new_set = rh.range.new_set;
2515 * This one handles all set-related commands
2516 * ipfw set { show | enable | disable }
2518 * ipfw set move X to Y
2519 * ipfw set move rule X to Y
2522 ipfw_sets_handler(char *av[])
2533 memset(&rt, 0, sizeof(rt));
2536 errx(EX_USAGE, "set needs command");
2537 if (_substrcmp(*av, "show") == 0) {
2538 struct format_opts fo;
2539 ipfw_cfg_lheader *cfg;
2541 memset(&fo, 0, sizeof(fo));
2542 if (ipfw_get_config(&g_co, &fo, &cfg, &size) != 0)
2543 err(EX_OSERR, "requesting config failed");
2545 for (i = 0, msg = "disable"; i < RESVD_SET; i++)
2546 if ((cfg->set_mask & (1<<i)) == 0) {
2547 printf("%s %d", msg, i);
2550 msg = (cfg->set_mask != (uint32_t)-1) ? " enable" : "enable";
2551 for (i = 0; i < RESVD_SET; i++)
2552 if ((cfg->set_mask & (1<<i)) != 0) {
2553 printf("%s %d", msg, i);
2558 } else if (_substrcmp(*av, "swap") == 0) {
2560 if ( av[0] == NULL || av[1] == NULL )
2561 errx(EX_USAGE, "set swap needs 2 set numbers\n");
2562 rt.set = atoi(av[0]);
2563 rt.new_set = atoi(av[1]);
2564 if (!isdigit(*(av[0])) || rt.set > RESVD_SET)
2565 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2566 if (!isdigit(*(av[1])) || rt.new_set > RESVD_SET)
2567 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2568 i = do_range_cmd(IP_FW_SET_SWAP, &rt);
2569 } else if (_substrcmp(*av, "move") == 0) {
2571 if (av[0] && _substrcmp(*av, "rule") == 0) {
2572 rt.flags = IPFW_RCFLAG_RANGE; /* move rules to new set */
2576 cmd = IP_FW_SET_MOVE; /* Move set to new one */
2577 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
2578 av[3] != NULL || _substrcmp(av[1], "to") != 0)
2579 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2580 rulenum = atoi(av[0]);
2581 rt.new_set = atoi(av[2]);
2582 if (cmd == IP_FW_XMOVE) {
2583 rt.start_rule = rulenum;
2584 rt.end_rule = rulenum;
2587 rt.new_set = atoi(av[2]);
2588 if (!isdigit(*(av[0])) || (cmd == 3 && rt.set > RESVD_SET) ||
2589 (cmd == 2 && rt.start_rule == IPFW_DEFAULT_RULE) )
2590 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2591 if (!isdigit(*(av[2])) || rt.new_set > RESVD_SET)
2592 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2593 i = do_range_cmd(cmd, &rt);
2595 err(EX_OSERR, "failed to move %s",
2596 cmd == IP_FW_SET_MOVE ? "set": "rule");
2597 } else if (_substrcmp(*av, "disable") == 0 ||
2598 _substrcmp(*av, "enable") == 0 ) {
2599 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2602 masks[0] = masks[1] = 0;
2605 if (isdigit(**av)) {
2607 if (i < 0 || i > RESVD_SET)
2609 "invalid set number %d\n", i);
2610 masks[which] |= (1<<i);
2611 } else if (_substrcmp(*av, "disable") == 0)
2613 else if (_substrcmp(*av, "enable") == 0)
2617 "invalid set command %s\n", *av);
2620 if ( (masks[0] & masks[1]) != 0 )
2622 "cannot enable and disable the same set\n");
2625 rt.new_set = masks[1];
2626 i = do_range_cmd(IP_FW_SET_ENABLE, &rt);
2628 warn("set enable/disable: setsockopt(IP_FW_SET_ENABLE)");
2630 errx(EX_USAGE, "invalid set command %s\n", *av);
2634 ipfw_sysctl_handler(char *av[], int which)
2638 if (av[0] == NULL) {
2639 warnx("missing keyword to enable/disable\n");
2640 } else if (_substrcmp(*av, "firewall") == 0) {
2641 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2642 &which, sizeof(which));
2643 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
2644 &which, sizeof(which));
2645 } else if (_substrcmp(*av, "one_pass") == 0) {
2646 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2647 &which, sizeof(which));
2648 } else if (_substrcmp(*av, "debug") == 0) {
2649 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2650 &which, sizeof(which));
2651 } else if (_substrcmp(*av, "verbose") == 0) {
2652 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2653 &which, sizeof(which));
2654 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2655 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2656 &which, sizeof(which));
2658 } else if (_substrcmp(*av, "altq") == 0) {
2659 altq_set_enabled(which);
2662 warnx("unrecognize enable/disable keyword: %s\n", *av);
2666 typedef void state_cb(struct cmdline_opts *co, struct format_opts *fo,
2667 void *arg, void *state);
2670 prepare_format_dyn(struct cmdline_opts *co, struct format_opts *fo,
2671 void *arg __unused, void *_state)
2677 d = (ipfw_dyn_rule *)_state;
2678 /* Count _ALL_ states */
2681 if (fo->show_counters == 0)
2685 /* skip states from another set */
2686 bcopy((char *)&d->rule + sizeof(uint16_t), &set,
2688 if (set != co->use_set - 1)
2692 width = pr_u64(NULL, &d->pcnt, 0);
2693 if (width > fo->pcwidth)
2694 fo->pcwidth = width;
2696 width = pr_u64(NULL, &d->bcnt, 0);
2697 if (width > fo->bcwidth)
2698 fo->bcwidth = width;
2702 foreach_state(struct cmdline_opts *co, struct format_opts *fo,
2703 caddr_t base, size_t sz, state_cb dyn_bc, void *dyn_arg)
2709 ipfw_obj_ctlv *ctlv;
2715 ctlv = (ipfw_obj_ctlv *)base;
2716 switch (ctlv->head.type) {
2717 case IPFW_TLV_DYNSTATE_LIST:
2718 base += sizeof(*ctlv);
2719 sz -= sizeof(*ctlv);
2720 ttype = IPFW_TLV_DYN_ENT;
2729 tlv = (ipfw_obj_tlv *)base;
2730 if (tlv->type != ttype)
2733 fptr(co, fo, farg, tlv + 1);
2735 base += tlv->length;
2743 prepare_format_opts(struct cmdline_opts *co, struct format_opts *fo,
2744 ipfw_obj_tlv *rtlv, int rcnt, caddr_t dynbase, size_t dynsz)
2746 int bcwidth, pcwidth, width;
2748 struct ip_fw_bcounter *cntr;
2749 struct ip_fw_rule *r;
2753 if (fo->show_counters != 0) {
2754 for (n = 0; n < rcnt; n++,
2755 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2756 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2757 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2758 /* skip rules from another set */
2759 if (co->use_set && r->set != co->use_set - 1)
2762 /* packet counter */
2763 width = pr_u64(NULL, &cntr->pcnt, 0);
2764 if (width > pcwidth)
2768 width = pr_u64(NULL, &cntr->bcnt, 0);
2769 if (width > bcwidth)
2773 fo->bcwidth = bcwidth;
2774 fo->pcwidth = pcwidth;
2777 if (co->do_dynamic && dynsz > 0)
2778 foreach_state(co, fo, dynbase, dynsz, prepare_format_dyn, NULL);
2782 list_static_range(struct cmdline_opts *co, struct format_opts *fo,
2783 struct buf_pr *bp, ipfw_obj_tlv *rtlv, int rcnt)
2786 struct ip_fw_rule *r;
2787 struct ip_fw_bcounter *cntr;
2789 for (n = seen = 0; n < rcnt; n++,
2790 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2792 if ((fo->show_counters | fo->show_time) != 0) {
2793 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2794 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2797 r = (struct ip_fw_rule *)(rtlv + 1);
2799 if (r->rulenum > fo->last)
2801 if (co->use_set && r->set != co->use_set - 1)
2803 if (r->rulenum >= fo->first && r->rulenum <= fo->last) {
2804 show_static_rule(co, fo, bp, r, cntr);
2805 printf("%s", bp->buf);
2815 list_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2816 void *_arg, void *_state)
2823 d = (ipfw_dyn_rule *)_state;
2824 bp = (struct buf_pr *)_arg;
2826 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2827 if (rulenum > fo->last)
2830 bcopy((char *)&d->rule + sizeof(uint16_t),
2831 &set, sizeof(uint8_t));
2832 if (set != co->use_set - 1)
2835 if (rulenum >= fo->first) {
2836 show_dyn_state(co, fo, bp, d);
2837 printf("%s\n", bp->buf);
2843 list_dyn_range(struct cmdline_opts *co, struct format_opts *fo,
2844 struct buf_pr *bp, caddr_t base, size_t sz)
2847 sz = foreach_state(co, fo, base, sz, list_dyn_state, bp);
2852 ipfw_list(int ac, char *av[], int show_counters)
2854 ipfw_cfg_lheader *cfg;
2855 struct format_opts sfo;
2863 if (g_co.test_only) {
2864 fprintf(stderr, "Testing only, list disabled\n");
2868 dummynet_list(ac, av, show_counters);
2874 memset(&sfo, 0, sizeof(sfo));
2876 /* Determine rule range to request */
2878 for (lac = ac, lav = av; lac != 0; lac--) {
2879 rnum = strtoul(*lav++, &endptr, 10);
2880 if (sfo.first == 0 || rnum < sfo.first)
2884 rnum = strtoul(endptr + 1, &endptr, 10);
2885 if (sfo.last == 0 || rnum > sfo.last)
2890 /* get configuration from kernel */
2892 sfo.show_counters = show_counters;
2893 sfo.show_time = g_co.do_time;
2894 if (g_co.do_dynamic != 2)
2895 sfo.flags |= IPFW_CFG_GET_STATIC;
2896 if (g_co.do_dynamic != 0)
2897 sfo.flags |= IPFW_CFG_GET_STATES;
2898 if ((sfo.show_counters | sfo.show_time) != 0)
2899 sfo.flags |= IPFW_CFG_GET_COUNTERS;
2900 if (ipfw_get_config(&g_co, &sfo, &cfg, &sz) != 0)
2901 err(EX_OSERR, "retrieving config failed");
2903 error = ipfw_show_config(&g_co, &sfo, cfg, sz, ac, av);
2912 ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
2913 ipfw_cfg_lheader *cfg, size_t sz, int ac, char *av[])
2918 int exitval = EX_OK;
2924 ipfw_obj_ctlv *ctlv;
2925 ipfw_obj_tlv *rbase;
2928 * Handle tablenames TLV first, if any
2933 readsz = sizeof(*cfg);
2936 fo->set_mask = cfg->set_mask;
2938 ctlv = (ipfw_obj_ctlv *)(cfg + 1);
2939 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2940 object_sort_ctlv(ctlv);
2942 readsz += ctlv->head.length;
2943 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2946 if (cfg->flags & IPFW_CFG_GET_STATIC) {
2947 /* We've requested static rules */
2948 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2949 rbase = (ipfw_obj_tlv *)(ctlv + 1);
2951 readsz += ctlv->head.length;
2952 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2957 if ((cfg->flags & IPFW_CFG_GET_STATES) && (readsz != sz)) {
2958 /* We may have some dynamic states */
2959 dynsz = sz - readsz;
2960 /* Skip empty header */
2961 if (dynsz != sizeof(ipfw_obj_ctlv))
2962 dynbase = (caddr_t)ctlv;
2967 prepare_format_opts(co, fo, rbase, rcnt, dynbase, dynsz);
2968 bp_alloc(&bp, 4096);
2970 /* if no rule numbers were specified, list all rules */
2973 fo->last = IPFW_DEFAULT_RULE;
2974 if (cfg->flags & IPFW_CFG_GET_STATIC)
2975 list_static_range(co, fo, &bp, rbase, rcnt);
2977 if (co->do_dynamic && dynsz > 0) {
2978 printf("## Dynamic rules (%d %zu):\n", fo->dcnt,
2980 list_dyn_range(co, fo, &bp, dynbase, dynsz);
2987 /* display specific rules requested on command line */
2988 for (lac = ac, lav = av; lac != 0; lac--) {
2989 /* convert command line rule # */
2990 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2992 fo->last = strtoul(endptr + 1, &endptr, 10);
2995 warnx("invalid rule number: %s", *(lav - 1));
2999 if ((cfg->flags & IPFW_CFG_GET_STATIC) == 0)
3002 if (list_static_range(co, fo, &bp, rbase, rcnt) == 0) {
3003 /* give precedence to other error(s) */
3004 if (exitval == EX_OK)
3005 exitval = EX_UNAVAILABLE;
3006 if (fo->first == fo->last)
3007 warnx("rule %u does not exist", fo->first);
3009 warnx("no rules in range %u-%u",
3010 fo->first, fo->last);
3014 if (co->do_dynamic && dynsz > 0) {
3015 printf("## Dynamic rules:\n");
3016 for (lac = ac, lav = av; lac != 0; lac--) {
3017 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
3019 fo->last = strtoul(endptr+1, &endptr, 10);
3021 /* already warned */
3023 list_dyn_range(co, fo, &bp, dynbase, dynsz);
3033 * Retrieves current ipfw configuration of given type
3034 * and stores its pointer to @pcfg.
3036 * Caller is responsible for freeing @pcfg.
3038 * Returns 0 on success.
3042 ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
3043 ipfw_cfg_lheader **pcfg, size_t *psize)
3045 ipfw_cfg_lheader *cfg;
3050 if (co->test_only != 0) {
3051 fprintf(stderr, "Testing only, list disabled\n");
3055 /* Start with some data size */
3059 for (i = 0; i < 16; i++) {
3062 if ((cfg = calloc(1, sz)) == NULL)
3065 cfg->flags = fo->flags;
3066 cfg->start_rule = fo->first;
3067 cfg->end_rule = fo->last;
3069 if (do_get3(IP_FW_XGET, &cfg->opheader, &sz) != 0) {
3070 if (errno != ENOMEM) {
3075 /* Buffer size is not enough. Try to increase */
3092 lookup_host (char *host, struct in_addr *ipaddr)
3096 if (!inet_aton(host, ipaddr)) {
3097 if ((he = gethostbyname(host)) == NULL)
3099 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
3113 ipfw_check_object_name(const char *name)
3118 * Check that name is null-terminated and contains
3119 * valid symbols only. Valid mask is:
3120 * [a-zA-Z0-9\-_\.]{1,63}
3123 if (l == 0 || l >= 64)
3125 for (i = 0; i < l; i++) {
3127 if (isalpha(c) || isdigit(c) || c == '_' ||
3128 c == '-' || c == '.')
3135 static const char *default_state_name = "default";
3138 state_check_name(const char *name)
3141 if (ipfw_check_object_name(name) != 0)
3143 if (strcmp(name, "any") == 0)
3149 eaction_check_name(const char *name)
3152 if (ipfw_check_object_name(name) != 0)
3154 /* Restrict some 'special' names */
3155 if (match_token(rule_actions, name) != -1 &&
3156 match_token(rule_action_params, name) != -1)
3162 pack_object(struct tidx *tstate, const char *name, int otype)
3164 ipfw_obj_ntlv *ntlv;
3167 for (i = 0; i < tstate->count; i++) {
3168 if (strcmp(tstate->idx[i].name, name) != 0)
3170 if (tstate->idx[i].set != tstate->set)
3172 if (tstate->idx[i].head.type != otype)
3175 return (tstate->idx[i].idx);
3178 if (tstate->count + 1 > tstate->size) {
3180 tstate->idx = realloc(tstate->idx, tstate->size *
3181 sizeof(ipfw_obj_ntlv));
3182 if (tstate->idx == NULL)
3186 ntlv = &tstate->idx[i];
3187 memset(ntlv, 0, sizeof(ipfw_obj_ntlv));
3188 strlcpy(ntlv->name, name, sizeof(ntlv->name));
3189 ntlv->head.type = otype;
3190 ntlv->head.length = sizeof(ipfw_obj_ntlv);
3191 ntlv->set = tstate->set;
3192 ntlv->idx = ++tstate->counter;
3199 pack_table(struct tidx *tstate, const char *name)
3202 if (table_check_name(name) != 0)
3205 return (pack_object(tstate, name, IPFW_TLV_TBL_NAME));
3209 fill_table(struct _ipfw_insn *cmd, char *av, uint8_t opcode,
3210 struct tidx *tstate)
3212 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
3216 if ((p = strchr(av + 6, ')')) == NULL)
3217 errx(EX_DATAERR, "forgotten parenthesis: '%s'", av);
3219 p = strchr(av + 6, ',');
3223 if ((uidx = pack_table(tstate, av + 6)) == 0)
3224 errx(EX_DATAERR, "Invalid table name: %s", av + 6);
3226 cmd->opcode = opcode;
3229 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3230 d[0] = strtoul(p, NULL, 0);
3232 cmd->len |= F_INSN_SIZE(ipfw_insn);
3237 * fills the addr and mask fields in the instruction as appropriate from av.
3238 * Update length as appropriate.
3239 * The following formats are allowed:
3240 * me returns O_IP_*_ME
3241 * 1.2.3.4 single IP address
3242 * 1.2.3.4:5.6.7.8 address:mask
3243 * 1.2.3.4/24 address/mask
3244 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
3245 * We can have multiple comma-separated address/mask entries.
3248 fill_ip(ipfw_insn_ip *cmd, char *av, int cblen, struct tidx *tstate)
3251 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
3253 cmd->o.len &= ~F_LEN_MASK; /* zero len */
3255 if (_substrcmp(av, "any") == 0)
3258 if (_substrcmp(av, "me") == 0) {
3259 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
3263 if (strncmp(av, "table(", 6) == 0) {
3264 fill_table(&cmd->o, av, O_IP_DST_LOOKUP, tstate);
3270 * After the address we can have '/' or ':' indicating a mask,
3271 * ',' indicating another address follows, '{' indicating a
3272 * set of addresses of unspecified size.
3274 char *t = NULL, *p = strpbrk(av, "/:,{");
3278 CHECK_LENGTH(cblen, (int)F_INSN_SIZE(ipfw_insn) + 2 + len);
3283 if ((t = strpbrk(p, ",{")) != NULL) {
3290 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
3291 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
3294 if (!inet_aton(p, (struct in_addr *)&d[1]))
3295 errx(EX_DATAERR, "bad netmask ``%s''", p);
3300 d[1] = htonl(0U); /* mask */
3301 else if (masklen > 32)
3302 errx(EX_DATAERR, "bad width ``%s''", p);
3304 d[1] = htonl(~0U << (32 - masklen));
3306 case '{': /* no mask, assume /24 and put back the '{' */
3307 d[1] = htonl(~0U << (32 - 24));
3311 case ',': /* single address plus continuation */
3314 case 0: /* initialization value */
3316 d[1] = htonl(~0U); /* force /32 */
3319 d[0] &= d[1]; /* mask base address with mask */
3322 /* find next separator */
3324 p = strpbrk(p, ",{");
3325 if (p && *p == '{') {
3327 * We have a set of addresses. They are stored as follows:
3328 * arg1 is the set size (powers of 2, 2..256)
3329 * addr is the base address IN HOST FORMAT
3330 * mask.. is an array of arg1 bits (rounded up to
3331 * the next multiple of 32) with bits set
3332 * for each host in the map.
3334 uint32_t *map = (uint32_t *)&cmd->mask;
3336 int i = contigmask((uint8_t *)&(d[1]), 32);
3339 errx(EX_DATAERR, "address set cannot be in a list");
3340 if (i < 24 || i > 31)
3341 errx(EX_DATAERR, "invalid set with mask %d\n", i);
3342 cmd->o.arg1 = 1<<(32-i); /* map length */
3343 d[0] = ntohl(d[0]); /* base addr in host format */
3344 cmd->o.opcode = O_IP_DST_SET; /* default */
3345 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
3346 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
3347 map[i] = 0; /* clear map */
3351 high = low + cmd->o.arg1 - 1;
3353 * Here, i stores the previous value when we specify a range
3354 * of addresses within a mask, e.g. 45-63. i = -1 means we
3355 * have no previous value.
3357 i = -1; /* previous value in a range */
3358 while (isdigit(*av)) {
3360 int a = strtol(av, &s, 0);
3362 if (s == av) { /* no parameter */
3364 errx(EX_DATAERR, "set not closed\n");
3366 errx(EX_DATAERR, "incomplete range %d-", i);
3369 if (a < low || a > high)
3370 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
3373 if (i == -1) /* no previous in range */
3375 else { /* check that range is valid */
3377 errx(EX_DATAERR, "invalid range %d-%d",
3380 errx(EX_DATAERR, "double '-' in range");
3383 map[i/32] |= 1<<(i & 31);
3394 if (av) /* then *av must be a ',' */
3397 /* Check this entry */
3398 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
3400 * 'any' turns the entire list into a NOP.
3401 * 'not any' never matches, so it is removed from the
3402 * list unless it is the only item, in which case we
3405 if (cmd->o.len & F_NOT) { /* "not any" never matches */
3406 if (av == NULL && len == 0) /* only this entry */
3407 errx(EX_DATAERR, "not any never matches");
3409 /* else do nothing and skip this entry */
3412 /* A single IP can be stored in an optimized format */
3413 if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
3414 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
3417 len += 2; /* two words... */
3420 if (len + 1 > F_LEN_MASK)
3421 errx(EX_DATAERR, "address list too long");
3422 cmd->o.len |= len+1;
3426 /* n2mask sets n bits of the mask */
3428 n2mask(struct in6_addr *mask, int n)
3430 static int minimask[9] =
3431 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
3434 memset(mask, 0, sizeof(struct in6_addr));
3435 p = (u_char *) mask;
3436 for (; n > 0; p++, n -= 8) {
3446 fill_flags_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3447 struct _s_x *flags, char *p)
3450 uint32_t set = 0, clear = 0;
3452 if (fill_flags(flags, p, &e, &set, &clear) != 0)
3453 errx(EX_DATAERR, "invalid flag %s", e);
3455 cmd->opcode = opcode;
3456 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
3457 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3462 ipfw_delete(char *av[])
3467 int exitval = EX_OK;
3471 NEED1("missing rule specification");
3472 if ( *av && _substrcmp(*av, "set") == 0) {
3473 /* Do not allow using the following syntax:
3474 * ipfw set N delete set M
3477 errx(EX_DATAERR, "invalid syntax");
3478 do_set = 1; /* delete set */
3483 while (*av && isdigit(**av)) {
3484 i = strtol(*av, &sep, 10);
3487 j = strtol(sep + 1, NULL, 10);
3490 exitval = ipfw_delete_nat(i);
3491 } else if (g_co.do_pipe) {
3492 exitval = ipfw_delete_pipe(g_co.do_pipe, i);
3494 memset(&rt, 0, sizeof(rt));
3497 rt.flags = IPFW_RCFLAG_SET;
3499 rt.start_rule = i & 0xffff;
3500 rt.end_rule = j & 0xffff;
3501 if (rt.start_rule == 0 && rt.end_rule == 0)
3502 rt.flags |= IPFW_RCFLAG_ALL;
3504 rt.flags |= IPFW_RCFLAG_RANGE;
3505 if (g_co.use_set != 0) {
3506 rt.set = g_co.use_set - 1;
3507 rt.flags |= IPFW_RCFLAG_SET;
3510 if (g_co.do_dynamic == 2)
3511 rt.flags |= IPFW_RCFLAG_DYNAMIC;
3512 i = do_range_cmd(IP_FW_XDEL, &rt);
3514 exitval = EX_UNAVAILABLE;
3517 warn("rule %u: setsockopt(IP_FW_XDEL)",
3519 } else if (rt.new_set == 0 && do_set == 0 &&
3520 g_co.do_dynamic != 2) {
3521 exitval = EX_UNAVAILABLE;
3524 if (rt.start_rule != rt.end_rule)
3525 warnx("no rules rules in %u-%u range",
3526 rt.start_rule, rt.end_rule);
3528 warnx("rule %u not found",
3533 if (exitval != EX_OK && g_co.do_force == 0)
3539 * fill the interface structure. We do not check the name as we can
3540 * create interfaces dynamically, so checking them at insert time
3541 * makes relatively little sense.
3542 * Interface names containing '*', '?', or '[' are assumed to be shell
3543 * patterns which match interfaces.
3546 fill_iface(ipfw_insn_if *cmd, char *arg, int cblen, struct tidx *tstate)
3551 cmd->name[0] = '\0';
3552 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3556 /* Parse the interface or address */
3557 if (strcmp(arg, "any") == 0)
3558 cmd->o.len = 0; /* effectively ignore this command */
3559 else if (strncmp(arg, "table(", 6) == 0) {
3560 if ((p = strchr(arg + 6, ')')) == NULL)
3561 errx(EX_DATAERR, "forgotten parenthesis: '%s'", arg);
3563 p = strchr(arg + 6, ',');
3566 if ((uidx = pack_table(tstate, arg + 6)) == 0)
3567 errx(EX_DATAERR, "Invalid table name: %s", arg + 6);
3569 cmd->name[0] = '\1'; /* Special value indicating table */
3571 } else if (!isdigit(*arg)) {
3572 strlcpy(cmd->name, arg, sizeof(cmd->name));
3573 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3574 } else if (!inet_aton(arg, &cmd->p.ip))
3575 errx(EX_DATAERR, "bad ip address ``%s''", arg);
3579 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
3583 char *ap, *ptr, *optr;
3584 struct ether_addr *mac;
3585 const char *macset = "0123456789abcdefABCDEF:";
3587 if (strcmp(p, "any") == 0) {
3588 for (i = 0; i < ETHER_ADDR_LEN; i++)
3589 addr[i] = mask[i] = 0;
3593 optr = ptr = strdup(p);
3594 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
3596 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
3597 errx(EX_DATAERR, "Incorrect MAC address");
3598 bcopy(mac, addr, ETHER_ADDR_LEN);
3600 errx(EX_DATAERR, "Incorrect MAC address");
3602 if (ptr != NULL) { /* we have mask? */
3603 if (p[ptr - optr - 1] == '/') { /* mask len */
3604 long ml = strtol(ptr, &ap, 10);
3605 if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
3606 errx(EX_DATAERR, "Incorrect mask length");
3607 for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
3608 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
3611 if (strspn(ptr, macset) != l ||
3612 (mac = ether_aton(ptr)) == NULL)
3613 errx(EX_DATAERR, "Incorrect mask");
3614 bcopy(mac, mask, ETHER_ADDR_LEN);
3616 } else { /* default mask: ff:ff:ff:ff:ff:ff */
3617 for (i = 0; i < ETHER_ADDR_LEN; i++)
3620 for (i = 0; i < ETHER_ADDR_LEN; i++)
3627 * helper function, updates the pointer to cmd with the length
3628 * of the current command, and also cleans up the first word of
3629 * the new command in case it has been clobbered before.
3632 next_cmd(ipfw_insn *cmd, int *len)
3635 CHECK_LENGTH(*len, 0);
3637 bzero(cmd, sizeof(*cmd));
3642 * Takes arguments and copies them into a comment
3645 fill_comment(ipfw_insn *cmd, char **av, int cblen)
3648 char *p = (char *)(cmd + 1);
3650 cmd->opcode = O_NOP;
3651 cmd->len = (cmd->len & (F_NOT | F_OR));
3653 /* Compute length of comment string. */
3654 for (i = 0, l = 0; av[i] != NULL; i++)
3655 l += strlen(av[i]) + 1;
3660 "comment too long (max 80 chars)");
3662 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
3665 for (i = 0; av[i] != NULL; i++) {
3674 * A function to fill simple commands of size 1.
3675 * Existing flags are preserved.
3678 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3680 cmd->opcode = opcode;
3681 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3686 * Fetch and add the MAC address and type, with masks. This generates one or
3687 * two microinstructions, and returns the pointer to the last one.
3690 add_mac(ipfw_insn *cmd, char *av[], int cblen)
3694 if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
3695 errx(EX_DATAERR, "MAC dst src");
3697 cmd->opcode = O_MACADDR2;
3698 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3701 mac = (ipfw_insn_mac *)cmd;
3702 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
3703 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
3704 &(mac->mask[ETHER_ADDR_LEN])); /* src */
3709 add_mactype(ipfw_insn *cmd, char *av, int cblen)
3712 errx(EX_DATAERR, "missing MAC type");
3713 if (strcmp(av, "any") != 0) { /* we have a non-null type */
3714 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
3716 cmd->opcode = O_MAC_TYPE;
3723 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
3725 struct protoent *pe;
3729 proto = strtol(av, &ep, 10);
3730 if (*ep != '\0' || proto <= 0) {
3731 if ((pe = getprotobyname(av)) == NULL)
3733 proto = pe->p_proto;
3736 fill_cmd(cmd, O_PROTO, 0, proto);
3742 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
3744 u_char proto = IPPROTO_IP;
3746 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3747 ; /* do not set O_IP4 nor O_IP6 */
3748 else if (strcmp(av, "ip4") == 0)
3749 /* explicit "just IPv4" rule */
3750 fill_cmd(cmd, O_IP4, 0, 0);
3751 else if (strcmp(av, "ip6") == 0) {
3752 /* explicit "just IPv6" rule */
3753 proto = IPPROTO_IPV6;
3754 fill_cmd(cmd, O_IP6, 0, 0);
3756 return add_proto0(cmd, av, protop);
3763 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
3765 u_char proto = IPPROTO_IP;
3767 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3768 ; /* do not set O_IP4 nor O_IP6 */
3769 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3770 /* explicit "just IPv4" rule */
3771 fill_cmd(cmd, O_IP4, 0, 0);
3772 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3773 /* explicit "just IPv6" rule */
3774 proto = IPPROTO_IPV6;
3775 fill_cmd(cmd, O_IP6, 0, 0);
3777 return add_proto0(cmd, av, protop);
3784 add_srcip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3786 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3787 if (cmd->opcode == O_IP_DST_SET) /* set */
3788 cmd->opcode = O_IP_SRC_SET;
3789 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3790 cmd->opcode = O_IP_SRC_LOOKUP;
3791 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3792 cmd->opcode = O_IP_SRC_ME;
3793 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3794 cmd->opcode = O_IP_SRC;
3795 else /* addr/mask */
3796 cmd->opcode = O_IP_SRC_MASK;
3801 add_dstip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3803 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3804 if (cmd->opcode == O_IP_DST_SET) /* set */
3806 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3808 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3809 cmd->opcode = O_IP_DST_ME;
3810 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3811 cmd->opcode = O_IP_DST;
3812 else /* addr/mask */
3813 cmd->opcode = O_IP_DST_MASK;
3818 add_srcmac(ipfw_insn *cmd, char *av, struct tidx *tstate)
3821 if (strncmp(av, "table(", 6) == 0)
3822 fill_table(cmd, av, O_MAC_SRC_LOOKUP, tstate);
3824 errx(EX_DATAERR, "only mac table lookup is supported %s", av);
3829 add_dstmac(ipfw_insn *cmd, char *av, struct tidx *tstate)
3832 if (strncmp(av, "table(", 6) == 0)
3833 fill_table(cmd, av, O_MAC_DST_LOOKUP, tstate);
3835 errx(EX_DATAERR, "only mac table lookup is supported %s", av);
3840 static struct _s_x f_reserved_keywords[] = {
3843 { "diverted", TOK_OR },
3844 { "dst-port", TOK_OR },
3845 { "src-port", TOK_OR },
3846 { "established", TOK_OR },
3847 { "keep-state", TOK_OR },
3849 { "icmptypes", TOK_OR },
3857 { NULL, 0 } /* terminator */
3861 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
3864 if (match_token(f_reserved_keywords, av) != -1)
3867 if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
3868 /* XXX todo: check that we have a protocol with ports */
3869 cmd->opcode = opcode;
3876 add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3879 char *host, *ch, buf[INET6_ADDRSTRLEN];
3880 ipfw_insn *ret = NULL;
3883 /* Copy first address in set if needed */
3884 if ((ch = strpbrk(av, "/,")) != NULL) {
3886 strlcpy(buf, av, sizeof(buf));
3887 if (len < sizeof(buf))
3893 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3894 inet_pton(AF_INET6, host, &a) == 1)
3895 ret = add_srcip6(cmd, av, cblen, tstate);
3896 /* XXX: should check for IPv4, not !IPv6 */
3897 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3898 inet_pton(AF_INET6, host, &a) != 1))
3899 ret = add_srcip(cmd, av, cblen, tstate);
3900 if (ret == NULL && strcmp(av, "any") != 0)
3907 add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3910 char *host, *ch, buf[INET6_ADDRSTRLEN];
3911 ipfw_insn *ret = NULL;
3914 /* Copy first address in set if needed */
3915 if ((ch = strpbrk(av, "/,")) != NULL) {
3917 strlcpy(buf, av, sizeof(buf));
3918 if (len < sizeof(buf))
3924 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3925 inet_pton(AF_INET6, host, &a) == 1)
3926 ret = add_dstip6(cmd, av, cblen, tstate);
3927 /* XXX: should check for IPv4, not !IPv6 */
3928 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3929 inet_pton(AF_INET6, host, &a) != 1))
3930 ret = add_dstip(cmd, av, cblen, tstate);
3931 if (ret == NULL && strcmp(av, "any") != 0)
3938 arg_or_targ_relaxed(const char *arg, const char *action)
3940 uint32_t arg1 = (uint32_t)(-1);
3943 errx(EX_USAGE, "missing argument for %s", action);
3944 if (isdigit(arg[0])) {
3945 arg1 = strtoul(arg, NULL, 10);
3946 if (arg1 <= 0 || arg1 >= IP_FW_TABLEARG)
3947 errx(EX_DATAERR, "illegal argument %s(%u) for %s",
3949 } else if (_substrcmp(arg, "tablearg") == 0)
3954 static inline uint16_t
3955 arg_or_targ(const char *arg, const char *action)
3957 uint32_t arg1 = arg_or_targ_relaxed(arg, action);
3959 if (arg1 == (uint32_t)(-1))
3960 errx(EX_DATAERR, "illegal argument %s(%u) for %s",
3966 get_divert_port(const char *arg, const char *action)
3968 uint32_t arg1 = arg_or_targ_relaxed(arg, action);
3970 if (arg1 != (uint32_t)(-1))
3975 s = getservbyname(arg, "divert");
3977 errx(EX_DATAERR, "illegal divert/tee port");
3978 return (ntohs(s->s_port));
3982 * Parse arguments and assemble the microinstructions which make up a rule.
3983 * Rules are added into the 'rulebuf' and then copied in the correct order
3984 * into the actual rule.
3986 * The syntax for a rule starts with the action, followed by
3987 * optional action parameters, and the various match patterns.
3988 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
3989 * (generated if the rule includes a keep-state option), then the
3990 * various match patterns, log/altq actions, and the actual action.
3994 compile_rule(char *av[], uint32_t *rbuf, int *rbufsize, struct tidx *tstate)
3997 * rules are added into the 'rulebuf' and then copied in
3998 * the correct order into the actual rule.
3999 * Some things that need to go out of order (prob, action etc.)
4002 static uint32_t actbuf[255], cmdbuf[255];
4003 int rblen, ablen, cblen;
4005 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
4006 ipfw_insn *first_cmd; /* first match pattern */
4008 struct ip_fw_rule *rule;
4011 * various flags used to record that we entered some fields.
4013 ipfw_insn *have_state = NULL; /* any state-related option */
4014 int have_rstate = 0;
4015 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
4016 ipfw_insn *have_skipcmd = NULL;
4021 int open_par = 0; /* open parenthesis ( */
4023 /* proto is here because it is used to fetch ports */
4024 u_char proto = IPPROTO_IP; /* default protocol */
4026 double match_prob = 1; /* match probability, default is always match */
4028 bzero(actbuf, sizeof(actbuf)); /* actions go here */
4029 bzero(cmdbuf, sizeof(cmdbuf));
4030 bzero(rbuf, *rbufsize);
4032 rule = (struct ip_fw_rule *)rbuf;
4033 cmd = (ipfw_insn *)cmdbuf;
4034 action = (ipfw_insn *)actbuf;
4036 rblen = *rbufsize / sizeof(uint32_t);
4037 rblen -= sizeof(struct ip_fw_rule) / sizeof(uint32_t);
4038 ablen = sizeof(actbuf) / sizeof(actbuf[0]);
4039 cblen = sizeof(cmdbuf) / sizeof(cmdbuf[0]);
4040 cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
4042 #define CHECK_RBUFLEN(len) { CHECK_LENGTH(rblen, len); rblen -= len; }
4043 #define CHECK_ACTLEN CHECK_LENGTH(ablen, action->len)
4047 /* [rule N] -- Rule number optional */
4048 if (av[0] && isdigit(**av)) {
4049 rule->rulenum = atoi(*av);
4053 /* [set N] -- set number (0..RESVD_SET), optional */
4054 if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
4055 int set = strtoul(av[1], NULL, 10);
4056 if (set < 0 || set > RESVD_SET)
4057 errx(EX_DATAERR, "illegal set %s", av[1]);
4063 /* [prob D] -- match probability, optional */
4064 if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
4065 match_prob = strtod(av[1], NULL);
4067 if (match_prob <= 0 || match_prob > 1)
4068 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
4072 /* action -- mandatory */
4073 NEED1("missing action");
4074 i = match_token(rule_actions, *av);
4076 action->len = 1; /* default */
4079 case TOK_CHECKSTATE:
4080 have_state = action;
4081 action->opcode = O_CHECK_STATE;
4083 match_token(rule_options, *av) == TOK_COMMENT) {
4084 action->arg1 = pack_object(tstate,
4085 default_state_name, IPFW_TLV_STATE_NAME);
4088 if (*av[0] == ':') {
4089 if (strcmp(*av + 1, "any") == 0)
4091 else if (state_check_name(*av + 1) == 0)
4092 action->arg1 = pack_object(tstate, *av + 1,
4093 IPFW_TLV_STATE_NAME);
4095 errx(EX_DATAERR, "Invalid state name %s",
4100 errx(EX_DATAERR, "Invalid state name %s", *av);
4104 action->opcode = O_REJECT;
4105 action->arg1 = ICMP_REJECT_ABORT;
4109 action->opcode = O_UNREACH6;
4110 action->arg1 = ICMP6_UNREACH_ABORT;
4114 action->opcode = O_ACCEPT;
4118 action->opcode = O_DENY;
4123 action->opcode = O_REJECT;
4124 action->arg1 = ICMP_UNREACH_HOST;
4128 action->opcode = O_REJECT;
4129 action->arg1 = ICMP_REJECT_RST;
4133 action->opcode = O_UNREACH6;
4134 action->arg1 = ICMP6_UNREACH_RST;
4138 action->opcode = O_REJECT;
4139 NEED1("missing reject code");
4140 action->arg1 = get_reject_code(*av);
4142 if (action->arg1 == ICMP_UNREACH_NEEDFRAG && isdigit(**av)) {
4145 mtu = strtoul(*av, NULL, 10);
4146 if (mtu < 68 || mtu >= IP_MAXPACKET)
4147 errx(EX_DATAERR, "illegal argument for %s",
4149 action->len = F_INSN_SIZE(ipfw_insn_u16);
4150 ((ipfw_insn_u16 *)action)->ports[0] = mtu;
4156 action->opcode = O_UNREACH6;
4157 NEED1("missing unreach code");
4158 action->arg1 = get_unreach6_code(*av);
4163 action->opcode = O_COUNT;
4167 action->opcode = O_NAT;
4168 action->len = F_INSN_SIZE(ipfw_insn_nat);
4170 if (*av != NULL && _substrcmp(*av, "global") == 0)
4171 action->arg1 = IP_FW_NAT44_GLOBAL;
4173 action->arg1 = arg_or_targ(av[0], *(av - 1));
4177 action->opcode = O_QUEUE;
4178 action->arg1 = arg_or_targ(av[0], *(av - 1));
4182 action->opcode = O_PIPE;
4183 action->arg1 = arg_or_targ(av[0], *(av - 1));
4187 action->opcode = O_SKIPTO;
4188 action->arg1 = arg_or_targ(av[0], *(av - 1));
4192 action->opcode = O_NETGRAPH;
4193 action->arg1 = arg_or_targ(av[0], *(av - 1));
4197 action->opcode = O_NGTEE;
4198 action->arg1 = arg_or_targ(av[0], *(av - 1));
4202 action->opcode = O_DIVERT;
4203 action->arg1 = get_divert_port(av[0], *(av - 1));
4207 action->opcode = O_TEE;
4208 action->arg1 = get_divert_port(av[0], *(av - 1));
4212 action->opcode = O_CALLRETURN;
4213 action->arg1 = arg_or_targ(av[0], *(av - 1));
4219 * Locate the address-port separator (':' or ',').
4220 * Could be one of the following:
4224 * IPv6 w:x:y::z,port
4225 * IPv6 [w:x:y::z]:port
4227 struct sockaddr_storage result;
4228 struct addrinfo *res;
4231 u_short port_number = 0;
4233 NEED1("missing forward address[:port]");
4235 if (strncmp(*av, "tablearg", 8) == 0 &&
4236 ((*av)[8] == '\0' || (*av)[8] == ',' || (*av)[8] == ':'))
4237 memcpy(++(*av), "0.0.0.0", 7);
4240 * Are we an bracket-enclosed IPv6 address?
4242 if (strchr(*av, '['))
4246 * locate the address-port separator (':' or ',')
4248 s = strchr(*av, ',');
4250 s = strchr(*av, ']');
4251 /* Prevent erroneous parsing on brackets. */
4257 /* Distinguish between IPv4:port and IPv6 cases. */
4259 if (s && strchr(s+1, ':'))
4260 s = NULL; /* no port */
4264 /* Terminate host portion and set s to start of port. */
4266 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
4269 "illegal forwarding port ``%s''", s);
4270 port_number = (u_short)i;
4274 * Resolve the host name or address to a family and a
4275 * network representation of the address.
4277 if (getaddrinfo(*av, NULL, NULL, &res))
4278 errx(EX_DATAERR, NULL);
4279 /* Just use the first host in the answer. */
4280 family = res->ai_family;
4281 memcpy(&result, res->ai_addr, res->ai_addrlen);
4284 if (family == PF_INET) {
4285 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
4287 action->opcode = O_FORWARD_IP;
4288 action->len = F_INSN_SIZE(ipfw_insn_sa);
4292 * In the kernel we assume AF_INET and use only
4293 * sin_port and sin_addr. Remember to set sin_len as
4294 * the routing code seems to use it too.
4296 p->sa.sin_len = sizeof(struct sockaddr_in);
4297 p->sa.sin_family = AF_INET;
4298 p->sa.sin_port = port_number;
4299 p->sa.sin_addr.s_addr =
4300 ((struct sockaddr_in *)&result)->sin_addr.s_addr;
4301 } else if (family == PF_INET6) {
4302 ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
4304 action->opcode = O_FORWARD_IP6;
4305 action->len = F_INSN_SIZE(ipfw_insn_sa6);
4308 p->sa.sin6_len = sizeof(struct sockaddr_in6);
4309 p->sa.sin6_family = AF_INET6;
4310 p->sa.sin6_port = port_number;
4311 p->sa.sin6_flowinfo = 0;
4312 p->sa.sin6_scope_id =
4313 ((struct sockaddr_in6 *)&result)->sin6_scope_id;
4314 bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
4315 &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
4317 errx(EX_DATAERR, "Invalid address family in forward action");
4323 /* pretend it is a 'count' rule followed by the comment */
4324 action->opcode = O_COUNT;
4325 av--; /* go back... */
4331 size_t intsize = sizeof(int);
4333 action->opcode = O_SETFIB;
4334 NEED1("missing fib number");
4335 if (_substrcmp(*av, "tablearg") == 0) {
4336 action->arg1 = IP_FW_TARG;
4338 action->arg1 = strtoul(*av, NULL, 10);
4339 if (sysctlbyname("net.fibs", &numfibs, &intsize,
4341 errx(EX_DATAERR, "fibs not supported.\n");
4342 if (action->arg1 >= numfibs) /* Temporary */
4343 errx(EX_DATAERR, "fib too large.\n");
4344 /* Add high-order bit to fib to make room for tablearg*/
4345 action->arg1 |= 0x8000;
4355 action->opcode = O_SETDSCP;
4356 NEED1("missing DSCP code");
4357 if (_substrcmp(*av, "tablearg") == 0) {
4358 action->arg1 = IP_FW_TARG;
4360 if (isalpha(*av[0])) {
4361 if ((code = match_token(f_ipdscp, *av)) == -1)
4362 errx(EX_DATAERR, "Unknown DSCP code");
4363 action->arg1 = code;
4365 action->arg1 = strtoul(*av, NULL, 10);
4367 * Add high-order bit to DSCP to make room
4370 action->arg1 |= 0x8000;
4377 action->opcode = O_REASS;
4381 fill_cmd(action, O_CALLRETURN, F_NOT, 0);
4385 action->opcode = O_SETMARK;
4386 action->len = F_INSN_SIZE(ipfw_insn_u32);
4387 NEED1("missing mark");
4388 if (strcmp(*av, "tablearg") == 0) {
4389 action->arg1 = IP_FW_TARG;
4391 ((ipfw_insn_u32 *)action)->d[0] =
4392 strtoul(*av, NULL, 0);
4393 /* This is not a tablearg */
4394 action->arg1 |= 0x8000;
4401 case TOK_TCPSETMSS: {
4405 idx = pack_object(tstate, "tcp-setmss", IPFW_TLV_EACTION);
4407 errx(EX_DATAERR, "pack_object failed");
4408 fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4409 NEED1("Missing MSS value");
4410 action = next_cmd(action, &ablen);
4413 mss = strtoul(*av, NULL, 10);
4414 if (mss == 0 || mss > UINT16_MAX)
4415 errx(EX_USAGE, "invalid MSS value %s", *av);
4416 fill_cmd(action, O_EXTERNAL_DATA, 0, (uint16_t)mss);
4423 if (match_token(rule_eactions, *av) == -1)
4424 errx(EX_DATAERR, "invalid action %s\n", *av);
4426 * External actions support.
4427 * XXX: we support only syntax with instance name.
4428 * For known external actions (from rule_eactions list)
4429 * we can handle syntax directly. But with `eaction'
4430 * keyword we can use only `eaction <name> <instance>'
4436 NEED1("Missing eaction name");
4437 if (eaction_check_name(*av) != 0)
4438 errx(EX_DATAERR, "Invalid eaction name %s", *av);
4439 idx = pack_object(tstate, *av, IPFW_TLV_EACTION);
4441 errx(EX_DATAERR, "pack_object failed");
4442 fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4444 NEED1("Missing eaction instance name");
4445 action = next_cmd(action, &ablen);
4448 if (eaction_check_name(*av) != 0)
4449 errx(EX_DATAERR, "Invalid eaction instance name %s",
4452 * External action instance object has TLV type depended
4453 * from the external action name object index. Since we
4454 * currently don't know this index, use zero as TLV type.
4456 idx = pack_object(tstate, *av, 0);
4458 errx(EX_DATAERR, "pack_object failed");
4459 fill_cmd(action, O_EXTERNAL_INSTANCE, 0, idx);
4463 action = next_cmd(action, &ablen);
4466 * [altq queuename] -- altq tag, optional
4467 * [log [logamount N]] -- log, optional
4469 * If they exist, it go first in the cmdbuf, but then it is
4470 * skipped in the copy section to the end of the buffer.
4472 while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
4477 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
4482 "log cannot be specified more than once");
4483 have_log = (ipfw_insn *)c;
4484 cmd->len = F_INSN_SIZE(ipfw_insn_log);
4486 cmd->opcode = O_LOG;
4487 if (av[0] && _substrcmp(*av, "logamount") == 0) {
4489 NEED1("logamount requires argument");
4493 "logamount must be positive");
4497 len = sizeof(c->max_log);
4498 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
4499 &c->max_log, &len, NULL, 0) == -1) {
4500 if (g_co.test_only) {
4504 errx(1, "sysctlbyname(\"%s\")",
4505 "net.inet.ip.fw.verbose_limit");
4514 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
4516 NEED1("missing altq queue name");
4519 "altq cannot be specified more than once");
4520 have_altq = (ipfw_insn *)a;
4521 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
4523 cmd->opcode = O_ALTQ;
4524 a->qid = altq_name_to_qid(*av);
4535 errx(EX_USAGE, "tag and untag cannot be "
4536 "specified more than once");
4537 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
4538 rule_action_params);
4540 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
4548 cmd = next_cmd(cmd, &cblen);
4551 if (have_state) { /* must be a check-state, we are done */
4553 match_token(rule_options, *av) == TOK_COMMENT) {
4554 /* check-state has a comment */
4556 fill_comment(cmd, av, cblen);
4557 cmd = next_cmd(cmd, &cblen);
4563 #define OR_START(target) \
4564 if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
4566 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
4569 if ( (av[0])[1] == '\0') { \
4580 strcmp(*av, ")") == 0 || \
4581 strcmp(*av, "}") == 0)) { \
4586 errx(EX_USAGE, "missing \")\"\n"); \
4590 if (av[0] && _substrcmp(*av, "not") == 0) { \
4591 if (cmd->len & F_NOT) \
4592 errx(EX_USAGE, "double \"not\" not allowed\n"); \
4593 cmd->len |= F_NOT; \
4597 #define OR_BLOCK(target) \
4598 if (av[0] && _substrcmp(*av, "or") == 0) { \
4599 if (prev == NULL || open_par == 0) \
4600 errx(EX_DATAERR, "invalid OR block"); \
4601 prev->len |= F_OR; \
4611 * MAC addresses, optional.
4612 * If we have this, we skip the part "proto from src to dst"
4613 * and jump straight to the option parsing.
4616 NEED1("missing protocol");
4617 if (_substrcmp(*av, "MAC") == 0 ||
4618 _substrcmp(*av, "mac") == 0) {
4619 av++; /* the "MAC" keyword */
4620 add_mac(cmd, av); /* exits in case of errors */
4621 cmd = next_cmd(cmd);
4622 av += 2; /* dst-mac and src-mac */
4624 NEED1("missing mac type");
4625 if (add_mactype(cmd, av[0]))
4626 cmd = next_cmd(cmd);
4627 av++; /* any or mac-type */
4633 * protocol, mandatory
4635 OR_START(get_proto);
4637 NEED1("missing protocol");
4638 if (add_proto_compat(cmd, *av, &proto)) {
4640 if (F_LEN(cmd) != 0) {
4642 cmd = next_cmd(cmd, &cblen);
4644 } else if (first_cmd != cmd) {
4645 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
4647 rule->flags |= IPFW_RULE_JUSTOPTS;
4650 OR_BLOCK(get_proto);
4652 first_cmd = cmd; /* update pointer to use in compact form */
4657 if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
4658 errx(EX_USAGE, "missing ``from''");
4662 * source IP, mandatory
4664 OR_START(source_ip);
4665 NOT_BLOCK; /* optional "not" */
4666 NEED1("missing source address");
4667 if (add_src(cmd, *av, proto, cblen, tstate)) {
4669 if (F_LEN(cmd) != 0) { /* ! any */
4671 cmd = next_cmd(cmd, &cblen);
4674 errx(EX_USAGE, "bad source address %s", *av);
4675 OR_BLOCK(source_ip);
4678 * source ports, optional
4680 NOT_BLOCK; /* optional "not" */
4681 if ( av[0] != NULL ) {
4682 if (_substrcmp(*av, "any") == 0 ||
4683 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4685 if (F_LEN(cmd) != 0)
4686 cmd = next_cmd(cmd, &cblen);
4693 if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
4694 errx(EX_USAGE, "missing ``to''");
4698 * destination, mandatory
4701 NOT_BLOCK; /* optional "not" */
4702 NEED1("missing dst address");
4703 if (add_dst(cmd, *av, proto, cblen, tstate)) {
4705 if (F_LEN(cmd) != 0) { /* ! any */
4707 cmd = next_cmd(cmd, &cblen);
4710 errx( EX_USAGE, "bad destination address %s", *av);
4714 * dest. ports, optional
4716 NOT_BLOCK; /* optional "not" */
4718 if (_substrcmp(*av, "any") == 0 ||
4719 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4721 if (F_LEN(cmd) != 0)
4722 cmd = next_cmd(cmd, &cblen);
4725 if (first_cmd == cmd)
4726 rule->flags |= IPFW_RULE_NOOPT;
4730 while ( av[0] != NULL ) {
4732 ipfw_insn_u32 *cmd32; /* alias for cmd */
4735 cmd32 = (ipfw_insn_u32 *)cmd;
4737 if (*s == '!') { /* alternate syntax for NOT */
4738 if (cmd->len & F_NOT)
4739 errx(EX_USAGE, "double \"not\" not allowed\n");
4743 i = match_token(rule_options, s);
4747 if (cmd->len & F_NOT)
4748 errx(EX_USAGE, "double \"not\" not allowed\n");
4753 if (open_par == 0 || prev == NULL)
4754 errx(EX_USAGE, "invalid \"or\" block\n");
4758 case TOK_STARTBRACE:
4760 errx(EX_USAGE, "+nested \"(\" not allowed\n");
4766 errx(EX_USAGE, "+missing \")\"\n");
4772 fill_cmd(cmd, O_IN, 0, 0);
4776 cmd->len ^= F_NOT; /* toggle F_NOT */
4777 fill_cmd(cmd, O_IN, 0, 0);
4781 fill_cmd(cmd, O_DIVERTED, 0, 3);
4784 case TOK_DIVERTEDLOOPBACK:
4785 fill_cmd(cmd, O_DIVERTED, 0, 1);
4788 case TOK_DIVERTEDOUTPUT:
4789 fill_cmd(cmd, O_DIVERTED, 0, 2);
4793 uint32_t set = 0, clear = 0;
4795 if (*av != NULL && fill_flags(f_ipoff, *av, NULL,
4800 * Compatibility: no argument after "frag"
4801 * keyword equals to "frag offset".
4806 fill_cmd(cmd, O_FRAG, 0,
4807 (set & 0xff) | ( (clear & 0xff) << 8));
4812 fill_cmd(cmd, O_LAYER2, 0, 0);
4818 NEED1("recv, xmit, via require interface name"
4820 fill_iface((ipfw_insn_if *)cmd, av[0], cblen, tstate);
4822 if (F_LEN(cmd) == 0) /* not a valid address */
4825 cmd->opcode = O_XMIT;
4826 else if (i == TOK_RECV)
4827 cmd->opcode = O_RECV;
4828 else if (i == TOK_VIA)
4829 cmd->opcode = O_VIA;
4833 NEED1("icmptypes requires list of types");
4834 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
4838 case TOK_ICMP6TYPES:
4839 NEED1("icmptypes requires list of types");
4840 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
4845 NEED1("ipttl requires TTL");
4846 if (strpbrk(*av, "-,")) {
4847 if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
4848 errx(EX_DATAERR, "invalid ipttl %s", *av);
4850 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
4855 NEED1("ipid requires id");
4856 if (strpbrk(*av, "-,")) {
4857 if (!add_ports(cmd, *av, 0, O_IPID, cblen))
4858 errx(EX_DATAERR, "invalid ipid %s", *av);
4860 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
4865 NEED1("iplen requires length");
4866 if (strpbrk(*av, "-,")) {
4867 if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
4868 errx(EX_DATAERR, "invalid ip len %s", *av);
4870 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
4875 NEED1("ipver requires version");
4876 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
4880 case TOK_IPPRECEDENCE:
4881 NEED1("ipprecedence requires value");
4882 fill_cmd(cmd, O_IPPRECEDENCE, 0,
4883 (strtoul(*av, NULL, 0) & 7) << 5);
4888 NEED1("missing DSCP code");
4889 fill_dscp(cmd, *av, cblen);
4894 NEED1("missing argument for ipoptions");
4895 fill_flags_cmd(cmd, O_IPOPT, f_ipopts, *av);
4900 NEED1("missing argument for iptos");
4901 fill_flags_cmd(cmd, O_IPTOS, f_iptos, *av);
4906 NEED1("uid requires argument");
4912 cmd->opcode = O_UID;
4913 uid = strtoul(*av, &end, 0);
4914 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
4916 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
4917 cmd32->d[0] = pwd->pw_uid;
4918 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4924 NEED1("gid requires argument");
4930 cmd->opcode = O_GID;
4931 gid = strtoul(*av, &end, 0);
4932 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
4934 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
4935 cmd32->d[0] = grp->gr_gid;
4936 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4942 NEED1("jail requires argument");
4947 cmd->opcode = O_JAIL;
4949 * If av is a number, then we'll just pass it as-is. If
4950 * it's a name, try to resolve that to a jid.
4952 * We save the jail_getid(3) call for a fallback because
4953 * it entails an unconditional trip to the kernel to
4954 * either validate a jid or resolve a name to a jid.
4955 * This specific token doesn't currently require a
4956 * jid to be an active jail, so we save a transition
4957 * by simply using a number that we're given.
4959 jid = strtoul(*av, &end, 10);
4961 jid = jail_getid(*av);
4963 errx(EX_DATAERR, "%s", jail_errmsg);
4965 cmd32->d[0] = (uint32_t)jid;
4966 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4972 fill_cmd(cmd, O_ESTAB, 0, 0);
4976 fill_cmd(cmd, O_TCPFLAGS, 0,
4977 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
4980 case TOK_TCPDATALEN:
4981 NEED1("tcpdatalen requires length");
4982 if (strpbrk(*av, "-,")) {
4983 if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
4984 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
4986 fill_cmd(cmd, O_TCPDATALEN, 0,
4987 strtoul(*av, NULL, 0));
4992 NEED1("missing argument for tcpoptions");
4993 fill_flags_cmd(cmd, O_TCPOPTS, f_tcpopts, *av);
4999 NEED1("tcpseq/tcpack requires argument");
5000 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
5001 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
5002 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
5008 NEED1("tcpmss/tcpwin requires size");
5009 if (strpbrk(*av, "-,")) {
5010 if (add_ports(cmd, *av, 0,
5011 i == TOK_TCPWIN ? O_TCPWIN : O_TCPMSS,
5013 errx(EX_DATAERR, "invalid %s size %s",
5016 fill_cmd(cmd, i == TOK_TCPWIN ? O_TCPWIN :
5017 O_TCPMSS, 0, strtoul(*av, NULL, 0));
5022 NEED1("missing argument for tcpflags");
5023 cmd->opcode = O_TCPFLAGS;
5024 fill_flags_cmd(cmd, O_TCPFLAGS, f_tcpflags, *av);
5029 case TOK_RECORDSTATE: {
5033 errx(EX_USAGE, "keep-state or record-state cannot be part "
5036 errx(EX_USAGE, "only one of keep-state, record-state, "
5037 " limit and set-limit is allowed");
5038 if (*av != NULL && *av[0] == ':') {
5039 if (state_check_name(*av + 1) != 0)
5041 "Invalid state name %s", *av);
5042 uidx = pack_object(tstate, *av + 1,
5043 IPFW_TLV_STATE_NAME);
5046 uidx = pack_object(tstate, default_state_name,
5047 IPFW_TLV_STATE_NAME);
5049 have_rstate = i == TOK_RECORDSTATE;
5050 fill_cmd(cmd, O_KEEP_STATE, 0, uidx);
5055 case TOK_SETLIMIT: {
5056 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
5061 "limit or set-limit cannot be part of an or block");
5063 errx(EX_USAGE, "only one of keep-state, record-state, "
5064 " limit and set-limit is allowed");
5066 have_rstate = i == TOK_SETLIMIT;
5068 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
5070 cmd->opcode = O_LIMIT;
5071 c->limit_mask = c->conn_limit = 0;
5073 while ( av[0] != NULL ) {
5074 if ((val = match_token(limit_masks, *av)) <= 0)
5076 c->limit_mask |= val;
5080 if (c->limit_mask == 0)
5081 errx(EX_USAGE, "limit: missing limit mask");
5083 GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
5084 TOK_LIMIT, rule_options);
5087 if (*av != NULL && *av[0] == ':') {
5088 if (state_check_name(*av + 1) != 0)
5090 "Invalid state name %s", *av);
5091 cmd->arg1 = pack_object(tstate, *av + 1,
5092 IPFW_TLV_STATE_NAME);
5095 cmd->arg1 = pack_object(tstate,
5096 default_state_name, IPFW_TLV_STATE_NAME);
5101 NEED1("missing protocol");
5102 if (add_proto(cmd, *av, &proto)) {
5105 errx(EX_DATAERR, "invalid protocol ``%s''",
5110 NEED1("missing source IP");
5111 if (add_srcip(cmd, *av, cblen, tstate)) {
5117 NEED1("missing destination IP");
5118 if (add_dstip(cmd, *av, cblen, tstate)) {
5124 NEED1("missing source IP6");
5125 if (add_srcip6(cmd, *av, cblen, tstate)) {
5131 NEED1("missing destination IP6");
5132 if (add_dstip6(cmd, *av, cblen, tstate)) {
5139 NEED1("missing source MAC");
5140 if (add_srcmac(cmd, *av, tstate)) {
5146 NEED1("missing destination MAC");
5147 if (add_dstmac(cmd, *av, tstate)) {
5153 NEED1("missing source port");
5154 if (_substrcmp(*av, "any") == 0 ||
5155 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
5158 errx(EX_DATAERR, "invalid source port %s", *av);
5162 NEED1("missing destination port");
5163 if (_substrcmp(*av, "any") == 0 ||
5164 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
5167 errx(EX_DATAERR, "invalid destination port %s",
5172 if (add_mac(cmd, av, cblen))
5177 NEED1("missing mac type");
5178 if (!add_mactype(cmd, *av, cblen))
5179 errx(EX_DATAERR, "invalid mac type %s", *av);
5183 case TOK_VERREVPATH:
5184 fill_cmd(cmd, O_VERREVPATH, 0, 0);
5187 case TOK_VERSRCREACH:
5188 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
5192 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
5196 fill_cmd(cmd, O_IPSEC, 0, 0);
5200 fill_cmd(cmd, O_IP6, 0, 0);
5204 fill_cmd(cmd, O_IP4, 0, 0);
5208 NEED1("missing extension header");
5209 fill_ext6hdr( cmd, *av );
5214 if (proto != IPPROTO_IPV6 )
5215 errx( EX_USAGE, "flow-id filter is active "
5216 "only for ipv6 protocol\n");
5217 fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
5222 fill_comment(cmd, av, cblen);
5227 if (av[0] && strpbrk(*av, "-,")) {
5228 if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
5229 errx(EX_DATAERR, "tagged: invalid tag"
5235 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
5236 TOK_TAGGED, rule_options);
5237 fill_cmd(cmd, O_TAGGED, 0, tag);
5243 NEED1("fib requires fib number");
5244 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
5248 fill_cmd(cmd, O_SOCKARG, 0, 0);
5252 ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
5254 if (!av[0] || !av[1])
5255 errx(EX_USAGE, "format: lookup argument tablenum");
5256 cmd->opcode = O_IP_DST_LOOKUP;
5257 cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
5258 i = match_token(lookup_keys, *av);
5260 errx(EX_USAGE, "format: cannot lookup on %s", *av);
5261 __PAST_END(c->d, 1) = i;
5264 if ((i = pack_table(tstate, *av)) == 0)
5265 errx(EX_DATAERR, "Invalid table name: %s", *av);
5272 NEED1("missing table name");
5273 if (strncmp(*av, "table(", 6) != 0)
5275 "enclose table name into \"table()\"");
5276 fill_table(cmd, *av, O_IP_FLOW_LOOKUP, tstate);
5280 case TOK_SKIPACTION:
5282 errx(EX_USAGE, "only one defer-action "
5285 fill_cmd(cmd, O_SKIP_ACTION, 0, 0);
5289 NEED1("missing mark value:mask");
5290 fill_mark(cmd, *av, cblen);
5295 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
5297 if (F_LEN(cmd) > 0) { /* prepare to advance */
5299 cmd = next_cmd(cmd, &cblen);
5305 if (!have_state && have_skipcmd)
5306 warnx("Rule contains \"defer-immediate-action\" "
5307 "and doesn't contain any state-related options.");
5310 * Now copy stuff into the rule.
5311 * If we have a keep-state option, the first instruction
5312 * must be a PROBE_STATE (which is generated here).
5313 * If we have a LOG option, it was stored as the first command,
5314 * and now must be moved to the top of the action part.
5316 dst = (ipfw_insn *)rule->cmd;
5319 * First thing to write into the command stream is the match probability.
5321 if (match_prob != 1) { /* 1 means always match */
5322 dst->opcode = O_PROB;
5324 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
5329 * generate O_PROBE_STATE if necessary
5331 if (have_state && have_state->opcode != O_CHECK_STATE && !have_rstate) {
5332 fill_cmd(dst, O_PROBE_STATE, 0, have_state->arg1);
5333 dst = next_cmd(dst, &rblen);
5337 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG,
5340 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
5344 switch (src->opcode) {
5353 bcopy(src, dst, i * sizeof(uint32_t));
5359 * put back the have_state command as last opcode
5361 if (have_state && have_state->opcode != O_CHECK_STATE) {
5362 i = F_LEN(have_state);
5364 bcopy(have_state, dst, i * sizeof(uint32_t));
5369 * put back the have_skipcmd command as very last opcode
5372 i = F_LEN(have_skipcmd);
5374 bcopy(have_skipcmd, dst, i * sizeof(uint32_t));
5379 * start action section
5381 rule->act_ofs = dst - rule->cmd;
5383 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
5385 i = F_LEN(have_log);
5387 bcopy(have_log, dst, i * sizeof(uint32_t));
5391 i = F_LEN(have_altq);
5393 bcopy(have_altq, dst, i * sizeof(uint32_t));
5397 i = F_LEN(have_tag);
5399 bcopy(have_tag, dst, i * sizeof(uint32_t));
5404 * copy all other actions
5406 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
5409 bcopy(src, dst, i * sizeof(uint32_t));
5413 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
5414 *rbufsize = (char *)dst - (char *)rule;
5418 compare_ntlv(const void *_a, const void *_b)
5420 const ipfw_obj_ntlv *a, *b;
5422 a = (const ipfw_obj_ntlv *)_a;
5423 b = (const ipfw_obj_ntlv *)_b;
5425 if (a->set < b->set)
5427 else if (a->set > b->set)
5430 if (a->idx < b->idx)
5432 else if (a->idx > b->idx)
5435 if (a->head.type < b->head.type)
5437 else if (a->head.type > b->head.type)
5444 * Provide kernel with sorted list of referenced objects
5447 object_sort_ctlv(ipfw_obj_ctlv *ctlv)
5450 qsort(ctlv + 1, ctlv->count, ctlv->objsize, compare_ntlv);
5458 compare_object_kntlv(const void *k, const void *v)
5460 const ipfw_obj_ntlv *ntlv;
5461 struct object_kt key;
5463 key = *((const struct object_kt *)k);
5464 ntlv = (const ipfw_obj_ntlv *)v;
5466 if (key.uidx < ntlv->idx)
5468 else if (key.uidx > ntlv->idx)
5471 if (key.type < ntlv->head.type)
5473 else if (key.type > ntlv->head.type)
5480 * Finds object name in @ctlv by @idx and @type.
5481 * Uses the following facts:
5482 * 1) All TLVs are the same size
5483 * 2) Kernel implementation provides already sorted list.
5485 * Returns table name or NULL.
5488 object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx, uint16_t type)
5490 ipfw_obj_ntlv *ntlv;
5491 struct object_kt key;
5496 ntlv = bsearch(&key, (ctlv + 1), ctlv->count, ctlv->objsize,
5497 compare_object_kntlv);
5500 return (ntlv->name);
5506 table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx)
5509 return (object_search_ctlv(ctlv, idx, IPFW_TLV_TBL_NAME));
5513 * Adds one or more rules to ipfw chain.
5518 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
5519 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ] (*2) (*3)
5524 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
5525 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ]
5528 * Rules in reply are modified to store their actual ruleset number.
5530 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
5531 * according to their idx field and there has to be no duplicates.
5532 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
5533 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
5536 ipfw_add(char *av[])
5538 uint32_t rulebuf[1024];
5539 int rbufsize, default_off, tlen, rlen;
5542 struct ip_fw_rule *rule;
5544 ip_fw3_opheader *op3;
5545 ipfw_obj_ctlv *ctlv, *tstate;
5547 rbufsize = sizeof(rulebuf);
5548 memset(rulebuf, 0, rbufsize);
5549 memset(&ts, 0, sizeof(ts));
5551 /* Optimize case with no tables */
5552 default_off = sizeof(ipfw_obj_ctlv) + sizeof(ip_fw3_opheader);
5553 op3 = (ip_fw3_opheader *)rulebuf;
5554 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5555 rule = (struct ip_fw_rule *)(ctlv + 1);
5556 rbufsize -= default_off;
5558 compile_rule(av, (uint32_t *)rule, &rbufsize, &ts);
5559 /* Align rule size to u64 boundary */
5560 rlen = roundup2(rbufsize, sizeof(uint64_t));
5565 if (ts.count != 0) {
5566 /* Some tables. We have to alloc more data */
5567 tlen = ts.count * sizeof(ipfw_obj_ntlv);
5568 sz = default_off + sizeof(ipfw_obj_ctlv) + tlen + rlen;
5570 if ((tbuf = calloc(1, sz)) == NULL)
5571 err(EX_UNAVAILABLE, "malloc() failed for IP_FW_ADD");
5572 op3 = (ip_fw3_opheader *)tbuf;
5574 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5575 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
5576 ctlv->head.length = sizeof(ipfw_obj_ctlv) + tlen;
5577 ctlv->count = ts.count;
5578 ctlv->objsize = sizeof(ipfw_obj_ntlv);
5579 memcpy(ctlv + 1, ts.idx, tlen);
5580 object_sort_ctlv(ctlv);
5583 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
5584 ctlv->head.type = IPFW_TLV_RULE_LIST;
5585 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5587 memcpy(ctlv + 1, rule, rbufsize);
5589 /* Simply add header */
5590 sz = rlen + default_off;
5591 memset(ctlv, 0, sizeof(*ctlv));
5592 ctlv->head.type = IPFW_TLV_RULE_LIST;
5593 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5597 if (do_get3(IP_FW_XADD, op3, &sz) != 0)
5598 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_XADD");
5600 if (!g_co.do_quiet) {
5601 struct format_opts sfo;
5603 memset(&sfo, 0, sizeof(sfo));
5604 sfo.tstate = tstate;
5605 sfo.set_mask = (uint32_t)(-1);
5606 bp_alloc(&bp, 4096);
5607 show_static_rule(&g_co, &sfo, &bp, rule, NULL);
5608 printf("%s", bp.buf);
5620 * clear the counters or the log counters.
5621 * optname has the following values:
5622 * 0 (zero both counters and logging)
5623 * 1 (zero logging only)
5626 ipfw_zero(int ac, char *av[], int optname)
5630 char const *name = optname ? "RESETLOG" : "ZERO";
5634 optname = optname ? IP_FW_XRESETLOG : IP_FW_XZERO;
5638 /* clear all entries */
5639 memset(&rt, 0, sizeof(rt));
5640 rt.flags = IPFW_RCFLAG_ALL;
5641 if (do_range_cmd(optname, &rt) < 0)
5642 err(EX_UNAVAILABLE, "setsockopt(IP_FW_X%s)", name);
5644 printf("%s.\n", optname == IP_FW_XZERO ?
5645 "Accounting cleared":"Logging counts reset");
5652 if (isdigit(**av)) {
5653 arg = strtonum(*av, 0, 0xffff, &errstr);
5656 "invalid rule number %s\n", *av);
5657 memset(&rt, 0, sizeof(rt));
5658 rt.start_rule = arg;
5660 rt.flags |= IPFW_RCFLAG_RANGE;
5661 if (g_co.use_set != 0) {
5662 rt.set = g_co.use_set - 1;
5663 rt.flags |= IPFW_RCFLAG_SET;
5665 if (do_range_cmd(optname, &rt) != 0) {
5666 warn("rule %u: setsockopt(IP_FW_X%s)",
5668 failed = EX_UNAVAILABLE;
5669 } else if (rt.new_set == 0) {
5670 printf("Entry %d not found\n", arg);
5671 failed = EX_UNAVAILABLE;
5672 } else if (!g_co.do_quiet)
5673 printf("Entry %d %s.\n", arg,
5674 optname == IP_FW_XZERO ?
5675 "cleared" : "logging count reset");
5677 errx(EX_USAGE, "invalid rule number ``%s''", *av);
5681 if (failed != EX_OK)
5686 ipfw_flush(int force)
5690 if (!force && !g_co.do_quiet) { /* need to ask user */
5693 printf("Are you sure? [yn] ");
5696 c = toupper(getc(stdin));
5697 while (c != '\n' && getc(stdin) != '\n')
5699 return; /* and do not flush */
5700 } while (c != 'Y' && c != 'N');
5702 if (c == 'N') /* user said no */
5709 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
5710 memset(&rt, 0, sizeof(rt));
5711 if (g_co.use_set != 0) {
5712 rt.set = g_co.use_set - 1;
5713 rt.flags = IPFW_RCFLAG_SET;
5715 rt.flags = IPFW_RCFLAG_ALL;
5716 if (do_range_cmd(IP_FW_XDEL, &rt) != 0)
5717 err(EX_UNAVAILABLE, "setsockopt(IP_FW_XDEL)");
5719 printf("Flushed all %s.\n", g_co.do_pipe ? "pipes" : "rules");
5722 static struct _s_x intcmds[] = {
5723 { "talist", TOK_TALIST },
5724 { "iflist", TOK_IFLIST },
5725 { "olist", TOK_OLIST },
5726 { "vlist", TOK_VLIST },
5730 static struct _s_x otypes[] = {
5731 { "EACTION", IPFW_TLV_EACTION },
5732 { "DYNSTATE", IPFW_TLV_STATE_NAME },
5737 lookup_eaction_name(ipfw_obj_ntlv *ntlv, int cnt, uint16_t type)
5743 for (i = 0; i < cnt; i++) {
5744 if (ntlv[i].head.type != IPFW_TLV_EACTION)
5746 if (IPFW_TLV_EACTION_NAME(ntlv[i].idx) != type)
5748 name = ntlv[i].name;
5755 ipfw_list_objects(int ac __unused, char *av[] __unused)
5757 ipfw_obj_lheader req, *olh;
5758 ipfw_obj_ntlv *ntlv;
5763 memset(&req, 0, sizeof(req));
5765 if (do_get3(IP_FW_DUMP_SRVOBJECTS, &req.opheader, &sz) != 0)
5766 if (errno != ENOMEM)
5770 if ((olh = calloc(1, sz)) == NULL)
5774 if (do_get3(IP_FW_DUMP_SRVOBJECTS, &olh->opheader, &sz) != 0) {
5780 printf("Objects list:\n");
5782 printf("There are no objects\n");
5783 ntlv = (ipfw_obj_ntlv *)(olh + 1);
5784 for (i = 0; i < olh->count; i++) {
5785 name = match_value(otypes, ntlv->head.type);
5787 name = lookup_eaction_name(
5788 (ipfw_obj_ntlv *)(olh + 1), olh->count,
5791 printf(" kidx: %4d\ttype: %10d\tname: %s\n",
5792 ntlv->idx, ntlv->head.type, ntlv->name);
5794 printf(" kidx: %4d\ttype: %10s\tname: %s\n",
5795 ntlv->idx, name, ntlv->name);
5802 ipfw_internal_handler(int ac, char *av[])
5807 NEED1("internal cmd required");
5809 if ((tcmd = match_token(intcmds, *av)) == -1)
5810 errx(EX_USAGE, "invalid internal sub-cmd: %s", *av);
5814 ipfw_list_tifaces();
5817 ipfw_list_ta(ac, av);
5820 ipfw_list_objects(ac, av);
5823 ipfw_list_values(ac, av);
5829 ipfw_get_tracked_ifaces(ipfw_obj_lheader **polh)
5831 ipfw_obj_lheader req, *olh;
5834 memset(&req, 0, sizeof(req));
5837 if (do_get3(IP_FW_XIFLIST, &req.opheader, &sz) != 0) {
5838 if (errno != ENOMEM)
5843 if ((olh = calloc(1, sz)) == NULL)
5847 if (do_get3(IP_FW_XIFLIST, &olh->opheader, &sz) != 0) {
5857 ifinfo_cmp(const void *a, const void *b)
5859 const ipfw_iface_info *ia, *ib;
5861 ia = (const ipfw_iface_info *)a;
5862 ib = (const ipfw_iface_info *)b;
5864 return (stringnum_cmp(ia->ifname, ib->ifname));
5868 * Retrieves table list from kernel,
5869 * optionally sorts it and calls requested function for each table.
5870 * Returns 0 on success.
5873 ipfw_list_tifaces(void)
5875 ipfw_obj_lheader *olh = NULL;
5876 ipfw_iface_info *info;
5880 if ((error = ipfw_get_tracked_ifaces(&olh)) != 0)
5881 err(EX_OSERR, "Unable to request ipfw tracked interface list");
5883 qsort(olh + 1, olh->count, olh->objsize, ifinfo_cmp);
5885 info = (ipfw_iface_info *)(olh + 1);
5886 for (i = 0; i < olh->count; i++) {
5887 if (info->flags & IPFW_IFFLAG_RESOLVED)
5888 printf("%s ifindex: %d refcount: %u changes: %u\n",
5889 info->ifname, info->ifindex, info->refcnt,
5892 printf("%s ifindex: unresolved refcount: %u changes: %u\n",
5893 info->ifname, info->refcnt, info->gencnt);
5894 info = (ipfw_iface_info *)((caddr_t)info + olh->objsize);