2 * Copyright (c) 2002-2003 Luigi Rizzo
3 * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
4 * Copyright (c) 1994 Ugen J.S.Antsilevich
6 * Idea and grammar partially left from:
7 * Copyright (c) 1993 Daniel Boulet
9 * Redistribution and use in source forms, with and without modification,
10 * are permitted provided that this entire comment appears intact.
12 * Redistribution in binary form may occur without any restrictions.
13 * Obviously, it would be nice if you gave credit where credit is due
14 * but requiring it would be too onerous.
16 * This software is provided ``AS IS'' without any warranties of any kind.
18 * NEW command line interface for IP firewall facility
23 #include <sys/types.h>
24 #include <sys/param.h>
25 #include <sys/socket.h>
26 #include <sys/sockio.h>
27 #include <sys/sysctl.h>
44 #include <time.h> /* ctime */
45 #include <timeconv.h> /* _long_to_time */
48 #include <stddef.h> /* offsetof */
50 #include <net/ethernet.h>
51 #include <net/if.h> /* only IFNAMSIZ */
52 #include <netinet/in.h>
53 #include <netinet/in_systm.h> /* only n_short, n_long */
54 #include <netinet/ip.h>
55 #include <netinet/ip_icmp.h>
56 #include <netinet/ip_fw.h>
57 #include <netinet/tcp.h>
58 #include <arpa/inet.h>
60 struct cmdline_opts co; /* global options */
66 int show_time; /* show timestamp */
67 uint32_t set_mask; /* enabled sets mask */
68 uint32_t flags; /* request flags */
69 uint32_t first; /* first rule to request */
70 uint32_t last; /* last rule to request */
71 uint32_t dcnt; /* number of dynamic states */
72 ipfw_obj_ctlv *tstate; /* table state data */
75 int resvd_set_number = RESVD_SET;
79 #define CHECK_LENGTH(v, len) do { \
81 errx(EX_DATAERR, "Rule too long"); \
84 * Check if we have enough space in cmd buffer. Note that since
85 * first 8? u32 words are reserved by reserved header, full cmd
86 * buffer can't be used, so we need to protect from buffer overrun
87 * only. At the beginning, cblen is less than actual buffer size by
88 * size of ipfw_insn_u32 instruction + 1 u32 work. This eliminates need
89 * for checking small instructions fitting in given range.
90 * We also (ab)use the fact that ipfw_insn is always the first field
91 * for any custom instruction.
93 #define CHECK_CMDLEN CHECK_LENGTH(cblen, F_LEN((ipfw_insn *)cmd))
95 #define GET_UINT_ARG(arg, min, max, tok, s_x) do { \
97 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
98 if (_substrcmp(*av, "tablearg") == 0) { \
107 _xval = strtol(*av, &end, 10); \
109 if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
110 errx(EX_DATAERR, "%s: invalid argument: %s", \
111 match_value(s_x, tok), *av); \
113 if (errno == ERANGE || _xval < min || _xval > max) \
114 errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
115 match_value(s_x, tok), min, max, *av); \
117 if (_xval == IP_FW_TARG) \
118 errx(EX_DATAERR, "%s: illegal argument value: %s", \
119 match_value(s_x, tok), *av); \
124 static struct _s_x f_tcpflags[] = {
135 static struct _s_x f_tcpopts[] = {
136 { "mss", IP_FW_TCPOPT_MSS },
137 { "maxseg", IP_FW_TCPOPT_MSS },
138 { "window", IP_FW_TCPOPT_WINDOW },
139 { "sack", IP_FW_TCPOPT_SACK },
140 { "ts", IP_FW_TCPOPT_TS },
141 { "timestamp", IP_FW_TCPOPT_TS },
142 { "cc", IP_FW_TCPOPT_CC },
148 * IP options span the range 0 to 255 so we need to remap them
149 * (though in fact only the low 5 bits are significant).
151 static struct _s_x f_ipopts[] = {
152 { "ssrr", IP_FW_IPOPT_SSRR},
153 { "lsrr", IP_FW_IPOPT_LSRR},
154 { "rr", IP_FW_IPOPT_RR},
155 { "ts", IP_FW_IPOPT_TS},
160 static struct _s_x f_iptos[] = {
161 { "lowdelay", IPTOS_LOWDELAY},
162 { "throughput", IPTOS_THROUGHPUT},
163 { "reliability", IPTOS_RELIABILITY},
164 { "mincost", IPTOS_MINCOST},
165 { "congestion", IPTOS_ECN_CE},
166 { "ecntransport", IPTOS_ECN_ECT0},
167 { "ip tos option", 0},
171 struct _s_x f_ipdscp[] = {
172 { "af11", IPTOS_DSCP_AF11 >> 2 }, /* 001010 */
173 { "af12", IPTOS_DSCP_AF12 >> 2 }, /* 001100 */
174 { "af13", IPTOS_DSCP_AF13 >> 2 }, /* 001110 */
175 { "af21", IPTOS_DSCP_AF21 >> 2 }, /* 010010 */
176 { "af22", IPTOS_DSCP_AF22 >> 2 }, /* 010100 */
177 { "af23", IPTOS_DSCP_AF23 >> 2 }, /* 010110 */
178 { "af31", IPTOS_DSCP_AF31 >> 2 }, /* 011010 */
179 { "af32", IPTOS_DSCP_AF32 >> 2 }, /* 011100 */
180 { "af33", IPTOS_DSCP_AF33 >> 2 }, /* 011110 */
181 { "af41", IPTOS_DSCP_AF41 >> 2 }, /* 100010 */
182 { "af42", IPTOS_DSCP_AF42 >> 2 }, /* 100100 */
183 { "af43", IPTOS_DSCP_AF43 >> 2 }, /* 100110 */
184 { "be", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
185 { "ef", IPTOS_DSCP_EF >> 2 }, /* 101110 */
186 { "cs0", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
187 { "cs1", IPTOS_DSCP_CS1 >> 2 }, /* 001000 */
188 { "cs2", IPTOS_DSCP_CS2 >> 2 }, /* 010000 */
189 { "cs3", IPTOS_DSCP_CS3 >> 2 }, /* 011000 */
190 { "cs4", IPTOS_DSCP_CS4 >> 2 }, /* 100000 */
191 { "cs5", IPTOS_DSCP_CS5 >> 2 }, /* 101000 */
192 { "cs6", IPTOS_DSCP_CS6 >> 2 }, /* 110000 */
193 { "cs7", IPTOS_DSCP_CS7 >> 2 }, /* 100000 */
197 static struct _s_x limit_masks[] = {
198 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
199 {"src-addr", DYN_SRC_ADDR},
200 {"src-port", DYN_SRC_PORT},
201 {"dst-addr", DYN_DST_ADDR},
202 {"dst-port", DYN_DST_PORT},
207 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
208 * This is only used in this code.
210 #define IPPROTO_ETHERTYPE 0x1000
211 static struct _s_x ether_types[] = {
213 * Note, we cannot use "-:&/" in the names because they are field
214 * separators in the type specifications. Also, we use s = NULL as
215 * end-delimiter, because a type of 0 can be legal.
228 { "pppoe_disc", 0x8863 },
229 { "pppoe_sess", 0x8864 },
230 { "ipx_8022", 0x00E0 },
231 { "ipx_8023", 0x0000 },
232 { "ipx_ii", 0x8137 },
233 { "ipx_snap", 0x8137 },
239 static struct _s_x rule_eactions[] = {
240 { "nat64clat", TOK_NAT64CLAT },
241 { "nat64lsn", TOK_NAT64LSN },
242 { "nat64stl", TOK_NAT64STL },
243 { "nptv6", TOK_NPTV6 },
244 { "tcp-setmss", TOK_TCPSETMSS },
245 { NULL, 0 } /* terminator */
248 static struct _s_x rule_actions[] = {
249 { "abort6", TOK_ABORT6 },
250 { "abort", TOK_ABORT },
251 { "accept", TOK_ACCEPT },
252 { "pass", TOK_ACCEPT },
253 { "allow", TOK_ACCEPT },
254 { "permit", TOK_ACCEPT },
255 { "count", TOK_COUNT },
256 { "pipe", TOK_PIPE },
257 { "queue", TOK_QUEUE },
258 { "divert", TOK_DIVERT },
260 { "netgraph", TOK_NETGRAPH },
261 { "ngtee", TOK_NGTEE },
262 { "fwd", TOK_FORWARD },
263 { "forward", TOK_FORWARD },
264 { "skipto", TOK_SKIPTO },
265 { "deny", TOK_DENY },
266 { "drop", TOK_DENY },
267 { "reject", TOK_REJECT },
268 { "reset6", TOK_RESET6 },
269 { "reset", TOK_RESET },
270 { "unreach6", TOK_UNREACH6 },
271 { "unreach", TOK_UNREACH },
272 { "check-state", TOK_CHECKSTATE },
273 { "//", TOK_COMMENT },
275 { "reass", TOK_REASS },
276 { "setfib", TOK_SETFIB },
277 { "setdscp", TOK_SETDSCP },
278 { "call", TOK_CALL },
279 { "return", TOK_RETURN },
280 { "eaction", TOK_EACTION },
281 { "tcp-setmss", TOK_TCPSETMSS },
282 { NULL, 0 } /* terminator */
285 static struct _s_x rule_action_params[] = {
286 { "altq", TOK_ALTQ },
289 { "untag", TOK_UNTAG },
290 { NULL, 0 } /* terminator */
294 * The 'lookup' instruction accepts one of the following arguments.
295 * -1 is a terminator for the list.
296 * Arguments are passed as v[1] in O_DST_LOOKUP options.
298 static int lookup_key[] = {
299 TOK_DSTIP, TOK_SRCIP, TOK_DSTPORT, TOK_SRCPORT,
300 TOK_UID, TOK_JAIL, TOK_DSCP, -1 };
302 static struct _s_x rule_options[] = {
303 { "tagged", TOK_TAGGED },
306 { "jail", TOK_JAIL },
308 { "limit", TOK_LIMIT },
309 { "set-limit", TOK_SETLIMIT },
310 { "keep-state", TOK_KEEPSTATE },
311 { "record-state", TOK_RECORDSTATE },
312 { "bridged", TOK_LAYER2 },
313 { "layer2", TOK_LAYER2 },
315 { "diverted", TOK_DIVERTED },
316 { "diverted-loopback", TOK_DIVERTEDLOOPBACK },
317 { "diverted-output", TOK_DIVERTEDOUTPUT },
318 { "xmit", TOK_XMIT },
319 { "recv", TOK_RECV },
321 { "fragment", TOK_FRAG },
322 { "frag", TOK_FRAG },
324 { "ipoptions", TOK_IPOPTS },
325 { "ipopts", TOK_IPOPTS },
326 { "iplen", TOK_IPLEN },
327 { "ipid", TOK_IPID },
328 { "ipprecedence", TOK_IPPRECEDENCE },
329 { "dscp", TOK_DSCP },
330 { "iptos", TOK_IPTOS },
331 { "ipttl", TOK_IPTTL },
332 { "ipversion", TOK_IPVER },
333 { "ipver", TOK_IPVER },
334 { "estab", TOK_ESTAB },
335 { "established", TOK_ESTAB },
336 { "setup", TOK_SETUP },
337 { "sockarg", TOK_SOCKARG },
338 { "tcpdatalen", TOK_TCPDATALEN },
339 { "tcpflags", TOK_TCPFLAGS },
340 { "tcpflgs", TOK_TCPFLAGS },
341 { "tcpoptions", TOK_TCPOPTS },
342 { "tcpopts", TOK_TCPOPTS },
343 { "tcpseq", TOK_TCPSEQ },
344 { "tcpack", TOK_TCPACK },
345 { "tcpwin", TOK_TCPWIN },
346 { "icmptype", TOK_ICMPTYPES },
347 { "icmptypes", TOK_ICMPTYPES },
348 { "dst-ip", TOK_DSTIP },
349 { "src-ip", TOK_SRCIP },
350 { "dst-port", TOK_DSTPORT },
351 { "src-port", TOK_SRCPORT },
352 { "proto", TOK_PROTO },
355 { "mac-type", TOK_MACTYPE },
356 { "verrevpath", TOK_VERREVPATH },
357 { "versrcreach", TOK_VERSRCREACH },
358 { "antispoof", TOK_ANTISPOOF },
359 { "ipsec", TOK_IPSEC },
360 { "icmp6type", TOK_ICMP6TYPES },
361 { "icmp6types", TOK_ICMP6TYPES },
362 { "ext6hdr", TOK_EXT6HDR},
363 { "flow-id", TOK_FLOWID},
368 { "dst-ipv6", TOK_DSTIP6},
369 { "dst-ip6", TOK_DSTIP6},
370 { "src-ipv6", TOK_SRCIP6},
371 { "src-ip6", TOK_SRCIP6},
372 { "lookup", TOK_LOOKUP},
374 { "defer-action", TOK_SKIPACTION },
375 { "defer-immediate-action", TOK_SKIPACTION },
376 { "//", TOK_COMMENT },
378 { "not", TOK_NOT }, /* pseudo option */
379 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
380 { "or", TOK_OR }, /* pseudo option */
381 { "|", /* escape */ TOK_OR }, /* pseudo option */
382 { "{", TOK_STARTBRACE }, /* pseudo option */
383 { "(", TOK_STARTBRACE }, /* pseudo option */
384 { "}", TOK_ENDBRACE }, /* pseudo option */
385 { ")", TOK_ENDBRACE }, /* pseudo option */
386 { NULL, 0 } /* terminator */
389 void bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg);
390 static int ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
391 ipfw_cfg_lheader **pcfg, size_t *psize);
392 static int ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
393 ipfw_cfg_lheader *cfg, size_t sz, int ac, char **av);
394 static void ipfw_list_tifaces(void);
397 static uint16_t pack_object(struct tidx *tstate, char *name, int otype);
398 static uint16_t pack_table(struct tidx *tstate, char *name);
400 static char *table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx);
401 static void object_sort_ctlv(ipfw_obj_ctlv *ctlv);
402 static char *object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx,
406 * Simple string buffer API.
407 * Used to simplify buffer passing between function and for
408 * transparent overrun handling.
412 * Allocates new buffer of given size @sz.
414 * Returns 0 on success.
417 bp_alloc(struct buf_pr *b, size_t size)
419 memset(b, 0, sizeof(struct buf_pr));
421 if ((b->buf = calloc(1, size)) == NULL)
432 bp_free(struct buf_pr *b)
439 * Flushes buffer so new writer start from beginning.
442 bp_flush(struct buf_pr *b)
451 * Print message specified by @format and args.
452 * Automatically manage buffer space and transparently handle
455 * Returns number of bytes that should have been printed.
458 bprintf(struct buf_pr *b, char *format, ...)
463 va_start(args, format);
465 i = vsnprintf(b->ptr, b->avail, format, args);
468 if (i > b->avail || i < 0) {
469 /* Overflow or print error */
482 * Special values printer for tablearg-aware opcodes.
485 bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg)
489 bprintf(bp, "%s", str);
490 if (arg == IP_FW_TARG)
491 bprintf(bp, "tablearg");
493 bprintf(bp, "%u", arg);
497 * Helper routine to print a possibly unaligned uint64_t on
498 * various platform. If width > 0, print the value with
499 * the desired width, followed by a space;
500 * otherwise, return the required width.
503 pr_u64(struct buf_pr *b, uint64_t *pd, int width)
506 #define U64_FMT "I64"
508 #define U64_FMT "llu"
511 unsigned long long d;
513 bcopy (pd, &u, sizeof(u));
516 bprintf(b, "%*" U64_FMT " ", width, d) :
517 snprintf(NULL, 0, "%" U64_FMT, d) ;
523 safe_calloc(size_t number, size_t size)
525 void *ret = calloc(number, size);
528 err(EX_OSERR, "calloc");
533 safe_realloc(void *ptr, size_t size)
535 void *ret = realloc(ptr, size);
538 err(EX_OSERR, "realloc");
543 * Compare things like interface or table names.
546 stringnum_cmp(const char *a, const char *b)
558 return (strcmp(a, b));
563 * conditionally runs the command.
564 * Selected options or negative -> getsockopt
567 do_cmd(int optname, void *optval, uintptr_t optlen)
574 if (ipfw_socket == -1)
575 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
577 err(EX_UNAVAILABLE, "socket");
579 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
580 optname == IP_FW_ADD || optname == IP_FW3 ||
581 optname == IP_FW_NAT_GET_CONFIG ||
583 optname == IP_FW_NAT_GET_LOG) {
586 i = getsockopt(ipfw_socket, IPPROTO_IP, optname, optval,
587 (socklen_t *)optlen);
589 i = setsockopt(ipfw_socket, IPPROTO_IP, optname, optval, optlen);
595 * do_set3 - pass ipfw control cmd to kernel
596 * @optname: option name
597 * @optval: pointer to option data
598 * @optlen: option length
600 * Assumes op3 header is already embedded.
601 * Calls setsockopt() with IP_FW3 as kernel-visible opcode.
602 * Returns 0 on success or errno otherwise.
605 do_set3(int optname, ip_fw3_opheader *op3, size_t optlen)
611 if (ipfw_socket == -1)
612 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
614 err(EX_UNAVAILABLE, "socket");
616 op3->opcode = optname;
618 return (setsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, optlen));
622 * do_get3 - pass ipfw control cmd to kernel
623 * @optname: option name
624 * @optval: pointer to option data
625 * @optlen: pointer to option length
627 * Assumes op3 header is already embedded.
628 * Calls getsockopt() with IP_FW3 as kernel-visible opcode.
629 * Returns 0 on success or errno otherwise.
632 do_get3(int optname, ip_fw3_opheader *op3, size_t *optlen)
640 if (ipfw_socket == -1)
641 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
643 err(EX_UNAVAILABLE, "socket");
645 op3->opcode = optname;
648 error = getsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, &len);
655 * match_token takes a table and a string, returns the value associated
656 * with the string (-1 in case of failure).
659 match_token(struct _s_x *table, const char *string)
662 uint i = strlen(string);
664 for (pt = table ; i && pt->s != NULL ; pt++)
665 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
671 * match_token_relaxed takes a table and a string, returns the value associated
672 * with the string for the best match.
675 * value from @table for matched records
676 * -1 for non-matched records
677 * -2 if more than one records match @string.
680 match_token_relaxed(struct _s_x *table, const char *string)
688 for (pt = table ; i != 0 && pt->s != NULL ; pt++) {
689 if (strncmp(pt->s, string, i) != 0)
698 return (c > 0 ? -2: -1);
702 get_token(struct _s_x *table, const char *string, const char *errbase)
706 if ((tcmd = match_token_relaxed(table, string)) < 0)
707 errx(EX_USAGE, "%s %s %s",
708 (tcmd == 0) ? "invalid" : "ambiguous", errbase, string);
714 * match_value takes a table and a value, returns the string associated
715 * with the value (NULL in case of failure).
718 match_value(struct _s_x *p, int value)
720 for (; p->s != NULL; p++)
727 concat_tokens(char *buf, size_t bufsize, struct _s_x *table, char *delimiter)
733 for (sz = 0, pt = table ; pt->s != NULL; pt++) {
734 l = snprintf(buf + sz, bufsize - sz, "%s%s",
735 (sz == 0) ? "" : delimiter, pt->s);
746 * helper function to process a set of flags and set bits in the
750 fill_flags(struct _s_x *flags, char *p, char **e, uint32_t *set,
753 char *q; /* points to the separator */
755 uint32_t *which; /* mask we are working on */
766 val = match_token(flags, p);
772 *which |= (uint32_t)val;
779 print_flags_buffer(char *buf, size_t sz, struct _s_x *list, uint32_t set)
781 char const *comma = "";
784 for (i = 0; list[i].x != 0; i++) {
785 if ((set & list[i].x) == 0)
789 l = snprintf(buf, sz, "%s%s", comma, list[i].s);
799 * _substrcmp takes two strings and returns 1 if they do not match,
800 * and 0 if they match exactly or the first string is a sub-string
801 * of the second. A warning is printed to stderr in the case that the
802 * first string is a sub-string of the second.
804 * This function will be removed in the future through the usual
805 * deprecation process.
808 _substrcmp(const char *str1, const char* str2)
811 if (strncmp(str1, str2, strlen(str1)) != 0)
814 if (strlen(str1) != strlen(str2))
815 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
821 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
822 * and 0 if they match exactly or the second string is a sub-string
823 * of the first. A warning is printed to stderr in the case that the
824 * first string does not match the third.
826 * This function exists to warn about the bizarre construction
827 * strncmp(str, "by", 2) which is used to allow people to use a shortcut
828 * for "bytes". The problem is that in addition to accepting "by",
829 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
830 * other string beginning with "by".
832 * This function will be removed in the future through the usual
833 * deprecation process.
836 _substrcmp2(const char *str1, const char* str2, const char* str3)
839 if (strncmp(str1, str2, strlen(str2)) != 0)
842 if (strcmp(str1, str3) != 0)
843 warnx("DEPRECATED: '%s' matched '%s'",
849 * prints one port, symbolic or numeric
852 print_port(struct buf_pr *bp, int proto, uint16_t port)
855 if (proto == IPPROTO_ETHERTYPE) {
858 if (co.do_resolv && (s = match_value(ether_types, port)) )
859 bprintf(bp, "%s", s);
861 bprintf(bp, "0x%04x", port);
863 struct servent *se = NULL;
865 struct protoent *pe = getprotobynumber(proto);
867 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
870 bprintf(bp, "%s", se->s_name);
872 bprintf(bp, "%d", port);
876 static struct _s_x _port_name[] = {
877 {"dst-port", O_IP_DSTPORT},
878 {"src-port", O_IP_SRCPORT},
882 {"mac-type", O_MAC_TYPE},
883 {"tcpdatalen", O_TCPDATALEN},
884 {"tcpwin", O_TCPWIN},
885 {"tagged", O_TAGGED},
890 * Print the values in a list 16-bit items of the types above.
891 * XXX todo: add support for mask.
894 print_newports(struct buf_pr *bp, ipfw_insn_u16 *cmd, int proto, int opcode)
896 uint16_t *p = cmd->ports;
901 sep = match_value(_port_name, opcode);
904 bprintf(bp, " %s", sep);
907 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
908 bprintf(bp, "%s", sep);
909 print_port(bp, proto, p[0]);
912 print_port(bp, proto, p[1]);
919 * Like strtol, but also translates service names into port numbers
920 * for some protocols.
922 * proto == -1 disables the protocol check;
923 * proto == IPPROTO_ETHERTYPE looks up an internal table
924 * proto == <some value in /etc/protocols> matches the values there.
925 * Returns *end == s in case the parameter is not found.
928 strtoport(char *s, char **end, int base, int proto)
934 *end = s; /* default - not found */
936 return 0; /* not found */
939 return strtol(s, end, base);
942 * find separator. '\\' escapes the next char.
944 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\' ||
945 *s1 == '_' || *s1 == '.') ; s1++)
946 if (*s1 == '\\' && s1[1] != '\0')
949 buf = safe_calloc(s1 - s + 1, 1);
952 * copy into a buffer skipping backslashes
954 for (p = s, i = 0; p != s1 ; p++)
959 if (proto == IPPROTO_ETHERTYPE) {
960 i = match_token(ether_types, buf);
962 if (i != -1) { /* found */
967 struct protoent *pe = NULL;
971 pe = getprotobynumber(proto);
973 se = getservbyname(buf, pe ? pe->p_name : NULL);
977 return ntohs(se->s_port);
980 return 0; /* not found */
984 * Fill the body of the command with the list of port ranges.
987 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
989 uint16_t a, b, *p = cmd->ports;
994 a = strtoport(av, &s, 0, proto);
995 if (s == av) /* empty or invalid argument */
998 CHECK_LENGTH(cblen, i + 2);
1001 case '-': /* a range */
1003 b = strtoport(av, &s, 0, proto);
1004 /* Reject expressions like '1-abc' or '1-2-3'. */
1005 if (s == av || (*s != ',' && *s != '\0'))
1010 case ',': /* comma separated list */
1015 warnx("port list: invalid separator <%c> in <%s>",
1025 if (i + 1 > F_LEN_MASK)
1026 errx(EX_DATAERR, "too many ports/ranges\n");
1027 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
1033 * Fill the body of the command with the list of DiffServ codepoints.
1036 fill_dscp(ipfw_insn *cmd, char *av, int cblen)
1038 uint32_t *low, *high;
1042 cmd->opcode = O_DSCP;
1043 cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
1047 low = (uint32_t *)(cmd + 1);
1060 if ((code = match_token(f_ipdscp, s)) == -1)
1061 errx(EX_DATAERR, "Unknown DSCP code");
1063 code = strtoul(s, NULL, 10);
1064 if (code < 0 || code > 63)
1065 errx(EX_DATAERR, "Invalid DSCP value");
1069 *high |= 1 << (code - 32);
1077 static struct _s_x icmpcodes[] = {
1078 { "net", ICMP_UNREACH_NET },
1079 { "host", ICMP_UNREACH_HOST },
1080 { "protocol", ICMP_UNREACH_PROTOCOL },
1081 { "port", ICMP_UNREACH_PORT },
1082 { "needfrag", ICMP_UNREACH_NEEDFRAG },
1083 { "srcfail", ICMP_UNREACH_SRCFAIL },
1084 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
1085 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
1086 { "isolated", ICMP_UNREACH_ISOLATED },
1087 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
1088 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
1089 { "tosnet", ICMP_UNREACH_TOSNET },
1090 { "toshost", ICMP_UNREACH_TOSHOST },
1091 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
1092 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
1093 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
1098 fill_reject_code(u_short *codep, char *str)
1103 val = strtoul(str, &s, 0);
1104 if (s == str || *s != '\0' || val >= 0x100)
1105 val = match_token(icmpcodes, str);
1107 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
1113 print_reject_code(struct buf_pr *bp, uint16_t code)
1117 if ((s = match_value(icmpcodes, code)) != NULL)
1118 bprintf(bp, "unreach %s", s);
1120 bprintf(bp, "unreach %u", code);
1124 * Returns the number of bits set (from left) in a contiguous bitmask,
1125 * or -1 if the mask is not contiguous.
1126 * XXX this needs a proper fix.
1127 * This effectively works on masks in big-endian (network) format.
1128 * when compiled on little endian architectures.
1130 * First bit is bit 7 of the first byte -- note, for MAC addresses,
1131 * the first bit on the wire is bit 0 of the first byte.
1132 * len is the max length in bits.
1135 contigmask(uint8_t *p, int len)
1139 for (i=0; i<len ; i++)
1140 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
1142 for (n=i+1; n < len; n++)
1143 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
1144 return -1; /* mask not contiguous */
1149 * print flags set/clear in the two bitmasks passed as parameters.
1150 * There is a specialized check for f_tcpflags.
1153 print_flags(struct buf_pr *bp, char const *name, ipfw_insn *cmd,
1156 char const *comma = "";
1158 uint8_t set = cmd->arg1 & 0xff;
1159 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
1161 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
1162 bprintf(bp, " setup");
1166 bprintf(bp, " %s ", name);
1167 for (i=0; list[i].x != 0; i++) {
1168 if (set & list[i].x) {
1170 bprintf(bp, "%s%s", comma, list[i].s);
1173 if (clear & list[i].x) {
1174 clear &= ~list[i].x;
1175 bprintf(bp, "%s!%s", comma, list[i].s);
1183 * Print the ip address contained in a command.
1186 print_ip(struct buf_pr *bp, const struct format_opts *fo, ipfw_insn_ip *cmd)
1188 struct hostent *he = NULL;
1190 uint32_t len = F_LEN((ipfw_insn *)cmd);
1191 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
1195 if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
1197 const char *arg = "<invalid>";
1199 if (d < sizeof(lookup_key)/sizeof(lookup_key[0]))
1200 arg = match_value(rule_options, lookup_key[d]);
1201 t = table_search_ctlv(fo->tstate, ((ipfw_insn *)cmd)->arg1);
1202 bprintf(bp, "lookup %s %s", arg, t);
1205 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
1209 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
1210 cmd->o.opcode == O_IP_DST_LOOKUP) {
1211 t = table_search_ctlv(fo->tstate, ((ipfw_insn *)cmd)->arg1);
1212 bprintf(bp, "table(%s", t);
1213 if (len == F_INSN_SIZE(ipfw_insn_u32))
1214 bprintf(bp, ",%u", *a);
1218 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
1219 uint32_t x, *map = (uint32_t *)&(cmd->mask);
1223 x = cmd->o.arg1 - 1;
1225 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1226 bprintf(bp, "%s/%d", inet_ntoa(cmd->addr),
1227 contigmask((uint8_t *)&x, 32));
1228 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1229 x &= 0xff; /* base */
1231 * Print bits and ranges.
1232 * Locate first bit set (i), then locate first bit unset (j).
1233 * If we have 3+ consecutive bits set, then print them as a
1234 * range, otherwise only print the initial bit and rescan.
1236 for (i=0; i < cmd->o.arg1; i++)
1237 if (map[i/32] & (1<<(i & 31))) {
1238 for (j=i+1; j < cmd->o.arg1; j++)
1239 if (!(map[ j/32] & (1<<(j & 31))))
1241 bprintf(bp, "%c%d", comma, i+x);
1242 if (j>i+2) { /* range has at least 3 elements */
1243 bprintf(bp, "-%d", j-1+x);
1252 * len == 2 indicates a single IP, whereas lists of 1 or more
1253 * addr/mask pairs have len = (2n+1). We convert len to n so we
1254 * use that to count the number of entries.
1256 for (len = len / 2; len > 0; len--, a += 2) {
1257 int mb = /* mask length */
1258 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1259 32 : contigmask((uint8_t *)&(a[1]), 32);
1260 if (mb == 32 && co.do_resolv)
1261 he = gethostbyaddr((char *)&(a[0]), sizeof(in_addr_t),
1263 if (he != NULL) /* resolved to name */
1264 bprintf(bp, "%s", he->h_name);
1265 else if (mb == 0) /* any */
1267 else { /* numeric IP followed by some kind of mask */
1268 ia = (struct in_addr *)&a[0];
1269 bprintf(bp, "%s", inet_ntoa(*ia));
1271 ia = (struct in_addr *)&a[1];
1272 bprintf(bp, ":%s", inet_ntoa(*ia));
1274 bprintf(bp, "/%d", mb);
1282 * prints a MAC address/mask pair
1285 format_mac(struct buf_pr *bp, uint8_t *addr, uint8_t *mask)
1287 int l = contigmask(mask, 48);
1290 bprintf(bp, " any");
1292 bprintf(bp, " %02x:%02x:%02x:%02x:%02x:%02x",
1293 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1295 bprintf(bp, "&%02x:%02x:%02x:%02x:%02x:%02x",
1296 mask[0], mask[1], mask[2],
1297 mask[3], mask[4], mask[5]);
1299 bprintf(bp, "/%d", l);
1304 print_mac(struct buf_pr *bp, ipfw_insn_mac *mac)
1307 bprintf(bp, " MAC");
1308 format_mac(bp, mac->addr, mac->mask);
1309 format_mac(bp, mac->addr + 6, mac->mask + 6);
1313 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1322 type = strtoul(av, &av, 0);
1324 if (*av != ',' && *av != '\0')
1325 errx(EX_DATAERR, "invalid ICMP type");
1328 errx(EX_DATAERR, "ICMP type out of range");
1330 cmd->d[0] |= 1 << type;
1332 cmd->o.opcode = O_ICMPTYPE;
1333 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1337 print_icmptypes(struct buf_pr *bp, ipfw_insn_u32 *cmd)
1342 bprintf(bp, " icmptypes");
1343 for (i = 0; i < 32; i++) {
1344 if ( (cmd->d[0] & (1 << (i))) == 0)
1346 bprintf(bp, "%c%d", sep, i);
1352 print_dscp(struct buf_pr *bp, ipfw_insn_u32 *cmd)
1359 bprintf(bp, " dscp");
1362 if (*v & (1 << i)) {
1363 if ((code = match_value(f_ipdscp, i)) != NULL)
1364 bprintf(bp, "%c%s", sep, code);
1366 bprintf(bp, "%c%d", sep, i);
1370 if ((++i % 32) == 0)
1375 #define insntod(cmd, type) ((ipfw_insn_ ## type *)(cmd))
1377 struct ip_fw_rule *rule;
1378 const ipfw_insn *eaction;
1381 #define HAVE_PROTO 0x0001
1382 #define HAVE_SRCIP 0x0002
1383 #define HAVE_DSTIP 0x0004
1384 #define HAVE_PROBE_STATE 0x0008
1390 init_show_state(struct show_state *state, struct ip_fw_rule *rule)
1393 state->printed = calloc(rule->cmd_len, sizeof(uint8_t));
1394 if (state->printed == NULL)
1397 state->eaction = NULL;
1400 state->or_block = 0;
1405 free_show_state(struct show_state *state)
1408 free(state->printed);
1412 is_printed_opcode(struct show_state *state, const ipfw_insn *cmd)
1415 return (state->printed[cmd - state->rule->cmd]);
1419 mark_printed(struct show_state *state, const ipfw_insn *cmd)
1422 state->printed[cmd - state->rule->cmd] = 1;
1426 print_limit_mask(struct buf_pr *bp, const ipfw_insn_limit *limit)
1428 struct _s_x *p = limit_masks;
1429 char const *comma = " ";
1432 for (x = limit->limit_mask; p->x != 0; p++) {
1433 if ((x & p->x) == p->x) {
1435 bprintf(bp, "%s%s", comma, p->s);
1439 bprint_uint_arg(bp, " ", limit->conn_limit);
1443 print_instruction(struct buf_pr *bp, const struct format_opts *fo,
1444 struct show_state *state, ipfw_insn *cmd)
1446 struct protoent *pe;
1452 if (is_printed_opcode(state, cmd))
1454 if ((cmd->len & F_OR) != 0 && state->or_block == 0)
1456 if (cmd->opcode != O_IN && (cmd->len & F_NOT) != 0)
1457 bprintf(bp, " not");
1459 switch (cmd->opcode) {
1461 d = 1.0 * insntod(cmd, u32)->d[0] / 0x7fffffff;
1462 bprintf(bp, "prob %f ", d);
1464 case O_PROBE_STATE: /* no need to print anything here */
1465 state->flags |= HAVE_PROBE_STATE;
1468 case O_IP_SRC_LOOKUP:
1472 if (state->flags & HAVE_SRCIP)
1473 bprintf(bp, " src-ip");
1474 print_ip(bp, fo, insntod(cmd, ip));
1477 case O_IP_DST_LOOKUP:
1481 if (state->flags & HAVE_DSTIP)
1482 bprintf(bp, " dst-ip");
1483 print_ip(bp, fo, insntod(cmd, ip));
1486 case O_IP6_SRC_MASK:
1488 if (state->flags & HAVE_SRCIP)
1489 bprintf(bp, " src-ip6");
1490 print_ip6(bp, insntod(cmd, ip6));
1493 case O_IP6_DST_MASK:
1495 if (state->flags & HAVE_DSTIP)
1496 bprintf(bp, " dst-ip6");
1497 print_ip6(bp, insntod(cmd, ip6));
1500 print_flow6id(bp, insntod(cmd, u32));
1504 print_newports(bp, insntod(cmd, u16), state->proto,
1505 (state->flags & (HAVE_SRCIP | HAVE_DSTIP)) ==
1506 (HAVE_SRCIP | HAVE_DSTIP) ? cmd->opcode: 0);
1509 pe = getprotobynumber(cmd->arg1);
1510 if (state->flags & HAVE_PROTO)
1511 bprintf(bp, " proto");
1513 bprintf(bp, " %s", pe->p_name);
1515 bprintf(bp, " %u", cmd->arg1);
1516 state->proto = cmd->arg1;
1519 print_mac(bp, insntod(cmd, mac));
1522 print_newports(bp, insntod(cmd, u16),
1523 IPPROTO_ETHERTYPE, cmd->opcode);
1526 bprintf(bp, " frag");
1529 bprintf(bp, " fib %u", cmd->arg1);
1532 bprintf(bp, " sockarg");
1535 bprintf(bp, cmd->len & F_NOT ? " out" : " in");
1538 switch (cmd->arg1) {
1540 bprintf(bp, " diverted");
1543 bprintf(bp, " diverted-output");
1546 bprintf(bp, " diverted-loopback");
1549 bprintf(bp, " diverted-?<%u>", cmd->arg1);
1554 bprintf(bp, " layer2");
1559 if (cmd->opcode == O_XMIT)
1561 else if (cmd->opcode == O_RECV)
1563 else /* if (cmd->opcode == O_VIA) */
1565 switch (insntod(cmd, if)->name[0]) {
1567 bprintf(bp, " %s %s", s,
1568 inet_ntoa(insntod(cmd, if)->p.ip));
1571 bprintf(bp, " %s table(%s)", s,
1572 table_search_ctlv(fo->tstate,
1573 insntod(cmd, if)->p.kidx));
1576 bprintf(bp, " %s %s", s,
1577 insntod(cmd, if)->name);
1580 case O_IP_FLOW_LOOKUP:
1581 s = table_search_ctlv(fo->tstate, cmd->arg1);
1582 bprintf(bp, " flow table(%s", s);
1583 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))
1584 bprintf(bp, ",%u", insntod(cmd, u32)->d[0]);
1592 if (F_LEN(cmd) == 1) {
1593 switch (cmd->opcode) {
1610 bprintf(bp, " %s %u", s, cmd->arg1);
1612 print_newports(bp, insntod(cmd, u16), 0,
1616 bprintf(bp, " ipver %u", cmd->arg1);
1618 case O_IPPRECEDENCE:
1619 bprintf(bp, " ipprecedence %u", cmd->arg1 >> 5);
1622 print_dscp(bp, insntod(cmd, u32));
1625 print_flags(bp, "ipoptions", cmd, f_ipopts);
1628 print_flags(bp, "iptos", cmd, f_iptos);
1631 print_icmptypes(bp, insntod(cmd, u32));
1634 bprintf(bp, " established");
1637 print_flags(bp, "tcpflags", cmd, f_tcpflags);
1640 print_flags(bp, "tcpoptions", cmd, f_tcpopts);
1643 bprintf(bp, " tcpack %d",
1644 ntohl(insntod(cmd, u32)->d[0]));
1647 bprintf(bp, " tcpseq %d",
1648 ntohl(insntod(cmd, u32)->d[0]));
1651 pwd = getpwuid(insntod(cmd, u32)->d[0]);
1653 bprintf(bp, " uid %s", pwd->pw_name);
1655 bprintf(bp, " uid %u",
1656 insntod(cmd, u32)->d[0]);
1659 grp = getgrgid(insntod(cmd, u32)->d[0]);
1661 bprintf(bp, " gid %s", grp->gr_name);
1663 bprintf(bp, " gid %u",
1664 insntod(cmd, u32)->d[0]);
1667 bprintf(bp, " jail %d", insntod(cmd, u32)->d[0]);
1670 bprintf(bp, " verrevpath");
1673 bprintf(bp, " versrcreach");
1676 bprintf(bp, " antispoof");
1679 bprintf(bp, " ipsec");
1682 bprintf(bp, " // %s", (char *)(cmd + 1));
1685 if (state->flags & HAVE_PROBE_STATE)
1686 bprintf(bp, " keep-state");
1688 bprintf(bp, " record-state");
1690 object_search_ctlv(fo->tstate, cmd->arg1,
1691 IPFW_TLV_STATE_NAME));
1694 if (state->flags & HAVE_PROBE_STATE)
1695 bprintf(bp, " limit");
1697 bprintf(bp, " set-limit");
1698 print_limit_mask(bp, insntod(cmd, limit));
1700 object_search_ctlv(fo->tstate, cmd->arg1,
1701 IPFW_TLV_STATE_NAME));
1704 if (state->flags & HAVE_PROTO)
1705 bprintf(bp, " proto");
1706 bprintf(bp, " ip6");
1709 if (state->flags & HAVE_PROTO)
1710 bprintf(bp, " proto");
1711 bprintf(bp, " ip4");
1714 print_icmp6types(bp, insntod(cmd, u32));
1717 print_ext6hdr(bp, cmd);
1720 if (F_LEN(cmd) == 1)
1721 bprint_uint_arg(bp, " tagged ", cmd->arg1);
1723 print_newports(bp, insntod(cmd, u16),
1727 bprintf(bp, " defer-immediate-action");
1730 bprintf(bp, " [opcode %d len %d]", cmd->opcode,
1733 if (cmd->len & F_OR) {
1735 state->or_block = 1;
1736 } else if (state->or_block != 0) {
1738 state->or_block = 0;
1740 mark_printed(state, cmd);
1746 print_opcode(struct buf_pr *bp, struct format_opts *fo,
1747 struct show_state *state, int opcode)
1752 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
1753 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1754 /* We use zero opcode to print the rest of options */
1755 if (opcode >= 0 && cmd->opcode != opcode)
1758 * Skip O_NOP, when we printing the rest
1759 * of options, it will be handled separately.
1761 if (cmd->opcode == O_NOP && opcode != O_NOP)
1763 if (!print_instruction(bp, fo, state, cmd))
1771 print_fwd(struct buf_pr *bp, const ipfw_insn *cmd)
1773 char buf[INET6_ADDRSTRLEN + IF_NAMESIZE + 2];
1778 if (cmd->opcode == O_FORWARD_IP) {
1779 sa = insntod(cmd, sa);
1780 port = sa->sa.sin_port;
1781 if (sa->sa.sin_addr.s_addr == INADDR_ANY)
1782 bprintf(bp, "fwd tablearg");
1784 bprintf(bp, "fwd %s", inet_ntoa(sa->sa.sin_addr));
1786 sa6 = insntod(cmd, sa6);
1787 port = sa6->sa.sin6_port;
1788 bprintf(bp, "fwd ");
1789 if (getnameinfo((const struct sockaddr *)&sa6->sa,
1790 sizeof(struct sockaddr_in6), buf, sizeof(buf), NULL, 0,
1791 NI_NUMERICHOST) == 0)
1792 bprintf(bp, "%s", buf);
1795 bprintf(bp, ",%u", port);
1799 print_action_instruction(struct buf_pr *bp, const struct format_opts *fo,
1800 struct show_state *state, const ipfw_insn *cmd)
1804 if (is_printed_opcode(state, cmd))
1806 switch (cmd->opcode) {
1808 bprintf(bp, "check-state");
1810 s = object_search_ctlv(fo->tstate, cmd->arg1,
1811 IPFW_TLV_STATE_NAME);
1814 bprintf(bp, " :%s", s ? s: "any");
1817 bprintf(bp, "allow");
1820 bprintf(bp, "count");
1823 bprintf(bp, "deny");
1826 if (cmd->arg1 == ICMP_REJECT_RST)
1827 bprintf(bp, "reset");
1828 else if (cmd->arg1 == ICMP_REJECT_ABORT)
1829 bprintf(bp, "abort");
1830 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1831 bprintf(bp, "reject");
1833 print_reject_code(bp, cmd->arg1);
1836 if (cmd->arg1 == ICMP6_UNREACH_RST)
1837 bprintf(bp, "reset6");
1838 else if (cmd->arg1 == ICMP6_UNREACH_ABORT)
1839 bprintf(bp, "abort6");
1841 print_unreach6_code(bp, cmd->arg1);
1844 bprint_uint_arg(bp, "skipto ", cmd->arg1);
1847 bprint_uint_arg(bp, "pipe ", cmd->arg1);
1850 bprint_uint_arg(bp, "queue ", cmd->arg1);
1853 bprint_uint_arg(bp, "divert ", cmd->arg1);
1856 bprint_uint_arg(bp, "tee ", cmd->arg1);
1859 bprint_uint_arg(bp, "netgraph ", cmd->arg1);
1862 bprint_uint_arg(bp, "ngtee ", cmd->arg1);
1869 if (insntod(cmd, log)->max_log > 0)
1870 bprintf(bp, " log logamount %d",
1871 insntod(cmd, log)->max_log);
1873 bprintf(bp, " log");
1877 print_altq_cmd(bp, insntod(cmd, altq));
1881 bprint_uint_arg(bp, cmd->len & F_NOT ? " untag ":
1882 " tag ", cmd->arg1);
1885 if (cmd->arg1 != IP_FW_NAT44_GLOBAL)
1886 bprint_uint_arg(bp, "nat ", cmd->arg1);
1888 bprintf(bp, "nat global");
1891 if (cmd->arg1 == IP_FW_TARG)
1892 bprint_uint_arg(bp, "setfib ", cmd->arg1);
1894 bprintf(bp, "setfib %u", cmd->arg1 & 0x7FFF);
1896 case O_EXTERNAL_ACTION:
1898 * The external action can consists of two following
1899 * each other opcodes - O_EXTERNAL_ACTION and
1900 * O_EXTERNAL_INSTANCE. The first contains the ID of
1901 * name of external action. The second contains the ID
1902 * of name of external action instance.
1903 * NOTE: in case when external action has no named
1904 * instances support, the second opcode isn't needed.
1906 state->eaction = cmd;
1907 s = object_search_ctlv(fo->tstate, cmd->arg1,
1909 if (match_token(rule_eactions, s) != -1)
1910 bprintf(bp, "%s", s);
1912 bprintf(bp, "eaction %s", s);
1914 case O_EXTERNAL_INSTANCE:
1915 if (state->eaction == NULL)
1918 * XXX: we need to teach ipfw(9) to rewrite opcodes
1919 * in the user buffer on rule addition. When we add
1920 * the rule, we specify zero TLV type for
1921 * O_EXTERNAL_INSTANCE object. To show correct
1922 * rule after `ipfw add` we need to search instance
1923 * name with zero type. But when we do `ipfw show`
1924 * we calculate TLV type using IPFW_TLV_EACTION_NAME()
1927 s = object_search_ctlv(fo->tstate, cmd->arg1, 0);
1929 s = object_search_ctlv(fo->tstate,
1930 cmd->arg1, IPFW_TLV_EACTION_NAME(
1931 state->eaction->arg1));
1932 bprintf(bp, " %s", s);
1934 case O_EXTERNAL_DATA:
1935 if (state->eaction == NULL)
1938 * Currently we support data formatting only for
1939 * external data with datalen u16. For unknown data
1940 * print its size in bytes.
1942 if (cmd->len == F_INSN_SIZE(ipfw_insn))
1943 bprintf(bp, " %u", cmd->arg1);
1945 bprintf(bp, " %ubytes",
1946 cmd->len * sizeof(uint32_t));
1949 if (cmd->arg1 == IP_FW_TARG) {
1950 bprintf(bp, "setdscp tablearg");
1953 s = match_value(f_ipdscp, cmd->arg1 & 0x3F);
1955 bprintf(bp, "setdscp %s", s);
1957 bprintf(bp, "setdscp %u", cmd->arg1 & 0x3F);
1960 bprintf(bp, "reass");
1963 if (cmd->len & F_NOT)
1964 bprintf(bp, "return");
1966 bprint_uint_arg(bp, "call ", cmd->arg1);
1969 bprintf(bp, "** unrecognized action %d len %d ",
1970 cmd->opcode, cmd->len);
1972 mark_printed(state, cmd);
1979 print_action(struct buf_pr *bp, struct format_opts *fo,
1980 struct show_state *state, uint8_t opcode)
1985 for (l = state->rule->cmd_len - state->rule->act_ofs,
1986 cmd = ACTION_PTR(state->rule); l > 0;
1987 l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1988 if (cmd->opcode != opcode)
1990 if (!print_action_instruction(bp, fo, state, cmd))
1998 print_proto(struct buf_pr *bp, struct format_opts *fo,
1999 struct show_state *state)
2002 int l, proto, ip4, ip6;
2004 /* Count all O_PROTO, O_IP4, O_IP6 instructions. */
2005 proto = ip4 = ip6 = 0;
2006 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2007 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2008 switch (cmd->opcode) {
2014 if (cmd->len & F_OR)
2019 if (cmd->len & F_OR)
2026 if (proto == 0 && ip4 == 0 && ip6 == 0) {
2027 state->proto = IPPROTO_IP;
2028 state->flags |= HAVE_PROTO;
2032 /* To handle the case { ip4 or ip6 }, print opcode with F_OR first */
2035 cmd = print_opcode(bp, fo, state, ip4 > ip6 ? O_IP4: O_IP6);
2036 if (cmd != NULL && (cmd->len & F_OR))
2037 cmd = print_opcode(bp, fo, state, ip4 > ip6 ? O_IP6: O_IP4);
2038 if (cmd == NULL || (cmd->len & F_OR))
2039 for (l = proto; l > 0; l--) {
2040 cmd = print_opcode(bp, fo, state, O_PROTO);
2041 if (cmd == NULL || (cmd->len & F_OR) == 0)
2044 /* Initialize proto, it is used by print_newports() */
2045 state->flags |= HAVE_PROTO;
2046 if (state->proto == 0 && ip6 != 0)
2047 state->proto = IPPROTO_IPV6;
2051 match_opcode(int opcode, const int opcodes[], size_t nops)
2055 for (i = 0; i < nops; i++)
2056 if (opcode == opcodes[i])
2062 print_address(struct buf_pr *bp, struct format_opts *fo,
2063 struct show_state *state, const int opcodes[], size_t nops, int portop,
2067 int count, l, portcnt, pf;
2069 count = portcnt = 0;
2070 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2071 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2072 if (match_opcode(cmd->opcode, opcodes, nops))
2074 else if (cmd->opcode == portop)
2078 bprintf(bp, " any");
2079 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2080 l > 0 && count > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2081 if (!match_opcode(cmd->opcode, opcodes, nops))
2083 print_instruction(bp, fo, state, cmd);
2084 if ((cmd->len & F_OR) == 0)
2089 * If several O_IP_?PORT opcodes specified, leave them to the
2093 for (l = state->rule->act_ofs, cmd = state->rule->cmd, pf = 0;
2094 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2095 if (cmd->opcode != portop) {
2096 pf = (cmd->len & F_OR);
2099 /* Print opcode iff it is not in OR block. */
2100 if (pf == 0 && (cmd->len & F_OR) == 0)
2101 print_instruction(bp, fo, state, cmd);
2105 state->flags |= flag;
2108 static const int action_opcodes[] = {
2109 O_CHECK_STATE, O_ACCEPT, O_COUNT, O_DENY, O_REJECT,
2110 O_UNREACH6, O_SKIPTO, O_PIPE, O_QUEUE, O_DIVERT, O_TEE,
2111 O_NETGRAPH, O_NGTEE, O_FORWARD_IP, O_FORWARD_IP6, O_NAT,
2112 O_SETFIB, O_SETDSCP, O_REASS, O_CALLRETURN,
2113 /* keep the following opcodes at the end of the list */
2114 O_EXTERNAL_ACTION, O_EXTERNAL_INSTANCE, O_EXTERNAL_DATA
2117 static const int modifier_opcodes[] = {
2118 O_LOG, O_ALTQ, O_TAG
2121 static const int src_opcodes[] = {
2122 O_IP_SRC, O_IP_SRC_LOOKUP, O_IP_SRC_MASK, O_IP_SRC_ME,
2123 O_IP_SRC_SET, O_IP6_SRC, O_IP6_SRC_MASK, O_IP6_SRC_ME
2126 static const int dst_opcodes[] = {
2127 O_IP_DST, O_IP_DST_LOOKUP, O_IP_DST_MASK, O_IP_DST_ME,
2128 O_IP_DST_SET, O_IP6_DST, O_IP6_DST_MASK, O_IP6_DST_ME
2132 show_static_rule(struct cmdline_opts *co, struct format_opts *fo,
2133 struct buf_pr *bp, struct ip_fw_rule *rule, struct ip_fw_bcounter *cntr)
2135 struct show_state state;
2137 static int twidth = 0;
2140 /* Print # DISABLED or skip the rule */
2141 if ((fo->set_mask & (1 << rule->set)) == 0) {
2146 bprintf(bp, "# DISABLED ");
2148 if (init_show_state(&state, rule) != 0) {
2149 warn("init_show_state() failed");
2152 bprintf(bp, "%05u ", rule->rulenum);
2154 /* Print counters if enabled */
2155 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2156 pr_u64(bp, &cntr->pcnt, fo->pcwidth);
2157 pr_u64(bp, &cntr->bcnt, fo->bcwidth);
2160 /* Print timestamp */
2161 if (co->do_time == TIMESTAMP_NUMERIC)
2162 bprintf(bp, "%10u ", cntr->timestamp);
2163 else if (co->do_time == TIMESTAMP_STRING) {
2165 time_t t = (time_t)0;
2168 strcpy(timestr, ctime(&t));
2169 *strchr(timestr, '\n') = '\0';
2170 twidth = strlen(timestr);
2172 if (cntr->timestamp > 0) {
2173 t = _long_to_time(cntr->timestamp);
2175 strcpy(timestr, ctime(&t));
2176 *strchr(timestr, '\n') = '\0';
2177 bprintf(bp, "%s ", timestr);
2179 bprintf(bp, "%*s", twidth, " ");
2183 /* Print set number */
2185 bprintf(bp, "set %d ", rule->set);
2187 /* Print the optional "match probability" */
2188 cmd = print_opcode(bp, fo, &state, O_PROB);
2189 /* Print rule action */
2190 for (i = 0; i < nitems(action_opcodes); i++) {
2191 cmd = print_action(bp, fo, &state, action_opcodes[i]);
2194 /* Handle special cases */
2195 switch (cmd->opcode) {
2198 case O_EXTERNAL_ACTION:
2199 case O_EXTERNAL_INSTANCE:
2200 /* External action can have several instructions */
2205 /* Print rule modifiers */
2206 for (i = 0; i < nitems(modifier_opcodes); i++)
2207 print_action(bp, fo, &state, modifier_opcodes[i]);
2211 if (co->comment_only != 0)
2214 if (rule->flags & IPFW_RULE_JUSTOPTS) {
2215 state.flags |= HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP;
2219 print_proto(bp, fo, &state);
2222 bprintf(bp, " from");
2223 print_address(bp, fo, &state, src_opcodes, nitems(src_opcodes),
2224 O_IP_SRCPORT, HAVE_SRCIP);
2226 /* Print destination */
2228 print_address(bp, fo, &state, dst_opcodes, nitems(dst_opcodes),
2229 O_IP_DSTPORT, HAVE_DSTIP);
2232 /* Print the rest of options */
2233 while (print_opcode(bp, fo, &state, -1))
2236 /* Print comment at the end */
2237 cmd = print_opcode(bp, fo, &state, O_NOP);
2238 if (co->comment_only != 0 && cmd == NULL)
2239 bprintf(bp, " // ...");
2241 free_show_state(&state);
2245 show_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2246 struct buf_pr *bp, ipfw_dyn_rule *d)
2248 struct protoent *pe;
2251 char buf[INET6_ADDRSTRLEN];
2253 if (d->expire == 0 && d->dyn_type != O_LIMIT_PARENT)
2256 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2257 bprintf(bp, "%05d", rulenum);
2258 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2260 pr_u64(bp, &d->pcnt, fo->pcwidth);
2261 pr_u64(bp, &d->bcnt, fo->bcwidth);
2262 bprintf(bp, "(%ds)", d->expire);
2264 switch (d->dyn_type) {
2265 case O_LIMIT_PARENT:
2266 bprintf(bp, " PARENT %d", d->count);
2269 bprintf(bp, " LIMIT");
2271 case O_KEEP_STATE: /* bidir, no mask */
2272 bprintf(bp, " STATE");
2276 if ((pe = getprotobynumber(d->id.proto)) != NULL)
2277 bprintf(bp, " %s", pe->p_name);
2279 bprintf(bp, " proto %u", d->id.proto);
2281 if (d->id.addr_type == 4) {
2282 a.s_addr = htonl(d->id.src_ip);
2283 bprintf(bp, " %s %d", inet_ntoa(a), d->id.src_port);
2285 a.s_addr = htonl(d->id.dst_ip);
2286 bprintf(bp, " <-> %s %d", inet_ntoa(a), d->id.dst_port);
2287 } else if (d->id.addr_type == 6) {
2288 bprintf(bp, " %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
2289 sizeof(buf)), d->id.src_port);
2290 bprintf(bp, " <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6,
2291 buf, sizeof(buf)), d->id.dst_port);
2293 bprintf(bp, " UNKNOWN <-> UNKNOWN");
2295 bprintf(bp, " :%s", object_search_ctlv(fo->tstate,
2296 d->kidx, IPFW_TLV_STATE_NAME));
2298 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
2299 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
2301 bprintf(bp, " state 0x%08x%s", d->state,
2302 d->state ? " ": ",");
2303 if (d->state & IPFW_DYN_ORPHANED)
2304 bprintf(bp, "ORPHANED,");
2305 if ((d->state & BOTH_SYN) == BOTH_SYN)
2306 bprintf(bp, "BOTH_SYN,");
2308 if (d->state & TH_SYN)
2309 bprintf(bp, "F_SYN,");
2310 if (d->state & (TH_SYN << 8))
2311 bprintf(bp, "R_SYN,");
2313 if ((d->state & BOTH_FIN) == BOTH_FIN)
2314 bprintf(bp, "BOTH_FIN,");
2316 if (d->state & TH_FIN)
2317 bprintf(bp, "F_FIN,");
2318 if (d->state & (TH_FIN << 8))
2319 bprintf(bp, "R_FIN,");
2321 bprintf(bp, " f_ack 0x%x, r_ack 0x%x", d->ack_fwd,
2327 do_range_cmd(int cmd, ipfw_range_tlv *rt)
2329 ipfw_range_header rh;
2332 memset(&rh, 0, sizeof(rh));
2333 memcpy(&rh.range, rt, sizeof(*rt));
2334 rh.range.head.length = sizeof(*rt);
2335 rh.range.head.type = IPFW_TLV_RANGE;
2338 if (do_get3(cmd, &rh.opheader, &sz) != 0)
2340 /* Save number of matched objects */
2341 rt->new_set = rh.range.new_set;
2346 * This one handles all set-related commands
2347 * ipfw set { show | enable | disable }
2349 * ipfw set move X to Y
2350 * ipfw set move rule X to Y
2353 ipfw_sets_handler(char *av[])
2364 memset(&rt, 0, sizeof(rt));
2367 errx(EX_USAGE, "set needs command");
2368 if (_substrcmp(*av, "show") == 0) {
2369 struct format_opts fo;
2370 ipfw_cfg_lheader *cfg;
2372 memset(&fo, 0, sizeof(fo));
2373 if (ipfw_get_config(&co, &fo, &cfg, &size) != 0)
2374 err(EX_OSERR, "requesting config failed");
2376 for (i = 0, msg = "disable"; i < RESVD_SET; i++)
2377 if ((cfg->set_mask & (1<<i)) == 0) {
2378 printf("%s %d", msg, i);
2381 msg = (cfg->set_mask != (uint32_t)-1) ? " enable" : "enable";
2382 for (i = 0; i < RESVD_SET; i++)
2383 if ((cfg->set_mask & (1<<i)) != 0) {
2384 printf("%s %d", msg, i);
2389 } else if (_substrcmp(*av, "swap") == 0) {
2391 if ( av[0] == NULL || av[1] == NULL )
2392 errx(EX_USAGE, "set swap needs 2 set numbers\n");
2393 rt.set = atoi(av[0]);
2394 rt.new_set = atoi(av[1]);
2395 if (!isdigit(*(av[0])) || rt.set > RESVD_SET)
2396 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2397 if (!isdigit(*(av[1])) || rt.new_set > RESVD_SET)
2398 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2399 i = do_range_cmd(IP_FW_SET_SWAP, &rt);
2400 } else if (_substrcmp(*av, "move") == 0) {
2402 if (av[0] && _substrcmp(*av, "rule") == 0) {
2403 rt.flags = IPFW_RCFLAG_RANGE; /* move rules to new set */
2407 cmd = IP_FW_SET_MOVE; /* Move set to new one */
2408 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
2409 av[3] != NULL || _substrcmp(av[1], "to") != 0)
2410 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2411 rulenum = atoi(av[0]);
2412 rt.new_set = atoi(av[2]);
2413 if (cmd == IP_FW_XMOVE) {
2414 rt.start_rule = rulenum;
2415 rt.end_rule = rulenum;
2418 rt.new_set = atoi(av[2]);
2419 if (!isdigit(*(av[0])) || (cmd == 3 && rt.set > RESVD_SET) ||
2420 (cmd == 2 && rt.start_rule == IPFW_DEFAULT_RULE) )
2421 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2422 if (!isdigit(*(av[2])) || rt.new_set > RESVD_SET)
2423 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2424 i = do_range_cmd(cmd, &rt);
2426 err(EX_OSERR, "failed to move %s",
2427 cmd == IP_FW_SET_MOVE ? "set": "rule");
2428 } else if (_substrcmp(*av, "disable") == 0 ||
2429 _substrcmp(*av, "enable") == 0 ) {
2430 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2433 masks[0] = masks[1] = 0;
2436 if (isdigit(**av)) {
2438 if (i < 0 || i > RESVD_SET)
2440 "invalid set number %d\n", i);
2441 masks[which] |= (1<<i);
2442 } else if (_substrcmp(*av, "disable") == 0)
2444 else if (_substrcmp(*av, "enable") == 0)
2448 "invalid set command %s\n", *av);
2451 if ( (masks[0] & masks[1]) != 0 )
2453 "cannot enable and disable the same set\n");
2456 rt.new_set = masks[1];
2457 i = do_range_cmd(IP_FW_SET_ENABLE, &rt);
2459 warn("set enable/disable: setsockopt(IP_FW_SET_ENABLE)");
2461 errx(EX_USAGE, "invalid set command %s\n", *av);
2465 ipfw_sysctl_handler(char *av[], int which)
2469 if (av[0] == NULL) {
2470 warnx("missing keyword to enable/disable\n");
2471 } else if (_substrcmp(*av, "firewall") == 0) {
2472 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2473 &which, sizeof(which));
2474 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
2475 &which, sizeof(which));
2476 } else if (_substrcmp(*av, "one_pass") == 0) {
2477 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2478 &which, sizeof(which));
2479 } else if (_substrcmp(*av, "debug") == 0) {
2480 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2481 &which, sizeof(which));
2482 } else if (_substrcmp(*av, "verbose") == 0) {
2483 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2484 &which, sizeof(which));
2485 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2486 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2487 &which, sizeof(which));
2489 } else if (_substrcmp(*av, "altq") == 0) {
2490 altq_set_enabled(which);
2493 warnx("unrecognize enable/disable keyword: %s\n", *av);
2497 typedef void state_cb(struct cmdline_opts *co, struct format_opts *fo,
2498 void *arg, void *state);
2501 prepare_format_dyn(struct cmdline_opts *co, struct format_opts *fo,
2502 void *arg, void *_state)
2508 d = (ipfw_dyn_rule *)_state;
2509 /* Count _ALL_ states */
2512 if (fo->show_counters == 0)
2516 /* skip states from another set */
2517 bcopy((char *)&d->rule + sizeof(uint16_t), &set,
2519 if (set != co->use_set - 1)
2523 width = pr_u64(NULL, &d->pcnt, 0);
2524 if (width > fo->pcwidth)
2525 fo->pcwidth = width;
2527 width = pr_u64(NULL, &d->bcnt, 0);
2528 if (width > fo->bcwidth)
2529 fo->bcwidth = width;
2533 foreach_state(struct cmdline_opts *co, struct format_opts *fo,
2534 caddr_t base, size_t sz, state_cb dyn_bc, void *dyn_arg)
2540 ipfw_obj_ctlv *ctlv;
2546 ctlv = (ipfw_obj_ctlv *)base;
2547 switch (ctlv->head.type) {
2548 case IPFW_TLV_DYNSTATE_LIST:
2549 base += sizeof(*ctlv);
2550 sz -= sizeof(*ctlv);
2551 ttype = IPFW_TLV_DYN_ENT;
2560 tlv = (ipfw_obj_tlv *)base;
2561 if (tlv->type != ttype)
2564 fptr(co, fo, farg, tlv + 1);
2566 base += tlv->length;
2574 prepare_format_opts(struct cmdline_opts *co, struct format_opts *fo,
2575 ipfw_obj_tlv *rtlv, int rcnt, caddr_t dynbase, size_t dynsz)
2577 int bcwidth, pcwidth, width;
2579 struct ip_fw_bcounter *cntr;
2580 struct ip_fw_rule *r;
2584 if (fo->show_counters != 0) {
2585 for (n = 0; n < rcnt; n++,
2586 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2587 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2588 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2589 /* skip rules from another set */
2590 if (co->use_set && r->set != co->use_set - 1)
2593 /* packet counter */
2594 width = pr_u64(NULL, &cntr->pcnt, 0);
2595 if (width > pcwidth)
2599 width = pr_u64(NULL, &cntr->bcnt, 0);
2600 if (width > bcwidth)
2604 fo->bcwidth = bcwidth;
2605 fo->pcwidth = pcwidth;
2608 if (co->do_dynamic && dynsz > 0)
2609 foreach_state(co, fo, dynbase, dynsz, prepare_format_dyn, NULL);
2613 list_static_range(struct cmdline_opts *co, struct format_opts *fo,
2614 struct buf_pr *bp, ipfw_obj_tlv *rtlv, int rcnt)
2617 struct ip_fw_rule *r;
2618 struct ip_fw_bcounter *cntr;
2621 for (n = seen = 0; n < rcnt; n++,
2622 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2624 if ((fo->show_counters | fo->show_time) != 0) {
2625 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2626 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2629 r = (struct ip_fw_rule *)(rtlv + 1);
2631 if (r->rulenum > fo->last)
2633 if (co->use_set && r->set != co->use_set - 1)
2635 if (r->rulenum >= fo->first && r->rulenum <= fo->last) {
2636 show_static_rule(co, fo, bp, r, cntr);
2637 printf("%s", bp->buf);
2648 list_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2649 void *_arg, void *_state)
2656 d = (ipfw_dyn_rule *)_state;
2657 bp = (struct buf_pr *)_arg;
2659 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2660 if (rulenum > fo->last)
2663 bcopy((char *)&d->rule + sizeof(uint16_t),
2664 &set, sizeof(uint8_t));
2665 if (set != co->use_set - 1)
2668 if (rulenum >= fo->first) {
2669 show_dyn_state(co, fo, bp, d);
2670 printf("%s\n", bp->buf);
2676 list_dyn_range(struct cmdline_opts *co, struct format_opts *fo,
2677 struct buf_pr *bp, caddr_t base, size_t sz)
2680 sz = foreach_state(co, fo, base, sz, list_dyn_state, bp);
2685 ipfw_list(int ac, char *av[], int show_counters)
2687 ipfw_cfg_lheader *cfg;
2688 struct format_opts sfo;
2697 fprintf(stderr, "Testing only, list disabled\n");
2701 dummynet_list(ac, av, show_counters);
2707 memset(&sfo, 0, sizeof(sfo));
2709 /* Determine rule range to request */
2711 for (lac = ac, lav = av; lac != 0; lac--) {
2712 rnum = strtoul(*lav++, &endptr, 10);
2713 if (sfo.first == 0 || rnum < sfo.first)
2717 rnum = strtoul(endptr + 1, &endptr, 10);
2718 if (sfo.last == 0 || rnum > sfo.last)
2723 /* get configuraion from kernel */
2725 sfo.show_counters = show_counters;
2726 sfo.show_time = co.do_time;
2727 if (co.do_dynamic != 2)
2728 sfo.flags |= IPFW_CFG_GET_STATIC;
2729 if (co.do_dynamic != 0)
2730 sfo.flags |= IPFW_CFG_GET_STATES;
2731 if ((sfo.show_counters | sfo.show_time) != 0)
2732 sfo.flags |= IPFW_CFG_GET_COUNTERS;
2733 if (ipfw_get_config(&co, &sfo, &cfg, &sz) != 0)
2734 err(EX_OSERR, "retrieving config failed");
2736 error = ipfw_show_config(&co, &sfo, cfg, sz, ac, av);
2745 ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
2746 ipfw_cfg_lheader *cfg, size_t sz, int ac, char *av[])
2751 int exitval = EX_OK;
2757 ipfw_obj_ctlv *ctlv, *tstate;
2758 ipfw_obj_tlv *rbase;
2761 * Handle tablenames TLV first, if any
2767 readsz = sizeof(*cfg);
2770 fo->set_mask = cfg->set_mask;
2772 ctlv = (ipfw_obj_ctlv *)(cfg + 1);
2773 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2774 object_sort_ctlv(ctlv);
2776 readsz += ctlv->head.length;
2777 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2780 if (cfg->flags & IPFW_CFG_GET_STATIC) {
2781 /* We've requested static rules */
2782 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2783 rbase = (ipfw_obj_tlv *)(ctlv + 1);
2785 readsz += ctlv->head.length;
2786 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2791 if ((cfg->flags & IPFW_CFG_GET_STATES) && (readsz != sz)) {
2792 /* We may have some dynamic states */
2793 dynsz = sz - readsz;
2794 /* Skip empty header */
2795 if (dynsz != sizeof(ipfw_obj_ctlv))
2796 dynbase = (caddr_t)ctlv;
2801 prepare_format_opts(co, fo, rbase, rcnt, dynbase, dynsz);
2802 bp_alloc(&bp, 4096);
2804 /* if no rule numbers were specified, list all rules */
2807 fo->last = IPFW_DEFAULT_RULE;
2808 if (cfg->flags & IPFW_CFG_GET_STATIC)
2809 list_static_range(co, fo, &bp, rbase, rcnt);
2811 if (co->do_dynamic && dynsz > 0) {
2812 printf("## Dynamic rules (%d %zu):\n", fo->dcnt,
2814 list_dyn_range(co, fo, &bp, dynbase, dynsz);
2821 /* display specific rules requested on command line */
2822 for (lac = ac, lav = av; lac != 0; lac--) {
2823 /* convert command line rule # */
2824 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2826 fo->last = strtoul(endptr + 1, &endptr, 10);
2829 warnx("invalid rule number: %s", *(lav - 1));
2833 if ((cfg->flags & IPFW_CFG_GET_STATIC) == 0)
2836 if (list_static_range(co, fo, &bp, rbase, rcnt) == 0) {
2837 /* give precedence to other error(s) */
2838 if (exitval == EX_OK)
2839 exitval = EX_UNAVAILABLE;
2840 if (fo->first == fo->last)
2841 warnx("rule %u does not exist", fo->first);
2843 warnx("no rules in range %u-%u",
2844 fo->first, fo->last);
2848 if (co->do_dynamic && dynsz > 0) {
2849 printf("## Dynamic rules:\n");
2850 for (lac = ac, lav = av; lac != 0; lac--) {
2851 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2853 fo->last = strtoul(endptr+1, &endptr, 10);
2855 /* already warned */
2857 list_dyn_range(co, fo, &bp, dynbase, dynsz);
2867 * Retrieves current ipfw configuration of given type
2868 * and stores its pointer to @pcfg.
2870 * Caller is responsible for freeing @pcfg.
2872 * Returns 0 on success.
2876 ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
2877 ipfw_cfg_lheader **pcfg, size_t *psize)
2879 ipfw_cfg_lheader *cfg;
2884 if (co->test_only != 0) {
2885 fprintf(stderr, "Testing only, list disabled\n");
2889 /* Start with some data size */
2893 for (i = 0; i < 16; i++) {
2896 if ((cfg = calloc(1, sz)) == NULL)
2899 cfg->flags = fo->flags;
2900 cfg->start_rule = fo->first;
2901 cfg->end_rule = fo->last;
2903 if (do_get3(IP_FW_XGET, &cfg->opheader, &sz) != 0) {
2904 if (errno != ENOMEM) {
2909 /* Buffer size is not enough. Try to increase */
2926 lookup_host (char *host, struct in_addr *ipaddr)
2930 if (!inet_aton(host, ipaddr)) {
2931 if ((he = gethostbyname(host)) == NULL)
2933 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2947 ipfw_check_object_name(const char *name)
2952 * Check that name is null-terminated and contains
2953 * valid symbols only. Valid mask is:
2954 * [a-zA-Z0-9\-_\.]{1,63}
2957 if (l == 0 || l >= 64)
2959 for (i = 0; i < l; i++) {
2961 if (isalpha(c) || isdigit(c) || c == '_' ||
2962 c == '-' || c == '.')
2969 static char *default_state_name = "default";
2971 state_check_name(const char *name)
2974 if (ipfw_check_object_name(name) != 0)
2976 if (strcmp(name, "any") == 0)
2982 eaction_check_name(const char *name)
2985 if (ipfw_check_object_name(name) != 0)
2987 /* Restrict some 'special' names */
2988 if (match_token(rule_actions, name) != -1 &&
2989 match_token(rule_action_params, name) != -1)
2995 pack_object(struct tidx *tstate, char *name, int otype)
2998 ipfw_obj_ntlv *ntlv;
3000 for (i = 0; i < tstate->count; i++) {
3001 if (strcmp(tstate->idx[i].name, name) != 0)
3003 if (tstate->idx[i].set != tstate->set)
3005 if (tstate->idx[i].head.type != otype)
3008 return (tstate->idx[i].idx);
3011 if (tstate->count + 1 > tstate->size) {
3013 tstate->idx = realloc(tstate->idx, tstate->size *
3014 sizeof(ipfw_obj_ntlv));
3015 if (tstate->idx == NULL)
3019 ntlv = &tstate->idx[i];
3020 memset(ntlv, 0, sizeof(ipfw_obj_ntlv));
3021 strlcpy(ntlv->name, name, sizeof(ntlv->name));
3022 ntlv->head.type = otype;
3023 ntlv->head.length = sizeof(ipfw_obj_ntlv);
3024 ntlv->set = tstate->set;
3025 ntlv->idx = ++tstate->counter;
3032 pack_table(struct tidx *tstate, char *name)
3035 if (table_check_name(name) != 0)
3038 return (pack_object(tstate, name, IPFW_TLV_TBL_NAME));
3042 fill_table(struct _ipfw_insn *cmd, char *av, uint8_t opcode,
3043 struct tidx *tstate)
3045 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
3049 if ((p = strchr(av + 6, ')')) == NULL)
3050 errx(EX_DATAERR, "forgotten parenthesis: '%s'", av);
3052 p = strchr(av + 6, ',');
3056 if ((uidx = pack_table(tstate, av + 6)) == 0)
3057 errx(EX_DATAERR, "Invalid table name: %s", av + 6);
3059 cmd->opcode = opcode;
3062 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3063 d[0] = strtoul(p, NULL, 0);
3065 cmd->len |= F_INSN_SIZE(ipfw_insn);
3070 * fills the addr and mask fields in the instruction as appropriate from av.
3071 * Update length as appropriate.
3072 * The following formats are allowed:
3073 * me returns O_IP_*_ME
3074 * 1.2.3.4 single IP address
3075 * 1.2.3.4:5.6.7.8 address:mask
3076 * 1.2.3.4/24 address/mask
3077 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
3078 * We can have multiple comma-separated address/mask entries.
3081 fill_ip(ipfw_insn_ip *cmd, char *av, int cblen, struct tidx *tstate)
3084 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
3086 cmd->o.len &= ~F_LEN_MASK; /* zero len */
3088 if (_substrcmp(av, "any") == 0)
3091 if (_substrcmp(av, "me") == 0) {
3092 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
3096 if (strncmp(av, "table(", 6) == 0) {
3097 fill_table(&cmd->o, av, O_IP_DST_LOOKUP, tstate);
3103 * After the address we can have '/' or ':' indicating a mask,
3104 * ',' indicating another address follows, '{' indicating a
3105 * set of addresses of unspecified size.
3107 char *t = NULL, *p = strpbrk(av, "/:,{");
3111 CHECK_LENGTH(cblen, F_INSN_SIZE(ipfw_insn) + 2 + len);
3116 if ((t = strpbrk(p, ",{")) != NULL) {
3123 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
3124 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
3127 if (!inet_aton(p, (struct in_addr *)&d[1]))
3128 errx(EX_DATAERR, "bad netmask ``%s''", p);
3133 d[1] = htonl(0U); /* mask */
3134 else if (masklen > 32)
3135 errx(EX_DATAERR, "bad width ``%s''", p);
3137 d[1] = htonl(~0U << (32 - masklen));
3139 case '{': /* no mask, assume /24 and put back the '{' */
3140 d[1] = htonl(~0U << (32 - 24));
3144 case ',': /* single address plus continuation */
3147 case 0: /* initialization value */
3149 d[1] = htonl(~0U); /* force /32 */
3152 d[0] &= d[1]; /* mask base address with mask */
3155 /* find next separator */
3157 p = strpbrk(p, ",{");
3158 if (p && *p == '{') {
3160 * We have a set of addresses. They are stored as follows:
3161 * arg1 is the set size (powers of 2, 2..256)
3162 * addr is the base address IN HOST FORMAT
3163 * mask.. is an array of arg1 bits (rounded up to
3164 * the next multiple of 32) with bits set
3165 * for each host in the map.
3167 uint32_t *map = (uint32_t *)&cmd->mask;
3169 int i = contigmask((uint8_t *)&(d[1]), 32);
3172 errx(EX_DATAERR, "address set cannot be in a list");
3173 if (i < 24 || i > 31)
3174 errx(EX_DATAERR, "invalid set with mask %d\n", i);
3175 cmd->o.arg1 = 1<<(32-i); /* map length */
3176 d[0] = ntohl(d[0]); /* base addr in host format */
3177 cmd->o.opcode = O_IP_DST_SET; /* default */
3178 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
3179 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
3180 map[i] = 0; /* clear map */
3184 high = low + cmd->o.arg1 - 1;
3186 * Here, i stores the previous value when we specify a range
3187 * of addresses within a mask, e.g. 45-63. i = -1 means we
3188 * have no previous value.
3190 i = -1; /* previous value in a range */
3191 while (isdigit(*av)) {
3193 int a = strtol(av, &s, 0);
3195 if (s == av) { /* no parameter */
3197 errx(EX_DATAERR, "set not closed\n");
3199 errx(EX_DATAERR, "incomplete range %d-", i);
3202 if (a < low || a > high)
3203 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
3206 if (i == -1) /* no previous in range */
3208 else { /* check that range is valid */
3210 errx(EX_DATAERR, "invalid range %d-%d",
3213 errx(EX_DATAERR, "double '-' in range");
3216 map[i/32] |= 1<<(i & 31);
3227 if (av) /* then *av must be a ',' */
3230 /* Check this entry */
3231 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
3233 * 'any' turns the entire list into a NOP.
3234 * 'not any' never matches, so it is removed from the
3235 * list unless it is the only item, in which case we
3238 if (cmd->o.len & F_NOT) { /* "not any" never matches */
3239 if (av == NULL && len == 0) /* only this entry */
3240 errx(EX_DATAERR, "not any never matches");
3242 /* else do nothing and skip this entry */
3245 /* A single IP can be stored in an optimized format */
3246 if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
3247 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
3250 len += 2; /* two words... */
3253 if (len + 1 > F_LEN_MASK)
3254 errx(EX_DATAERR, "address list too long");
3255 cmd->o.len |= len+1;
3259 /* n2mask sets n bits of the mask */
3261 n2mask(struct in6_addr *mask, int n)
3263 static int minimask[9] =
3264 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
3267 memset(mask, 0, sizeof(struct in6_addr));
3268 p = (u_char *) mask;
3269 for (; n > 0; p++, n -= 8) {
3279 fill_flags_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3280 struct _s_x *flags, char *p)
3283 uint32_t set = 0, clear = 0;
3285 if (fill_flags(flags, p, &e, &set, &clear) != 0)
3286 errx(EX_DATAERR, "invalid flag %s", e);
3288 cmd->opcode = opcode;
3289 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
3290 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3295 ipfw_delete(char *av[])
3300 int exitval = EX_OK;
3304 NEED1("missing rule specification");
3305 if ( *av && _substrcmp(*av, "set") == 0) {
3306 /* Do not allow using the following syntax:
3307 * ipfw set N delete set M
3310 errx(EX_DATAERR, "invalid syntax");
3311 do_set = 1; /* delete set */
3316 while (*av && isdigit(**av)) {
3317 i = strtol(*av, &sep, 10);
3320 j = strtol(sep + 1, NULL, 10);
3323 exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
3325 exitval = EX_UNAVAILABLE;
3328 warn("nat %u not available", i);
3330 } else if (co.do_pipe) {
3331 exitval = ipfw_delete_pipe(co.do_pipe, i);
3333 memset(&rt, 0, sizeof(rt));
3336 rt.flags = IPFW_RCFLAG_SET;
3338 rt.start_rule = i & 0xffff;
3339 rt.end_rule = j & 0xffff;
3340 if (rt.start_rule == 0 && rt.end_rule == 0)
3341 rt.flags |= IPFW_RCFLAG_ALL;
3343 rt.flags |= IPFW_RCFLAG_RANGE;
3344 if (co.use_set != 0) {
3345 rt.set = co.use_set - 1;
3346 rt.flags |= IPFW_RCFLAG_SET;
3349 if (co.do_dynamic == 2)
3350 rt.flags |= IPFW_RCFLAG_DYNAMIC;
3351 i = do_range_cmd(IP_FW_XDEL, &rt);
3353 exitval = EX_UNAVAILABLE;
3356 warn("rule %u: setsockopt(IP_FW_XDEL)",
3358 } else if (rt.new_set == 0 && do_set == 0 &&
3359 co.do_dynamic != 2) {
3360 exitval = EX_UNAVAILABLE;
3363 if (rt.start_rule != rt.end_rule)
3364 warnx("no rules rules in %u-%u range",
3365 rt.start_rule, rt.end_rule);
3367 warnx("rule %u not found",
3372 if (exitval != EX_OK && co.do_force == 0)
3378 * fill the interface structure. We do not check the name as we can
3379 * create interfaces dynamically, so checking them at insert time
3380 * makes relatively little sense.
3381 * Interface names containing '*', '?', or '[' are assumed to be shell
3382 * patterns which match interfaces.
3385 fill_iface(ipfw_insn_if *cmd, char *arg, int cblen, struct tidx *tstate)
3390 cmd->name[0] = '\0';
3391 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3395 /* Parse the interface or address */
3396 if (strcmp(arg, "any") == 0)
3397 cmd->o.len = 0; /* effectively ignore this command */
3398 else if (strncmp(arg, "table(", 6) == 0) {
3399 if ((p = strchr(arg + 6, ')')) == NULL)
3400 errx(EX_DATAERR, "forgotten parenthesis: '%s'", arg);
3402 p = strchr(arg + 6, ',');
3405 if ((uidx = pack_table(tstate, arg + 6)) == 0)
3406 errx(EX_DATAERR, "Invalid table name: %s", arg + 6);
3408 cmd->name[0] = '\1'; /* Special value indicating table */
3410 } else if (!isdigit(*arg)) {
3411 strlcpy(cmd->name, arg, sizeof(cmd->name));
3412 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3413 } else if (!inet_aton(arg, &cmd->p.ip))
3414 errx(EX_DATAERR, "bad ip address ``%s''", arg);
3418 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
3422 char *ap, *ptr, *optr;
3423 struct ether_addr *mac;
3424 const char *macset = "0123456789abcdefABCDEF:";
3426 if (strcmp(p, "any") == 0) {
3427 for (i = 0; i < ETHER_ADDR_LEN; i++)
3428 addr[i] = mask[i] = 0;
3432 optr = ptr = strdup(p);
3433 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
3435 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
3436 errx(EX_DATAERR, "Incorrect MAC address");
3437 bcopy(mac, addr, ETHER_ADDR_LEN);
3439 errx(EX_DATAERR, "Incorrect MAC address");
3441 if (ptr != NULL) { /* we have mask? */
3442 if (p[ptr - optr - 1] == '/') { /* mask len */
3443 long ml = strtol(ptr, &ap, 10);
3444 if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
3445 errx(EX_DATAERR, "Incorrect mask length");
3446 for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
3447 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
3450 if (strspn(ptr, macset) != l ||
3451 (mac = ether_aton(ptr)) == NULL)
3452 errx(EX_DATAERR, "Incorrect mask");
3453 bcopy(mac, mask, ETHER_ADDR_LEN);
3455 } else { /* default mask: ff:ff:ff:ff:ff:ff */
3456 for (i = 0; i < ETHER_ADDR_LEN; i++)
3459 for (i = 0; i < ETHER_ADDR_LEN; i++)
3466 * helper function, updates the pointer to cmd with the length
3467 * of the current command, and also cleans up the first word of
3468 * the new command in case it has been clobbered before.
3471 next_cmd(ipfw_insn *cmd, int *len)
3474 CHECK_LENGTH(*len, 0);
3476 bzero(cmd, sizeof(*cmd));
3481 * Takes arguments and copies them into a comment
3484 fill_comment(ipfw_insn *cmd, char **av, int cblen)
3487 char *p = (char *)(cmd + 1);
3489 cmd->opcode = O_NOP;
3490 cmd->len = (cmd->len & (F_NOT | F_OR));
3492 /* Compute length of comment string. */
3493 for (i = 0, l = 0; av[i] != NULL; i++)
3494 l += strlen(av[i]) + 1;
3499 "comment too long (max 80 chars)");
3501 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
3504 for (i = 0; av[i] != NULL; i++) {
3513 * A function to fill simple commands of size 1.
3514 * Existing flags are preserved.
3517 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3519 cmd->opcode = opcode;
3520 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3525 * Fetch and add the MAC address and type, with masks. This generates one or
3526 * two microinstructions, and returns the pointer to the last one.
3529 add_mac(ipfw_insn *cmd, char *av[], int cblen)
3533 if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
3534 errx(EX_DATAERR, "MAC dst src");
3536 cmd->opcode = O_MACADDR2;
3537 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3540 mac = (ipfw_insn_mac *)cmd;
3541 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
3542 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
3543 &(mac->mask[ETHER_ADDR_LEN])); /* src */
3548 add_mactype(ipfw_insn *cmd, char *av, int cblen)
3551 errx(EX_DATAERR, "missing MAC type");
3552 if (strcmp(av, "any") != 0) { /* we have a non-null type */
3553 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
3555 cmd->opcode = O_MAC_TYPE;
3562 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
3564 struct protoent *pe;
3568 proto = strtol(av, &ep, 10);
3569 if (*ep != '\0' || proto <= 0) {
3570 if ((pe = getprotobyname(av)) == NULL)
3572 proto = pe->p_proto;
3575 fill_cmd(cmd, O_PROTO, 0, proto);
3581 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
3583 u_char proto = IPPROTO_IP;
3585 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3586 ; /* do not set O_IP4 nor O_IP6 */
3587 else if (strcmp(av, "ip4") == 0)
3588 /* explicit "just IPv4" rule */
3589 fill_cmd(cmd, O_IP4, 0, 0);
3590 else if (strcmp(av, "ip6") == 0) {
3591 /* explicit "just IPv6" rule */
3592 proto = IPPROTO_IPV6;
3593 fill_cmd(cmd, O_IP6, 0, 0);
3595 return add_proto0(cmd, av, protop);
3602 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
3604 u_char proto = IPPROTO_IP;
3606 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3607 ; /* do not set O_IP4 nor O_IP6 */
3608 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3609 /* explicit "just IPv4" rule */
3610 fill_cmd(cmd, O_IP4, 0, 0);
3611 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3612 /* explicit "just IPv6" rule */
3613 proto = IPPROTO_IPV6;
3614 fill_cmd(cmd, O_IP6, 0, 0);
3616 return add_proto0(cmd, av, protop);
3623 add_srcip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3625 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3626 if (cmd->opcode == O_IP_DST_SET) /* set */
3627 cmd->opcode = O_IP_SRC_SET;
3628 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3629 cmd->opcode = O_IP_SRC_LOOKUP;
3630 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3631 cmd->opcode = O_IP_SRC_ME;
3632 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3633 cmd->opcode = O_IP_SRC;
3634 else /* addr/mask */
3635 cmd->opcode = O_IP_SRC_MASK;
3640 add_dstip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3642 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3643 if (cmd->opcode == O_IP_DST_SET) /* set */
3645 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3647 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3648 cmd->opcode = O_IP_DST_ME;
3649 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3650 cmd->opcode = O_IP_DST;
3651 else /* addr/mask */
3652 cmd->opcode = O_IP_DST_MASK;
3656 static struct _s_x f_reserved_keywords[] = {
3659 { "diverted", TOK_OR },
3660 { "dst-port", TOK_OR },
3661 { "src-port", TOK_OR },
3662 { "established", TOK_OR },
3663 { "keep-state", TOK_OR },
3665 { "icmptypes", TOK_OR },
3673 { NULL, 0 } /* terminator */
3677 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
3680 if (match_token(f_reserved_keywords, av) != -1)
3683 if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
3684 /* XXX todo: check that we have a protocol with ports */
3685 cmd->opcode = opcode;
3692 add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3695 char *host, *ch, buf[INET6_ADDRSTRLEN];
3696 ipfw_insn *ret = NULL;
3699 /* Copy first address in set if needed */
3700 if ((ch = strpbrk(av, "/,")) != NULL) {
3702 strlcpy(buf, av, sizeof(buf));
3703 if (len < sizeof(buf))
3709 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3710 inet_pton(AF_INET6, host, &a) == 1)
3711 ret = add_srcip6(cmd, av, cblen, tstate);
3712 /* XXX: should check for IPv4, not !IPv6 */
3713 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3714 inet_pton(AF_INET6, host, &a) != 1))
3715 ret = add_srcip(cmd, av, cblen, tstate);
3716 if (ret == NULL && strcmp(av, "any") != 0)
3723 add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3726 char *host, *ch, buf[INET6_ADDRSTRLEN];
3727 ipfw_insn *ret = NULL;
3730 /* Copy first address in set if needed */
3731 if ((ch = strpbrk(av, "/,")) != NULL) {
3733 strlcpy(buf, av, sizeof(buf));
3734 if (len < sizeof(buf))
3740 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3741 inet_pton(AF_INET6, host, &a) == 1)
3742 ret = add_dstip6(cmd, av, cblen, tstate);
3743 /* XXX: should check for IPv4, not !IPv6 */
3744 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3745 inet_pton(AF_INET6, host, &a) != 1))
3746 ret = add_dstip(cmd, av, cblen, tstate);
3747 if (ret == NULL && strcmp(av, "any") != 0)
3754 * Parse arguments and assemble the microinstructions which make up a rule.
3755 * Rules are added into the 'rulebuf' and then copied in the correct order
3756 * into the actual rule.
3758 * The syntax for a rule starts with the action, followed by
3759 * optional action parameters, and the various match patterns.
3760 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
3761 * (generated if the rule includes a keep-state option), then the
3762 * various match patterns, log/altq actions, and the actual action.
3766 compile_rule(char *av[], uint32_t *rbuf, int *rbufsize, struct tidx *tstate)
3769 * rules are added into the 'rulebuf' and then copied in
3770 * the correct order into the actual rule.
3771 * Some things that need to go out of order (prob, action etc.)
3774 static uint32_t actbuf[255], cmdbuf[255];
3775 int rblen, ablen, cblen;
3777 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
3778 ipfw_insn *first_cmd; /* first match pattern */
3780 struct ip_fw_rule *rule;
3783 * various flags used to record that we entered some fields.
3785 ipfw_insn *have_state = NULL; /* any state-related option */
3786 int have_rstate = 0;
3787 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
3788 ipfw_insn *have_skipcmd = NULL;
3793 int open_par = 0; /* open parenthesis ( */
3795 /* proto is here because it is used to fetch ports */
3796 u_char proto = IPPROTO_IP; /* default protocol */
3798 double match_prob = 1; /* match probability, default is always match */
3800 bzero(actbuf, sizeof(actbuf)); /* actions go here */
3801 bzero(cmdbuf, sizeof(cmdbuf));
3802 bzero(rbuf, *rbufsize);
3804 rule = (struct ip_fw_rule *)rbuf;
3805 cmd = (ipfw_insn *)cmdbuf;
3806 action = (ipfw_insn *)actbuf;
3808 rblen = *rbufsize / sizeof(uint32_t);
3809 rblen -= sizeof(struct ip_fw_rule) / sizeof(uint32_t);
3810 ablen = sizeof(actbuf) / sizeof(actbuf[0]);
3811 cblen = sizeof(cmdbuf) / sizeof(cmdbuf[0]);
3812 cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
3814 #define CHECK_RBUFLEN(len) { CHECK_LENGTH(rblen, len); rblen -= len; }
3815 #define CHECK_ACTLEN CHECK_LENGTH(ablen, action->len)
3819 /* [rule N] -- Rule number optional */
3820 if (av[0] && isdigit(**av)) {
3821 rule->rulenum = atoi(*av);
3825 /* [set N] -- set number (0..RESVD_SET), optional */
3826 if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
3827 int set = strtoul(av[1], NULL, 10);
3828 if (set < 0 || set > RESVD_SET)
3829 errx(EX_DATAERR, "illegal set %s", av[1]);
3835 /* [prob D] -- match probability, optional */
3836 if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
3837 match_prob = strtod(av[1], NULL);
3839 if (match_prob <= 0 || match_prob > 1)
3840 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
3844 /* action -- mandatory */
3845 NEED1("missing action");
3846 i = match_token(rule_actions, *av);
3848 action->len = 1; /* default */
3851 case TOK_CHECKSTATE:
3852 have_state = action;
3853 action->opcode = O_CHECK_STATE;
3855 match_token(rule_options, *av) == TOK_COMMENT) {
3856 action->arg1 = pack_object(tstate,
3857 default_state_name, IPFW_TLV_STATE_NAME);
3860 if (*av[0] == ':') {
3861 if (strcmp(*av + 1, "any") == 0)
3863 else if (state_check_name(*av + 1) == 0)
3864 action->arg1 = pack_object(tstate, *av + 1,
3865 IPFW_TLV_STATE_NAME);
3867 errx(EX_DATAERR, "Invalid state name %s",
3872 errx(EX_DATAERR, "Invalid state name %s", *av);
3876 action->opcode = O_REJECT;
3877 action->arg1 = ICMP_REJECT_ABORT;
3881 action->opcode = O_UNREACH6;
3882 action->arg1 = ICMP6_UNREACH_ABORT;
3886 action->opcode = O_ACCEPT;
3890 action->opcode = O_DENY;
3895 action->opcode = O_REJECT;
3896 action->arg1 = ICMP_UNREACH_HOST;
3900 action->opcode = O_REJECT;
3901 action->arg1 = ICMP_REJECT_RST;
3905 action->opcode = O_UNREACH6;
3906 action->arg1 = ICMP6_UNREACH_RST;
3910 action->opcode = O_REJECT;
3911 NEED1("missing reject code");
3912 fill_reject_code(&action->arg1, *av);
3917 action->opcode = O_UNREACH6;
3918 NEED1("missing unreach code");
3919 fill_unreach6_code(&action->arg1, *av);
3924 action->opcode = O_COUNT;
3928 action->opcode = O_NAT;
3929 action->len = F_INSN_SIZE(ipfw_insn_nat);
3931 if (*av != NULL && _substrcmp(*av, "global") == 0) {
3932 action->arg1 = IP_FW_NAT44_GLOBAL;
3938 action->opcode = O_QUEUE;
3941 action->opcode = O_PIPE;
3944 action->opcode = O_SKIPTO;
3947 action->opcode = O_NETGRAPH;
3950 action->opcode = O_NGTEE;
3953 action->opcode = O_DIVERT;
3956 action->opcode = O_TEE;
3959 action->opcode = O_CALLRETURN;
3962 errx(EX_USAGE, "missing argument for %s", *(av - 1));
3963 if (isdigit(**av)) {
3964 action->arg1 = strtoul(*av, NULL, 10);
3965 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
3966 errx(EX_DATAERR, "illegal argument for %s",
3968 } else if (_substrcmp(*av, "tablearg") == 0) {
3969 action->arg1 = IP_FW_TARG;
3970 } else if (i == TOK_DIVERT || i == TOK_TEE) {
3973 s = getservbyname(av[0], "divert");
3975 action->arg1 = ntohs(s->s_port);
3977 errx(EX_DATAERR, "illegal divert/tee port");
3979 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
3985 * Locate the address-port separator (':' or ',').
3986 * Could be one of the following:
3990 * IPv6 w:x:y::z,port
3991 * The ':' can only be used with hostname and IPv4 address.
3992 * XXX-BZ Should we also support [w:x:y::z]:port?
3994 struct sockaddr_storage result;
3995 struct addrinfo *res;
3998 u_short port_number;
4000 NEED1("missing forward address[:port]");
4003 * locate the address-port separator (':' or ',')
4005 s = strchr(*av, ',');
4007 /* Distinguish between IPv4:port and IPv6 cases. */
4008 s = strchr(*av, ':');
4009 if (s && strchr(s+1, ':'))
4010 s = NULL; /* no port */
4015 /* Terminate host portion and set s to start of port. */
4017 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
4020 "illegal forwarding port ``%s''", s);
4021 port_number = (u_short)i;
4024 if (_substrcmp(*av, "tablearg") == 0) {
4026 ((struct sockaddr_in*)&result)->sin_addr.s_addr =
4030 * Resolve the host name or address to a family and a
4031 * network representation of the address.
4033 if (getaddrinfo(*av, NULL, NULL, &res))
4034 errx(EX_DATAERR, NULL);
4035 /* Just use the first host in the answer. */
4036 family = res->ai_family;
4037 memcpy(&result, res->ai_addr, res->ai_addrlen);
4041 if (family == PF_INET) {
4042 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
4044 action->opcode = O_FORWARD_IP;
4045 action->len = F_INSN_SIZE(ipfw_insn_sa);
4049 * In the kernel we assume AF_INET and use only
4050 * sin_port and sin_addr. Remember to set sin_len as
4051 * the routing code seems to use it too.
4053 p->sa.sin_len = sizeof(struct sockaddr_in);
4054 p->sa.sin_family = AF_INET;
4055 p->sa.sin_port = port_number;
4056 p->sa.sin_addr.s_addr =
4057 ((struct sockaddr_in *)&result)->sin_addr.s_addr;
4058 } else if (family == PF_INET6) {
4059 ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
4061 action->opcode = O_FORWARD_IP6;
4062 action->len = F_INSN_SIZE(ipfw_insn_sa6);
4065 p->sa.sin6_len = sizeof(struct sockaddr_in6);
4066 p->sa.sin6_family = AF_INET6;
4067 p->sa.sin6_port = port_number;
4068 p->sa.sin6_flowinfo = 0;
4069 p->sa.sin6_scope_id =
4070 ((struct sockaddr_in6 *)&result)->sin6_scope_id;
4071 bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
4072 &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
4074 errx(EX_DATAERR, "Invalid address family in forward action");
4080 /* pretend it is a 'count' rule followed by the comment */
4081 action->opcode = O_COUNT;
4082 av--; /* go back... */
4088 size_t intsize = sizeof(int);
4090 action->opcode = O_SETFIB;
4091 NEED1("missing fib number");
4092 if (_substrcmp(*av, "tablearg") == 0) {
4093 action->arg1 = IP_FW_TARG;
4095 action->arg1 = strtoul(*av, NULL, 10);
4096 if (sysctlbyname("net.fibs", &numfibs, &intsize,
4098 errx(EX_DATAERR, "fibs not suported.\n");
4099 if (action->arg1 >= numfibs) /* Temporary */
4100 errx(EX_DATAERR, "fib too large.\n");
4101 /* Add high-order bit to fib to make room for tablearg*/
4102 action->arg1 |= 0x8000;
4112 action->opcode = O_SETDSCP;
4113 NEED1("missing DSCP code");
4114 if (_substrcmp(*av, "tablearg") == 0) {
4115 action->arg1 = IP_FW_TARG;
4117 if (isalpha(*av[0])) {
4118 if ((code = match_token(f_ipdscp, *av)) == -1)
4119 errx(EX_DATAERR, "Unknown DSCP code");
4120 action->arg1 = code;
4122 action->arg1 = strtoul(*av, NULL, 10);
4124 * Add high-order bit to DSCP to make room
4127 action->arg1 |= 0x8000;
4134 action->opcode = O_REASS;
4138 fill_cmd(action, O_CALLRETURN, F_NOT, 0);
4141 case TOK_TCPSETMSS: {
4145 idx = pack_object(tstate, "tcp-setmss", IPFW_TLV_EACTION);
4147 errx(EX_DATAERR, "pack_object failed");
4148 fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4149 NEED1("Missing MSS value");
4150 action = next_cmd(action, &ablen);
4153 mss = strtoul(*av, NULL, 10);
4154 if (mss == 0 || mss > UINT16_MAX)
4155 errx(EX_USAGE, "invalid MSS value %s", *av);
4156 fill_cmd(action, O_EXTERNAL_DATA, 0, (uint16_t)mss);
4163 if (match_token(rule_eactions, *av) == -1)
4164 errx(EX_DATAERR, "invalid action %s\n", *av);
4166 * External actions support.
4167 * XXX: we support only syntax with instance name.
4168 * For known external actions (from rule_eactions list)
4169 * we can handle syntax directly. But with `eaction'
4170 * keyword we can use only `eaction <name> <instance>'
4176 NEED1("Missing eaction name");
4177 if (eaction_check_name(*av) != 0)
4178 errx(EX_DATAERR, "Invalid eaction name %s", *av);
4179 idx = pack_object(tstate, *av, IPFW_TLV_EACTION);
4181 errx(EX_DATAERR, "pack_object failed");
4182 fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4184 NEED1("Missing eaction instance name");
4185 action = next_cmd(action, &ablen);
4188 if (eaction_check_name(*av) != 0)
4189 errx(EX_DATAERR, "Invalid eaction instance name %s",
4192 * External action instance object has TLV type depended
4193 * from the external action name object index. Since we
4194 * currently don't know this index, use zero as TLV type.
4196 idx = pack_object(tstate, *av, 0);
4198 errx(EX_DATAERR, "pack_object failed");
4199 fill_cmd(action, O_EXTERNAL_INSTANCE, 0, idx);
4203 action = next_cmd(action, &ablen);
4206 * [altq queuename] -- altq tag, optional
4207 * [log [logamount N]] -- log, optional
4209 * If they exist, it go first in the cmdbuf, but then it is
4210 * skipped in the copy section to the end of the buffer.
4212 while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
4217 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
4222 "log cannot be specified more than once");
4223 have_log = (ipfw_insn *)c;
4224 cmd->len = F_INSN_SIZE(ipfw_insn_log);
4226 cmd->opcode = O_LOG;
4227 if (av[0] && _substrcmp(*av, "logamount") == 0) {
4229 NEED1("logamount requires argument");
4233 "logamount must be positive");
4237 len = sizeof(c->max_log);
4238 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
4239 &c->max_log, &len, NULL, 0) == -1) {
4244 errx(1, "sysctlbyname(\"%s\")",
4245 "net.inet.ip.fw.verbose_limit");
4254 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
4256 NEED1("missing altq queue name");
4259 "altq cannot be specified more than once");
4260 have_altq = (ipfw_insn *)a;
4261 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
4263 cmd->opcode = O_ALTQ;
4264 a->qid = altq_name_to_qid(*av);
4275 errx(EX_USAGE, "tag and untag cannot be "
4276 "specified more than once");
4277 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
4278 rule_action_params);
4280 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
4288 cmd = next_cmd(cmd, &cblen);
4291 if (have_state) { /* must be a check-state, we are done */
4293 match_token(rule_options, *av) == TOK_COMMENT) {
4294 /* check-state has a comment */
4296 fill_comment(cmd, av, cblen);
4297 cmd = next_cmd(cmd, &cblen);
4303 #define OR_START(target) \
4304 if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
4306 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
4309 if ( (av[0])[1] == '\0') { \
4320 strcmp(*av, ")") == 0 || \
4321 strcmp(*av, "}") == 0)) { \
4326 errx(EX_USAGE, "missing \")\"\n"); \
4330 if (av[0] && _substrcmp(*av, "not") == 0) { \
4331 if (cmd->len & F_NOT) \
4332 errx(EX_USAGE, "double \"not\" not allowed\n"); \
4333 cmd->len |= F_NOT; \
4337 #define OR_BLOCK(target) \
4338 if (av[0] && _substrcmp(*av, "or") == 0) { \
4339 if (prev == NULL || open_par == 0) \
4340 errx(EX_DATAERR, "invalid OR block"); \
4341 prev->len |= F_OR; \
4351 * MAC addresses, optional.
4352 * If we have this, we skip the part "proto from src to dst"
4353 * and jump straight to the option parsing.
4356 NEED1("missing protocol");
4357 if (_substrcmp(*av, "MAC") == 0 ||
4358 _substrcmp(*av, "mac") == 0) {
4359 av++; /* the "MAC" keyword */
4360 add_mac(cmd, av); /* exits in case of errors */
4361 cmd = next_cmd(cmd);
4362 av += 2; /* dst-mac and src-mac */
4364 NEED1("missing mac type");
4365 if (add_mactype(cmd, av[0]))
4366 cmd = next_cmd(cmd);
4367 av++; /* any or mac-type */
4373 * protocol, mandatory
4375 OR_START(get_proto);
4377 NEED1("missing protocol");
4378 if (add_proto_compat(cmd, *av, &proto)) {
4380 if (F_LEN(cmd) != 0) {
4382 cmd = next_cmd(cmd, &cblen);
4384 } else if (first_cmd != cmd) {
4385 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
4387 rule->flags |= IPFW_RULE_JUSTOPTS;
4390 OR_BLOCK(get_proto);
4395 if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
4396 errx(EX_USAGE, "missing ``from''");
4400 * source IP, mandatory
4402 OR_START(source_ip);
4403 NOT_BLOCK; /* optional "not" */
4404 NEED1("missing source address");
4405 if (add_src(cmd, *av, proto, cblen, tstate)) {
4407 if (F_LEN(cmd) != 0) { /* ! any */
4409 cmd = next_cmd(cmd, &cblen);
4412 errx(EX_USAGE, "bad source address %s", *av);
4413 OR_BLOCK(source_ip);
4416 * source ports, optional
4418 NOT_BLOCK; /* optional "not" */
4419 if ( av[0] != NULL ) {
4420 if (_substrcmp(*av, "any") == 0 ||
4421 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4423 if (F_LEN(cmd) != 0)
4424 cmd = next_cmd(cmd, &cblen);
4431 if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
4432 errx(EX_USAGE, "missing ``to''");
4436 * destination, mandatory
4439 NOT_BLOCK; /* optional "not" */
4440 NEED1("missing dst address");
4441 if (add_dst(cmd, *av, proto, cblen, tstate)) {
4443 if (F_LEN(cmd) != 0) { /* ! any */
4445 cmd = next_cmd(cmd, &cblen);
4448 errx( EX_USAGE, "bad destination address %s", *av);
4452 * dest. ports, optional
4454 NOT_BLOCK; /* optional "not" */
4456 if (_substrcmp(*av, "any") == 0 ||
4457 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4459 if (F_LEN(cmd) != 0)
4460 cmd = next_cmd(cmd, &cblen);
4466 while ( av[0] != NULL ) {
4468 ipfw_insn_u32 *cmd32; /* alias for cmd */
4471 cmd32 = (ipfw_insn_u32 *)cmd;
4473 if (*s == '!') { /* alternate syntax for NOT */
4474 if (cmd->len & F_NOT)
4475 errx(EX_USAGE, "double \"not\" not allowed\n");
4479 i = match_token(rule_options, s);
4483 if (cmd->len & F_NOT)
4484 errx(EX_USAGE, "double \"not\" not allowed\n");
4489 if (open_par == 0 || prev == NULL)
4490 errx(EX_USAGE, "invalid \"or\" block\n");
4494 case TOK_STARTBRACE:
4496 errx(EX_USAGE, "+nested \"(\" not allowed\n");
4502 errx(EX_USAGE, "+missing \")\"\n");
4508 fill_cmd(cmd, O_IN, 0, 0);
4512 cmd->len ^= F_NOT; /* toggle F_NOT */
4513 fill_cmd(cmd, O_IN, 0, 0);
4517 fill_cmd(cmd, O_DIVERTED, 0, 3);
4520 case TOK_DIVERTEDLOOPBACK:
4521 fill_cmd(cmd, O_DIVERTED, 0, 1);
4524 case TOK_DIVERTEDOUTPUT:
4525 fill_cmd(cmd, O_DIVERTED, 0, 2);
4529 fill_cmd(cmd, O_FRAG, 0, 0);
4533 fill_cmd(cmd, O_LAYER2, 0, 0);
4539 NEED1("recv, xmit, via require interface name"
4541 fill_iface((ipfw_insn_if *)cmd, av[0], cblen, tstate);
4543 if (F_LEN(cmd) == 0) /* not a valid address */
4546 cmd->opcode = O_XMIT;
4547 else if (i == TOK_RECV)
4548 cmd->opcode = O_RECV;
4549 else if (i == TOK_VIA)
4550 cmd->opcode = O_VIA;
4554 NEED1("icmptypes requires list of types");
4555 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
4559 case TOK_ICMP6TYPES:
4560 NEED1("icmptypes requires list of types");
4561 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
4566 NEED1("ipttl requires TTL");
4567 if (strpbrk(*av, "-,")) {
4568 if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
4569 errx(EX_DATAERR, "invalid ipttl %s", *av);
4571 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
4576 NEED1("ipid requires id");
4577 if (strpbrk(*av, "-,")) {
4578 if (!add_ports(cmd, *av, 0, O_IPID, cblen))
4579 errx(EX_DATAERR, "invalid ipid %s", *av);
4581 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
4586 NEED1("iplen requires length");
4587 if (strpbrk(*av, "-,")) {
4588 if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
4589 errx(EX_DATAERR, "invalid ip len %s", *av);
4591 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
4596 NEED1("ipver requires version");
4597 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
4601 case TOK_IPPRECEDENCE:
4602 NEED1("ipprecedence requires value");
4603 fill_cmd(cmd, O_IPPRECEDENCE, 0,
4604 (strtoul(*av, NULL, 0) & 7) << 5);
4609 NEED1("missing DSCP code");
4610 fill_dscp(cmd, *av, cblen);
4615 NEED1("missing argument for ipoptions");
4616 fill_flags_cmd(cmd, O_IPOPT, f_ipopts, *av);
4621 NEED1("missing argument for iptos");
4622 fill_flags_cmd(cmd, O_IPTOS, f_iptos, *av);
4627 NEED1("uid requires argument");
4633 cmd->opcode = O_UID;
4634 uid = strtoul(*av, &end, 0);
4635 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
4637 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
4638 cmd32->d[0] = pwd->pw_uid;
4639 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4645 NEED1("gid requires argument");
4651 cmd->opcode = O_GID;
4652 gid = strtoul(*av, &end, 0);
4653 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
4655 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
4656 cmd32->d[0] = grp->gr_gid;
4657 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4663 NEED1("jail requires argument");
4667 cmd->opcode = O_JAIL;
4668 jid = jail_getid(*av);
4670 errx(EX_DATAERR, "%s", jail_errmsg);
4671 cmd32->d[0] = (uint32_t)jid;
4672 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4678 fill_cmd(cmd, O_ESTAB, 0, 0);
4682 fill_cmd(cmd, O_TCPFLAGS, 0,
4683 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
4686 case TOK_TCPDATALEN:
4687 NEED1("tcpdatalen requires length");
4688 if (strpbrk(*av, "-,")) {
4689 if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
4690 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
4692 fill_cmd(cmd, O_TCPDATALEN, 0,
4693 strtoul(*av, NULL, 0));
4698 NEED1("missing argument for tcpoptions");
4699 fill_flags_cmd(cmd, O_TCPOPTS, f_tcpopts, *av);
4705 NEED1("tcpseq/tcpack requires argument");
4706 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
4707 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
4708 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
4713 NEED1("tcpwin requires length");
4714 if (strpbrk(*av, "-,")) {
4715 if (!add_ports(cmd, *av, 0, O_TCPWIN, cblen))
4716 errx(EX_DATAERR, "invalid tcpwin len %s", *av);
4718 fill_cmd(cmd, O_TCPWIN, 0,
4719 strtoul(*av, NULL, 0));
4724 NEED1("missing argument for tcpflags");
4725 cmd->opcode = O_TCPFLAGS;
4726 fill_flags_cmd(cmd, O_TCPFLAGS, f_tcpflags, *av);
4731 case TOK_RECORDSTATE: {
4735 errx(EX_USAGE, "keep-state or record-state cannot be part "
4738 errx(EX_USAGE, "only one of keep-state, record-state, "
4739 " limit and set-limit is allowed");
4740 if (*av != NULL && *av[0] == ':') {
4741 if (state_check_name(*av + 1) != 0)
4743 "Invalid state name %s", *av);
4744 uidx = pack_object(tstate, *av + 1,
4745 IPFW_TLV_STATE_NAME);
4748 uidx = pack_object(tstate, default_state_name,
4749 IPFW_TLV_STATE_NAME);
4751 have_rstate = i == TOK_RECORDSTATE;
4752 fill_cmd(cmd, O_KEEP_STATE, 0, uidx);
4757 case TOK_SETLIMIT: {
4758 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
4763 "limit or set-limit cannot be part of an or block");
4765 errx(EX_USAGE, "only one of keep-state, record-state, "
4766 " limit and set-limit is allowed");
4768 have_rstate = i == TOK_SETLIMIT;
4770 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
4772 cmd->opcode = O_LIMIT;
4773 c->limit_mask = c->conn_limit = 0;
4775 while ( av[0] != NULL ) {
4776 if ((val = match_token(limit_masks, *av)) <= 0)
4778 c->limit_mask |= val;
4782 if (c->limit_mask == 0)
4783 errx(EX_USAGE, "limit: missing limit mask");
4785 GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
4786 TOK_LIMIT, rule_options);
4789 if (*av != NULL && *av[0] == ':') {
4790 if (state_check_name(*av + 1) != 0)
4792 "Invalid state name %s", *av);
4793 cmd->arg1 = pack_object(tstate, *av + 1,
4794 IPFW_TLV_STATE_NAME);
4797 cmd->arg1 = pack_object(tstate,
4798 default_state_name, IPFW_TLV_STATE_NAME);
4803 NEED1("missing protocol");
4804 if (add_proto(cmd, *av, &proto)) {
4807 errx(EX_DATAERR, "invalid protocol ``%s''",
4812 NEED1("missing source IP");
4813 if (add_srcip(cmd, *av, cblen, tstate)) {
4819 NEED1("missing destination IP");
4820 if (add_dstip(cmd, *av, cblen, tstate)) {
4826 NEED1("missing source IP6");
4827 if (add_srcip6(cmd, *av, cblen, tstate)) {
4833 NEED1("missing destination IP6");
4834 if (add_dstip6(cmd, *av, cblen, tstate)) {
4840 NEED1("missing source port");
4841 if (_substrcmp(*av, "any") == 0 ||
4842 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4845 errx(EX_DATAERR, "invalid source port %s", *av);
4849 NEED1("missing destination port");
4850 if (_substrcmp(*av, "any") == 0 ||
4851 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4854 errx(EX_DATAERR, "invalid destination port %s",
4859 if (add_mac(cmd, av, cblen))
4864 NEED1("missing mac type");
4865 if (!add_mactype(cmd, *av, cblen))
4866 errx(EX_DATAERR, "invalid mac type %s", *av);
4870 case TOK_VERREVPATH:
4871 fill_cmd(cmd, O_VERREVPATH, 0, 0);
4874 case TOK_VERSRCREACH:
4875 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
4879 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
4883 fill_cmd(cmd, O_IPSEC, 0, 0);
4887 fill_cmd(cmd, O_IP6, 0, 0);
4891 fill_cmd(cmd, O_IP4, 0, 0);
4895 fill_ext6hdr( cmd, *av );
4900 if (proto != IPPROTO_IPV6 )
4901 errx( EX_USAGE, "flow-id filter is active "
4902 "only for ipv6 protocol\n");
4903 fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
4908 fill_comment(cmd, av, cblen);
4913 if (av[0] && strpbrk(*av, "-,")) {
4914 if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
4915 errx(EX_DATAERR, "tagged: invalid tag"
4921 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
4922 TOK_TAGGED, rule_options);
4923 fill_cmd(cmd, O_TAGGED, 0, tag);
4929 NEED1("fib requires fib number");
4930 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
4934 fill_cmd(cmd, O_SOCKARG, 0, 0);
4938 ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
4941 if (!av[0] || !av[1])
4942 errx(EX_USAGE, "format: lookup argument tablenum");
4943 cmd->opcode = O_IP_DST_LOOKUP;
4944 cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
4945 i = match_token(rule_options, *av);
4946 for (j = 0; lookup_key[j] >= 0 ; j++) {
4947 if (i == lookup_key[j])
4950 if (lookup_key[j] <= 0)
4951 errx(EX_USAGE, "format: cannot lookup on %s", *av);
4952 __PAST_END(c->d, 1) = j; // i converted to option
4955 if ((j = pack_table(tstate, *av)) == 0)
4956 errx(EX_DATAERR, "Invalid table name: %s", *av);
4963 NEED1("missing table name");
4964 if (strncmp(*av, "table(", 6) != 0)
4966 "enclose table name into \"table()\"");
4967 fill_table(cmd, *av, O_IP_FLOW_LOOKUP, tstate);
4971 case TOK_SKIPACTION:
4973 errx(EX_USAGE, "only one defer-action "
4976 fill_cmd(cmd, O_SKIP_ACTION, 0, 0);
4980 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
4982 if (F_LEN(cmd) > 0) { /* prepare to advance */
4984 cmd = next_cmd(cmd, &cblen);
4990 if (!have_state && have_skipcmd)
4991 warnx("Rule contains \"defer-immediate-action\" "
4992 "and doesn't contain any state-related options.");
4995 * Now copy stuff into the rule.
4996 * If we have a keep-state option, the first instruction
4997 * must be a PROBE_STATE (which is generated here).
4998 * If we have a LOG option, it was stored as the first command,
4999 * and now must be moved to the top of the action part.
5001 dst = (ipfw_insn *)rule->cmd;
5004 * First thing to write into the command stream is the match probability.
5006 if (match_prob != 1) { /* 1 means always match */
5007 dst->opcode = O_PROB;
5009 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
5014 * generate O_PROBE_STATE if necessary
5016 if (have_state && have_state->opcode != O_CHECK_STATE && !have_rstate) {
5017 fill_cmd(dst, O_PROBE_STATE, 0, have_state->arg1);
5018 dst = next_cmd(dst, &rblen);
5022 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG,
5025 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
5029 switch (src->opcode) {
5038 bcopy(src, dst, i * sizeof(uint32_t));
5044 * put back the have_state command as last opcode
5046 if (have_state && have_state->opcode != O_CHECK_STATE) {
5047 i = F_LEN(have_state);
5049 bcopy(have_state, dst, i * sizeof(uint32_t));
5054 * put back the have_skipcmd command as very last opcode
5057 i = F_LEN(have_skipcmd);
5059 bcopy(have_skipcmd, dst, i * sizeof(uint32_t));
5064 * start action section
5066 rule->act_ofs = dst - rule->cmd;
5068 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
5070 i = F_LEN(have_log);
5072 bcopy(have_log, dst, i * sizeof(uint32_t));
5076 i = F_LEN(have_altq);
5078 bcopy(have_altq, dst, i * sizeof(uint32_t));
5082 i = F_LEN(have_tag);
5084 bcopy(have_tag, dst, i * sizeof(uint32_t));
5089 * copy all other actions
5091 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
5094 bcopy(src, dst, i * sizeof(uint32_t));
5098 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
5099 *rbufsize = (char *)dst - (char *)rule;
5103 compare_ntlv(const void *_a, const void *_b)
5105 ipfw_obj_ntlv *a, *b;
5107 a = (ipfw_obj_ntlv *)_a;
5108 b = (ipfw_obj_ntlv *)_b;
5110 if (a->set < b->set)
5112 else if (a->set > b->set)
5115 if (a->idx < b->idx)
5117 else if (a->idx > b->idx)
5120 if (a->head.type < b->head.type)
5122 else if (a->head.type > b->head.type)
5129 * Provide kernel with sorted list of referenced objects
5132 object_sort_ctlv(ipfw_obj_ctlv *ctlv)
5135 qsort(ctlv + 1, ctlv->count, ctlv->objsize, compare_ntlv);
5143 compare_object_kntlv(const void *k, const void *v)
5145 ipfw_obj_ntlv *ntlv;
5146 struct object_kt key;
5148 key = *((struct object_kt *)k);
5149 ntlv = (ipfw_obj_ntlv *)v;
5151 if (key.uidx < ntlv->idx)
5153 else if (key.uidx > ntlv->idx)
5156 if (key.type < ntlv->head.type)
5158 else if (key.type > ntlv->head.type)
5165 * Finds object name in @ctlv by @idx and @type.
5166 * Uses the following facts:
5167 * 1) All TLVs are the same size
5168 * 2) Kernel implementation provides already sorted list.
5170 * Returns table name or NULL.
5173 object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx, uint16_t type)
5175 ipfw_obj_ntlv *ntlv;
5176 struct object_kt key;
5181 ntlv = bsearch(&key, (ctlv + 1), ctlv->count, ctlv->objsize,
5182 compare_object_kntlv);
5185 return (ntlv->name);
5191 table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx)
5194 return (object_search_ctlv(ctlv, idx, IPFW_TLV_TBL_NAME));
5198 * Adds one or more rules to ipfw chain.
5203 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
5204 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ] (*2) (*3)
5209 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
5210 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ]
5213 * Rules in reply are modified to store their actual ruleset number.
5215 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
5216 * according to their idx field and there has to be no duplicates.
5217 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
5218 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
5221 ipfw_add(char *av[])
5223 uint32_t rulebuf[1024];
5224 int rbufsize, default_off, tlen, rlen;
5227 struct ip_fw_rule *rule;
5229 ip_fw3_opheader *op3;
5230 ipfw_obj_ctlv *ctlv, *tstate;
5232 rbufsize = sizeof(rulebuf);
5233 memset(rulebuf, 0, rbufsize);
5234 memset(&ts, 0, sizeof(ts));
5236 /* Optimize case with no tables */
5237 default_off = sizeof(ipfw_obj_ctlv) + sizeof(ip_fw3_opheader);
5238 op3 = (ip_fw3_opheader *)rulebuf;
5239 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5240 rule = (struct ip_fw_rule *)(ctlv + 1);
5241 rbufsize -= default_off;
5243 compile_rule(av, (uint32_t *)rule, &rbufsize, &ts);
5244 /* Align rule size to u64 boundary */
5245 rlen = roundup2(rbufsize, sizeof(uint64_t));
5250 if (ts.count != 0) {
5251 /* Some tables. We have to alloc more data */
5252 tlen = ts.count * sizeof(ipfw_obj_ntlv);
5253 sz = default_off + sizeof(ipfw_obj_ctlv) + tlen + rlen;
5255 if ((tbuf = calloc(1, sz)) == NULL)
5256 err(EX_UNAVAILABLE, "malloc() failed for IP_FW_ADD");
5257 op3 = (ip_fw3_opheader *)tbuf;
5259 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5260 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
5261 ctlv->head.length = sizeof(ipfw_obj_ctlv) + tlen;
5262 ctlv->count = ts.count;
5263 ctlv->objsize = sizeof(ipfw_obj_ntlv);
5264 memcpy(ctlv + 1, ts.idx, tlen);
5265 object_sort_ctlv(ctlv);
5268 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
5269 ctlv->head.type = IPFW_TLV_RULE_LIST;
5270 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5272 memcpy(ctlv + 1, rule, rbufsize);
5274 /* Simply add header */
5275 sz = rlen + default_off;
5276 memset(ctlv, 0, sizeof(*ctlv));
5277 ctlv->head.type = IPFW_TLV_RULE_LIST;
5278 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5282 if (do_get3(IP_FW_XADD, op3, &sz) != 0)
5283 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_XADD");
5286 struct format_opts sfo;
5288 memset(&sfo, 0, sizeof(sfo));
5289 sfo.tstate = tstate;
5290 sfo.set_mask = (uint32_t)(-1);
5291 bp_alloc(&bp, 4096);
5292 show_static_rule(&co, &sfo, &bp, rule, NULL);
5293 printf("%s", bp.buf);
5305 * clear the counters or the log counters.
5306 * optname has the following values:
5307 * 0 (zero both counters and logging)
5308 * 1 (zero logging only)
5311 ipfw_zero(int ac, char *av[], int optname)
5315 char const *name = optname ? "RESETLOG" : "ZERO";
5319 optname = optname ? IP_FW_XRESETLOG : IP_FW_XZERO;
5323 /* clear all entries */
5324 memset(&rt, 0, sizeof(rt));
5325 rt.flags = IPFW_RCFLAG_ALL;
5326 if (do_range_cmd(optname, &rt) < 0)
5327 err(EX_UNAVAILABLE, "setsockopt(IP_FW_X%s)", name);
5329 printf("%s.\n", optname == IP_FW_XZERO ?
5330 "Accounting cleared":"Logging counts reset");
5337 if (isdigit(**av)) {
5338 arg = strtonum(*av, 0, 0xffff, &errstr);
5341 "invalid rule number %s\n", *av);
5342 memset(&rt, 0, sizeof(rt));
5343 rt.start_rule = arg;
5345 rt.flags |= IPFW_RCFLAG_RANGE;
5346 if (co.use_set != 0) {
5347 rt.set = co.use_set - 1;
5348 rt.flags |= IPFW_RCFLAG_SET;
5350 if (do_range_cmd(optname, &rt) != 0) {
5351 warn("rule %u: setsockopt(IP_FW_X%s)",
5353 failed = EX_UNAVAILABLE;
5354 } else if (rt.new_set == 0) {
5355 printf("Entry %d not found\n", arg);
5356 failed = EX_UNAVAILABLE;
5357 } else if (!co.do_quiet)
5358 printf("Entry %d %s.\n", arg,
5359 optname == IP_FW_XZERO ?
5360 "cleared" : "logging count reset");
5362 errx(EX_USAGE, "invalid rule number ``%s''", *av);
5366 if (failed != EX_OK)
5371 ipfw_flush(int force)
5375 if (!force && !co.do_quiet) { /* need to ask user */
5378 printf("Are you sure? [yn] ");
5381 c = toupper(getc(stdin));
5382 while (c != '\n' && getc(stdin) != '\n')
5384 return; /* and do not flush */
5385 } while (c != 'Y' && c != 'N');
5387 if (c == 'N') /* user said no */
5394 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
5395 memset(&rt, 0, sizeof(rt));
5396 if (co.use_set != 0) {
5397 rt.set = co.use_set - 1;
5398 rt.flags = IPFW_RCFLAG_SET;
5400 rt.flags = IPFW_RCFLAG_ALL;
5401 if (do_range_cmd(IP_FW_XDEL, &rt) != 0)
5402 err(EX_UNAVAILABLE, "setsockopt(IP_FW_XDEL)");
5404 printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
5407 static struct _s_x intcmds[] = {
5408 { "talist", TOK_TALIST },
5409 { "iflist", TOK_IFLIST },
5410 { "olist", TOK_OLIST },
5411 { "vlist", TOK_VLIST },
5415 static struct _s_x otypes[] = {
5416 { "EACTION", IPFW_TLV_EACTION },
5417 { "DYNSTATE", IPFW_TLV_STATE_NAME },
5422 lookup_eaction_name(ipfw_obj_ntlv *ntlv, int cnt, uint16_t type)
5428 for (i = 0; i < cnt; i++) {
5429 if (ntlv[i].head.type != IPFW_TLV_EACTION)
5431 if (IPFW_TLV_EACTION_NAME(ntlv[i].idx) != type)
5433 name = ntlv[i].name;
5440 ipfw_list_objects(int ac, char *av[])
5442 ipfw_obj_lheader req, *olh;
5443 ipfw_obj_ntlv *ntlv;
5448 memset(&req, 0, sizeof(req));
5450 if (do_get3(IP_FW_DUMP_SRVOBJECTS, &req.opheader, &sz) != 0)
5451 if (errno != ENOMEM)
5455 if ((olh = calloc(1, sz)) == NULL)
5459 if (do_get3(IP_FW_DUMP_SRVOBJECTS, &olh->opheader, &sz) != 0) {
5465 printf("Objects list:\n");
5467 printf("There are no objects\n");
5468 ntlv = (ipfw_obj_ntlv *)(olh + 1);
5469 for (i = 0; i < olh->count; i++) {
5470 name = match_value(otypes, ntlv->head.type);
5472 name = lookup_eaction_name(
5473 (ipfw_obj_ntlv *)(olh + 1), olh->count,
5476 printf(" kidx: %4d\ttype: %10d\tname: %s\n",
5477 ntlv->idx, ntlv->head.type, ntlv->name);
5479 printf(" kidx: %4d\ttype: %10s\tname: %s\n",
5480 ntlv->idx, name, ntlv->name);
5487 ipfw_internal_handler(int ac, char *av[])
5492 NEED1("internal cmd required");
5494 if ((tcmd = match_token(intcmds, *av)) == -1)
5495 errx(EX_USAGE, "invalid internal sub-cmd: %s", *av);
5499 ipfw_list_tifaces();
5502 ipfw_list_ta(ac, av);
5505 ipfw_list_objects(ac, av);
5508 ipfw_list_values(ac, av);
5514 ipfw_get_tracked_ifaces(ipfw_obj_lheader **polh)
5516 ipfw_obj_lheader req, *olh;
5519 memset(&req, 0, sizeof(req));
5522 if (do_get3(IP_FW_XIFLIST, &req.opheader, &sz) != 0) {
5523 if (errno != ENOMEM)
5528 if ((olh = calloc(1, sz)) == NULL)
5532 if (do_get3(IP_FW_XIFLIST, &olh->opheader, &sz) != 0) {
5542 ifinfo_cmp(const void *a, const void *b)
5544 ipfw_iface_info *ia, *ib;
5546 ia = (ipfw_iface_info *)a;
5547 ib = (ipfw_iface_info *)b;
5549 return (stringnum_cmp(ia->ifname, ib->ifname));
5553 * Retrieves table list from kernel,
5554 * optionally sorts it and calls requested function for each table.
5555 * Returns 0 on success.
5560 ipfw_obj_lheader *olh;
5561 ipfw_iface_info *info;
5564 if ((error = ipfw_get_tracked_ifaces(&olh)) != 0)
5565 err(EX_OSERR, "Unable to request ipfw tracked interface list");
5568 qsort(olh + 1, olh->count, olh->objsize, ifinfo_cmp);
5570 info = (ipfw_iface_info *)(olh + 1);
5571 for (i = 0; i < olh->count; i++) {
5572 if (info->flags & IPFW_IFFLAG_RESOLVED)
5573 printf("%s ifindex: %d refcount: %u changes: %u\n",
5574 info->ifname, info->ifindex, info->refcnt,
5577 printf("%s ifindex: unresolved refcount: %u changes: %u\n",
5578 info->ifname, info->refcnt, info->gencnt);
5579 info = (ipfw_iface_info *)((caddr_t)info + olh->objsize);