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 { "tcpmss", TOK_TCPMSS },
342 { "tcpoptions", TOK_TCPOPTS },
343 { "tcpopts", TOK_TCPOPTS },
344 { "tcpseq", TOK_TCPSEQ },
345 { "tcpack", TOK_TCPACK },
346 { "tcpwin", TOK_TCPWIN },
347 { "icmptype", TOK_ICMPTYPES },
348 { "icmptypes", TOK_ICMPTYPES },
349 { "dst-ip", TOK_DSTIP },
350 { "src-ip", TOK_SRCIP },
351 { "dst-port", TOK_DSTPORT },
352 { "src-port", TOK_SRCPORT },
353 { "proto", TOK_PROTO },
356 { "mac-type", TOK_MACTYPE },
357 { "verrevpath", TOK_VERREVPATH },
358 { "versrcreach", TOK_VERSRCREACH },
359 { "antispoof", TOK_ANTISPOOF },
360 { "ipsec", TOK_IPSEC },
361 { "icmp6type", TOK_ICMP6TYPES },
362 { "icmp6types", TOK_ICMP6TYPES },
363 { "ext6hdr", TOK_EXT6HDR},
364 { "flow-id", TOK_FLOWID},
369 { "dst-ipv6", TOK_DSTIP6},
370 { "dst-ip6", TOK_DSTIP6},
371 { "src-ipv6", TOK_SRCIP6},
372 { "src-ip6", TOK_SRCIP6},
373 { "lookup", TOK_LOOKUP},
375 { "defer-action", TOK_SKIPACTION },
376 { "defer-immediate-action", TOK_SKIPACTION },
377 { "//", TOK_COMMENT },
379 { "not", TOK_NOT }, /* pseudo option */
380 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
381 { "or", TOK_OR }, /* pseudo option */
382 { "|", /* escape */ TOK_OR }, /* pseudo option */
383 { "{", TOK_STARTBRACE }, /* pseudo option */
384 { "(", TOK_STARTBRACE }, /* pseudo option */
385 { "}", TOK_ENDBRACE }, /* pseudo option */
386 { ")", TOK_ENDBRACE }, /* pseudo option */
387 { NULL, 0 } /* terminator */
390 void bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg);
391 static int ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
392 ipfw_cfg_lheader **pcfg, size_t *psize);
393 static int ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
394 ipfw_cfg_lheader *cfg, size_t sz, int ac, char **av);
395 static void ipfw_list_tifaces(void);
398 static uint16_t pack_object(struct tidx *tstate, char *name, int otype);
399 static uint16_t pack_table(struct tidx *tstate, char *name);
401 static char *table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx);
402 static void object_sort_ctlv(ipfw_obj_ctlv *ctlv);
403 static char *object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx,
407 * Simple string buffer API.
408 * Used to simplify buffer passing between function and for
409 * transparent overrun handling.
413 * Allocates new buffer of given size @sz.
415 * Returns 0 on success.
418 bp_alloc(struct buf_pr *b, size_t size)
420 memset(b, 0, sizeof(struct buf_pr));
422 if ((b->buf = calloc(1, size)) == NULL)
433 bp_free(struct buf_pr *b)
440 * Flushes buffer so new writer start from beginning.
443 bp_flush(struct buf_pr *b)
452 * Print message specified by @format and args.
453 * Automatically manage buffer space and transparently handle
456 * Returns number of bytes that should have been printed.
459 bprintf(struct buf_pr *b, char *format, ...)
464 va_start(args, format);
466 i = vsnprintf(b->ptr, b->avail, format, args);
469 if (i > b->avail || i < 0) {
470 /* Overflow or print error */
483 * Special values printer for tablearg-aware opcodes.
486 bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg)
490 bprintf(bp, "%s", str);
491 if (arg == IP_FW_TARG)
492 bprintf(bp, "tablearg");
494 bprintf(bp, "%u", arg);
498 * Helper routine to print a possibly unaligned uint64_t on
499 * various platform. If width > 0, print the value with
500 * the desired width, followed by a space;
501 * otherwise, return the required width.
504 pr_u64(struct buf_pr *b, uint64_t *pd, int width)
507 #define U64_FMT "I64"
509 #define U64_FMT "llu"
512 unsigned long long d;
514 bcopy (pd, &u, sizeof(u));
517 bprintf(b, "%*" U64_FMT " ", width, d) :
518 snprintf(NULL, 0, "%" U64_FMT, d) ;
524 safe_calloc(size_t number, size_t size)
526 void *ret = calloc(number, size);
529 err(EX_OSERR, "calloc");
534 safe_realloc(void *ptr, size_t size)
536 void *ret = realloc(ptr, size);
539 err(EX_OSERR, "realloc");
544 * Compare things like interface or table names.
547 stringnum_cmp(const char *a, const char *b)
559 return (strcmp(a, b));
564 * conditionally runs the command.
565 * Selected options or negative -> getsockopt
568 do_cmd(int optname, void *optval, uintptr_t optlen)
575 if (ipfw_socket == -1)
576 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
578 err(EX_UNAVAILABLE, "socket");
580 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
581 optname == IP_FW_ADD || optname == IP_FW3 ||
582 optname == IP_FW_NAT_GET_CONFIG ||
584 optname == IP_FW_NAT_GET_LOG) {
587 i = getsockopt(ipfw_socket, IPPROTO_IP, optname, optval,
588 (socklen_t *)optlen);
590 i = setsockopt(ipfw_socket, IPPROTO_IP, optname, optval, optlen);
596 * do_set3 - pass ipfw control cmd to kernel
597 * @optname: option name
598 * @optval: pointer to option data
599 * @optlen: option length
601 * Assumes op3 header is already embedded.
602 * Calls setsockopt() with IP_FW3 as kernel-visible opcode.
603 * Returns 0 on success or errno otherwise.
606 do_set3(int optname, ip_fw3_opheader *op3, size_t optlen)
612 if (ipfw_socket == -1)
613 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
615 err(EX_UNAVAILABLE, "socket");
617 op3->opcode = optname;
619 return (setsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, optlen));
623 * do_get3 - pass ipfw control cmd to kernel
624 * @optname: option name
625 * @optval: pointer to option data
626 * @optlen: pointer to option length
628 * Assumes op3 header is already embedded.
629 * Calls getsockopt() with IP_FW3 as kernel-visible opcode.
630 * Returns 0 on success or errno otherwise.
633 do_get3(int optname, ip_fw3_opheader *op3, size_t *optlen)
641 if (ipfw_socket == -1)
642 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
644 err(EX_UNAVAILABLE, "socket");
646 op3->opcode = optname;
649 error = getsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, &len);
656 * match_token takes a table and a string, returns the value associated
657 * with the string (-1 in case of failure).
660 match_token(struct _s_x *table, const char *string)
663 uint i = strlen(string);
665 for (pt = table ; i && pt->s != NULL ; pt++)
666 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
672 * match_token_relaxed takes a table and a string, returns the value associated
673 * with the string for the best match.
676 * value from @table for matched records
677 * -1 for non-matched records
678 * -2 if more than one records match @string.
681 match_token_relaxed(struct _s_x *table, const char *string)
689 for (pt = table ; i != 0 && pt->s != NULL ; pt++) {
690 if (strncmp(pt->s, string, i) != 0)
699 return (c > 0 ? -2: -1);
703 get_token(struct _s_x *table, const char *string, const char *errbase)
707 if ((tcmd = match_token_relaxed(table, string)) < 0)
708 errx(EX_USAGE, "%s %s %s",
709 (tcmd == 0) ? "invalid" : "ambiguous", errbase, string);
715 * match_value takes a table and a value, returns the string associated
716 * with the value (NULL in case of failure).
719 match_value(struct _s_x *p, int value)
721 for (; p->s != NULL; p++)
728 concat_tokens(char *buf, size_t bufsize, struct _s_x *table, char *delimiter)
734 for (sz = 0, pt = table ; pt->s != NULL; pt++) {
735 l = snprintf(buf + sz, bufsize - sz, "%s%s",
736 (sz == 0) ? "" : delimiter, pt->s);
747 * helper function to process a set of flags and set bits in the
751 fill_flags(struct _s_x *flags, char *p, char **e, uint32_t *set,
754 char *q; /* points to the separator */
756 uint32_t *which; /* mask we are working on */
767 val = match_token(flags, p);
773 *which |= (uint32_t)val;
780 print_flags_buffer(char *buf, size_t sz, struct _s_x *list, uint32_t set)
782 char const *comma = "";
785 for (i = 0; list[i].x != 0; i++) {
786 if ((set & list[i].x) == 0)
790 l = snprintf(buf, sz, "%s%s", comma, list[i].s);
800 * _substrcmp takes two strings and returns 1 if they do not match,
801 * and 0 if they match exactly or the first string is a sub-string
802 * of the second. A warning is printed to stderr in the case that the
803 * first string is a sub-string of the second.
805 * This function will be removed in the future through the usual
806 * deprecation process.
809 _substrcmp(const char *str1, const char* str2)
812 if (strncmp(str1, str2, strlen(str1)) != 0)
815 if (strlen(str1) != strlen(str2))
816 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
822 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
823 * and 0 if they match exactly or the second string is a sub-string
824 * of the first. A warning is printed to stderr in the case that the
825 * first string does not match the third.
827 * This function exists to warn about the bizarre construction
828 * strncmp(str, "by", 2) which is used to allow people to use a shortcut
829 * for "bytes". The problem is that in addition to accepting "by",
830 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
831 * other string beginning with "by".
833 * This function will be removed in the future through the usual
834 * deprecation process.
837 _substrcmp2(const char *str1, const char* str2, const char* str3)
840 if (strncmp(str1, str2, strlen(str2)) != 0)
843 if (strcmp(str1, str3) != 0)
844 warnx("DEPRECATED: '%s' matched '%s'",
850 * prints one port, symbolic or numeric
853 print_port(struct buf_pr *bp, int proto, uint16_t port)
856 if (proto == IPPROTO_ETHERTYPE) {
859 if (co.do_resolv && (s = match_value(ether_types, port)) )
860 bprintf(bp, "%s", s);
862 bprintf(bp, "0x%04x", port);
864 struct servent *se = NULL;
866 struct protoent *pe = getprotobynumber(proto);
868 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
871 bprintf(bp, "%s", se->s_name);
873 bprintf(bp, "%d", port);
877 static struct _s_x _port_name[] = {
878 {"dst-port", O_IP_DSTPORT},
879 {"src-port", O_IP_SRCPORT},
883 {"mac-type", O_MAC_TYPE},
884 {"tcpdatalen", O_TCPDATALEN},
885 {"tcpmss", O_TCPMSS},
886 {"tcpwin", O_TCPWIN},
887 {"tagged", O_TAGGED},
892 * Print the values in a list 16-bit items of the types above.
893 * XXX todo: add support for mask.
896 print_newports(struct buf_pr *bp, ipfw_insn_u16 *cmd, int proto, int opcode)
898 uint16_t *p = cmd->ports;
903 sep = match_value(_port_name, opcode);
906 bprintf(bp, " %s", sep);
909 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
910 bprintf(bp, "%s", sep);
911 print_port(bp, proto, p[0]);
914 print_port(bp, proto, p[1]);
921 * Like strtol, but also translates service names into port numbers
922 * for some protocols.
924 * proto == -1 disables the protocol check;
925 * proto == IPPROTO_ETHERTYPE looks up an internal table
926 * proto == <some value in /etc/protocols> matches the values there.
927 * Returns *end == s in case the parameter is not found.
930 strtoport(char *s, char **end, int base, int proto)
936 *end = s; /* default - not found */
938 return 0; /* not found */
941 return strtol(s, end, base);
944 * find separator. '\\' escapes the next char.
946 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\' ||
947 *s1 == '_' || *s1 == '.') ; s1++)
948 if (*s1 == '\\' && s1[1] != '\0')
951 buf = safe_calloc(s1 - s + 1, 1);
954 * copy into a buffer skipping backslashes
956 for (p = s, i = 0; p != s1 ; p++)
961 if (proto == IPPROTO_ETHERTYPE) {
962 i = match_token(ether_types, buf);
964 if (i != -1) { /* found */
969 struct protoent *pe = NULL;
973 pe = getprotobynumber(proto);
975 se = getservbyname(buf, pe ? pe->p_name : NULL);
979 return ntohs(se->s_port);
982 return 0; /* not found */
986 * Fill the body of the command with the list of port ranges.
989 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
991 uint16_t a, b, *p = cmd->ports;
996 a = strtoport(av, &s, 0, proto);
997 if (s == av) /* empty or invalid argument */
1000 CHECK_LENGTH(cblen, i + 2);
1003 case '-': /* a range */
1005 b = strtoport(av, &s, 0, proto);
1006 /* Reject expressions like '1-abc' or '1-2-3'. */
1007 if (s == av || (*s != ',' && *s != '\0'))
1012 case ',': /* comma separated list */
1017 warnx("port list: invalid separator <%c> in <%s>",
1027 if (i + 1 > F_LEN_MASK)
1028 errx(EX_DATAERR, "too many ports/ranges\n");
1029 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
1035 * Fill the body of the command with the list of DiffServ codepoints.
1038 fill_dscp(ipfw_insn *cmd, char *av, int cblen)
1040 uint32_t *low, *high;
1044 cmd->opcode = O_DSCP;
1045 cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
1049 low = (uint32_t *)(cmd + 1);
1062 if ((code = match_token(f_ipdscp, s)) == -1)
1063 errx(EX_DATAERR, "Unknown DSCP code");
1065 code = strtoul(s, NULL, 10);
1066 if (code < 0 || code > 63)
1067 errx(EX_DATAERR, "Invalid DSCP value");
1071 *high |= 1 << (code - 32);
1079 static struct _s_x icmpcodes[] = {
1080 { "net", ICMP_UNREACH_NET },
1081 { "host", ICMP_UNREACH_HOST },
1082 { "protocol", ICMP_UNREACH_PROTOCOL },
1083 { "port", ICMP_UNREACH_PORT },
1084 { "needfrag", ICMP_UNREACH_NEEDFRAG },
1085 { "srcfail", ICMP_UNREACH_SRCFAIL },
1086 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
1087 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
1088 { "isolated", ICMP_UNREACH_ISOLATED },
1089 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
1090 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
1091 { "tosnet", ICMP_UNREACH_TOSNET },
1092 { "toshost", ICMP_UNREACH_TOSHOST },
1093 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
1094 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
1095 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
1100 fill_reject_code(u_short *codep, char *str)
1105 val = strtoul(str, &s, 0);
1106 if (s == str || *s != '\0' || val >= 0x100)
1107 val = match_token(icmpcodes, str);
1109 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
1115 print_reject_code(struct buf_pr *bp, uint16_t code)
1119 if ((s = match_value(icmpcodes, code)) != NULL)
1120 bprintf(bp, "unreach %s", s);
1122 bprintf(bp, "unreach %u", code);
1126 * Returns the number of bits set (from left) in a contiguous bitmask,
1127 * or -1 if the mask is not contiguous.
1128 * XXX this needs a proper fix.
1129 * This effectively works on masks in big-endian (network) format.
1130 * when compiled on little endian architectures.
1132 * First bit is bit 7 of the first byte -- note, for MAC addresses,
1133 * the first bit on the wire is bit 0 of the first byte.
1134 * len is the max length in bits.
1137 contigmask(uint8_t *p, int len)
1141 for (i=0; i<len ; i++)
1142 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
1144 for (n=i+1; n < len; n++)
1145 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
1146 return -1; /* mask not contiguous */
1151 * print flags set/clear in the two bitmasks passed as parameters.
1152 * There is a specialized check for f_tcpflags.
1155 print_flags(struct buf_pr *bp, char const *name, ipfw_insn *cmd,
1158 char const *comma = "";
1160 uint8_t set = cmd->arg1 & 0xff;
1161 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
1163 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
1164 bprintf(bp, " setup");
1168 bprintf(bp, " %s ", name);
1169 for (i=0; list[i].x != 0; i++) {
1170 if (set & list[i].x) {
1172 bprintf(bp, "%s%s", comma, list[i].s);
1175 if (clear & list[i].x) {
1176 clear &= ~list[i].x;
1177 bprintf(bp, "%s!%s", comma, list[i].s);
1185 * Print the ip address contained in a command.
1188 print_ip(struct buf_pr *bp, const struct format_opts *fo, ipfw_insn_ip *cmd)
1190 struct hostent *he = NULL;
1192 uint32_t len = F_LEN((ipfw_insn *)cmd);
1193 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
1197 if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
1199 const char *arg = "<invalid>";
1201 if (d < sizeof(lookup_key)/sizeof(lookup_key[0]))
1202 arg = match_value(rule_options, lookup_key[d]);
1203 t = table_search_ctlv(fo->tstate, ((ipfw_insn *)cmd)->arg1);
1204 bprintf(bp, "lookup %s %s", arg, t);
1207 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
1211 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
1212 cmd->o.opcode == O_IP_DST_LOOKUP) {
1213 t = table_search_ctlv(fo->tstate, ((ipfw_insn *)cmd)->arg1);
1214 bprintf(bp, "table(%s", t);
1215 if (len == F_INSN_SIZE(ipfw_insn_u32))
1216 bprintf(bp, ",%u", *a);
1220 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
1221 uint32_t x, *map = (uint32_t *)&(cmd->mask);
1225 x = cmd->o.arg1 - 1;
1227 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1228 bprintf(bp, "%s/%d", inet_ntoa(cmd->addr),
1229 contigmask((uint8_t *)&x, 32));
1230 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1231 x &= 0xff; /* base */
1233 * Print bits and ranges.
1234 * Locate first bit set (i), then locate first bit unset (j).
1235 * If we have 3+ consecutive bits set, then print them as a
1236 * range, otherwise only print the initial bit and rescan.
1238 for (i=0; i < cmd->o.arg1; i++)
1239 if (map[i/32] & (1<<(i & 31))) {
1240 for (j=i+1; j < cmd->o.arg1; j++)
1241 if (!(map[ j/32] & (1<<(j & 31))))
1243 bprintf(bp, "%c%d", comma, i+x);
1244 if (j>i+2) { /* range has at least 3 elements */
1245 bprintf(bp, "-%d", j-1+x);
1254 * len == 2 indicates a single IP, whereas lists of 1 or more
1255 * addr/mask pairs have len = (2n+1). We convert len to n so we
1256 * use that to count the number of entries.
1258 for (len = len / 2; len > 0; len--, a += 2) {
1259 int mb = /* mask length */
1260 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1261 32 : contigmask((uint8_t *)&(a[1]), 32);
1262 if (mb == 32 && co.do_resolv)
1263 he = gethostbyaddr((char *)&(a[0]), sizeof(in_addr_t),
1265 if (he != NULL) /* resolved to name */
1266 bprintf(bp, "%s", he->h_name);
1267 else if (mb == 0) /* any */
1269 else { /* numeric IP followed by some kind of mask */
1270 ia = (struct in_addr *)&a[0];
1271 bprintf(bp, "%s", inet_ntoa(*ia));
1273 ia = (struct in_addr *)&a[1];
1274 bprintf(bp, ":%s", inet_ntoa(*ia));
1276 bprintf(bp, "/%d", mb);
1284 * prints a MAC address/mask pair
1287 format_mac(struct buf_pr *bp, uint8_t *addr, uint8_t *mask)
1289 int l = contigmask(mask, 48);
1292 bprintf(bp, " any");
1294 bprintf(bp, " %02x:%02x:%02x:%02x:%02x:%02x",
1295 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1297 bprintf(bp, "&%02x:%02x:%02x:%02x:%02x:%02x",
1298 mask[0], mask[1], mask[2],
1299 mask[3], mask[4], mask[5]);
1301 bprintf(bp, "/%d", l);
1306 print_mac(struct buf_pr *bp, ipfw_insn_mac *mac)
1309 bprintf(bp, " MAC");
1310 format_mac(bp, mac->addr, mac->mask);
1311 format_mac(bp, mac->addr + 6, mac->mask + 6);
1315 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1324 type = strtoul(av, &av, 0);
1326 if (*av != ',' && *av != '\0')
1327 errx(EX_DATAERR, "invalid ICMP type");
1330 errx(EX_DATAERR, "ICMP type out of range");
1332 cmd->d[0] |= 1 << type;
1334 cmd->o.opcode = O_ICMPTYPE;
1335 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1339 print_icmptypes(struct buf_pr *bp, ipfw_insn_u32 *cmd)
1344 bprintf(bp, " icmptypes");
1345 for (i = 0; i < 32; i++) {
1346 if ( (cmd->d[0] & (1 << (i))) == 0)
1348 bprintf(bp, "%c%d", sep, i);
1354 print_dscp(struct buf_pr *bp, ipfw_insn_u32 *cmd)
1361 bprintf(bp, " dscp");
1364 if (*v & (1 << i)) {
1365 if ((code = match_value(f_ipdscp, i)) != NULL)
1366 bprintf(bp, "%c%s", sep, code);
1368 bprintf(bp, "%c%d", sep, i);
1372 if ((++i % 32) == 0)
1377 #define insntod(cmd, type) ((ipfw_insn_ ## type *)(cmd))
1379 struct ip_fw_rule *rule;
1380 const ipfw_insn *eaction;
1383 #define HAVE_PROTO 0x0001
1384 #define HAVE_SRCIP 0x0002
1385 #define HAVE_DSTIP 0x0004
1386 #define HAVE_PROBE_STATE 0x0008
1392 init_show_state(struct show_state *state, struct ip_fw_rule *rule)
1395 state->printed = calloc(rule->cmd_len, sizeof(uint8_t));
1396 if (state->printed == NULL)
1399 state->eaction = NULL;
1402 state->or_block = 0;
1407 free_show_state(struct show_state *state)
1410 free(state->printed);
1414 is_printed_opcode(struct show_state *state, const ipfw_insn *cmd)
1417 return (state->printed[cmd - state->rule->cmd]);
1421 mark_printed(struct show_state *state, const ipfw_insn *cmd)
1424 state->printed[cmd - state->rule->cmd] = 1;
1428 print_limit_mask(struct buf_pr *bp, const ipfw_insn_limit *limit)
1430 struct _s_x *p = limit_masks;
1431 char const *comma = " ";
1434 for (x = limit->limit_mask; p->x != 0; p++) {
1435 if ((x & p->x) == p->x) {
1437 bprintf(bp, "%s%s", comma, p->s);
1441 bprint_uint_arg(bp, " ", limit->conn_limit);
1445 print_instruction(struct buf_pr *bp, const struct format_opts *fo,
1446 struct show_state *state, ipfw_insn *cmd)
1448 struct protoent *pe;
1454 if (is_printed_opcode(state, cmd))
1456 if ((cmd->len & F_OR) != 0 && state->or_block == 0)
1458 if (cmd->opcode != O_IN && (cmd->len & F_NOT) != 0)
1459 bprintf(bp, " not");
1461 switch (cmd->opcode) {
1463 d = 1.0 * insntod(cmd, u32)->d[0] / 0x7fffffff;
1464 bprintf(bp, "prob %f ", d);
1466 case O_PROBE_STATE: /* no need to print anything here */
1467 state->flags |= HAVE_PROBE_STATE;
1470 case O_IP_SRC_LOOKUP:
1474 if (state->flags & HAVE_SRCIP)
1475 bprintf(bp, " src-ip");
1476 print_ip(bp, fo, insntod(cmd, ip));
1479 case O_IP_DST_LOOKUP:
1483 if (state->flags & HAVE_DSTIP)
1484 bprintf(bp, " dst-ip");
1485 print_ip(bp, fo, insntod(cmd, ip));
1488 case O_IP6_SRC_MASK:
1490 if (state->flags & HAVE_SRCIP)
1491 bprintf(bp, " src-ip6");
1492 print_ip6(bp, insntod(cmd, ip6));
1495 case O_IP6_DST_MASK:
1497 if (state->flags & HAVE_DSTIP)
1498 bprintf(bp, " dst-ip6");
1499 print_ip6(bp, insntod(cmd, ip6));
1502 print_flow6id(bp, insntod(cmd, u32));
1506 print_newports(bp, insntod(cmd, u16), state->proto,
1507 (state->flags & (HAVE_SRCIP | HAVE_DSTIP)) ==
1508 (HAVE_SRCIP | HAVE_DSTIP) ? cmd->opcode: 0);
1511 pe = getprotobynumber(cmd->arg1);
1512 if (state->flags & HAVE_PROTO)
1513 bprintf(bp, " proto");
1515 bprintf(bp, " %s", pe->p_name);
1517 bprintf(bp, " %u", cmd->arg1);
1518 state->proto = cmd->arg1;
1521 print_mac(bp, insntod(cmd, mac));
1524 print_newports(bp, insntod(cmd, u16),
1525 IPPROTO_ETHERTYPE, cmd->opcode);
1528 bprintf(bp, " frag");
1531 bprintf(bp, " fib %u", cmd->arg1);
1534 bprintf(bp, " sockarg");
1537 bprintf(bp, cmd->len & F_NOT ? " out" : " in");
1540 switch (cmd->arg1) {
1542 bprintf(bp, " diverted");
1545 bprintf(bp, " diverted-output");
1548 bprintf(bp, " diverted-loopback");
1551 bprintf(bp, " diverted-?<%u>", cmd->arg1);
1556 bprintf(bp, " layer2");
1561 if (cmd->opcode == O_XMIT)
1563 else if (cmd->opcode == O_RECV)
1565 else /* if (cmd->opcode == O_VIA) */
1567 switch (insntod(cmd, if)->name[0]) {
1569 bprintf(bp, " %s %s", s,
1570 inet_ntoa(insntod(cmd, if)->p.ip));
1573 bprintf(bp, " %s table(%s)", s,
1574 table_search_ctlv(fo->tstate,
1575 insntod(cmd, if)->p.kidx));
1578 bprintf(bp, " %s %s", s,
1579 insntod(cmd, if)->name);
1582 case O_IP_FLOW_LOOKUP:
1583 s = table_search_ctlv(fo->tstate, cmd->arg1);
1584 bprintf(bp, " flow table(%s", s);
1585 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))
1586 bprintf(bp, ",%u", insntod(cmd, u32)->d[0]);
1595 if (F_LEN(cmd) == 1) {
1596 switch (cmd->opcode) {
1616 bprintf(bp, " %s %u", s, cmd->arg1);
1618 print_newports(bp, insntod(cmd, u16), 0,
1622 bprintf(bp, " ipver %u", cmd->arg1);
1624 case O_IPPRECEDENCE:
1625 bprintf(bp, " ipprecedence %u", cmd->arg1 >> 5);
1628 print_dscp(bp, insntod(cmd, u32));
1631 print_flags(bp, "ipoptions", cmd, f_ipopts);
1634 print_flags(bp, "iptos", cmd, f_iptos);
1637 print_icmptypes(bp, insntod(cmd, u32));
1640 bprintf(bp, " established");
1643 print_flags(bp, "tcpflags", cmd, f_tcpflags);
1646 print_flags(bp, "tcpoptions", cmd, f_tcpopts);
1649 bprintf(bp, " tcpack %d",
1650 ntohl(insntod(cmd, u32)->d[0]));
1653 bprintf(bp, " tcpseq %d",
1654 ntohl(insntod(cmd, u32)->d[0]));
1657 pwd = getpwuid(insntod(cmd, u32)->d[0]);
1659 bprintf(bp, " uid %s", pwd->pw_name);
1661 bprintf(bp, " uid %u",
1662 insntod(cmd, u32)->d[0]);
1665 grp = getgrgid(insntod(cmd, u32)->d[0]);
1667 bprintf(bp, " gid %s", grp->gr_name);
1669 bprintf(bp, " gid %u",
1670 insntod(cmd, u32)->d[0]);
1673 bprintf(bp, " jail %d", insntod(cmd, u32)->d[0]);
1676 bprintf(bp, " verrevpath");
1679 bprintf(bp, " versrcreach");
1682 bprintf(bp, " antispoof");
1685 bprintf(bp, " ipsec");
1688 bprintf(bp, " // %s", (char *)(cmd + 1));
1691 if (state->flags & HAVE_PROBE_STATE)
1692 bprintf(bp, " keep-state");
1694 bprintf(bp, " record-state");
1696 object_search_ctlv(fo->tstate, cmd->arg1,
1697 IPFW_TLV_STATE_NAME));
1700 if (state->flags & HAVE_PROBE_STATE)
1701 bprintf(bp, " limit");
1703 bprintf(bp, " set-limit");
1704 print_limit_mask(bp, insntod(cmd, limit));
1706 object_search_ctlv(fo->tstate, cmd->arg1,
1707 IPFW_TLV_STATE_NAME));
1710 if (state->flags & HAVE_PROTO)
1711 bprintf(bp, " proto");
1712 bprintf(bp, " ip6");
1715 if (state->flags & HAVE_PROTO)
1716 bprintf(bp, " proto");
1717 bprintf(bp, " ip4");
1720 print_icmp6types(bp, insntod(cmd, u32));
1723 print_ext6hdr(bp, cmd);
1726 if (F_LEN(cmd) == 1)
1727 bprint_uint_arg(bp, " tagged ", cmd->arg1);
1729 print_newports(bp, insntod(cmd, u16),
1733 bprintf(bp, " defer-immediate-action");
1736 bprintf(bp, " [opcode %d len %d]", cmd->opcode,
1739 if (cmd->len & F_OR) {
1741 state->or_block = 1;
1742 } else if (state->or_block != 0) {
1744 state->or_block = 0;
1746 mark_printed(state, cmd);
1752 print_opcode(struct buf_pr *bp, struct format_opts *fo,
1753 struct show_state *state, int opcode)
1758 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
1759 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1760 /* We use zero opcode to print the rest of options */
1761 if (opcode >= 0 && cmd->opcode != opcode)
1764 * Skip O_NOP, when we printing the rest
1765 * of options, it will be handled separately.
1767 if (cmd->opcode == O_NOP && opcode != O_NOP)
1769 if (!print_instruction(bp, fo, state, cmd))
1777 print_fwd(struct buf_pr *bp, const ipfw_insn *cmd)
1779 char buf[INET6_ADDRSTRLEN + IF_NAMESIZE + 2];
1784 if (cmd->opcode == O_FORWARD_IP) {
1785 sa = insntod(cmd, sa);
1786 port = sa->sa.sin_port;
1787 if (sa->sa.sin_addr.s_addr == INADDR_ANY)
1788 bprintf(bp, "fwd tablearg");
1790 bprintf(bp, "fwd %s", inet_ntoa(sa->sa.sin_addr));
1792 sa6 = insntod(cmd, sa6);
1793 port = sa6->sa.sin6_port;
1794 bprintf(bp, "fwd ");
1795 if (getnameinfo((const struct sockaddr *)&sa6->sa,
1796 sizeof(struct sockaddr_in6), buf, sizeof(buf), NULL, 0,
1797 NI_NUMERICHOST) == 0)
1798 bprintf(bp, "%s", buf);
1801 bprintf(bp, ",%u", port);
1805 print_action_instruction(struct buf_pr *bp, const struct format_opts *fo,
1806 struct show_state *state, const ipfw_insn *cmd)
1810 if (is_printed_opcode(state, cmd))
1812 switch (cmd->opcode) {
1814 bprintf(bp, "check-state");
1816 s = object_search_ctlv(fo->tstate, cmd->arg1,
1817 IPFW_TLV_STATE_NAME);
1820 bprintf(bp, " :%s", s ? s: "any");
1823 bprintf(bp, "allow");
1826 bprintf(bp, "count");
1829 bprintf(bp, "deny");
1832 if (cmd->arg1 == ICMP_REJECT_RST)
1833 bprintf(bp, "reset");
1834 else if (cmd->arg1 == ICMP_REJECT_ABORT)
1835 bprintf(bp, "abort");
1836 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1837 bprintf(bp, "reject");
1839 print_reject_code(bp, cmd->arg1);
1842 if (cmd->arg1 == ICMP6_UNREACH_RST)
1843 bprintf(bp, "reset6");
1844 else if (cmd->arg1 == ICMP6_UNREACH_ABORT)
1845 bprintf(bp, "abort6");
1847 print_unreach6_code(bp, cmd->arg1);
1850 bprint_uint_arg(bp, "skipto ", cmd->arg1);
1853 bprint_uint_arg(bp, "pipe ", cmd->arg1);
1856 bprint_uint_arg(bp, "queue ", cmd->arg1);
1859 bprint_uint_arg(bp, "divert ", cmd->arg1);
1862 bprint_uint_arg(bp, "tee ", cmd->arg1);
1865 bprint_uint_arg(bp, "netgraph ", cmd->arg1);
1868 bprint_uint_arg(bp, "ngtee ", cmd->arg1);
1875 if (insntod(cmd, log)->max_log > 0)
1876 bprintf(bp, " log logamount %d",
1877 insntod(cmd, log)->max_log);
1879 bprintf(bp, " log");
1883 print_altq_cmd(bp, insntod(cmd, altq));
1887 bprint_uint_arg(bp, cmd->len & F_NOT ? " untag ":
1888 " tag ", cmd->arg1);
1891 if (cmd->arg1 != IP_FW_NAT44_GLOBAL)
1892 bprint_uint_arg(bp, "nat ", cmd->arg1);
1894 bprintf(bp, "nat global");
1897 if (cmd->arg1 == IP_FW_TARG)
1898 bprint_uint_arg(bp, "setfib ", cmd->arg1);
1900 bprintf(bp, "setfib %u", cmd->arg1 & 0x7FFF);
1902 case O_EXTERNAL_ACTION:
1904 * The external action can consists of two following
1905 * each other opcodes - O_EXTERNAL_ACTION and
1906 * O_EXTERNAL_INSTANCE. The first contains the ID of
1907 * name of external action. The second contains the ID
1908 * of name of external action instance.
1909 * NOTE: in case when external action has no named
1910 * instances support, the second opcode isn't needed.
1912 state->eaction = cmd;
1913 s = object_search_ctlv(fo->tstate, cmd->arg1,
1915 if (match_token(rule_eactions, s) != -1)
1916 bprintf(bp, "%s", s);
1918 bprintf(bp, "eaction %s", s);
1920 case O_EXTERNAL_INSTANCE:
1921 if (state->eaction == NULL)
1924 * XXX: we need to teach ipfw(9) to rewrite opcodes
1925 * in the user buffer on rule addition. When we add
1926 * the rule, we specify zero TLV type for
1927 * O_EXTERNAL_INSTANCE object. To show correct
1928 * rule after `ipfw add` we need to search instance
1929 * name with zero type. But when we do `ipfw show`
1930 * we calculate TLV type using IPFW_TLV_EACTION_NAME()
1933 s = object_search_ctlv(fo->tstate, cmd->arg1, 0);
1935 s = object_search_ctlv(fo->tstate,
1936 cmd->arg1, IPFW_TLV_EACTION_NAME(
1937 state->eaction->arg1));
1938 bprintf(bp, " %s", s);
1940 case O_EXTERNAL_DATA:
1941 if (state->eaction == NULL)
1944 * Currently we support data formatting only for
1945 * external data with datalen u16. For unknown data
1946 * print its size in bytes.
1948 if (cmd->len == F_INSN_SIZE(ipfw_insn))
1949 bprintf(bp, " %u", cmd->arg1);
1951 bprintf(bp, " %ubytes",
1952 cmd->len * sizeof(uint32_t));
1955 if (cmd->arg1 == IP_FW_TARG) {
1956 bprintf(bp, "setdscp tablearg");
1959 s = match_value(f_ipdscp, cmd->arg1 & 0x3F);
1961 bprintf(bp, "setdscp %s", s);
1963 bprintf(bp, "setdscp %u", cmd->arg1 & 0x3F);
1966 bprintf(bp, "reass");
1969 if (cmd->len & F_NOT)
1970 bprintf(bp, "return");
1972 bprint_uint_arg(bp, "call ", cmd->arg1);
1975 bprintf(bp, "** unrecognized action %d len %d ",
1976 cmd->opcode, cmd->len);
1978 mark_printed(state, cmd);
1985 print_action(struct buf_pr *bp, struct format_opts *fo,
1986 struct show_state *state, uint8_t opcode)
1991 for (l = state->rule->cmd_len - state->rule->act_ofs,
1992 cmd = ACTION_PTR(state->rule); l > 0;
1993 l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1994 if (cmd->opcode != opcode)
1996 if (!print_action_instruction(bp, fo, state, cmd))
2004 print_proto(struct buf_pr *bp, struct format_opts *fo,
2005 struct show_state *state)
2008 int l, proto, ip4, ip6;
2010 /* Count all O_PROTO, O_IP4, O_IP6 instructions. */
2011 proto = ip4 = ip6 = 0;
2012 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2013 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2014 switch (cmd->opcode) {
2020 if (cmd->len & F_OR)
2025 if (cmd->len & F_OR)
2032 if (proto == 0 && ip4 == 0 && ip6 == 0) {
2033 state->proto = IPPROTO_IP;
2034 state->flags |= HAVE_PROTO;
2038 /* To handle the case { ip4 or ip6 }, print opcode with F_OR first */
2041 cmd = print_opcode(bp, fo, state, ip4 > ip6 ? O_IP4: O_IP6);
2042 if (cmd != NULL && (cmd->len & F_OR))
2043 cmd = print_opcode(bp, fo, state, ip4 > ip6 ? O_IP6: O_IP4);
2044 if (cmd == NULL || (cmd->len & F_OR))
2045 for (l = proto; l > 0; l--) {
2046 cmd = print_opcode(bp, fo, state, O_PROTO);
2047 if (cmd == NULL || (cmd->len & F_OR) == 0)
2050 /* Initialize proto, it is used by print_newports() */
2051 state->flags |= HAVE_PROTO;
2052 if (state->proto == 0 && ip6 != 0)
2053 state->proto = IPPROTO_IPV6;
2057 match_opcode(int opcode, const int opcodes[], size_t nops)
2061 for (i = 0; i < nops; i++)
2062 if (opcode == opcodes[i])
2068 print_address(struct buf_pr *bp, struct format_opts *fo,
2069 struct show_state *state, const int opcodes[], size_t nops, int portop,
2073 int count, l, portcnt, pf;
2075 count = portcnt = 0;
2076 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2077 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2078 if (match_opcode(cmd->opcode, opcodes, nops))
2080 else if (cmd->opcode == portop)
2084 bprintf(bp, " any");
2085 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2086 l > 0 && count > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2087 if (!match_opcode(cmd->opcode, opcodes, nops))
2089 print_instruction(bp, fo, state, cmd);
2090 if ((cmd->len & F_OR) == 0)
2095 * If several O_IP_?PORT opcodes specified, leave them to the
2099 for (l = state->rule->act_ofs, cmd = state->rule->cmd, pf = 0;
2100 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2101 if (cmd->opcode != portop) {
2102 pf = (cmd->len & F_OR);
2105 /* Print opcode iff it is not in OR block. */
2106 if (pf == 0 && (cmd->len & F_OR) == 0)
2107 print_instruction(bp, fo, state, cmd);
2111 state->flags |= flag;
2114 static const int action_opcodes[] = {
2115 O_CHECK_STATE, O_ACCEPT, O_COUNT, O_DENY, O_REJECT,
2116 O_UNREACH6, O_SKIPTO, O_PIPE, O_QUEUE, O_DIVERT, O_TEE,
2117 O_NETGRAPH, O_NGTEE, O_FORWARD_IP, O_FORWARD_IP6, O_NAT,
2118 O_SETFIB, O_SETDSCP, O_REASS, O_CALLRETURN,
2119 /* keep the following opcodes at the end of the list */
2120 O_EXTERNAL_ACTION, O_EXTERNAL_INSTANCE, O_EXTERNAL_DATA
2123 static const int modifier_opcodes[] = {
2124 O_LOG, O_ALTQ, O_TAG
2127 static const int src_opcodes[] = {
2128 O_IP_SRC, O_IP_SRC_LOOKUP, O_IP_SRC_MASK, O_IP_SRC_ME,
2129 O_IP_SRC_SET, O_IP6_SRC, O_IP6_SRC_MASK, O_IP6_SRC_ME
2132 static const int dst_opcodes[] = {
2133 O_IP_DST, O_IP_DST_LOOKUP, O_IP_DST_MASK, O_IP_DST_ME,
2134 O_IP_DST_SET, O_IP6_DST, O_IP6_DST_MASK, O_IP6_DST_ME
2138 show_static_rule(struct cmdline_opts *co, struct format_opts *fo,
2139 struct buf_pr *bp, struct ip_fw_rule *rule, struct ip_fw_bcounter *cntr)
2141 struct show_state state;
2143 static int twidth = 0;
2146 /* Print # DISABLED or skip the rule */
2147 if ((fo->set_mask & (1 << rule->set)) == 0) {
2152 bprintf(bp, "# DISABLED ");
2154 if (init_show_state(&state, rule) != 0) {
2155 warn("init_show_state() failed");
2158 bprintf(bp, "%05u ", rule->rulenum);
2160 /* Print counters if enabled */
2161 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2162 pr_u64(bp, &cntr->pcnt, fo->pcwidth);
2163 pr_u64(bp, &cntr->bcnt, fo->bcwidth);
2166 /* Print timestamp */
2167 if (co->do_time == TIMESTAMP_NUMERIC)
2168 bprintf(bp, "%10u ", cntr->timestamp);
2169 else if (co->do_time == TIMESTAMP_STRING) {
2171 time_t t = (time_t)0;
2174 strcpy(timestr, ctime(&t));
2175 *strchr(timestr, '\n') = '\0';
2176 twidth = strlen(timestr);
2178 if (cntr->timestamp > 0) {
2179 t = _long_to_time(cntr->timestamp);
2181 strcpy(timestr, ctime(&t));
2182 *strchr(timestr, '\n') = '\0';
2183 bprintf(bp, "%s ", timestr);
2185 bprintf(bp, "%*s", twidth, " ");
2189 /* Print set number */
2191 bprintf(bp, "set %d ", rule->set);
2193 /* Print the optional "match probability" */
2194 cmd = print_opcode(bp, fo, &state, O_PROB);
2195 /* Print rule action */
2196 for (i = 0; i < nitems(action_opcodes); i++) {
2197 cmd = print_action(bp, fo, &state, action_opcodes[i]);
2200 /* Handle special cases */
2201 switch (cmd->opcode) {
2204 case O_EXTERNAL_ACTION:
2205 case O_EXTERNAL_INSTANCE:
2206 /* External action can have several instructions */
2211 /* Print rule modifiers */
2212 for (i = 0; i < nitems(modifier_opcodes); i++)
2213 print_action(bp, fo, &state, modifier_opcodes[i]);
2217 if (co->comment_only != 0)
2220 if (rule->flags & IPFW_RULE_JUSTOPTS) {
2221 state.flags |= HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP;
2225 print_proto(bp, fo, &state);
2226 if (co->do_compact != 0 && (rule->flags & IPFW_RULE_NOOPT))
2230 bprintf(bp, " from");
2231 print_address(bp, fo, &state, src_opcodes, nitems(src_opcodes),
2232 O_IP_SRCPORT, HAVE_SRCIP);
2234 /* Print destination */
2236 print_address(bp, fo, &state, dst_opcodes, nitems(dst_opcodes),
2237 O_IP_DSTPORT, HAVE_DSTIP);
2240 /* Print the rest of options */
2241 while (print_opcode(bp, fo, &state, -1))
2244 /* Print comment at the end */
2245 cmd = print_opcode(bp, fo, &state, O_NOP);
2246 if (co->comment_only != 0 && cmd == NULL)
2247 bprintf(bp, " // ...");
2249 free_show_state(&state);
2253 show_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2254 struct buf_pr *bp, ipfw_dyn_rule *d)
2256 struct protoent *pe;
2259 char buf[INET6_ADDRSTRLEN];
2261 if (d->expire == 0 && d->dyn_type != O_LIMIT_PARENT)
2264 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2265 bprintf(bp, "%05d", rulenum);
2266 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2268 pr_u64(bp, &d->pcnt, fo->pcwidth);
2269 pr_u64(bp, &d->bcnt, fo->bcwidth);
2270 bprintf(bp, "(%ds)", d->expire);
2272 switch (d->dyn_type) {
2273 case O_LIMIT_PARENT:
2274 bprintf(bp, " PARENT %d", d->count);
2277 bprintf(bp, " LIMIT");
2279 case O_KEEP_STATE: /* bidir, no mask */
2280 bprintf(bp, " STATE");
2284 if ((pe = getprotobynumber(d->id.proto)) != NULL)
2285 bprintf(bp, " %s", pe->p_name);
2287 bprintf(bp, " proto %u", d->id.proto);
2289 if (d->id.addr_type == 4) {
2290 a.s_addr = htonl(d->id.src_ip);
2291 bprintf(bp, " %s %d", inet_ntoa(a), d->id.src_port);
2293 a.s_addr = htonl(d->id.dst_ip);
2294 bprintf(bp, " <-> %s %d", inet_ntoa(a), d->id.dst_port);
2295 } else if (d->id.addr_type == 6) {
2296 bprintf(bp, " %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
2297 sizeof(buf)), d->id.src_port);
2298 bprintf(bp, " <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6,
2299 buf, sizeof(buf)), d->id.dst_port);
2301 bprintf(bp, " UNKNOWN <-> UNKNOWN");
2303 bprintf(bp, " :%s", object_search_ctlv(fo->tstate,
2304 d->kidx, IPFW_TLV_STATE_NAME));
2306 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
2307 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
2309 bprintf(bp, " state 0x%08x%s", d->state,
2310 d->state ? " ": ",");
2311 if (d->state & IPFW_DYN_ORPHANED)
2312 bprintf(bp, "ORPHANED,");
2313 if ((d->state & BOTH_SYN) == BOTH_SYN)
2314 bprintf(bp, "BOTH_SYN,");
2316 if (d->state & TH_SYN)
2317 bprintf(bp, "F_SYN,");
2318 if (d->state & (TH_SYN << 8))
2319 bprintf(bp, "R_SYN,");
2321 if ((d->state & BOTH_FIN) == BOTH_FIN)
2322 bprintf(bp, "BOTH_FIN,");
2324 if (d->state & TH_FIN)
2325 bprintf(bp, "F_FIN,");
2326 if (d->state & (TH_FIN << 8))
2327 bprintf(bp, "R_FIN,");
2329 bprintf(bp, " f_ack 0x%x, r_ack 0x%x", d->ack_fwd,
2335 do_range_cmd(int cmd, ipfw_range_tlv *rt)
2337 ipfw_range_header rh;
2340 memset(&rh, 0, sizeof(rh));
2341 memcpy(&rh.range, rt, sizeof(*rt));
2342 rh.range.head.length = sizeof(*rt);
2343 rh.range.head.type = IPFW_TLV_RANGE;
2346 if (do_get3(cmd, &rh.opheader, &sz) != 0)
2348 /* Save number of matched objects */
2349 rt->new_set = rh.range.new_set;
2354 * This one handles all set-related commands
2355 * ipfw set { show | enable | disable }
2357 * ipfw set move X to Y
2358 * ipfw set move rule X to Y
2361 ipfw_sets_handler(char *av[])
2372 memset(&rt, 0, sizeof(rt));
2375 errx(EX_USAGE, "set needs command");
2376 if (_substrcmp(*av, "show") == 0) {
2377 struct format_opts fo;
2378 ipfw_cfg_lheader *cfg;
2380 memset(&fo, 0, sizeof(fo));
2381 if (ipfw_get_config(&co, &fo, &cfg, &size) != 0)
2382 err(EX_OSERR, "requesting config failed");
2384 for (i = 0, msg = "disable"; i < RESVD_SET; i++)
2385 if ((cfg->set_mask & (1<<i)) == 0) {
2386 printf("%s %d", msg, i);
2389 msg = (cfg->set_mask != (uint32_t)-1) ? " enable" : "enable";
2390 for (i = 0; i < RESVD_SET; i++)
2391 if ((cfg->set_mask & (1<<i)) != 0) {
2392 printf("%s %d", msg, i);
2397 } else if (_substrcmp(*av, "swap") == 0) {
2399 if ( av[0] == NULL || av[1] == NULL )
2400 errx(EX_USAGE, "set swap needs 2 set numbers\n");
2401 rt.set = atoi(av[0]);
2402 rt.new_set = atoi(av[1]);
2403 if (!isdigit(*(av[0])) || rt.set > RESVD_SET)
2404 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2405 if (!isdigit(*(av[1])) || rt.new_set > RESVD_SET)
2406 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2407 i = do_range_cmd(IP_FW_SET_SWAP, &rt);
2408 } else if (_substrcmp(*av, "move") == 0) {
2410 if (av[0] && _substrcmp(*av, "rule") == 0) {
2411 rt.flags = IPFW_RCFLAG_RANGE; /* move rules to new set */
2415 cmd = IP_FW_SET_MOVE; /* Move set to new one */
2416 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
2417 av[3] != NULL || _substrcmp(av[1], "to") != 0)
2418 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2419 rulenum = atoi(av[0]);
2420 rt.new_set = atoi(av[2]);
2421 if (cmd == IP_FW_XMOVE) {
2422 rt.start_rule = rulenum;
2423 rt.end_rule = rulenum;
2426 rt.new_set = atoi(av[2]);
2427 if (!isdigit(*(av[0])) || (cmd == 3 && rt.set > RESVD_SET) ||
2428 (cmd == 2 && rt.start_rule == IPFW_DEFAULT_RULE) )
2429 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2430 if (!isdigit(*(av[2])) || rt.new_set > RESVD_SET)
2431 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2432 i = do_range_cmd(cmd, &rt);
2434 err(EX_OSERR, "failed to move %s",
2435 cmd == IP_FW_SET_MOVE ? "set": "rule");
2436 } else if (_substrcmp(*av, "disable") == 0 ||
2437 _substrcmp(*av, "enable") == 0 ) {
2438 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2441 masks[0] = masks[1] = 0;
2444 if (isdigit(**av)) {
2446 if (i < 0 || i > RESVD_SET)
2448 "invalid set number %d\n", i);
2449 masks[which] |= (1<<i);
2450 } else if (_substrcmp(*av, "disable") == 0)
2452 else if (_substrcmp(*av, "enable") == 0)
2456 "invalid set command %s\n", *av);
2459 if ( (masks[0] & masks[1]) != 0 )
2461 "cannot enable and disable the same set\n");
2464 rt.new_set = masks[1];
2465 i = do_range_cmd(IP_FW_SET_ENABLE, &rt);
2467 warn("set enable/disable: setsockopt(IP_FW_SET_ENABLE)");
2469 errx(EX_USAGE, "invalid set command %s\n", *av);
2473 ipfw_sysctl_handler(char *av[], int which)
2477 if (av[0] == NULL) {
2478 warnx("missing keyword to enable/disable\n");
2479 } else if (_substrcmp(*av, "firewall") == 0) {
2480 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2481 &which, sizeof(which));
2482 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
2483 &which, sizeof(which));
2484 } else if (_substrcmp(*av, "one_pass") == 0) {
2485 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2486 &which, sizeof(which));
2487 } else if (_substrcmp(*av, "debug") == 0) {
2488 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2489 &which, sizeof(which));
2490 } else if (_substrcmp(*av, "verbose") == 0) {
2491 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2492 &which, sizeof(which));
2493 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2494 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2495 &which, sizeof(which));
2497 } else if (_substrcmp(*av, "altq") == 0) {
2498 altq_set_enabled(which);
2501 warnx("unrecognize enable/disable keyword: %s\n", *av);
2505 typedef void state_cb(struct cmdline_opts *co, struct format_opts *fo,
2506 void *arg, void *state);
2509 prepare_format_dyn(struct cmdline_opts *co, struct format_opts *fo,
2510 void *arg, void *_state)
2516 d = (ipfw_dyn_rule *)_state;
2517 /* Count _ALL_ states */
2520 if (fo->show_counters == 0)
2524 /* skip states from another set */
2525 bcopy((char *)&d->rule + sizeof(uint16_t), &set,
2527 if (set != co->use_set - 1)
2531 width = pr_u64(NULL, &d->pcnt, 0);
2532 if (width > fo->pcwidth)
2533 fo->pcwidth = width;
2535 width = pr_u64(NULL, &d->bcnt, 0);
2536 if (width > fo->bcwidth)
2537 fo->bcwidth = width;
2541 foreach_state(struct cmdline_opts *co, struct format_opts *fo,
2542 caddr_t base, size_t sz, state_cb dyn_bc, void *dyn_arg)
2548 ipfw_obj_ctlv *ctlv;
2554 ctlv = (ipfw_obj_ctlv *)base;
2555 switch (ctlv->head.type) {
2556 case IPFW_TLV_DYNSTATE_LIST:
2557 base += sizeof(*ctlv);
2558 sz -= sizeof(*ctlv);
2559 ttype = IPFW_TLV_DYN_ENT;
2568 tlv = (ipfw_obj_tlv *)base;
2569 if (tlv->type != ttype)
2572 fptr(co, fo, farg, tlv + 1);
2574 base += tlv->length;
2582 prepare_format_opts(struct cmdline_opts *co, struct format_opts *fo,
2583 ipfw_obj_tlv *rtlv, int rcnt, caddr_t dynbase, size_t dynsz)
2585 int bcwidth, pcwidth, width;
2587 struct ip_fw_bcounter *cntr;
2588 struct ip_fw_rule *r;
2592 if (fo->show_counters != 0) {
2593 for (n = 0; n < rcnt; n++,
2594 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2595 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2596 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2597 /* skip rules from another set */
2598 if (co->use_set && r->set != co->use_set - 1)
2601 /* packet counter */
2602 width = pr_u64(NULL, &cntr->pcnt, 0);
2603 if (width > pcwidth)
2607 width = pr_u64(NULL, &cntr->bcnt, 0);
2608 if (width > bcwidth)
2612 fo->bcwidth = bcwidth;
2613 fo->pcwidth = pcwidth;
2616 if (co->do_dynamic && dynsz > 0)
2617 foreach_state(co, fo, dynbase, dynsz, prepare_format_dyn, NULL);
2621 list_static_range(struct cmdline_opts *co, struct format_opts *fo,
2622 struct buf_pr *bp, ipfw_obj_tlv *rtlv, int rcnt)
2625 struct ip_fw_rule *r;
2626 struct ip_fw_bcounter *cntr;
2629 for (n = seen = 0; n < rcnt; n++,
2630 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2632 if ((fo->show_counters | fo->show_time) != 0) {
2633 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2634 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2637 r = (struct ip_fw_rule *)(rtlv + 1);
2639 if (r->rulenum > fo->last)
2641 if (co->use_set && r->set != co->use_set - 1)
2643 if (r->rulenum >= fo->first && r->rulenum <= fo->last) {
2644 show_static_rule(co, fo, bp, r, cntr);
2645 printf("%s", bp->buf);
2656 list_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2657 void *_arg, void *_state)
2664 d = (ipfw_dyn_rule *)_state;
2665 bp = (struct buf_pr *)_arg;
2667 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2668 if (rulenum > fo->last)
2671 bcopy((char *)&d->rule + sizeof(uint16_t),
2672 &set, sizeof(uint8_t));
2673 if (set != co->use_set - 1)
2676 if (rulenum >= fo->first) {
2677 show_dyn_state(co, fo, bp, d);
2678 printf("%s\n", bp->buf);
2684 list_dyn_range(struct cmdline_opts *co, struct format_opts *fo,
2685 struct buf_pr *bp, caddr_t base, size_t sz)
2688 sz = foreach_state(co, fo, base, sz, list_dyn_state, bp);
2693 ipfw_list(int ac, char *av[], int show_counters)
2695 ipfw_cfg_lheader *cfg;
2696 struct format_opts sfo;
2705 fprintf(stderr, "Testing only, list disabled\n");
2709 dummynet_list(ac, av, show_counters);
2715 memset(&sfo, 0, sizeof(sfo));
2717 /* Determine rule range to request */
2719 for (lac = ac, lav = av; lac != 0; lac--) {
2720 rnum = strtoul(*lav++, &endptr, 10);
2721 if (sfo.first == 0 || rnum < sfo.first)
2725 rnum = strtoul(endptr + 1, &endptr, 10);
2726 if (sfo.last == 0 || rnum > sfo.last)
2731 /* get configuraion from kernel */
2733 sfo.show_counters = show_counters;
2734 sfo.show_time = co.do_time;
2735 if (co.do_dynamic != 2)
2736 sfo.flags |= IPFW_CFG_GET_STATIC;
2737 if (co.do_dynamic != 0)
2738 sfo.flags |= IPFW_CFG_GET_STATES;
2739 if ((sfo.show_counters | sfo.show_time) != 0)
2740 sfo.flags |= IPFW_CFG_GET_COUNTERS;
2741 if (ipfw_get_config(&co, &sfo, &cfg, &sz) != 0)
2742 err(EX_OSERR, "retrieving config failed");
2744 error = ipfw_show_config(&co, &sfo, cfg, sz, ac, av);
2753 ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
2754 ipfw_cfg_lheader *cfg, size_t sz, int ac, char *av[])
2759 int exitval = EX_OK;
2765 ipfw_obj_ctlv *ctlv, *tstate;
2766 ipfw_obj_tlv *rbase;
2769 * Handle tablenames TLV first, if any
2775 readsz = sizeof(*cfg);
2778 fo->set_mask = cfg->set_mask;
2780 ctlv = (ipfw_obj_ctlv *)(cfg + 1);
2781 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2782 object_sort_ctlv(ctlv);
2784 readsz += ctlv->head.length;
2785 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2788 if (cfg->flags & IPFW_CFG_GET_STATIC) {
2789 /* We've requested static rules */
2790 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2791 rbase = (ipfw_obj_tlv *)(ctlv + 1);
2793 readsz += ctlv->head.length;
2794 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2799 if ((cfg->flags & IPFW_CFG_GET_STATES) && (readsz != sz)) {
2800 /* We may have some dynamic states */
2801 dynsz = sz - readsz;
2802 /* Skip empty header */
2803 if (dynsz != sizeof(ipfw_obj_ctlv))
2804 dynbase = (caddr_t)ctlv;
2809 prepare_format_opts(co, fo, rbase, rcnt, dynbase, dynsz);
2810 bp_alloc(&bp, 4096);
2812 /* if no rule numbers were specified, list all rules */
2815 fo->last = IPFW_DEFAULT_RULE;
2816 if (cfg->flags & IPFW_CFG_GET_STATIC)
2817 list_static_range(co, fo, &bp, rbase, rcnt);
2819 if (co->do_dynamic && dynsz > 0) {
2820 printf("## Dynamic rules (%d %zu):\n", fo->dcnt,
2822 list_dyn_range(co, fo, &bp, dynbase, dynsz);
2829 /* display specific rules requested on command line */
2830 for (lac = ac, lav = av; lac != 0; lac--) {
2831 /* convert command line rule # */
2832 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2834 fo->last = strtoul(endptr + 1, &endptr, 10);
2837 warnx("invalid rule number: %s", *(lav - 1));
2841 if ((cfg->flags & IPFW_CFG_GET_STATIC) == 0)
2844 if (list_static_range(co, fo, &bp, rbase, rcnt) == 0) {
2845 /* give precedence to other error(s) */
2846 if (exitval == EX_OK)
2847 exitval = EX_UNAVAILABLE;
2848 if (fo->first == fo->last)
2849 warnx("rule %u does not exist", fo->first);
2851 warnx("no rules in range %u-%u",
2852 fo->first, fo->last);
2856 if (co->do_dynamic && dynsz > 0) {
2857 printf("## Dynamic rules:\n");
2858 for (lac = ac, lav = av; lac != 0; lac--) {
2859 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2861 fo->last = strtoul(endptr+1, &endptr, 10);
2863 /* already warned */
2865 list_dyn_range(co, fo, &bp, dynbase, dynsz);
2875 * Retrieves current ipfw configuration of given type
2876 * and stores its pointer to @pcfg.
2878 * Caller is responsible for freeing @pcfg.
2880 * Returns 0 on success.
2884 ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
2885 ipfw_cfg_lheader **pcfg, size_t *psize)
2887 ipfw_cfg_lheader *cfg;
2892 if (co->test_only != 0) {
2893 fprintf(stderr, "Testing only, list disabled\n");
2897 /* Start with some data size */
2901 for (i = 0; i < 16; i++) {
2904 if ((cfg = calloc(1, sz)) == NULL)
2907 cfg->flags = fo->flags;
2908 cfg->start_rule = fo->first;
2909 cfg->end_rule = fo->last;
2911 if (do_get3(IP_FW_XGET, &cfg->opheader, &sz) != 0) {
2912 if (errno != ENOMEM) {
2917 /* Buffer size is not enough. Try to increase */
2934 lookup_host (char *host, struct in_addr *ipaddr)
2938 if (!inet_aton(host, ipaddr)) {
2939 if ((he = gethostbyname(host)) == NULL)
2941 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2955 ipfw_check_object_name(const char *name)
2960 * Check that name is null-terminated and contains
2961 * valid symbols only. Valid mask is:
2962 * [a-zA-Z0-9\-_\.]{1,63}
2965 if (l == 0 || l >= 64)
2967 for (i = 0; i < l; i++) {
2969 if (isalpha(c) || isdigit(c) || c == '_' ||
2970 c == '-' || c == '.')
2977 static char *default_state_name = "default";
2979 state_check_name(const char *name)
2982 if (ipfw_check_object_name(name) != 0)
2984 if (strcmp(name, "any") == 0)
2990 eaction_check_name(const char *name)
2993 if (ipfw_check_object_name(name) != 0)
2995 /* Restrict some 'special' names */
2996 if (match_token(rule_actions, name) != -1 &&
2997 match_token(rule_action_params, name) != -1)
3003 pack_object(struct tidx *tstate, char *name, int otype)
3006 ipfw_obj_ntlv *ntlv;
3008 for (i = 0; i < tstate->count; i++) {
3009 if (strcmp(tstate->idx[i].name, name) != 0)
3011 if (tstate->idx[i].set != tstate->set)
3013 if (tstate->idx[i].head.type != otype)
3016 return (tstate->idx[i].idx);
3019 if (tstate->count + 1 > tstate->size) {
3021 tstate->idx = realloc(tstate->idx, tstate->size *
3022 sizeof(ipfw_obj_ntlv));
3023 if (tstate->idx == NULL)
3027 ntlv = &tstate->idx[i];
3028 memset(ntlv, 0, sizeof(ipfw_obj_ntlv));
3029 strlcpy(ntlv->name, name, sizeof(ntlv->name));
3030 ntlv->head.type = otype;
3031 ntlv->head.length = sizeof(ipfw_obj_ntlv);
3032 ntlv->set = tstate->set;
3033 ntlv->idx = ++tstate->counter;
3040 pack_table(struct tidx *tstate, char *name)
3043 if (table_check_name(name) != 0)
3046 return (pack_object(tstate, name, IPFW_TLV_TBL_NAME));
3050 fill_table(struct _ipfw_insn *cmd, char *av, uint8_t opcode,
3051 struct tidx *tstate)
3053 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
3057 if ((p = strchr(av + 6, ')')) == NULL)
3058 errx(EX_DATAERR, "forgotten parenthesis: '%s'", av);
3060 p = strchr(av + 6, ',');
3064 if ((uidx = pack_table(tstate, av + 6)) == 0)
3065 errx(EX_DATAERR, "Invalid table name: %s", av + 6);
3067 cmd->opcode = opcode;
3070 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3071 d[0] = strtoul(p, NULL, 0);
3073 cmd->len |= F_INSN_SIZE(ipfw_insn);
3078 * fills the addr and mask fields in the instruction as appropriate from av.
3079 * Update length as appropriate.
3080 * The following formats are allowed:
3081 * me returns O_IP_*_ME
3082 * 1.2.3.4 single IP address
3083 * 1.2.3.4:5.6.7.8 address:mask
3084 * 1.2.3.4/24 address/mask
3085 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
3086 * We can have multiple comma-separated address/mask entries.
3089 fill_ip(ipfw_insn_ip *cmd, char *av, int cblen, struct tidx *tstate)
3092 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
3094 cmd->o.len &= ~F_LEN_MASK; /* zero len */
3096 if (_substrcmp(av, "any") == 0)
3099 if (_substrcmp(av, "me") == 0) {
3100 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
3104 if (strncmp(av, "table(", 6) == 0) {
3105 fill_table(&cmd->o, av, O_IP_DST_LOOKUP, tstate);
3111 * After the address we can have '/' or ':' indicating a mask,
3112 * ',' indicating another address follows, '{' indicating a
3113 * set of addresses of unspecified size.
3115 char *t = NULL, *p = strpbrk(av, "/:,{");
3119 CHECK_LENGTH(cblen, F_INSN_SIZE(ipfw_insn) + 2 + len);
3124 if ((t = strpbrk(p, ",{")) != NULL) {
3131 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
3132 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
3135 if (!inet_aton(p, (struct in_addr *)&d[1]))
3136 errx(EX_DATAERR, "bad netmask ``%s''", p);
3141 d[1] = htonl(0U); /* mask */
3142 else if (masklen > 32)
3143 errx(EX_DATAERR, "bad width ``%s''", p);
3145 d[1] = htonl(~0U << (32 - masklen));
3147 case '{': /* no mask, assume /24 and put back the '{' */
3148 d[1] = htonl(~0U << (32 - 24));
3152 case ',': /* single address plus continuation */
3155 case 0: /* initialization value */
3157 d[1] = htonl(~0U); /* force /32 */
3160 d[0] &= d[1]; /* mask base address with mask */
3163 /* find next separator */
3165 p = strpbrk(p, ",{");
3166 if (p && *p == '{') {
3168 * We have a set of addresses. They are stored as follows:
3169 * arg1 is the set size (powers of 2, 2..256)
3170 * addr is the base address IN HOST FORMAT
3171 * mask.. is an array of arg1 bits (rounded up to
3172 * the next multiple of 32) with bits set
3173 * for each host in the map.
3175 uint32_t *map = (uint32_t *)&cmd->mask;
3177 int i = contigmask((uint8_t *)&(d[1]), 32);
3180 errx(EX_DATAERR, "address set cannot be in a list");
3181 if (i < 24 || i > 31)
3182 errx(EX_DATAERR, "invalid set with mask %d\n", i);
3183 cmd->o.arg1 = 1<<(32-i); /* map length */
3184 d[0] = ntohl(d[0]); /* base addr in host format */
3185 cmd->o.opcode = O_IP_DST_SET; /* default */
3186 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
3187 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
3188 map[i] = 0; /* clear map */
3192 high = low + cmd->o.arg1 - 1;
3194 * Here, i stores the previous value when we specify a range
3195 * of addresses within a mask, e.g. 45-63. i = -1 means we
3196 * have no previous value.
3198 i = -1; /* previous value in a range */
3199 while (isdigit(*av)) {
3201 int a = strtol(av, &s, 0);
3203 if (s == av) { /* no parameter */
3205 errx(EX_DATAERR, "set not closed\n");
3207 errx(EX_DATAERR, "incomplete range %d-", i);
3210 if (a < low || a > high)
3211 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
3214 if (i == -1) /* no previous in range */
3216 else { /* check that range is valid */
3218 errx(EX_DATAERR, "invalid range %d-%d",
3221 errx(EX_DATAERR, "double '-' in range");
3224 map[i/32] |= 1<<(i & 31);
3235 if (av) /* then *av must be a ',' */
3238 /* Check this entry */
3239 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
3241 * 'any' turns the entire list into a NOP.
3242 * 'not any' never matches, so it is removed from the
3243 * list unless it is the only item, in which case we
3246 if (cmd->o.len & F_NOT) { /* "not any" never matches */
3247 if (av == NULL && len == 0) /* only this entry */
3248 errx(EX_DATAERR, "not any never matches");
3250 /* else do nothing and skip this entry */
3253 /* A single IP can be stored in an optimized format */
3254 if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
3255 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
3258 len += 2; /* two words... */
3261 if (len + 1 > F_LEN_MASK)
3262 errx(EX_DATAERR, "address list too long");
3263 cmd->o.len |= len+1;
3267 /* n2mask sets n bits of the mask */
3269 n2mask(struct in6_addr *mask, int n)
3271 static int minimask[9] =
3272 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
3275 memset(mask, 0, sizeof(struct in6_addr));
3276 p = (u_char *) mask;
3277 for (; n > 0; p++, n -= 8) {
3287 fill_flags_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3288 struct _s_x *flags, char *p)
3291 uint32_t set = 0, clear = 0;
3293 if (fill_flags(flags, p, &e, &set, &clear) != 0)
3294 errx(EX_DATAERR, "invalid flag %s", e);
3296 cmd->opcode = opcode;
3297 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
3298 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3303 ipfw_delete(char *av[])
3308 int exitval = EX_OK;
3312 NEED1("missing rule specification");
3313 if ( *av && _substrcmp(*av, "set") == 0) {
3314 /* Do not allow using the following syntax:
3315 * ipfw set N delete set M
3318 errx(EX_DATAERR, "invalid syntax");
3319 do_set = 1; /* delete set */
3324 while (*av && isdigit(**av)) {
3325 i = strtol(*av, &sep, 10);
3328 j = strtol(sep + 1, NULL, 10);
3331 exitval = ipfw_delete_nat(i);
3332 } else if (co.do_pipe) {
3333 exitval = ipfw_delete_pipe(co.do_pipe, i);
3335 memset(&rt, 0, sizeof(rt));
3338 rt.flags = IPFW_RCFLAG_SET;
3340 rt.start_rule = i & 0xffff;
3341 rt.end_rule = j & 0xffff;
3342 if (rt.start_rule == 0 && rt.end_rule == 0)
3343 rt.flags |= IPFW_RCFLAG_ALL;
3345 rt.flags |= IPFW_RCFLAG_RANGE;
3346 if (co.use_set != 0) {
3347 rt.set = co.use_set - 1;
3348 rt.flags |= IPFW_RCFLAG_SET;
3351 if (co.do_dynamic == 2)
3352 rt.flags |= IPFW_RCFLAG_DYNAMIC;
3353 i = do_range_cmd(IP_FW_XDEL, &rt);
3355 exitval = EX_UNAVAILABLE;
3358 warn("rule %u: setsockopt(IP_FW_XDEL)",
3360 } else if (rt.new_set == 0 && do_set == 0 &&
3361 co.do_dynamic != 2) {
3362 exitval = EX_UNAVAILABLE;
3365 if (rt.start_rule != rt.end_rule)
3366 warnx("no rules rules in %u-%u range",
3367 rt.start_rule, rt.end_rule);
3369 warnx("rule %u not found",
3374 if (exitval != EX_OK && co.do_force == 0)
3380 * fill the interface structure. We do not check the name as we can
3381 * create interfaces dynamically, so checking them at insert time
3382 * makes relatively little sense.
3383 * Interface names containing '*', '?', or '[' are assumed to be shell
3384 * patterns which match interfaces.
3387 fill_iface(ipfw_insn_if *cmd, char *arg, int cblen, struct tidx *tstate)
3392 cmd->name[0] = '\0';
3393 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3397 /* Parse the interface or address */
3398 if (strcmp(arg, "any") == 0)
3399 cmd->o.len = 0; /* effectively ignore this command */
3400 else if (strncmp(arg, "table(", 6) == 0) {
3401 if ((p = strchr(arg + 6, ')')) == NULL)
3402 errx(EX_DATAERR, "forgotten parenthesis: '%s'", arg);
3404 p = strchr(arg + 6, ',');
3407 if ((uidx = pack_table(tstate, arg + 6)) == 0)
3408 errx(EX_DATAERR, "Invalid table name: %s", arg + 6);
3410 cmd->name[0] = '\1'; /* Special value indicating table */
3412 } else if (!isdigit(*arg)) {
3413 strlcpy(cmd->name, arg, sizeof(cmd->name));
3414 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3415 } else if (!inet_aton(arg, &cmd->p.ip))
3416 errx(EX_DATAERR, "bad ip address ``%s''", arg);
3420 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
3424 char *ap, *ptr, *optr;
3425 struct ether_addr *mac;
3426 const char *macset = "0123456789abcdefABCDEF:";
3428 if (strcmp(p, "any") == 0) {
3429 for (i = 0; i < ETHER_ADDR_LEN; i++)
3430 addr[i] = mask[i] = 0;
3434 optr = ptr = strdup(p);
3435 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
3437 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
3438 errx(EX_DATAERR, "Incorrect MAC address");
3439 bcopy(mac, addr, ETHER_ADDR_LEN);
3441 errx(EX_DATAERR, "Incorrect MAC address");
3443 if (ptr != NULL) { /* we have mask? */
3444 if (p[ptr - optr - 1] == '/') { /* mask len */
3445 long ml = strtol(ptr, &ap, 10);
3446 if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
3447 errx(EX_DATAERR, "Incorrect mask length");
3448 for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
3449 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
3452 if (strspn(ptr, macset) != l ||
3453 (mac = ether_aton(ptr)) == NULL)
3454 errx(EX_DATAERR, "Incorrect mask");
3455 bcopy(mac, mask, ETHER_ADDR_LEN);
3457 } else { /* default mask: ff:ff:ff:ff:ff:ff */
3458 for (i = 0; i < ETHER_ADDR_LEN; i++)
3461 for (i = 0; i < ETHER_ADDR_LEN; i++)
3468 * helper function, updates the pointer to cmd with the length
3469 * of the current command, and also cleans up the first word of
3470 * the new command in case it has been clobbered before.
3473 next_cmd(ipfw_insn *cmd, int *len)
3476 CHECK_LENGTH(*len, 0);
3478 bzero(cmd, sizeof(*cmd));
3483 * Takes arguments and copies them into a comment
3486 fill_comment(ipfw_insn *cmd, char **av, int cblen)
3489 char *p = (char *)(cmd + 1);
3491 cmd->opcode = O_NOP;
3492 cmd->len = (cmd->len & (F_NOT | F_OR));
3494 /* Compute length of comment string. */
3495 for (i = 0, l = 0; av[i] != NULL; i++)
3496 l += strlen(av[i]) + 1;
3501 "comment too long (max 80 chars)");
3503 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
3506 for (i = 0; av[i] != NULL; i++) {
3515 * A function to fill simple commands of size 1.
3516 * Existing flags are preserved.
3519 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3521 cmd->opcode = opcode;
3522 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3527 * Fetch and add the MAC address and type, with masks. This generates one or
3528 * two microinstructions, and returns the pointer to the last one.
3531 add_mac(ipfw_insn *cmd, char *av[], int cblen)
3535 if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
3536 errx(EX_DATAERR, "MAC dst src");
3538 cmd->opcode = O_MACADDR2;
3539 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3542 mac = (ipfw_insn_mac *)cmd;
3543 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
3544 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
3545 &(mac->mask[ETHER_ADDR_LEN])); /* src */
3550 add_mactype(ipfw_insn *cmd, char *av, int cblen)
3553 errx(EX_DATAERR, "missing MAC type");
3554 if (strcmp(av, "any") != 0) { /* we have a non-null type */
3555 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
3557 cmd->opcode = O_MAC_TYPE;
3564 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
3566 struct protoent *pe;
3570 proto = strtol(av, &ep, 10);
3571 if (*ep != '\0' || proto <= 0) {
3572 if ((pe = getprotobyname(av)) == NULL)
3574 proto = pe->p_proto;
3577 fill_cmd(cmd, O_PROTO, 0, proto);
3583 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
3585 u_char proto = IPPROTO_IP;
3587 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3588 ; /* do not set O_IP4 nor O_IP6 */
3589 else if (strcmp(av, "ip4") == 0)
3590 /* explicit "just IPv4" rule */
3591 fill_cmd(cmd, O_IP4, 0, 0);
3592 else if (strcmp(av, "ip6") == 0) {
3593 /* explicit "just IPv6" rule */
3594 proto = IPPROTO_IPV6;
3595 fill_cmd(cmd, O_IP6, 0, 0);
3597 return add_proto0(cmd, av, protop);
3604 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
3606 u_char proto = IPPROTO_IP;
3608 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3609 ; /* do not set O_IP4 nor O_IP6 */
3610 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3611 /* explicit "just IPv4" rule */
3612 fill_cmd(cmd, O_IP4, 0, 0);
3613 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3614 /* explicit "just IPv6" rule */
3615 proto = IPPROTO_IPV6;
3616 fill_cmd(cmd, O_IP6, 0, 0);
3618 return add_proto0(cmd, av, protop);
3625 add_srcip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3627 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3628 if (cmd->opcode == O_IP_DST_SET) /* set */
3629 cmd->opcode = O_IP_SRC_SET;
3630 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3631 cmd->opcode = O_IP_SRC_LOOKUP;
3632 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3633 cmd->opcode = O_IP_SRC_ME;
3634 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3635 cmd->opcode = O_IP_SRC;
3636 else /* addr/mask */
3637 cmd->opcode = O_IP_SRC_MASK;
3642 add_dstip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3644 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3645 if (cmd->opcode == O_IP_DST_SET) /* set */
3647 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3649 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3650 cmd->opcode = O_IP_DST_ME;
3651 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3652 cmd->opcode = O_IP_DST;
3653 else /* addr/mask */
3654 cmd->opcode = O_IP_DST_MASK;
3658 static struct _s_x f_reserved_keywords[] = {
3661 { "diverted", TOK_OR },
3662 { "dst-port", TOK_OR },
3663 { "src-port", TOK_OR },
3664 { "established", TOK_OR },
3665 { "keep-state", TOK_OR },
3667 { "icmptypes", TOK_OR },
3675 { NULL, 0 } /* terminator */
3679 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
3682 if (match_token(f_reserved_keywords, av) != -1)
3685 if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
3686 /* XXX todo: check that we have a protocol with ports */
3687 cmd->opcode = opcode;
3694 add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3697 char *host, *ch, buf[INET6_ADDRSTRLEN];
3698 ipfw_insn *ret = NULL;
3701 /* Copy first address in set if needed */
3702 if ((ch = strpbrk(av, "/,")) != NULL) {
3704 strlcpy(buf, av, sizeof(buf));
3705 if (len < sizeof(buf))
3711 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3712 inet_pton(AF_INET6, host, &a) == 1)
3713 ret = add_srcip6(cmd, av, cblen, tstate);
3714 /* XXX: should check for IPv4, not !IPv6 */
3715 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3716 inet_pton(AF_INET6, host, &a) != 1))
3717 ret = add_srcip(cmd, av, cblen, tstate);
3718 if (ret == NULL && strcmp(av, "any") != 0)
3725 add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3728 char *host, *ch, buf[INET6_ADDRSTRLEN];
3729 ipfw_insn *ret = NULL;
3732 /* Copy first address in set if needed */
3733 if ((ch = strpbrk(av, "/,")) != NULL) {
3735 strlcpy(buf, av, sizeof(buf));
3736 if (len < sizeof(buf))
3742 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3743 inet_pton(AF_INET6, host, &a) == 1)
3744 ret = add_dstip6(cmd, av, cblen, tstate);
3745 /* XXX: should check for IPv4, not !IPv6 */
3746 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3747 inet_pton(AF_INET6, host, &a) != 1))
3748 ret = add_dstip(cmd, av, cblen, tstate);
3749 if (ret == NULL && strcmp(av, "any") != 0)
3756 * Parse arguments and assemble the microinstructions which make up a rule.
3757 * Rules are added into the 'rulebuf' and then copied in the correct order
3758 * into the actual rule.
3760 * The syntax for a rule starts with the action, followed by
3761 * optional action parameters, and the various match patterns.
3762 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
3763 * (generated if the rule includes a keep-state option), then the
3764 * various match patterns, log/altq actions, and the actual action.
3768 compile_rule(char *av[], uint32_t *rbuf, int *rbufsize, struct tidx *tstate)
3771 * rules are added into the 'rulebuf' and then copied in
3772 * the correct order into the actual rule.
3773 * Some things that need to go out of order (prob, action etc.)
3776 static uint32_t actbuf[255], cmdbuf[255];
3777 int rblen, ablen, cblen;
3779 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
3780 ipfw_insn *first_cmd; /* first match pattern */
3782 struct ip_fw_rule *rule;
3785 * various flags used to record that we entered some fields.
3787 ipfw_insn *have_state = NULL; /* any state-related option */
3788 int have_rstate = 0;
3789 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
3790 ipfw_insn *have_skipcmd = NULL;
3795 int open_par = 0; /* open parenthesis ( */
3797 /* proto is here because it is used to fetch ports */
3798 u_char proto = IPPROTO_IP; /* default protocol */
3800 double match_prob = 1; /* match probability, default is always match */
3802 bzero(actbuf, sizeof(actbuf)); /* actions go here */
3803 bzero(cmdbuf, sizeof(cmdbuf));
3804 bzero(rbuf, *rbufsize);
3806 rule = (struct ip_fw_rule *)rbuf;
3807 cmd = (ipfw_insn *)cmdbuf;
3808 action = (ipfw_insn *)actbuf;
3810 rblen = *rbufsize / sizeof(uint32_t);
3811 rblen -= sizeof(struct ip_fw_rule) / sizeof(uint32_t);
3812 ablen = sizeof(actbuf) / sizeof(actbuf[0]);
3813 cblen = sizeof(cmdbuf) / sizeof(cmdbuf[0]);
3814 cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
3816 #define CHECK_RBUFLEN(len) { CHECK_LENGTH(rblen, len); rblen -= len; }
3817 #define CHECK_ACTLEN CHECK_LENGTH(ablen, action->len)
3821 /* [rule N] -- Rule number optional */
3822 if (av[0] && isdigit(**av)) {
3823 rule->rulenum = atoi(*av);
3827 /* [set N] -- set number (0..RESVD_SET), optional */
3828 if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
3829 int set = strtoul(av[1], NULL, 10);
3830 if (set < 0 || set > RESVD_SET)
3831 errx(EX_DATAERR, "illegal set %s", av[1]);
3837 /* [prob D] -- match probability, optional */
3838 if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
3839 match_prob = strtod(av[1], NULL);
3841 if (match_prob <= 0 || match_prob > 1)
3842 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
3846 /* action -- mandatory */
3847 NEED1("missing action");
3848 i = match_token(rule_actions, *av);
3850 action->len = 1; /* default */
3853 case TOK_CHECKSTATE:
3854 have_state = action;
3855 action->opcode = O_CHECK_STATE;
3857 match_token(rule_options, *av) == TOK_COMMENT) {
3858 action->arg1 = pack_object(tstate,
3859 default_state_name, IPFW_TLV_STATE_NAME);
3862 if (*av[0] == ':') {
3863 if (strcmp(*av + 1, "any") == 0)
3865 else if (state_check_name(*av + 1) == 0)
3866 action->arg1 = pack_object(tstate, *av + 1,
3867 IPFW_TLV_STATE_NAME);
3869 errx(EX_DATAERR, "Invalid state name %s",
3874 errx(EX_DATAERR, "Invalid state name %s", *av);
3878 action->opcode = O_REJECT;
3879 action->arg1 = ICMP_REJECT_ABORT;
3883 action->opcode = O_UNREACH6;
3884 action->arg1 = ICMP6_UNREACH_ABORT;
3888 action->opcode = O_ACCEPT;
3892 action->opcode = O_DENY;
3897 action->opcode = O_REJECT;
3898 action->arg1 = ICMP_UNREACH_HOST;
3902 action->opcode = O_REJECT;
3903 action->arg1 = ICMP_REJECT_RST;
3907 action->opcode = O_UNREACH6;
3908 action->arg1 = ICMP6_UNREACH_RST;
3912 action->opcode = O_REJECT;
3913 NEED1("missing reject code");
3914 fill_reject_code(&action->arg1, *av);
3919 action->opcode = O_UNREACH6;
3920 NEED1("missing unreach code");
3921 fill_unreach6_code(&action->arg1, *av);
3926 action->opcode = O_COUNT;
3930 action->opcode = O_NAT;
3931 action->len = F_INSN_SIZE(ipfw_insn_nat);
3933 if (*av != NULL && _substrcmp(*av, "global") == 0) {
3934 action->arg1 = IP_FW_NAT44_GLOBAL;
3940 action->opcode = O_QUEUE;
3943 action->opcode = O_PIPE;
3946 action->opcode = O_SKIPTO;
3949 action->opcode = O_NETGRAPH;
3952 action->opcode = O_NGTEE;
3955 action->opcode = O_DIVERT;
3958 action->opcode = O_TEE;
3961 action->opcode = O_CALLRETURN;
3964 errx(EX_USAGE, "missing argument for %s", *(av - 1));
3965 if (isdigit(**av)) {
3966 action->arg1 = strtoul(*av, NULL, 10);
3967 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
3968 errx(EX_DATAERR, "illegal argument for %s",
3970 } else if (_substrcmp(*av, "tablearg") == 0) {
3971 action->arg1 = IP_FW_TARG;
3972 } else if (i == TOK_DIVERT || i == TOK_TEE) {
3975 s = getservbyname(av[0], "divert");
3977 action->arg1 = ntohs(s->s_port);
3979 errx(EX_DATAERR, "illegal divert/tee port");
3981 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
3987 * Locate the address-port separator (':' or ',').
3988 * Could be one of the following:
3992 * IPv6 w:x:y::z,port
3993 * The ':' can only be used with hostname and IPv4 address.
3994 * XXX-BZ Should we also support [w:x:y::z]:port?
3996 struct sockaddr_storage result;
3997 struct addrinfo *res;
4000 u_short port_number;
4002 NEED1("missing forward address[:port]");
4005 * locate the address-port separator (':' or ',')
4007 s = strchr(*av, ',');
4009 /* Distinguish between IPv4:port and IPv6 cases. */
4010 s = strchr(*av, ':');
4011 if (s && strchr(s+1, ':'))
4012 s = NULL; /* no port */
4017 /* Terminate host portion and set s to start of port. */
4019 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
4022 "illegal forwarding port ``%s''", s);
4023 port_number = (u_short)i;
4026 if (_substrcmp(*av, "tablearg") == 0) {
4028 ((struct sockaddr_in*)&result)->sin_addr.s_addr =
4032 * Resolve the host name or address to a family and a
4033 * network representation of the address.
4035 if (getaddrinfo(*av, NULL, NULL, &res))
4036 errx(EX_DATAERR, NULL);
4037 /* Just use the first host in the answer. */
4038 family = res->ai_family;
4039 memcpy(&result, res->ai_addr, res->ai_addrlen);
4043 if (family == PF_INET) {
4044 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
4046 action->opcode = O_FORWARD_IP;
4047 action->len = F_INSN_SIZE(ipfw_insn_sa);
4051 * In the kernel we assume AF_INET and use only
4052 * sin_port and sin_addr. Remember to set sin_len as
4053 * the routing code seems to use it too.
4055 p->sa.sin_len = sizeof(struct sockaddr_in);
4056 p->sa.sin_family = AF_INET;
4057 p->sa.sin_port = port_number;
4058 p->sa.sin_addr.s_addr =
4059 ((struct sockaddr_in *)&result)->sin_addr.s_addr;
4060 } else if (family == PF_INET6) {
4061 ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
4063 action->opcode = O_FORWARD_IP6;
4064 action->len = F_INSN_SIZE(ipfw_insn_sa6);
4067 p->sa.sin6_len = sizeof(struct sockaddr_in6);
4068 p->sa.sin6_family = AF_INET6;
4069 p->sa.sin6_port = port_number;
4070 p->sa.sin6_flowinfo = 0;
4071 p->sa.sin6_scope_id =
4072 ((struct sockaddr_in6 *)&result)->sin6_scope_id;
4073 bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
4074 &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
4076 errx(EX_DATAERR, "Invalid address family in forward action");
4082 /* pretend it is a 'count' rule followed by the comment */
4083 action->opcode = O_COUNT;
4084 av--; /* go back... */
4090 size_t intsize = sizeof(int);
4092 action->opcode = O_SETFIB;
4093 NEED1("missing fib number");
4094 if (_substrcmp(*av, "tablearg") == 0) {
4095 action->arg1 = IP_FW_TARG;
4097 action->arg1 = strtoul(*av, NULL, 10);
4098 if (sysctlbyname("net.fibs", &numfibs, &intsize,
4100 errx(EX_DATAERR, "fibs not suported.\n");
4101 if (action->arg1 >= numfibs) /* Temporary */
4102 errx(EX_DATAERR, "fib too large.\n");
4103 /* Add high-order bit to fib to make room for tablearg*/
4104 action->arg1 |= 0x8000;
4114 action->opcode = O_SETDSCP;
4115 NEED1("missing DSCP code");
4116 if (_substrcmp(*av, "tablearg") == 0) {
4117 action->arg1 = IP_FW_TARG;
4119 if (isalpha(*av[0])) {
4120 if ((code = match_token(f_ipdscp, *av)) == -1)
4121 errx(EX_DATAERR, "Unknown DSCP code");
4122 action->arg1 = code;
4124 action->arg1 = strtoul(*av, NULL, 10);
4126 * Add high-order bit to DSCP to make room
4129 action->arg1 |= 0x8000;
4136 action->opcode = O_REASS;
4140 fill_cmd(action, O_CALLRETURN, F_NOT, 0);
4143 case TOK_TCPSETMSS: {
4147 idx = pack_object(tstate, "tcp-setmss", IPFW_TLV_EACTION);
4149 errx(EX_DATAERR, "pack_object failed");
4150 fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4151 NEED1("Missing MSS value");
4152 action = next_cmd(action, &ablen);
4155 mss = strtoul(*av, NULL, 10);
4156 if (mss == 0 || mss > UINT16_MAX)
4157 errx(EX_USAGE, "invalid MSS value %s", *av);
4158 fill_cmd(action, O_EXTERNAL_DATA, 0, (uint16_t)mss);
4165 if (match_token(rule_eactions, *av) == -1)
4166 errx(EX_DATAERR, "invalid action %s\n", *av);
4168 * External actions support.
4169 * XXX: we support only syntax with instance name.
4170 * For known external actions (from rule_eactions list)
4171 * we can handle syntax directly. But with `eaction'
4172 * keyword we can use only `eaction <name> <instance>'
4178 NEED1("Missing eaction name");
4179 if (eaction_check_name(*av) != 0)
4180 errx(EX_DATAERR, "Invalid eaction name %s", *av);
4181 idx = pack_object(tstate, *av, IPFW_TLV_EACTION);
4183 errx(EX_DATAERR, "pack_object failed");
4184 fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4186 NEED1("Missing eaction instance name");
4187 action = next_cmd(action, &ablen);
4190 if (eaction_check_name(*av) != 0)
4191 errx(EX_DATAERR, "Invalid eaction instance name %s",
4194 * External action instance object has TLV type depended
4195 * from the external action name object index. Since we
4196 * currently don't know this index, use zero as TLV type.
4198 idx = pack_object(tstate, *av, 0);
4200 errx(EX_DATAERR, "pack_object failed");
4201 fill_cmd(action, O_EXTERNAL_INSTANCE, 0, idx);
4205 action = next_cmd(action, &ablen);
4208 * [altq queuename] -- altq tag, optional
4209 * [log [logamount N]] -- log, optional
4211 * If they exist, it go first in the cmdbuf, but then it is
4212 * skipped in the copy section to the end of the buffer.
4214 while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
4219 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
4224 "log cannot be specified more than once");
4225 have_log = (ipfw_insn *)c;
4226 cmd->len = F_INSN_SIZE(ipfw_insn_log);
4228 cmd->opcode = O_LOG;
4229 if (av[0] && _substrcmp(*av, "logamount") == 0) {
4231 NEED1("logamount requires argument");
4235 "logamount must be positive");
4239 len = sizeof(c->max_log);
4240 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
4241 &c->max_log, &len, NULL, 0) == -1) {
4246 errx(1, "sysctlbyname(\"%s\")",
4247 "net.inet.ip.fw.verbose_limit");
4256 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
4258 NEED1("missing altq queue name");
4261 "altq cannot be specified more than once");
4262 have_altq = (ipfw_insn *)a;
4263 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
4265 cmd->opcode = O_ALTQ;
4266 a->qid = altq_name_to_qid(*av);
4277 errx(EX_USAGE, "tag and untag cannot be "
4278 "specified more than once");
4279 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
4280 rule_action_params);
4282 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
4290 cmd = next_cmd(cmd, &cblen);
4293 if (have_state) { /* must be a check-state, we are done */
4295 match_token(rule_options, *av) == TOK_COMMENT) {
4296 /* check-state has a comment */
4298 fill_comment(cmd, av, cblen);
4299 cmd = next_cmd(cmd, &cblen);
4305 #define OR_START(target) \
4306 if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
4308 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
4311 if ( (av[0])[1] == '\0') { \
4322 strcmp(*av, ")") == 0 || \
4323 strcmp(*av, "}") == 0)) { \
4328 errx(EX_USAGE, "missing \")\"\n"); \
4332 if (av[0] && _substrcmp(*av, "not") == 0) { \
4333 if (cmd->len & F_NOT) \
4334 errx(EX_USAGE, "double \"not\" not allowed\n"); \
4335 cmd->len |= F_NOT; \
4339 #define OR_BLOCK(target) \
4340 if (av[0] && _substrcmp(*av, "or") == 0) { \
4341 if (prev == NULL || open_par == 0) \
4342 errx(EX_DATAERR, "invalid OR block"); \
4343 prev->len |= F_OR; \
4353 * MAC addresses, optional.
4354 * If we have this, we skip the part "proto from src to dst"
4355 * and jump straight to the option parsing.
4358 NEED1("missing protocol");
4359 if (_substrcmp(*av, "MAC") == 0 ||
4360 _substrcmp(*av, "mac") == 0) {
4361 av++; /* the "MAC" keyword */
4362 add_mac(cmd, av); /* exits in case of errors */
4363 cmd = next_cmd(cmd);
4364 av += 2; /* dst-mac and src-mac */
4366 NEED1("missing mac type");
4367 if (add_mactype(cmd, av[0]))
4368 cmd = next_cmd(cmd);
4369 av++; /* any or mac-type */
4375 * protocol, mandatory
4377 OR_START(get_proto);
4379 NEED1("missing protocol");
4380 if (add_proto_compat(cmd, *av, &proto)) {
4382 if (F_LEN(cmd) != 0) {
4384 cmd = next_cmd(cmd, &cblen);
4386 } else if (first_cmd != cmd) {
4387 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
4389 rule->flags |= IPFW_RULE_JUSTOPTS;
4392 OR_BLOCK(get_proto);
4394 first_cmd = cmd; /* update pointer to use in compact form */
4399 if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
4400 errx(EX_USAGE, "missing ``from''");
4404 * source IP, mandatory
4406 OR_START(source_ip);
4407 NOT_BLOCK; /* optional "not" */
4408 NEED1("missing source address");
4409 if (add_src(cmd, *av, proto, cblen, tstate)) {
4411 if (F_LEN(cmd) != 0) { /* ! any */
4413 cmd = next_cmd(cmd, &cblen);
4416 errx(EX_USAGE, "bad source address %s", *av);
4417 OR_BLOCK(source_ip);
4420 * source ports, optional
4422 NOT_BLOCK; /* optional "not" */
4423 if ( av[0] != NULL ) {
4424 if (_substrcmp(*av, "any") == 0 ||
4425 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4427 if (F_LEN(cmd) != 0)
4428 cmd = next_cmd(cmd, &cblen);
4435 if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
4436 errx(EX_USAGE, "missing ``to''");
4440 * destination, mandatory
4443 NOT_BLOCK; /* optional "not" */
4444 NEED1("missing dst address");
4445 if (add_dst(cmd, *av, proto, cblen, tstate)) {
4447 if (F_LEN(cmd) != 0) { /* ! any */
4449 cmd = next_cmd(cmd, &cblen);
4452 errx( EX_USAGE, "bad destination address %s", *av);
4456 * dest. ports, optional
4458 NOT_BLOCK; /* optional "not" */
4460 if (_substrcmp(*av, "any") == 0 ||
4461 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4463 if (F_LEN(cmd) != 0)
4464 cmd = next_cmd(cmd, &cblen);
4467 if (first_cmd == cmd)
4468 rule->flags |= IPFW_RULE_NOOPT;
4472 while ( av[0] != NULL ) {
4474 ipfw_insn_u32 *cmd32; /* alias for cmd */
4477 cmd32 = (ipfw_insn_u32 *)cmd;
4479 if (*s == '!') { /* alternate syntax for NOT */
4480 if (cmd->len & F_NOT)
4481 errx(EX_USAGE, "double \"not\" not allowed\n");
4485 i = match_token(rule_options, s);
4489 if (cmd->len & F_NOT)
4490 errx(EX_USAGE, "double \"not\" not allowed\n");
4495 if (open_par == 0 || prev == NULL)
4496 errx(EX_USAGE, "invalid \"or\" block\n");
4500 case TOK_STARTBRACE:
4502 errx(EX_USAGE, "+nested \"(\" not allowed\n");
4508 errx(EX_USAGE, "+missing \")\"\n");
4514 fill_cmd(cmd, O_IN, 0, 0);
4518 cmd->len ^= F_NOT; /* toggle F_NOT */
4519 fill_cmd(cmd, O_IN, 0, 0);
4523 fill_cmd(cmd, O_DIVERTED, 0, 3);
4526 case TOK_DIVERTEDLOOPBACK:
4527 fill_cmd(cmd, O_DIVERTED, 0, 1);
4530 case TOK_DIVERTEDOUTPUT:
4531 fill_cmd(cmd, O_DIVERTED, 0, 2);
4535 fill_cmd(cmd, O_FRAG, 0, 0);
4539 fill_cmd(cmd, O_LAYER2, 0, 0);
4545 NEED1("recv, xmit, via require interface name"
4547 fill_iface((ipfw_insn_if *)cmd, av[0], cblen, tstate);
4549 if (F_LEN(cmd) == 0) /* not a valid address */
4552 cmd->opcode = O_XMIT;
4553 else if (i == TOK_RECV)
4554 cmd->opcode = O_RECV;
4555 else if (i == TOK_VIA)
4556 cmd->opcode = O_VIA;
4560 NEED1("icmptypes requires list of types");
4561 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
4565 case TOK_ICMP6TYPES:
4566 NEED1("icmptypes requires list of types");
4567 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
4572 NEED1("ipttl requires TTL");
4573 if (strpbrk(*av, "-,")) {
4574 if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
4575 errx(EX_DATAERR, "invalid ipttl %s", *av);
4577 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
4582 NEED1("ipid requires id");
4583 if (strpbrk(*av, "-,")) {
4584 if (!add_ports(cmd, *av, 0, O_IPID, cblen))
4585 errx(EX_DATAERR, "invalid ipid %s", *av);
4587 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
4592 NEED1("iplen requires length");
4593 if (strpbrk(*av, "-,")) {
4594 if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
4595 errx(EX_DATAERR, "invalid ip len %s", *av);
4597 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
4602 NEED1("ipver requires version");
4603 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
4607 case TOK_IPPRECEDENCE:
4608 NEED1("ipprecedence requires value");
4609 fill_cmd(cmd, O_IPPRECEDENCE, 0,
4610 (strtoul(*av, NULL, 0) & 7) << 5);
4615 NEED1("missing DSCP code");
4616 fill_dscp(cmd, *av, cblen);
4621 NEED1("missing argument for ipoptions");
4622 fill_flags_cmd(cmd, O_IPOPT, f_ipopts, *av);
4627 NEED1("missing argument for iptos");
4628 fill_flags_cmd(cmd, O_IPTOS, f_iptos, *av);
4633 NEED1("uid requires argument");
4639 cmd->opcode = O_UID;
4640 uid = strtoul(*av, &end, 0);
4641 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
4643 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
4644 cmd32->d[0] = pwd->pw_uid;
4645 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4651 NEED1("gid requires argument");
4657 cmd->opcode = O_GID;
4658 gid = strtoul(*av, &end, 0);
4659 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
4661 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
4662 cmd32->d[0] = grp->gr_gid;
4663 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4669 NEED1("jail requires argument");
4674 cmd->opcode = O_JAIL;
4676 * If av is a number, then we'll just pass it as-is. If
4677 * it's a name, try to resolve that to a jid.
4679 * We save the jail_getid(3) call for a fallback because
4680 * it entails an unconditional trip to the kernel to
4681 * either validate a jid or resolve a name to a jid.
4682 * This specific token doesn't currently require a
4683 * jid to be an active jail, so we save a transition
4684 * by simply using a number that we're given.
4686 jid = strtoul(*av, &end, 10);
4688 jid = jail_getid(*av);
4690 errx(EX_DATAERR, "%s", jail_errmsg);
4692 cmd32->d[0] = (uint32_t)jid;
4693 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4699 fill_cmd(cmd, O_ESTAB, 0, 0);
4703 fill_cmd(cmd, O_TCPFLAGS, 0,
4704 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
4707 case TOK_TCPDATALEN:
4708 NEED1("tcpdatalen requires length");
4709 if (strpbrk(*av, "-,")) {
4710 if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
4711 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
4713 fill_cmd(cmd, O_TCPDATALEN, 0,
4714 strtoul(*av, NULL, 0));
4719 NEED1("missing argument for tcpoptions");
4720 fill_flags_cmd(cmd, O_TCPOPTS, f_tcpopts, *av);
4726 NEED1("tcpseq/tcpack requires argument");
4727 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
4728 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
4729 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
4735 NEED1("tcpmss/tcpwin requires size");
4736 if (strpbrk(*av, "-,")) {
4737 if (add_ports(cmd, *av, 0,
4738 i == TOK_TCPWIN ? O_TCPWIN : O_TCPMSS,
4740 errx(EX_DATAERR, "invalid %s size %s",
4743 fill_cmd(cmd, i == TOK_TCPWIN ? O_TCPWIN :
4744 O_TCPMSS, 0, strtoul(*av, NULL, 0));
4749 NEED1("missing argument for tcpflags");
4750 cmd->opcode = O_TCPFLAGS;
4751 fill_flags_cmd(cmd, O_TCPFLAGS, f_tcpflags, *av);
4756 case TOK_RECORDSTATE: {
4760 errx(EX_USAGE, "keep-state or record-state cannot be part "
4763 errx(EX_USAGE, "only one of keep-state, record-state, "
4764 " limit and set-limit is allowed");
4765 if (*av != NULL && *av[0] == ':') {
4766 if (state_check_name(*av + 1) != 0)
4768 "Invalid state name %s", *av);
4769 uidx = pack_object(tstate, *av + 1,
4770 IPFW_TLV_STATE_NAME);
4773 uidx = pack_object(tstate, default_state_name,
4774 IPFW_TLV_STATE_NAME);
4776 have_rstate = i == TOK_RECORDSTATE;
4777 fill_cmd(cmd, O_KEEP_STATE, 0, uidx);
4782 case TOK_SETLIMIT: {
4783 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
4788 "limit or set-limit cannot be part of an or block");
4790 errx(EX_USAGE, "only one of keep-state, record-state, "
4791 " limit and set-limit is allowed");
4793 have_rstate = i == TOK_SETLIMIT;
4795 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
4797 cmd->opcode = O_LIMIT;
4798 c->limit_mask = c->conn_limit = 0;
4800 while ( av[0] != NULL ) {
4801 if ((val = match_token(limit_masks, *av)) <= 0)
4803 c->limit_mask |= val;
4807 if (c->limit_mask == 0)
4808 errx(EX_USAGE, "limit: missing limit mask");
4810 GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
4811 TOK_LIMIT, rule_options);
4814 if (*av != NULL && *av[0] == ':') {
4815 if (state_check_name(*av + 1) != 0)
4817 "Invalid state name %s", *av);
4818 cmd->arg1 = pack_object(tstate, *av + 1,
4819 IPFW_TLV_STATE_NAME);
4822 cmd->arg1 = pack_object(tstate,
4823 default_state_name, IPFW_TLV_STATE_NAME);
4828 NEED1("missing protocol");
4829 if (add_proto(cmd, *av, &proto)) {
4832 errx(EX_DATAERR, "invalid protocol ``%s''",
4837 NEED1("missing source IP");
4838 if (add_srcip(cmd, *av, cblen, tstate)) {
4844 NEED1("missing destination IP");
4845 if (add_dstip(cmd, *av, cblen, tstate)) {
4851 NEED1("missing source IP6");
4852 if (add_srcip6(cmd, *av, cblen, tstate)) {
4858 NEED1("missing destination IP6");
4859 if (add_dstip6(cmd, *av, cblen, tstate)) {
4865 NEED1("missing source port");
4866 if (_substrcmp(*av, "any") == 0 ||
4867 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4870 errx(EX_DATAERR, "invalid source port %s", *av);
4874 NEED1("missing destination port");
4875 if (_substrcmp(*av, "any") == 0 ||
4876 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4879 errx(EX_DATAERR, "invalid destination port %s",
4884 if (add_mac(cmd, av, cblen))
4889 NEED1("missing mac type");
4890 if (!add_mactype(cmd, *av, cblen))
4891 errx(EX_DATAERR, "invalid mac type %s", *av);
4895 case TOK_VERREVPATH:
4896 fill_cmd(cmd, O_VERREVPATH, 0, 0);
4899 case TOK_VERSRCREACH:
4900 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
4904 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
4908 fill_cmd(cmd, O_IPSEC, 0, 0);
4912 fill_cmd(cmd, O_IP6, 0, 0);
4916 fill_cmd(cmd, O_IP4, 0, 0);
4920 fill_ext6hdr( cmd, *av );
4925 if (proto != IPPROTO_IPV6 )
4926 errx( EX_USAGE, "flow-id filter is active "
4927 "only for ipv6 protocol\n");
4928 fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
4933 fill_comment(cmd, av, cblen);
4938 if (av[0] && strpbrk(*av, "-,")) {
4939 if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
4940 errx(EX_DATAERR, "tagged: invalid tag"
4946 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
4947 TOK_TAGGED, rule_options);
4948 fill_cmd(cmd, O_TAGGED, 0, tag);
4954 NEED1("fib requires fib number");
4955 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
4959 fill_cmd(cmd, O_SOCKARG, 0, 0);
4963 ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
4966 if (!av[0] || !av[1])
4967 errx(EX_USAGE, "format: lookup argument tablenum");
4968 cmd->opcode = O_IP_DST_LOOKUP;
4969 cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
4970 i = match_token(rule_options, *av);
4971 for (j = 0; lookup_key[j] >= 0 ; j++) {
4972 if (i == lookup_key[j])
4975 if (lookup_key[j] <= 0)
4976 errx(EX_USAGE, "format: cannot lookup on %s", *av);
4977 __PAST_END(c->d, 1) = j; // i converted to option
4980 if ((j = pack_table(tstate, *av)) == 0)
4981 errx(EX_DATAERR, "Invalid table name: %s", *av);
4988 NEED1("missing table name");
4989 if (strncmp(*av, "table(", 6) != 0)
4991 "enclose table name into \"table()\"");
4992 fill_table(cmd, *av, O_IP_FLOW_LOOKUP, tstate);
4996 case TOK_SKIPACTION:
4998 errx(EX_USAGE, "only one defer-action "
5001 fill_cmd(cmd, O_SKIP_ACTION, 0, 0);
5005 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
5007 if (F_LEN(cmd) > 0) { /* prepare to advance */
5009 cmd = next_cmd(cmd, &cblen);
5015 if (!have_state && have_skipcmd)
5016 warnx("Rule contains \"defer-immediate-action\" "
5017 "and doesn't contain any state-related options.");
5020 * Now copy stuff into the rule.
5021 * If we have a keep-state option, the first instruction
5022 * must be a PROBE_STATE (which is generated here).
5023 * If we have a LOG option, it was stored as the first command,
5024 * and now must be moved to the top of the action part.
5026 dst = (ipfw_insn *)rule->cmd;
5029 * First thing to write into the command stream is the match probability.
5031 if (match_prob != 1) { /* 1 means always match */
5032 dst->opcode = O_PROB;
5034 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
5039 * generate O_PROBE_STATE if necessary
5041 if (have_state && have_state->opcode != O_CHECK_STATE && !have_rstate) {
5042 fill_cmd(dst, O_PROBE_STATE, 0, have_state->arg1);
5043 dst = next_cmd(dst, &rblen);
5047 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG,
5050 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
5054 switch (src->opcode) {
5063 bcopy(src, dst, i * sizeof(uint32_t));
5069 * put back the have_state command as last opcode
5071 if (have_state && have_state->opcode != O_CHECK_STATE) {
5072 i = F_LEN(have_state);
5074 bcopy(have_state, dst, i * sizeof(uint32_t));
5079 * put back the have_skipcmd command as very last opcode
5082 i = F_LEN(have_skipcmd);
5084 bcopy(have_skipcmd, dst, i * sizeof(uint32_t));
5089 * start action section
5091 rule->act_ofs = dst - rule->cmd;
5093 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
5095 i = F_LEN(have_log);
5097 bcopy(have_log, dst, i * sizeof(uint32_t));
5101 i = F_LEN(have_altq);
5103 bcopy(have_altq, dst, i * sizeof(uint32_t));
5107 i = F_LEN(have_tag);
5109 bcopy(have_tag, dst, i * sizeof(uint32_t));
5114 * copy all other actions
5116 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
5119 bcopy(src, dst, i * sizeof(uint32_t));
5123 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
5124 *rbufsize = (char *)dst - (char *)rule;
5128 compare_ntlv(const void *_a, const void *_b)
5130 ipfw_obj_ntlv *a, *b;
5132 a = (ipfw_obj_ntlv *)_a;
5133 b = (ipfw_obj_ntlv *)_b;
5135 if (a->set < b->set)
5137 else if (a->set > b->set)
5140 if (a->idx < b->idx)
5142 else if (a->idx > b->idx)
5145 if (a->head.type < b->head.type)
5147 else if (a->head.type > b->head.type)
5154 * Provide kernel with sorted list of referenced objects
5157 object_sort_ctlv(ipfw_obj_ctlv *ctlv)
5160 qsort(ctlv + 1, ctlv->count, ctlv->objsize, compare_ntlv);
5168 compare_object_kntlv(const void *k, const void *v)
5170 ipfw_obj_ntlv *ntlv;
5171 struct object_kt key;
5173 key = *((struct object_kt *)k);
5174 ntlv = (ipfw_obj_ntlv *)v;
5176 if (key.uidx < ntlv->idx)
5178 else if (key.uidx > ntlv->idx)
5181 if (key.type < ntlv->head.type)
5183 else if (key.type > ntlv->head.type)
5190 * Finds object name in @ctlv by @idx and @type.
5191 * Uses the following facts:
5192 * 1) All TLVs are the same size
5193 * 2) Kernel implementation provides already sorted list.
5195 * Returns table name or NULL.
5198 object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx, uint16_t type)
5200 ipfw_obj_ntlv *ntlv;
5201 struct object_kt key;
5206 ntlv = bsearch(&key, (ctlv + 1), ctlv->count, ctlv->objsize,
5207 compare_object_kntlv);
5210 return (ntlv->name);
5216 table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx)
5219 return (object_search_ctlv(ctlv, idx, IPFW_TLV_TBL_NAME));
5223 * Adds one or more rules to ipfw chain.
5228 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
5229 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ] (*2) (*3)
5234 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
5235 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ]
5238 * Rules in reply are modified to store their actual ruleset number.
5240 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
5241 * according to their idx field and there has to be no duplicates.
5242 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
5243 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
5246 ipfw_add(char *av[])
5248 uint32_t rulebuf[1024];
5249 int rbufsize, default_off, tlen, rlen;
5252 struct ip_fw_rule *rule;
5254 ip_fw3_opheader *op3;
5255 ipfw_obj_ctlv *ctlv, *tstate;
5257 rbufsize = sizeof(rulebuf);
5258 memset(rulebuf, 0, rbufsize);
5259 memset(&ts, 0, sizeof(ts));
5261 /* Optimize case with no tables */
5262 default_off = sizeof(ipfw_obj_ctlv) + sizeof(ip_fw3_opheader);
5263 op3 = (ip_fw3_opheader *)rulebuf;
5264 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5265 rule = (struct ip_fw_rule *)(ctlv + 1);
5266 rbufsize -= default_off;
5268 compile_rule(av, (uint32_t *)rule, &rbufsize, &ts);
5269 /* Align rule size to u64 boundary */
5270 rlen = roundup2(rbufsize, sizeof(uint64_t));
5275 if (ts.count != 0) {
5276 /* Some tables. We have to alloc more data */
5277 tlen = ts.count * sizeof(ipfw_obj_ntlv);
5278 sz = default_off + sizeof(ipfw_obj_ctlv) + tlen + rlen;
5280 if ((tbuf = calloc(1, sz)) == NULL)
5281 err(EX_UNAVAILABLE, "malloc() failed for IP_FW_ADD");
5282 op3 = (ip_fw3_opheader *)tbuf;
5284 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5285 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
5286 ctlv->head.length = sizeof(ipfw_obj_ctlv) + tlen;
5287 ctlv->count = ts.count;
5288 ctlv->objsize = sizeof(ipfw_obj_ntlv);
5289 memcpy(ctlv + 1, ts.idx, tlen);
5290 object_sort_ctlv(ctlv);
5293 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
5294 ctlv->head.type = IPFW_TLV_RULE_LIST;
5295 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5297 memcpy(ctlv + 1, rule, rbufsize);
5299 /* Simply add header */
5300 sz = rlen + default_off;
5301 memset(ctlv, 0, sizeof(*ctlv));
5302 ctlv->head.type = IPFW_TLV_RULE_LIST;
5303 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5307 if (do_get3(IP_FW_XADD, op3, &sz) != 0)
5308 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_XADD");
5311 struct format_opts sfo;
5313 memset(&sfo, 0, sizeof(sfo));
5314 sfo.tstate = tstate;
5315 sfo.set_mask = (uint32_t)(-1);
5316 bp_alloc(&bp, 4096);
5317 show_static_rule(&co, &sfo, &bp, rule, NULL);
5318 printf("%s", bp.buf);
5330 * clear the counters or the log counters.
5331 * optname has the following values:
5332 * 0 (zero both counters and logging)
5333 * 1 (zero logging only)
5336 ipfw_zero(int ac, char *av[], int optname)
5340 char const *name = optname ? "RESETLOG" : "ZERO";
5344 optname = optname ? IP_FW_XRESETLOG : IP_FW_XZERO;
5348 /* clear all entries */
5349 memset(&rt, 0, sizeof(rt));
5350 rt.flags = IPFW_RCFLAG_ALL;
5351 if (do_range_cmd(optname, &rt) < 0)
5352 err(EX_UNAVAILABLE, "setsockopt(IP_FW_X%s)", name);
5354 printf("%s.\n", optname == IP_FW_XZERO ?
5355 "Accounting cleared":"Logging counts reset");
5362 if (isdigit(**av)) {
5363 arg = strtonum(*av, 0, 0xffff, &errstr);
5366 "invalid rule number %s\n", *av);
5367 memset(&rt, 0, sizeof(rt));
5368 rt.start_rule = arg;
5370 rt.flags |= IPFW_RCFLAG_RANGE;
5371 if (co.use_set != 0) {
5372 rt.set = co.use_set - 1;
5373 rt.flags |= IPFW_RCFLAG_SET;
5375 if (do_range_cmd(optname, &rt) != 0) {
5376 warn("rule %u: setsockopt(IP_FW_X%s)",
5378 failed = EX_UNAVAILABLE;
5379 } else if (rt.new_set == 0) {
5380 printf("Entry %d not found\n", arg);
5381 failed = EX_UNAVAILABLE;
5382 } else if (!co.do_quiet)
5383 printf("Entry %d %s.\n", arg,
5384 optname == IP_FW_XZERO ?
5385 "cleared" : "logging count reset");
5387 errx(EX_USAGE, "invalid rule number ``%s''", *av);
5391 if (failed != EX_OK)
5396 ipfw_flush(int force)
5400 if (!force && !co.do_quiet) { /* need to ask user */
5403 printf("Are you sure? [yn] ");
5406 c = toupper(getc(stdin));
5407 while (c != '\n' && getc(stdin) != '\n')
5409 return; /* and do not flush */
5410 } while (c != 'Y' && c != 'N');
5412 if (c == 'N') /* user said no */
5419 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
5420 memset(&rt, 0, sizeof(rt));
5421 if (co.use_set != 0) {
5422 rt.set = co.use_set - 1;
5423 rt.flags = IPFW_RCFLAG_SET;
5425 rt.flags = IPFW_RCFLAG_ALL;
5426 if (do_range_cmd(IP_FW_XDEL, &rt) != 0)
5427 err(EX_UNAVAILABLE, "setsockopt(IP_FW_XDEL)");
5429 printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
5432 static struct _s_x intcmds[] = {
5433 { "talist", TOK_TALIST },
5434 { "iflist", TOK_IFLIST },
5435 { "olist", TOK_OLIST },
5436 { "vlist", TOK_VLIST },
5440 static struct _s_x otypes[] = {
5441 { "EACTION", IPFW_TLV_EACTION },
5442 { "DYNSTATE", IPFW_TLV_STATE_NAME },
5447 lookup_eaction_name(ipfw_obj_ntlv *ntlv, int cnt, uint16_t type)
5453 for (i = 0; i < cnt; i++) {
5454 if (ntlv[i].head.type != IPFW_TLV_EACTION)
5456 if (IPFW_TLV_EACTION_NAME(ntlv[i].idx) != type)
5458 name = ntlv[i].name;
5465 ipfw_list_objects(int ac, char *av[])
5467 ipfw_obj_lheader req, *olh;
5468 ipfw_obj_ntlv *ntlv;
5473 memset(&req, 0, sizeof(req));
5475 if (do_get3(IP_FW_DUMP_SRVOBJECTS, &req.opheader, &sz) != 0)
5476 if (errno != ENOMEM)
5480 if ((olh = calloc(1, sz)) == NULL)
5484 if (do_get3(IP_FW_DUMP_SRVOBJECTS, &olh->opheader, &sz) != 0) {
5490 printf("Objects list:\n");
5492 printf("There are no objects\n");
5493 ntlv = (ipfw_obj_ntlv *)(olh + 1);
5494 for (i = 0; i < olh->count; i++) {
5495 name = match_value(otypes, ntlv->head.type);
5497 name = lookup_eaction_name(
5498 (ipfw_obj_ntlv *)(olh + 1), olh->count,
5501 printf(" kidx: %4d\ttype: %10d\tname: %s\n",
5502 ntlv->idx, ntlv->head.type, ntlv->name);
5504 printf(" kidx: %4d\ttype: %10s\tname: %s\n",
5505 ntlv->idx, name, ntlv->name);
5512 ipfw_internal_handler(int ac, char *av[])
5517 NEED1("internal cmd required");
5519 if ((tcmd = match_token(intcmds, *av)) == -1)
5520 errx(EX_USAGE, "invalid internal sub-cmd: %s", *av);
5524 ipfw_list_tifaces();
5527 ipfw_list_ta(ac, av);
5530 ipfw_list_objects(ac, av);
5533 ipfw_list_values(ac, av);
5539 ipfw_get_tracked_ifaces(ipfw_obj_lheader **polh)
5541 ipfw_obj_lheader req, *olh;
5544 memset(&req, 0, sizeof(req));
5547 if (do_get3(IP_FW_XIFLIST, &req.opheader, &sz) != 0) {
5548 if (errno != ENOMEM)
5553 if ((olh = calloc(1, sz)) == NULL)
5557 if (do_get3(IP_FW_XIFLIST, &olh->opheader, &sz) != 0) {
5567 ifinfo_cmp(const void *a, const void *b)
5569 ipfw_iface_info *ia, *ib;
5571 ia = (ipfw_iface_info *)a;
5572 ib = (ipfw_iface_info *)b;
5574 return (stringnum_cmp(ia->ifname, ib->ifname));
5578 * Retrieves table list from kernel,
5579 * optionally sorts it and calls requested function for each table.
5580 * Returns 0 on success.
5585 ipfw_obj_lheader *olh;
5586 ipfw_iface_info *info;
5589 if ((error = ipfw_get_tracked_ifaces(&olh)) != 0)
5590 err(EX_OSERR, "Unable to request ipfw tracked interface list");
5593 qsort(olh + 1, olh->count, olh->objsize, ifinfo_cmp);
5595 info = (ipfw_iface_info *)(olh + 1);
5596 for (i = 0; i < olh->count; i++) {
5597 if (info->flags & IPFW_IFFLAG_RESOLVED)
5598 printf("%s ifindex: %d refcount: %u changes: %u\n",
5599 info->ifname, info->ifindex, info->refcnt,
5602 printf("%s ifindex: unresolved refcount: %u changes: %u\n",
5603 info->ifname, info->refcnt, info->gencnt);
5604 info = (ipfw_iface_info *)((caddr_t)info + olh->objsize);