2 * Copyright (c) 2002-2003 Luigi Rizzo
3 * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
4 * Copyright (c) 1994 Ugen J.S.Antsilevich
6 * Idea and grammar partially left from:
7 * Copyright (c) 1993 Daniel Boulet
9 * Redistribution and use in source forms, with and without modification,
10 * are permitted provided that this entire comment appears intact.
12 * Redistribution in binary form may occur without any restrictions.
13 * Obviously, it would be nice if you gave credit where credit is due
14 * but requiring it would be too onerous.
16 * This software is provided ``AS IS'' without any warranties of any kind.
18 * NEW command line interface for IP firewall facility
23 #include <sys/types.h>
24 #include <sys/param.h>
25 #include <sys/socket.h>
26 #include <sys/sockio.h>
27 #include <sys/sysctl.h>
44 #include <time.h> /* ctime */
45 #include <timeconv.h> /* _long_to_time */
48 #include <stddef.h> /* offsetof */
50 #include <net/ethernet.h>
51 #include <net/if.h> /* only IFNAMSIZ */
52 #include <netinet/in.h>
53 #include <netinet/in_systm.h> /* only n_short, n_long */
54 #include <netinet/ip.h>
55 #include <netinet/ip_icmp.h>
56 #include <netinet/ip_fw.h>
57 #include <netinet/tcp.h>
58 #include <arpa/inet.h>
60 struct cmdline_opts g_co; /* global options */
66 int show_time; /* show timestamp */
67 uint32_t set_mask; /* enabled sets mask */
68 uint32_t flags; /* request flags */
69 uint32_t first; /* first rule to request */
70 uint32_t last; /* last rule to request */
71 uint32_t dcnt; /* number of dynamic states */
72 ipfw_obj_ctlv *tstate; /* table state data */
75 int resvd_set_number = RESVD_SET;
77 static int ipfw_socket = -1;
79 #define CHECK_LENGTH(v, len) do { \
81 errx(EX_DATAERR, "Rule too long"); \
84 * Check if we have enough space in cmd buffer. Note that since
85 * first 8? u32 words are reserved by reserved header, full cmd
86 * buffer can't be used, so we need to protect from buffer overrun
87 * only. At the beginning, cblen is less than actual buffer size by
88 * size of ipfw_insn_u32 instruction + 1 u32 work. This eliminates need
89 * for checking small instructions fitting in given range.
90 * We also (ab)use the fact that ipfw_insn is always the first field
91 * for any custom instruction.
93 #define CHECK_CMDLEN CHECK_LENGTH(cblen, F_LEN((ipfw_insn *)cmd))
95 #define GET_UINT_ARG(arg, min, max, tok, s_x) do { \
97 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
98 if (_substrcmp(*av, "tablearg") == 0) { \
107 _xval = strtol(*av, &end, 10); \
109 if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
110 errx(EX_DATAERR, "%s: invalid argument: %s", \
111 match_value(s_x, tok), *av); \
113 if (errno == ERANGE || _xval < min || _xval > max) \
114 errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
115 match_value(s_x, tok), min, max, *av); \
117 if (_xval == IP_FW_TARG) \
118 errx(EX_DATAERR, "%s: illegal argument value: %s", \
119 match_value(s_x, tok), *av); \
124 static struct _s_x f_tcpflags[] = {
135 static struct _s_x f_tcpopts[] = {
136 { "mss", IP_FW_TCPOPT_MSS },
137 { "maxseg", IP_FW_TCPOPT_MSS },
138 { "window", IP_FW_TCPOPT_WINDOW },
139 { "sack", IP_FW_TCPOPT_SACK },
140 { "ts", IP_FW_TCPOPT_TS },
141 { "timestamp", IP_FW_TCPOPT_TS },
142 { "cc", IP_FW_TCPOPT_CC },
148 * IP options span the range 0 to 255 so we need to remap them
149 * (though in fact only the low 5 bits are significant).
151 static struct _s_x f_ipopts[] = {
152 { "ssrr", IP_FW_IPOPT_SSRR},
153 { "lsrr", IP_FW_IPOPT_LSRR},
154 { "rr", IP_FW_IPOPT_RR},
155 { "ts", IP_FW_IPOPT_TS},
160 static struct _s_x f_iptos[] = {
161 { "lowdelay", IPTOS_LOWDELAY},
162 { "throughput", IPTOS_THROUGHPUT},
163 { "reliability", IPTOS_RELIABILITY},
164 { "mincost", IPTOS_MINCOST},
165 { "congestion", IPTOS_ECN_CE},
166 { "ecntransport", IPTOS_ECN_ECT0},
167 { "ip tos option", 0},
171 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, const char *name, int otype);
399 static uint16_t pack_table(struct tidx *tstate, const 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, const char *format, ...)
464 va_start(args, format);
466 i = vsnprintf(b->ptr, b->avail, format, args);
469 if (i < 0 || (size_t)i > b->avail) {
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, void *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,
729 const char *delimiter)
735 for (sz = 0, pt = table ; pt->s != NULL; pt++) {
736 l = snprintf(buf + sz, bufsize - sz, "%s%s",
737 (sz == 0) ? "" : delimiter, pt->s);
748 * helper function to process a set of flags and set bits in the
752 fill_flags(struct _s_x *flags, char *p, char **e, uint32_t *set,
755 char *q; /* points to the separator */
757 uint32_t *which; /* mask we are working on */
768 val = match_token(flags, p);
774 *which |= (uint32_t)val;
781 print_flags_buffer(char *buf, size_t sz, struct _s_x *list, uint32_t set)
783 char const *comma = "";
786 for (i = 0; list[i].x != 0; i++) {
787 if ((set & list[i].x) == 0)
791 l = snprintf(buf, sz, "%s%s", comma, list[i].s);
792 if (l < 0 || (size_t)l >= sz)
801 * _substrcmp takes two strings and returns 1 if they do not match,
802 * and 0 if they match exactly or the first string is a sub-string
803 * of the second. A warning is printed to stderr in the case that the
804 * first string is a sub-string of the second.
806 * This function will be removed in the future through the usual
807 * deprecation process.
810 _substrcmp(const char *str1, const char* str2)
813 if (strncmp(str1, str2, strlen(str1)) != 0)
816 if (strlen(str1) != strlen(str2))
817 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
823 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
824 * and 0 if they match exactly or the second string is a sub-string
825 * of the first. A warning is printed to stderr in the case that the
826 * first string does not match the third.
828 * This function exists to warn about the bizarre construction
829 * strncmp(str, "by", 2) which is used to allow people to use a shortcut
830 * for "bytes". The problem is that in addition to accepting "by",
831 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
832 * other string beginning with "by".
834 * This function will be removed in the future through the usual
835 * deprecation process.
838 _substrcmp2(const char *str1, const char* str2, const char* str3)
841 if (strncmp(str1, str2, strlen(str2)) != 0)
844 if (strcmp(str1, str3) != 0)
845 warnx("DEPRECATED: '%s' matched '%s'",
851 * prints one port, symbolic or numeric
854 print_port(struct buf_pr *bp, int proto, uint16_t port)
857 if (proto == IPPROTO_ETHERTYPE) {
860 if (g_co.do_resolv && (s = match_value(ether_types, port)) )
861 bprintf(bp, "%s", s);
863 bprintf(bp, "0x%04x", port);
865 struct servent *se = NULL;
866 if (g_co.do_resolv) {
867 struct protoent *pe = getprotobynumber(proto);
869 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
872 bprintf(bp, "%s", se->s_name);
874 bprintf(bp, "%d", port);
878 static struct _s_x _port_name[] = {
879 {"dst-port", O_IP_DSTPORT},
880 {"src-port", O_IP_SRCPORT},
884 {"mac-type", O_MAC_TYPE},
885 {"tcpdatalen", O_TCPDATALEN},
886 {"tcpmss", O_TCPMSS},
887 {"tcpwin", O_TCPWIN},
888 {"tagged", O_TAGGED},
893 * Print the values in a list 16-bit items of the types above.
894 * XXX todo: add support for mask.
897 print_newports(struct buf_pr *bp, const ipfw_insn_u16 *cmd, int proto, int opcode)
899 const uint16_t *p = cmd->ports;
904 sep = match_value(_port_name, opcode);
907 bprintf(bp, " %s", sep);
910 for (i = F_LEN((const ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
911 bprintf(bp, "%s", sep);
912 print_port(bp, proto, p[0]);
915 print_port(bp, proto, p[1]);
922 * Like strtol, but also translates service names into port numbers
923 * for some protocols.
925 * proto == -1 disables the protocol check;
926 * proto == IPPROTO_ETHERTYPE looks up an internal table
927 * proto == <some value in /etc/protocols> matches the values there.
928 * Returns *end == s in case the parameter is not found.
931 strtoport(char *s, char **end, int base, int proto)
937 *end = s; /* default - not found */
939 return 0; /* not found */
942 return strtol(s, end, base);
945 * find separator. '\\' escapes the next char.
947 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\' ||
948 *s1 == '_' || *s1 == '.') ; s1++)
949 if (*s1 == '\\' && s1[1] != '\0')
952 buf = safe_calloc(s1 - s + 1, 1);
955 * copy into a buffer skipping backslashes
957 for (p = s, i = 0; p != s1 ; p++)
962 if (proto == IPPROTO_ETHERTYPE) {
963 i = match_token(ether_types, buf);
965 if (i != -1) { /* found */
970 struct protoent *pe = NULL;
974 pe = getprotobynumber(proto);
976 se = getservbyname(buf, pe ? pe->p_name : NULL);
980 return ntohs(se->s_port);
983 return 0; /* not found */
987 * Fill the body of the command with the list of port ranges.
990 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
992 uint16_t a, b, *p = cmd->ports;
997 a = strtoport(av, &s, 0, proto);
998 if (s == av) /* empty or invalid argument */
1001 CHECK_LENGTH(cblen, i + 2);
1004 case '-': /* a range */
1006 b = strtoport(av, &s, 0, proto);
1007 /* Reject expressions like '1-abc' or '1-2-3'. */
1008 if (s == av || (*s != ',' && *s != '\0'))
1013 case ',': /* comma separated list */
1018 warnx("port list: invalid separator <%c> in <%s>",
1028 if (i + 1 > F_LEN_MASK)
1029 errx(EX_DATAERR, "too many ports/ranges\n");
1030 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
1036 * Fill the body of the command with the list of DiffServ codepoints.
1039 fill_dscp(ipfw_insn *cmd, char *av, int cblen)
1041 uint32_t *low, *high;
1045 cmd->opcode = O_DSCP;
1046 cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
1050 low = (uint32_t *)(cmd + 1);
1063 if ((code = match_token(f_ipdscp, s)) == -1)
1064 errx(EX_DATAERR, "Unknown DSCP code");
1066 code = strtoul(s, NULL, 10);
1067 if (code < 0 || code > 63)
1068 errx(EX_DATAERR, "Invalid DSCP value");
1072 *high |= 1 << (code - 32);
1080 static struct _s_x icmpcodes[] = {
1081 { "net", ICMP_UNREACH_NET },
1082 { "host", ICMP_UNREACH_HOST },
1083 { "protocol", ICMP_UNREACH_PROTOCOL },
1084 { "port", ICMP_UNREACH_PORT },
1085 { "needfrag", ICMP_UNREACH_NEEDFRAG },
1086 { "srcfail", ICMP_UNREACH_SRCFAIL },
1087 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
1088 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
1089 { "isolated", ICMP_UNREACH_ISOLATED },
1090 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
1091 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
1092 { "tosnet", ICMP_UNREACH_TOSNET },
1093 { "toshost", ICMP_UNREACH_TOSHOST },
1094 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
1095 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
1096 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
1101 fill_reject_code(u_short *codep, char *str)
1106 val = strtoul(str, &s, 0);
1107 if (s == str || *s != '\0' || val >= 0x100)
1108 val = match_token(icmpcodes, str);
1110 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
1116 print_reject_code(struct buf_pr *bp, uint16_t code)
1120 if ((s = match_value(icmpcodes, code)) != NULL)
1121 bprintf(bp, "unreach %s", s);
1123 bprintf(bp, "unreach %u", code);
1127 * Returns the number of bits set (from left) in a contiguous bitmask,
1128 * or -1 if the mask is not contiguous.
1129 * XXX this needs a proper fix.
1130 * This effectively works on masks in big-endian (network) format.
1131 * when compiled on little endian architectures.
1133 * First bit is bit 7 of the first byte -- note, for MAC addresses,
1134 * the first bit on the wire is bit 0 of the first byte.
1135 * len is the max length in bits.
1138 contigmask(const uint8_t *p, int len)
1142 for (i=0; i<len ; i++)
1143 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
1145 for (n=i+1; n < len; n++)
1146 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
1147 return -1; /* mask not contiguous */
1152 * print flags set/clear in the two bitmasks passed as parameters.
1153 * There is a specialized check for f_tcpflags.
1156 print_flags(struct buf_pr *bp, char const *name, const ipfw_insn *cmd,
1159 char const *comma = "";
1161 uint8_t set = cmd->arg1 & 0xff;
1162 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
1164 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
1165 bprintf(bp, " setup");
1169 bprintf(bp, " %s ", name);
1170 for (i=0; list[i].x != 0; i++) {
1171 if (set & list[i].x) {
1173 bprintf(bp, "%s%s", comma, list[i].s);
1176 if (clear & list[i].x) {
1177 clear &= ~list[i].x;
1178 bprintf(bp, "%s!%s", comma, list[i].s);
1186 * Print the ip address contained in a command.
1189 print_ip(struct buf_pr *bp, const struct format_opts *fo,
1190 const ipfw_insn_ip *cmd)
1192 struct hostent *he = NULL;
1193 const struct in_addr *ia;
1194 const uint32_t *a = ((const ipfw_insn_u32 *)cmd)->d;
1195 uint32_t len = F_LEN((const ipfw_insn *)cmd);
1199 if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
1201 const char *arg = "<invalid>";
1203 if (d < sizeof(lookup_key)/sizeof(lookup_key[0]))
1204 arg = match_value(rule_options, lookup_key[d]);
1205 t = table_search_ctlv(fo->tstate,
1206 ((const ipfw_insn *)cmd)->arg1);
1207 bprintf(bp, "lookup %s %s", arg, t);
1210 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
1214 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
1215 cmd->o.opcode == O_IP_DST_LOOKUP) {
1216 t = table_search_ctlv(fo->tstate,
1217 ((const ipfw_insn *)cmd)->arg1);
1218 bprintf(bp, "table(%s", t);
1219 if (len == F_INSN_SIZE(ipfw_insn_u32))
1220 bprintf(bp, ",%u", *a);
1224 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
1225 const uint32_t *map = (const uint32_t *)&cmd->mask;
1226 struct in_addr addr;
1231 x = cmd->o.arg1 - 1;
1233 addr.s_addr = htonl(cmd->addr.s_addr);
1234 bprintf(bp, "%s/%d", inet_ntoa(addr),
1235 contigmask((uint8_t *)&x, 32));
1236 x = cmd->addr.s_addr;
1237 x &= 0xff; /* base */
1239 * Print bits and ranges.
1240 * Locate first bit set (i), then locate first bit unset (j).
1241 * If we have 3+ consecutive bits set, then print them as a
1242 * range, otherwise only print the initial bit and rescan.
1244 for (i=0; i < cmd->o.arg1; i++)
1245 if (map[i/32] & (1<<(i & 31))) {
1246 for (j=i+1; j < cmd->o.arg1; j++)
1247 if (!(map[ j/32] & (1<<(j & 31))))
1249 bprintf(bp, "%c%d", comma, i+x);
1250 if (j>i+2) { /* range has at least 3 elements */
1251 bprintf(bp, "-%d", j-1+x);
1260 * len == 2 indicates a single IP, whereas lists of 1 or more
1261 * addr/mask pairs have len = (2n+1). We convert len to n so we
1262 * use that to count the number of entries.
1264 for (len = len / 2; len > 0; len--, a += 2) {
1265 int mb = /* mask length */
1266 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1267 32 : contigmask((const uint8_t *)&(a[1]), 32);
1268 if (mb == 32 && g_co.do_resolv)
1269 he = gethostbyaddr((const char *)&(a[0]), sizeof(in_addr_t),
1271 if (he != NULL) /* resolved to name */
1272 bprintf(bp, "%s", he->h_name);
1273 else if (mb == 0) /* any */
1275 else { /* numeric IP followed by some kind of mask */
1276 ia = (const struct in_addr *)&a[0];
1277 bprintf(bp, "%s", inet_ntoa(*ia));
1279 ia = (const struct in_addr *)&a[1];
1280 bprintf(bp, ":%s", inet_ntoa(*ia));
1282 bprintf(bp, "/%d", mb);
1290 * prints a MAC address/mask pair
1293 format_mac(struct buf_pr *bp, const uint8_t *addr, const uint8_t *mask)
1295 int l = contigmask(mask, 48);
1298 bprintf(bp, " any");
1300 bprintf(bp, " %02x:%02x:%02x:%02x:%02x:%02x",
1301 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1303 bprintf(bp, "&%02x:%02x:%02x:%02x:%02x:%02x",
1304 mask[0], mask[1], mask[2],
1305 mask[3], mask[4], mask[5]);
1307 bprintf(bp, "/%d", l);
1312 print_mac(struct buf_pr *bp, const ipfw_insn_mac *mac)
1315 bprintf(bp, " MAC");
1316 format_mac(bp, mac->addr, mac->mask);
1317 format_mac(bp, mac->addr + 6, mac->mask + 6);
1321 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1330 type = strtoul(av, &av, 0);
1332 if (*av != ',' && *av != '\0')
1333 errx(EX_DATAERR, "invalid ICMP type");
1336 errx(EX_DATAERR, "ICMP type out of range");
1338 cmd->d[0] |= 1 << type;
1340 cmd->o.opcode = O_ICMPTYPE;
1341 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1345 print_icmptypes(struct buf_pr *bp, const ipfw_insn_u32 *cmd)
1350 bprintf(bp, " icmptypes");
1351 for (i = 0; i < 32; i++) {
1352 if ( (cmd->d[0] & (1 << (i))) == 0)
1354 bprintf(bp, "%c%d", sep, i);
1360 print_dscp(struct buf_pr *bp, const ipfw_insn_u32 *cmd)
1367 bprintf(bp, " dscp");
1370 if (*v & (1 << i)) {
1371 if ((code = match_value(f_ipdscp, i)) != NULL)
1372 bprintf(bp, "%c%s", sep, code);
1374 bprintf(bp, "%c%d", sep, i);
1378 if ((++i % 32) == 0)
1383 #define insntod(cmd, type) ((const ipfw_insn_ ## type *)(cmd))
1385 struct ip_fw_rule *rule;
1386 const ipfw_insn *eaction;
1389 #define HAVE_PROTO 0x0001
1390 #define HAVE_SRCIP 0x0002
1391 #define HAVE_DSTIP 0x0004
1392 #define HAVE_PROBE_STATE 0x0008
1398 init_show_state(struct show_state *state, struct ip_fw_rule *rule)
1401 state->printed = calloc(rule->cmd_len, sizeof(uint8_t));
1402 if (state->printed == NULL)
1405 state->eaction = NULL;
1408 state->or_block = 0;
1413 free_show_state(struct show_state *state)
1416 free(state->printed);
1420 is_printed_opcode(struct show_state *state, const ipfw_insn *cmd)
1423 return (state->printed[cmd - state->rule->cmd]);
1427 mark_printed(struct show_state *state, const ipfw_insn *cmd)
1430 state->printed[cmd - state->rule->cmd] = 1;
1434 print_limit_mask(struct buf_pr *bp, const ipfw_insn_limit *limit)
1436 struct _s_x *p = limit_masks;
1437 char const *comma = " ";
1440 for (x = limit->limit_mask; p->x != 0; p++) {
1441 if ((x & p->x) == p->x) {
1443 bprintf(bp, "%s%s", comma, p->s);
1447 bprint_uint_arg(bp, " ", limit->conn_limit);
1451 print_instruction(struct buf_pr *bp, const struct format_opts *fo,
1452 struct show_state *state, const ipfw_insn *cmd)
1454 struct protoent *pe;
1460 if (is_printed_opcode(state, cmd))
1462 if ((cmd->len & F_OR) != 0 && state->or_block == 0)
1464 if (cmd->opcode != O_IN && (cmd->len & F_NOT) != 0)
1465 bprintf(bp, " not");
1467 switch (cmd->opcode) {
1469 d = 1.0 * insntod(cmd, u32)->d[0] / 0x7fffffff;
1470 bprintf(bp, "prob %f ", d);
1472 case O_PROBE_STATE: /* no need to print anything here */
1473 state->flags |= HAVE_PROBE_STATE;
1476 case O_IP_SRC_LOOKUP:
1480 if (state->flags & HAVE_SRCIP)
1481 bprintf(bp, " src-ip");
1482 print_ip(bp, fo, insntod(cmd, ip));
1485 case O_IP_DST_LOOKUP:
1489 if (state->flags & HAVE_DSTIP)
1490 bprintf(bp, " dst-ip");
1491 print_ip(bp, fo, insntod(cmd, ip));
1494 case O_IP6_SRC_MASK:
1496 if (state->flags & HAVE_SRCIP)
1497 bprintf(bp, " src-ip6");
1498 print_ip6(bp, insntod(cmd, ip6));
1501 case O_IP6_DST_MASK:
1503 if (state->flags & HAVE_DSTIP)
1504 bprintf(bp, " dst-ip6");
1505 print_ip6(bp, insntod(cmd, ip6));
1508 print_flow6id(bp, insntod(cmd, u32));
1512 print_newports(bp, insntod(cmd, u16), state->proto,
1513 (state->flags & (HAVE_SRCIP | HAVE_DSTIP)) ==
1514 (HAVE_SRCIP | HAVE_DSTIP) ? cmd->opcode: 0);
1517 pe = getprotobynumber(cmd->arg1);
1518 if (state->flags & HAVE_PROTO)
1519 bprintf(bp, " proto");
1521 bprintf(bp, " %s", pe->p_name);
1523 bprintf(bp, " %u", cmd->arg1);
1524 state->proto = cmd->arg1;
1527 print_mac(bp, insntod(cmd, mac));
1530 print_newports(bp, insntod(cmd, u16),
1531 IPPROTO_ETHERTYPE, cmd->opcode);
1534 bprintf(bp, " frag");
1537 bprintf(bp, " fib %u", cmd->arg1);
1540 bprintf(bp, " sockarg");
1543 bprintf(bp, cmd->len & F_NOT ? " out" : " in");
1546 switch (cmd->arg1) {
1548 bprintf(bp, " diverted");
1551 bprintf(bp, " diverted-output");
1554 bprintf(bp, " diverted-loopback");
1557 bprintf(bp, " diverted-?<%u>", cmd->arg1);
1562 bprintf(bp, " layer2");
1567 if (cmd->opcode == O_XMIT)
1569 else if (cmd->opcode == O_RECV)
1571 else /* if (cmd->opcode == O_VIA) */
1573 switch (insntod(cmd, if)->name[0]) {
1575 bprintf(bp, " %s %s", s,
1576 inet_ntoa(insntod(cmd, if)->p.ip));
1579 bprintf(bp, " %s table(%s)", s,
1580 table_search_ctlv(fo->tstate,
1581 insntod(cmd, if)->p.kidx));
1584 bprintf(bp, " %s %s", s,
1585 insntod(cmd, if)->name);
1588 case O_IP_FLOW_LOOKUP:
1589 s = table_search_ctlv(fo->tstate, cmd->arg1);
1590 bprintf(bp, " flow table(%s", s);
1591 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))
1592 bprintf(bp, ",%u", insntod(cmd, u32)->d[0]);
1601 if (F_LEN(cmd) == 1) {
1602 switch (cmd->opcode) {
1625 bprintf(bp, " %s %u", s, cmd->arg1);
1627 print_newports(bp, insntod(cmd, u16), 0,
1631 bprintf(bp, " ipver %u", cmd->arg1);
1633 case O_IPPRECEDENCE:
1634 bprintf(bp, " ipprecedence %u", cmd->arg1 >> 5);
1637 print_dscp(bp, insntod(cmd, u32));
1640 print_flags(bp, "ipoptions", cmd, f_ipopts);
1643 print_flags(bp, "iptos", cmd, f_iptos);
1646 print_icmptypes(bp, insntod(cmd, u32));
1649 bprintf(bp, " established");
1652 print_flags(bp, "tcpflags", cmd, f_tcpflags);
1655 print_flags(bp, "tcpoptions", cmd, f_tcpopts);
1658 bprintf(bp, " tcpack %d",
1659 ntohl(insntod(cmd, u32)->d[0]));
1662 bprintf(bp, " tcpseq %d",
1663 ntohl(insntod(cmd, u32)->d[0]));
1666 pwd = getpwuid(insntod(cmd, u32)->d[0]);
1668 bprintf(bp, " uid %s", pwd->pw_name);
1670 bprintf(bp, " uid %u",
1671 insntod(cmd, u32)->d[0]);
1674 grp = getgrgid(insntod(cmd, u32)->d[0]);
1676 bprintf(bp, " gid %s", grp->gr_name);
1678 bprintf(bp, " gid %u",
1679 insntod(cmd, u32)->d[0]);
1682 bprintf(bp, " jail %d", insntod(cmd, u32)->d[0]);
1685 bprintf(bp, " verrevpath");
1688 bprintf(bp, " versrcreach");
1691 bprintf(bp, " antispoof");
1694 bprintf(bp, " ipsec");
1697 bprintf(bp, " // %s", (const char *)(cmd + 1));
1700 if (state->flags & HAVE_PROBE_STATE)
1701 bprintf(bp, " keep-state");
1703 bprintf(bp, " record-state");
1705 object_search_ctlv(fo->tstate, cmd->arg1,
1706 IPFW_TLV_STATE_NAME));
1709 if (state->flags & HAVE_PROBE_STATE)
1710 bprintf(bp, " limit");
1712 bprintf(bp, " set-limit");
1713 print_limit_mask(bp, insntod(cmd, limit));
1715 object_search_ctlv(fo->tstate, cmd->arg1,
1716 IPFW_TLV_STATE_NAME));
1719 if (state->flags & HAVE_PROTO)
1720 bprintf(bp, " proto");
1721 bprintf(bp, " ip6");
1724 if (state->flags & HAVE_PROTO)
1725 bprintf(bp, " proto");
1726 bprintf(bp, " ip4");
1729 print_icmp6types(bp, insntod(cmd, u32));
1732 print_ext6hdr(bp, cmd);
1735 if (F_LEN(cmd) == 1)
1736 bprint_uint_arg(bp, " tagged ", cmd->arg1);
1738 print_newports(bp, insntod(cmd, u16),
1742 bprintf(bp, " defer-immediate-action");
1745 bprintf(bp, " [opcode %d len %d]", cmd->opcode,
1748 if (cmd->len & F_OR) {
1750 state->or_block = 1;
1751 } else if (state->or_block != 0) {
1753 state->or_block = 0;
1755 mark_printed(state, cmd);
1761 print_opcode(struct buf_pr *bp, struct format_opts *fo,
1762 struct show_state *state, int opcode)
1767 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
1768 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1769 /* We use zero opcode to print the rest of options */
1770 if (opcode >= 0 && cmd->opcode != opcode)
1773 * Skip O_NOP, when we printing the rest
1774 * of options, it will be handled separately.
1776 if (cmd->opcode == O_NOP && opcode != O_NOP)
1778 if (!print_instruction(bp, fo, state, cmd))
1786 print_fwd(struct buf_pr *bp, const ipfw_insn *cmd)
1788 char buf[INET6_ADDRSTRLEN + IF_NAMESIZE + 2];
1789 const ipfw_insn_sa6 *sa6;
1790 const ipfw_insn_sa *sa;
1793 if (cmd->opcode == O_FORWARD_IP) {
1794 sa = insntod(cmd, sa);
1795 port = sa->sa.sin_port;
1796 if (sa->sa.sin_addr.s_addr == INADDR_ANY)
1797 bprintf(bp, "fwd tablearg");
1799 bprintf(bp, "fwd %s", inet_ntoa(sa->sa.sin_addr));
1801 sa6 = insntod(cmd, sa6);
1802 port = sa6->sa.sin6_port;
1803 bprintf(bp, "fwd ");
1804 if (getnameinfo((const struct sockaddr *)&sa6->sa,
1805 sizeof(struct sockaddr_in6), buf, sizeof(buf), NULL, 0,
1806 NI_NUMERICHOST) == 0)
1807 bprintf(bp, "%s", buf);
1810 bprintf(bp, ",%u", port);
1814 print_action_instruction(struct buf_pr *bp, const struct format_opts *fo,
1815 struct show_state *state, const ipfw_insn *cmd)
1819 if (is_printed_opcode(state, cmd))
1821 switch (cmd->opcode) {
1823 bprintf(bp, "check-state");
1825 s = object_search_ctlv(fo->tstate, cmd->arg1,
1826 IPFW_TLV_STATE_NAME);
1829 bprintf(bp, " :%s", s ? s: "any");
1832 bprintf(bp, "allow");
1835 bprintf(bp, "count");
1838 bprintf(bp, "deny");
1841 if (cmd->arg1 == ICMP_REJECT_RST)
1842 bprintf(bp, "reset");
1843 else if (cmd->arg1 == ICMP_REJECT_ABORT)
1844 bprintf(bp, "abort");
1845 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1846 bprintf(bp, "reject");
1848 print_reject_code(bp, cmd->arg1);
1851 if (cmd->arg1 == ICMP6_UNREACH_RST)
1852 bprintf(bp, "reset6");
1853 else if (cmd->arg1 == ICMP6_UNREACH_ABORT)
1854 bprintf(bp, "abort6");
1856 print_unreach6_code(bp, cmd->arg1);
1859 bprint_uint_arg(bp, "skipto ", cmd->arg1);
1862 bprint_uint_arg(bp, "pipe ", cmd->arg1);
1865 bprint_uint_arg(bp, "queue ", cmd->arg1);
1868 bprint_uint_arg(bp, "divert ", cmd->arg1);
1871 bprint_uint_arg(bp, "tee ", cmd->arg1);
1874 bprint_uint_arg(bp, "netgraph ", cmd->arg1);
1877 bprint_uint_arg(bp, "ngtee ", cmd->arg1);
1884 if (insntod(cmd, log)->max_log > 0)
1885 bprintf(bp, " log logamount %d",
1886 insntod(cmd, log)->max_log);
1888 bprintf(bp, " log");
1892 print_altq_cmd(bp, insntod(cmd, altq));
1896 bprint_uint_arg(bp, cmd->len & F_NOT ? " untag ":
1897 " tag ", cmd->arg1);
1900 if (cmd->arg1 != IP_FW_NAT44_GLOBAL)
1901 bprint_uint_arg(bp, "nat ", cmd->arg1);
1903 bprintf(bp, "nat global");
1906 if (cmd->arg1 == IP_FW_TARG)
1907 bprint_uint_arg(bp, "setfib ", cmd->arg1);
1909 bprintf(bp, "setfib %u", cmd->arg1 & 0x7FFF);
1911 case O_EXTERNAL_ACTION:
1913 * The external action can consists of two following
1914 * each other opcodes - O_EXTERNAL_ACTION and
1915 * O_EXTERNAL_INSTANCE. The first contains the ID of
1916 * name of external action. The second contains the ID
1917 * of name of external action instance.
1918 * NOTE: in case when external action has no named
1919 * instances support, the second opcode isn't needed.
1921 state->eaction = cmd;
1922 s = object_search_ctlv(fo->tstate, cmd->arg1,
1924 if (match_token(rule_eactions, s) != -1)
1925 bprintf(bp, "%s", s);
1927 bprintf(bp, "eaction %s", s);
1929 case O_EXTERNAL_INSTANCE:
1930 if (state->eaction == NULL)
1933 * XXX: we need to teach ipfw(9) to rewrite opcodes
1934 * in the user buffer on rule addition. When we add
1935 * the rule, we specify zero TLV type for
1936 * O_EXTERNAL_INSTANCE object. To show correct
1937 * rule after `ipfw add` we need to search instance
1938 * name with zero type. But when we do `ipfw show`
1939 * we calculate TLV type using IPFW_TLV_EACTION_NAME()
1942 s = object_search_ctlv(fo->tstate, cmd->arg1, 0);
1944 s = object_search_ctlv(fo->tstate,
1945 cmd->arg1, IPFW_TLV_EACTION_NAME(
1946 state->eaction->arg1));
1947 bprintf(bp, " %s", s);
1949 case O_EXTERNAL_DATA:
1950 if (state->eaction == NULL)
1953 * Currently we support data formatting only for
1954 * external data with datalen u16. For unknown data
1955 * print its size in bytes.
1957 if (cmd->len == F_INSN_SIZE(ipfw_insn))
1958 bprintf(bp, " %u", cmd->arg1);
1960 bprintf(bp, " %ubytes",
1961 cmd->len * sizeof(uint32_t));
1964 if (cmd->arg1 == IP_FW_TARG) {
1965 bprintf(bp, "setdscp tablearg");
1968 s = match_value(f_ipdscp, cmd->arg1 & 0x3F);
1970 bprintf(bp, "setdscp %s", s);
1972 bprintf(bp, "setdscp %u", cmd->arg1 & 0x3F);
1975 bprintf(bp, "reass");
1978 if (cmd->len & F_NOT)
1979 bprintf(bp, "return");
1981 bprint_uint_arg(bp, "call ", cmd->arg1);
1984 bprintf(bp, "** unrecognized action %d len %d ",
1985 cmd->opcode, cmd->len);
1987 mark_printed(state, cmd);
1994 print_action(struct buf_pr *bp, struct format_opts *fo,
1995 struct show_state *state, uint8_t opcode)
2000 for (l = state->rule->cmd_len - state->rule->act_ofs,
2001 cmd = ACTION_PTR(state->rule); l > 0;
2002 l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2003 if (cmd->opcode != opcode)
2005 if (!print_action_instruction(bp, fo, state, cmd))
2013 print_proto(struct buf_pr *bp, struct format_opts *fo,
2014 struct show_state *state)
2017 int l, proto, ip4, ip6;
2019 /* Count all O_PROTO, O_IP4, O_IP6 instructions. */
2020 proto = ip4 = ip6 = 0;
2021 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2022 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2023 switch (cmd->opcode) {
2029 if (cmd->len & F_OR)
2034 if (cmd->len & F_OR)
2041 if (proto == 0 && ip4 == 0 && ip6 == 0) {
2042 state->proto = IPPROTO_IP;
2043 state->flags |= HAVE_PROTO;
2047 /* To handle the case { ip4 or ip6 }, print opcode with F_OR first */
2050 cmd = print_opcode(bp, fo, state, ip4 > ip6 ? O_IP4: O_IP6);
2051 if (cmd != NULL && (cmd->len & F_OR))
2052 cmd = print_opcode(bp, fo, state, ip4 > ip6 ? O_IP6: O_IP4);
2053 if (cmd == NULL || (cmd->len & F_OR))
2054 for (l = proto; l > 0; l--) {
2055 cmd = print_opcode(bp, fo, state, O_PROTO);
2056 if (cmd == NULL || (cmd->len & F_OR) == 0)
2059 /* Initialize proto, it is used by print_newports() */
2060 state->flags |= HAVE_PROTO;
2061 if (state->proto == 0 && ip6 != 0)
2062 state->proto = IPPROTO_IPV6;
2066 match_opcode(int opcode, const int opcodes[], size_t nops)
2070 for (i = 0; i < nops; i++)
2071 if (opcode == opcodes[i])
2077 print_address(struct buf_pr *bp, struct format_opts *fo,
2078 struct show_state *state, const int opcodes[], size_t nops, int portop,
2082 int count, l, portcnt, pf;
2084 count = portcnt = 0;
2085 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2086 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2087 if (match_opcode(cmd->opcode, opcodes, nops))
2089 else if (cmd->opcode == portop)
2093 bprintf(bp, " any");
2094 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2095 l > 0 && count > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2096 if (!match_opcode(cmd->opcode, opcodes, nops))
2098 print_instruction(bp, fo, state, cmd);
2099 if ((cmd->len & F_OR) == 0)
2104 * If several O_IP_?PORT opcodes specified, leave them to the
2108 for (l = state->rule->act_ofs, cmd = state->rule->cmd, pf = 0;
2109 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2110 if (cmd->opcode != portop) {
2111 pf = (cmd->len & F_OR);
2114 /* Print opcode iff it is not in OR block. */
2115 if (pf == 0 && (cmd->len & F_OR) == 0)
2116 print_instruction(bp, fo, state, cmd);
2120 state->flags |= flag;
2123 static const int action_opcodes[] = {
2124 O_CHECK_STATE, O_ACCEPT, O_COUNT, O_DENY, O_REJECT,
2125 O_UNREACH6, O_SKIPTO, O_PIPE, O_QUEUE, O_DIVERT, O_TEE,
2126 O_NETGRAPH, O_NGTEE, O_FORWARD_IP, O_FORWARD_IP6, O_NAT,
2127 O_SETFIB, O_SETDSCP, O_REASS, O_CALLRETURN,
2128 /* keep the following opcodes at the end of the list */
2129 O_EXTERNAL_ACTION, O_EXTERNAL_INSTANCE, O_EXTERNAL_DATA
2132 static const int modifier_opcodes[] = {
2133 O_LOG, O_ALTQ, O_TAG
2136 static const int src_opcodes[] = {
2137 O_IP_SRC, O_IP_SRC_LOOKUP, O_IP_SRC_MASK, O_IP_SRC_ME,
2138 O_IP_SRC_SET, O_IP6_SRC, O_IP6_SRC_MASK, O_IP6_SRC_ME
2141 static const int dst_opcodes[] = {
2142 O_IP_DST, O_IP_DST_LOOKUP, O_IP_DST_MASK, O_IP_DST_ME,
2143 O_IP_DST_SET, O_IP6_DST, O_IP6_DST_MASK, O_IP6_DST_ME
2147 show_static_rule(struct cmdline_opts *co, struct format_opts *fo,
2148 struct buf_pr *bp, struct ip_fw_rule *rule, struct ip_fw_bcounter *cntr)
2150 static int twidth = 0;
2151 struct show_state state;
2155 /* Print # DISABLED or skip the rule */
2156 if ((fo->set_mask & (1 << rule->set)) == 0) {
2161 bprintf(bp, "# DISABLED ");
2163 if (init_show_state(&state, rule) != 0) {
2164 warn("init_show_state() failed");
2167 bprintf(bp, "%05u ", rule->rulenum);
2169 /* Print counters if enabled */
2170 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2171 pr_u64(bp, &cntr->pcnt, fo->pcwidth);
2172 pr_u64(bp, &cntr->bcnt, fo->bcwidth);
2175 /* Print timestamp */
2176 if (co->do_time == TIMESTAMP_NUMERIC)
2177 bprintf(bp, "%10u ", cntr->timestamp);
2178 else if (co->do_time == TIMESTAMP_STRING) {
2180 time_t t = (time_t)0;
2183 strcpy(timestr, ctime(&t));
2184 *strchr(timestr, '\n') = '\0';
2185 twidth = strlen(timestr);
2187 if (cntr->timestamp > 0) {
2188 t = _long_to_time(cntr->timestamp);
2190 strcpy(timestr, ctime(&t));
2191 *strchr(timestr, '\n') = '\0';
2192 bprintf(bp, "%s ", timestr);
2194 bprintf(bp, "%*s", twidth, " ");
2198 /* Print set number */
2200 bprintf(bp, "set %d ", rule->set);
2202 /* Print the optional "match probability" */
2203 cmd = print_opcode(bp, fo, &state, O_PROB);
2204 /* Print rule action */
2205 for (i = 0; i < nitems(action_opcodes); i++) {
2206 cmd = print_action(bp, fo, &state, action_opcodes[i]);
2209 /* Handle special cases */
2210 switch (cmd->opcode) {
2213 case O_EXTERNAL_ACTION:
2214 case O_EXTERNAL_INSTANCE:
2215 /* External action can have several instructions */
2220 /* Print rule modifiers */
2221 for (i = 0; i < nitems(modifier_opcodes); i++)
2222 print_action(bp, fo, &state, modifier_opcodes[i]);
2226 if (co->comment_only != 0)
2229 if (rule->flags & IPFW_RULE_JUSTOPTS) {
2230 state.flags |= HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP;
2234 print_proto(bp, fo, &state);
2235 if (co->do_compact != 0 && (rule->flags & IPFW_RULE_NOOPT))
2239 bprintf(bp, " from");
2240 print_address(bp, fo, &state, src_opcodes, nitems(src_opcodes),
2241 O_IP_SRCPORT, HAVE_SRCIP);
2243 /* Print destination */
2245 print_address(bp, fo, &state, dst_opcodes, nitems(dst_opcodes),
2246 O_IP_DSTPORT, HAVE_DSTIP);
2249 /* Print the rest of options */
2250 while (print_opcode(bp, fo, &state, -1))
2253 /* Print comment at the end */
2254 cmd = print_opcode(bp, fo, &state, O_NOP);
2255 if (co->comment_only != 0 && cmd == NULL)
2256 bprintf(bp, " // ...");
2258 free_show_state(&state);
2262 show_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2263 struct buf_pr *bp, ipfw_dyn_rule *d)
2265 struct protoent *pe;
2268 char buf[INET6_ADDRSTRLEN];
2270 if (d->expire == 0 && d->dyn_type != O_LIMIT_PARENT)
2273 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2274 bprintf(bp, "%05d", rulenum);
2275 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2277 pr_u64(bp, &d->pcnt, fo->pcwidth);
2278 pr_u64(bp, &d->bcnt, fo->bcwidth);
2279 bprintf(bp, "(%ds)", d->expire);
2281 switch (d->dyn_type) {
2282 case O_LIMIT_PARENT:
2283 bprintf(bp, " PARENT %d", d->count);
2286 bprintf(bp, " LIMIT");
2288 case O_KEEP_STATE: /* bidir, no mask */
2289 bprintf(bp, " STATE");
2293 if ((pe = getprotobynumber(d->id.proto)) != NULL)
2294 bprintf(bp, " %s", pe->p_name);
2296 bprintf(bp, " proto %u", d->id.proto);
2298 if (d->id.addr_type == 4) {
2299 a.s_addr = htonl(d->id.src_ip);
2300 bprintf(bp, " %s %d", inet_ntoa(a), d->id.src_port);
2302 a.s_addr = htonl(d->id.dst_ip);
2303 bprintf(bp, " <-> %s %d", inet_ntoa(a), d->id.dst_port);
2304 } else if (d->id.addr_type == 6) {
2305 bprintf(bp, " %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
2306 sizeof(buf)), d->id.src_port);
2307 bprintf(bp, " <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6,
2308 buf, sizeof(buf)), d->id.dst_port);
2310 bprintf(bp, " UNKNOWN <-> UNKNOWN");
2312 bprintf(bp, " :%s", object_search_ctlv(fo->tstate,
2313 d->kidx, IPFW_TLV_STATE_NAME));
2315 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
2316 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
2318 bprintf(bp, " state 0x%08x%s", d->state,
2319 d->state ? " ": ",");
2320 if (d->state & IPFW_DYN_ORPHANED)
2321 bprintf(bp, "ORPHANED,");
2322 if ((d->state & BOTH_SYN) == BOTH_SYN)
2323 bprintf(bp, "BOTH_SYN,");
2325 if (d->state & TH_SYN)
2326 bprintf(bp, "F_SYN,");
2327 if (d->state & (TH_SYN << 8))
2328 bprintf(bp, "R_SYN,");
2330 if ((d->state & BOTH_FIN) == BOTH_FIN)
2331 bprintf(bp, "BOTH_FIN,");
2333 if (d->state & TH_FIN)
2334 bprintf(bp, "F_FIN,");
2335 if (d->state & (TH_FIN << 8))
2336 bprintf(bp, "R_FIN,");
2338 bprintf(bp, " f_ack 0x%x, r_ack 0x%x", d->ack_fwd,
2344 do_range_cmd(int cmd, ipfw_range_tlv *rt)
2346 ipfw_range_header rh;
2349 memset(&rh, 0, sizeof(rh));
2350 memcpy(&rh.range, rt, sizeof(*rt));
2351 rh.range.head.length = sizeof(*rt);
2352 rh.range.head.type = IPFW_TLV_RANGE;
2355 if (do_get3(cmd, &rh.opheader, &sz) != 0)
2357 /* Save number of matched objects */
2358 rt->new_set = rh.range.new_set;
2363 * This one handles all set-related commands
2364 * ipfw set { show | enable | disable }
2366 * ipfw set move X to Y
2367 * ipfw set move rule X to Y
2370 ipfw_sets_handler(char *av[])
2381 memset(&rt, 0, sizeof(rt));
2384 errx(EX_USAGE, "set needs command");
2385 if (_substrcmp(*av, "show") == 0) {
2386 struct format_opts fo;
2387 ipfw_cfg_lheader *cfg;
2389 memset(&fo, 0, sizeof(fo));
2390 if (ipfw_get_config(&g_co, &fo, &cfg, &size) != 0)
2391 err(EX_OSERR, "requesting config failed");
2393 for (i = 0, msg = "disable"; i < RESVD_SET; i++)
2394 if ((cfg->set_mask & (1<<i)) == 0) {
2395 printf("%s %d", msg, i);
2398 msg = (cfg->set_mask != (uint32_t)-1) ? " enable" : "enable";
2399 for (i = 0; i < RESVD_SET; i++)
2400 if ((cfg->set_mask & (1<<i)) != 0) {
2401 printf("%s %d", msg, i);
2406 } else if (_substrcmp(*av, "swap") == 0) {
2408 if ( av[0] == NULL || av[1] == NULL )
2409 errx(EX_USAGE, "set swap needs 2 set numbers\n");
2410 rt.set = atoi(av[0]);
2411 rt.new_set = atoi(av[1]);
2412 if (!isdigit(*(av[0])) || rt.set > RESVD_SET)
2413 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2414 if (!isdigit(*(av[1])) || rt.new_set > RESVD_SET)
2415 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2416 i = do_range_cmd(IP_FW_SET_SWAP, &rt);
2417 } else if (_substrcmp(*av, "move") == 0) {
2419 if (av[0] && _substrcmp(*av, "rule") == 0) {
2420 rt.flags = IPFW_RCFLAG_RANGE; /* move rules to new set */
2424 cmd = IP_FW_SET_MOVE; /* Move set to new one */
2425 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
2426 av[3] != NULL || _substrcmp(av[1], "to") != 0)
2427 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2428 rulenum = atoi(av[0]);
2429 rt.new_set = atoi(av[2]);
2430 if (cmd == IP_FW_XMOVE) {
2431 rt.start_rule = rulenum;
2432 rt.end_rule = rulenum;
2435 rt.new_set = atoi(av[2]);
2436 if (!isdigit(*(av[0])) || (cmd == 3 && rt.set > RESVD_SET) ||
2437 (cmd == 2 && rt.start_rule == IPFW_DEFAULT_RULE) )
2438 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2439 if (!isdigit(*(av[2])) || rt.new_set > RESVD_SET)
2440 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2441 i = do_range_cmd(cmd, &rt);
2443 err(EX_OSERR, "failed to move %s",
2444 cmd == IP_FW_SET_MOVE ? "set": "rule");
2445 } else if (_substrcmp(*av, "disable") == 0 ||
2446 _substrcmp(*av, "enable") == 0 ) {
2447 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2450 masks[0] = masks[1] = 0;
2453 if (isdigit(**av)) {
2455 if (i < 0 || i > RESVD_SET)
2457 "invalid set number %d\n", i);
2458 masks[which] |= (1<<i);
2459 } else if (_substrcmp(*av, "disable") == 0)
2461 else if (_substrcmp(*av, "enable") == 0)
2465 "invalid set command %s\n", *av);
2468 if ( (masks[0] & masks[1]) != 0 )
2470 "cannot enable and disable the same set\n");
2473 rt.new_set = masks[1];
2474 i = do_range_cmd(IP_FW_SET_ENABLE, &rt);
2476 warn("set enable/disable: setsockopt(IP_FW_SET_ENABLE)");
2478 errx(EX_USAGE, "invalid set command %s\n", *av);
2482 ipfw_sysctl_handler(char *av[], int which)
2486 if (av[0] == NULL) {
2487 warnx("missing keyword to enable/disable\n");
2488 } else if (_substrcmp(*av, "firewall") == 0) {
2489 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2490 &which, sizeof(which));
2491 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
2492 &which, sizeof(which));
2493 } else if (_substrcmp(*av, "one_pass") == 0) {
2494 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2495 &which, sizeof(which));
2496 } else if (_substrcmp(*av, "debug") == 0) {
2497 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2498 &which, sizeof(which));
2499 } else if (_substrcmp(*av, "verbose") == 0) {
2500 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2501 &which, sizeof(which));
2502 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2503 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2504 &which, sizeof(which));
2506 } else if (_substrcmp(*av, "altq") == 0) {
2507 altq_set_enabled(which);
2510 warnx("unrecognize enable/disable keyword: %s\n", *av);
2514 typedef void state_cb(struct cmdline_opts *co, struct format_opts *fo,
2515 void *arg, void *state);
2518 prepare_format_dyn(struct cmdline_opts *co, struct format_opts *fo,
2519 void *arg __unused, void *_state)
2525 d = (ipfw_dyn_rule *)_state;
2526 /* Count _ALL_ states */
2529 if (fo->show_counters == 0)
2533 /* skip states from another set */
2534 bcopy((char *)&d->rule + sizeof(uint16_t), &set,
2536 if (set != co->use_set - 1)
2540 width = pr_u64(NULL, &d->pcnt, 0);
2541 if (width > fo->pcwidth)
2542 fo->pcwidth = width;
2544 width = pr_u64(NULL, &d->bcnt, 0);
2545 if (width > fo->bcwidth)
2546 fo->bcwidth = width;
2550 foreach_state(struct cmdline_opts *co, struct format_opts *fo,
2551 caddr_t base, size_t sz, state_cb dyn_bc, void *dyn_arg)
2557 ipfw_obj_ctlv *ctlv;
2563 ctlv = (ipfw_obj_ctlv *)base;
2564 switch (ctlv->head.type) {
2565 case IPFW_TLV_DYNSTATE_LIST:
2566 base += sizeof(*ctlv);
2567 sz -= sizeof(*ctlv);
2568 ttype = IPFW_TLV_DYN_ENT;
2577 tlv = (ipfw_obj_tlv *)base;
2578 if (tlv->type != ttype)
2581 fptr(co, fo, farg, tlv + 1);
2583 base += tlv->length;
2591 prepare_format_opts(struct cmdline_opts *co, struct format_opts *fo,
2592 ipfw_obj_tlv *rtlv, int rcnt, caddr_t dynbase, size_t dynsz)
2594 int bcwidth, pcwidth, width;
2596 struct ip_fw_bcounter *cntr;
2597 struct ip_fw_rule *r;
2601 if (fo->show_counters != 0) {
2602 for (n = 0; n < rcnt; n++,
2603 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2604 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2605 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2606 /* skip rules from another set */
2607 if (co->use_set && r->set != co->use_set - 1)
2610 /* packet counter */
2611 width = pr_u64(NULL, &cntr->pcnt, 0);
2612 if (width > pcwidth)
2616 width = pr_u64(NULL, &cntr->bcnt, 0);
2617 if (width > bcwidth)
2621 fo->bcwidth = bcwidth;
2622 fo->pcwidth = pcwidth;
2625 if (co->do_dynamic && dynsz > 0)
2626 foreach_state(co, fo, dynbase, dynsz, prepare_format_dyn, NULL);
2630 list_static_range(struct cmdline_opts *co, struct format_opts *fo,
2631 struct buf_pr *bp, ipfw_obj_tlv *rtlv, int rcnt)
2634 struct ip_fw_rule *r;
2635 struct ip_fw_bcounter *cntr;
2638 for (n = seen = 0; n < rcnt; n++,
2639 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2641 if ((fo->show_counters | fo->show_time) != 0) {
2642 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2643 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2646 r = (struct ip_fw_rule *)(rtlv + 1);
2648 if (r->rulenum > fo->last)
2650 if (co->use_set && r->set != co->use_set - 1)
2652 if (r->rulenum >= fo->first && r->rulenum <= fo->last) {
2653 show_static_rule(co, fo, bp, r, cntr);
2654 printf("%s", bp->buf);
2665 list_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2666 void *_arg, void *_state)
2673 d = (ipfw_dyn_rule *)_state;
2674 bp = (struct buf_pr *)_arg;
2676 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2677 if (rulenum > fo->last)
2680 bcopy((char *)&d->rule + sizeof(uint16_t),
2681 &set, sizeof(uint8_t));
2682 if (set != co->use_set - 1)
2685 if (rulenum >= fo->first) {
2686 show_dyn_state(co, fo, bp, d);
2687 printf("%s\n", bp->buf);
2693 list_dyn_range(struct cmdline_opts *co, struct format_opts *fo,
2694 struct buf_pr *bp, caddr_t base, size_t sz)
2697 sz = foreach_state(co, fo, base, sz, list_dyn_state, bp);
2702 ipfw_list(int ac, char *av[], int show_counters)
2704 ipfw_cfg_lheader *cfg;
2705 struct format_opts sfo;
2713 if (g_co.test_only) {
2714 fprintf(stderr, "Testing only, list disabled\n");
2718 dummynet_list(ac, av, show_counters);
2724 memset(&sfo, 0, sizeof(sfo));
2726 /* Determine rule range to request */
2728 for (lac = ac, lav = av; lac != 0; lac--) {
2729 rnum = strtoul(*lav++, &endptr, 10);
2730 if (sfo.first == 0 || rnum < sfo.first)
2734 rnum = strtoul(endptr + 1, &endptr, 10);
2735 if (sfo.last == 0 || rnum > sfo.last)
2740 /* get configuraion from kernel */
2742 sfo.show_counters = show_counters;
2743 sfo.show_time = g_co.do_time;
2744 if (g_co.do_dynamic != 2)
2745 sfo.flags |= IPFW_CFG_GET_STATIC;
2746 if (g_co.do_dynamic != 0)
2747 sfo.flags |= IPFW_CFG_GET_STATES;
2748 if ((sfo.show_counters | sfo.show_time) != 0)
2749 sfo.flags |= IPFW_CFG_GET_COUNTERS;
2750 if (ipfw_get_config(&g_co, &sfo, &cfg, &sz) != 0)
2751 err(EX_OSERR, "retrieving config failed");
2753 error = ipfw_show_config(&g_co, &sfo, cfg, sz, ac, av);
2762 ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
2763 ipfw_cfg_lheader *cfg, size_t sz, int ac, char *av[])
2768 int exitval = EX_OK;
2774 ipfw_obj_ctlv *ctlv, *tstate;
2775 ipfw_obj_tlv *rbase;
2778 * Handle tablenames TLV first, if any
2784 readsz = sizeof(*cfg);
2787 fo->set_mask = cfg->set_mask;
2789 ctlv = (ipfw_obj_ctlv *)(cfg + 1);
2790 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2791 object_sort_ctlv(ctlv);
2793 readsz += ctlv->head.length;
2794 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2797 if (cfg->flags & IPFW_CFG_GET_STATIC) {
2798 /* We've requested static rules */
2799 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2800 rbase = (ipfw_obj_tlv *)(ctlv + 1);
2802 readsz += ctlv->head.length;
2803 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2808 if ((cfg->flags & IPFW_CFG_GET_STATES) && (readsz != sz)) {
2809 /* We may have some dynamic states */
2810 dynsz = sz - readsz;
2811 /* Skip empty header */
2812 if (dynsz != sizeof(ipfw_obj_ctlv))
2813 dynbase = (caddr_t)ctlv;
2818 prepare_format_opts(co, fo, rbase, rcnt, dynbase, dynsz);
2819 bp_alloc(&bp, 4096);
2821 /* if no rule numbers were specified, list all rules */
2824 fo->last = IPFW_DEFAULT_RULE;
2825 if (cfg->flags & IPFW_CFG_GET_STATIC)
2826 list_static_range(co, fo, &bp, rbase, rcnt);
2828 if (co->do_dynamic && dynsz > 0) {
2829 printf("## Dynamic rules (%d %zu):\n", fo->dcnt,
2831 list_dyn_range(co, fo, &bp, dynbase, dynsz);
2838 /* display specific rules requested on command line */
2839 for (lac = ac, lav = av; lac != 0; lac--) {
2840 /* convert command line rule # */
2841 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2843 fo->last = strtoul(endptr + 1, &endptr, 10);
2846 warnx("invalid rule number: %s", *(lav - 1));
2850 if ((cfg->flags & IPFW_CFG_GET_STATIC) == 0)
2853 if (list_static_range(co, fo, &bp, rbase, rcnt) == 0) {
2854 /* give precedence to other error(s) */
2855 if (exitval == EX_OK)
2856 exitval = EX_UNAVAILABLE;
2857 if (fo->first == fo->last)
2858 warnx("rule %u does not exist", fo->first);
2860 warnx("no rules in range %u-%u",
2861 fo->first, fo->last);
2865 if (co->do_dynamic && dynsz > 0) {
2866 printf("## Dynamic rules:\n");
2867 for (lac = ac, lav = av; lac != 0; lac--) {
2868 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2870 fo->last = strtoul(endptr+1, &endptr, 10);
2872 /* already warned */
2874 list_dyn_range(co, fo, &bp, dynbase, dynsz);
2884 * Retrieves current ipfw configuration of given type
2885 * and stores its pointer to @pcfg.
2887 * Caller is responsible for freeing @pcfg.
2889 * Returns 0 on success.
2893 ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
2894 ipfw_cfg_lheader **pcfg, size_t *psize)
2896 ipfw_cfg_lheader *cfg;
2901 if (co->test_only != 0) {
2902 fprintf(stderr, "Testing only, list disabled\n");
2906 /* Start with some data size */
2910 for (i = 0; i < 16; i++) {
2913 if ((cfg = calloc(1, sz)) == NULL)
2916 cfg->flags = fo->flags;
2917 cfg->start_rule = fo->first;
2918 cfg->end_rule = fo->last;
2920 if (do_get3(IP_FW_XGET, &cfg->opheader, &sz) != 0) {
2921 if (errno != ENOMEM) {
2926 /* Buffer size is not enough. Try to increase */
2943 lookup_host (char *host, struct in_addr *ipaddr)
2947 if (!inet_aton(host, ipaddr)) {
2948 if ((he = gethostbyname(host)) == NULL)
2950 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2964 ipfw_check_object_name(const char *name)
2969 * Check that name is null-terminated and contains
2970 * valid symbols only. Valid mask is:
2971 * [a-zA-Z0-9\-_\.]{1,63}
2974 if (l == 0 || l >= 64)
2976 for (i = 0; i < l; i++) {
2978 if (isalpha(c) || isdigit(c) || c == '_' ||
2979 c == '-' || c == '.')
2986 static const char *default_state_name = "default";
2989 state_check_name(const char *name)
2992 if (ipfw_check_object_name(name) != 0)
2994 if (strcmp(name, "any") == 0)
3000 eaction_check_name(const char *name)
3003 if (ipfw_check_object_name(name) != 0)
3005 /* Restrict some 'special' names */
3006 if (match_token(rule_actions, name) != -1 &&
3007 match_token(rule_action_params, name) != -1)
3013 pack_object(struct tidx *tstate, const char *name, int otype)
3015 ipfw_obj_ntlv *ntlv;
3018 for (i = 0; i < tstate->count; i++) {
3019 if (strcmp(tstate->idx[i].name, name) != 0)
3021 if (tstate->idx[i].set != tstate->set)
3023 if (tstate->idx[i].head.type != otype)
3026 return (tstate->idx[i].idx);
3029 if (tstate->count + 1 > tstate->size) {
3031 tstate->idx = realloc(tstate->idx, tstate->size *
3032 sizeof(ipfw_obj_ntlv));
3033 if (tstate->idx == NULL)
3037 ntlv = &tstate->idx[i];
3038 memset(ntlv, 0, sizeof(ipfw_obj_ntlv));
3039 strlcpy(ntlv->name, name, sizeof(ntlv->name));
3040 ntlv->head.type = otype;
3041 ntlv->head.length = sizeof(ipfw_obj_ntlv);
3042 ntlv->set = tstate->set;
3043 ntlv->idx = ++tstate->counter;
3050 pack_table(struct tidx *tstate, const char *name)
3053 if (table_check_name(name) != 0)
3056 return (pack_object(tstate, name, IPFW_TLV_TBL_NAME));
3060 fill_table(struct _ipfw_insn *cmd, char *av, uint8_t opcode,
3061 struct tidx *tstate)
3063 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
3067 if ((p = strchr(av + 6, ')')) == NULL)
3068 errx(EX_DATAERR, "forgotten parenthesis: '%s'", av);
3070 p = strchr(av + 6, ',');
3074 if ((uidx = pack_table(tstate, av + 6)) == 0)
3075 errx(EX_DATAERR, "Invalid table name: %s", av + 6);
3077 cmd->opcode = opcode;
3080 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3081 d[0] = strtoul(p, NULL, 0);
3083 cmd->len |= F_INSN_SIZE(ipfw_insn);
3088 * fills the addr and mask fields in the instruction as appropriate from av.
3089 * Update length as appropriate.
3090 * The following formats are allowed:
3091 * me returns O_IP_*_ME
3092 * 1.2.3.4 single IP address
3093 * 1.2.3.4:5.6.7.8 address:mask
3094 * 1.2.3.4/24 address/mask
3095 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
3096 * We can have multiple comma-separated address/mask entries.
3099 fill_ip(ipfw_insn_ip *cmd, char *av, int cblen, struct tidx *tstate)
3102 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
3104 cmd->o.len &= ~F_LEN_MASK; /* zero len */
3106 if (_substrcmp(av, "any") == 0)
3109 if (_substrcmp(av, "me") == 0) {
3110 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
3114 if (strncmp(av, "table(", 6) == 0) {
3115 fill_table(&cmd->o, av, O_IP_DST_LOOKUP, tstate);
3121 * After the address we can have '/' or ':' indicating a mask,
3122 * ',' indicating another address follows, '{' indicating a
3123 * set of addresses of unspecified size.
3125 char *t = NULL, *p = strpbrk(av, "/:,{");
3129 CHECK_LENGTH(cblen, (int)F_INSN_SIZE(ipfw_insn) + 2 + len);
3134 if ((t = strpbrk(p, ",{")) != NULL) {
3141 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
3142 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
3145 if (!inet_aton(p, (struct in_addr *)&d[1]))
3146 errx(EX_DATAERR, "bad netmask ``%s''", p);
3151 d[1] = htonl(0U); /* mask */
3152 else if (masklen > 32)
3153 errx(EX_DATAERR, "bad width ``%s''", p);
3155 d[1] = htonl(~0U << (32 - masklen));
3157 case '{': /* no mask, assume /24 and put back the '{' */
3158 d[1] = htonl(~0U << (32 - 24));
3162 case ',': /* single address plus continuation */
3165 case 0: /* initialization value */
3167 d[1] = htonl(~0U); /* force /32 */
3170 d[0] &= d[1]; /* mask base address with mask */
3173 /* find next separator */
3175 p = strpbrk(p, ",{");
3176 if (p && *p == '{') {
3178 * We have a set of addresses. They are stored as follows:
3179 * arg1 is the set size (powers of 2, 2..256)
3180 * addr is the base address IN HOST FORMAT
3181 * mask.. is an array of arg1 bits (rounded up to
3182 * the next multiple of 32) with bits set
3183 * for each host in the map.
3185 uint32_t *map = (uint32_t *)&cmd->mask;
3187 int i = contigmask((uint8_t *)&(d[1]), 32);
3190 errx(EX_DATAERR, "address set cannot be in a list");
3191 if (i < 24 || i > 31)
3192 errx(EX_DATAERR, "invalid set with mask %d\n", i);
3193 cmd->o.arg1 = 1<<(32-i); /* map length */
3194 d[0] = ntohl(d[0]); /* base addr in host format */
3195 cmd->o.opcode = O_IP_DST_SET; /* default */
3196 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
3197 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
3198 map[i] = 0; /* clear map */
3202 high = low + cmd->o.arg1 - 1;
3204 * Here, i stores the previous value when we specify a range
3205 * of addresses within a mask, e.g. 45-63. i = -1 means we
3206 * have no previous value.
3208 i = -1; /* previous value in a range */
3209 while (isdigit(*av)) {
3211 int a = strtol(av, &s, 0);
3213 if (s == av) { /* no parameter */
3215 errx(EX_DATAERR, "set not closed\n");
3217 errx(EX_DATAERR, "incomplete range %d-", i);
3220 if (a < low || a > high)
3221 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
3224 if (i == -1) /* no previous in range */
3226 else { /* check that range is valid */
3228 errx(EX_DATAERR, "invalid range %d-%d",
3231 errx(EX_DATAERR, "double '-' in range");
3234 map[i/32] |= 1<<(i & 31);
3245 if (av) /* then *av must be a ',' */
3248 /* Check this entry */
3249 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
3251 * 'any' turns the entire list into a NOP.
3252 * 'not any' never matches, so it is removed from the
3253 * list unless it is the only item, in which case we
3256 if (cmd->o.len & F_NOT) { /* "not any" never matches */
3257 if (av == NULL && len == 0) /* only this entry */
3258 errx(EX_DATAERR, "not any never matches");
3260 /* else do nothing and skip this entry */
3263 /* A single IP can be stored in an optimized format */
3264 if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
3265 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
3268 len += 2; /* two words... */
3271 if (len + 1 > F_LEN_MASK)
3272 errx(EX_DATAERR, "address list too long");
3273 cmd->o.len |= len+1;
3277 /* n2mask sets n bits of the mask */
3279 n2mask(struct in6_addr *mask, int n)
3281 static int minimask[9] =
3282 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
3285 memset(mask, 0, sizeof(struct in6_addr));
3286 p = (u_char *) mask;
3287 for (; n > 0; p++, n -= 8) {
3297 fill_flags_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3298 struct _s_x *flags, char *p)
3301 uint32_t set = 0, clear = 0;
3303 if (fill_flags(flags, p, &e, &set, &clear) != 0)
3304 errx(EX_DATAERR, "invalid flag %s", e);
3306 cmd->opcode = opcode;
3307 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
3308 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3313 ipfw_delete(char *av[])
3318 int exitval = EX_OK;
3322 NEED1("missing rule specification");
3323 if ( *av && _substrcmp(*av, "set") == 0) {
3324 /* Do not allow using the following syntax:
3325 * ipfw set N delete set M
3328 errx(EX_DATAERR, "invalid syntax");
3329 do_set = 1; /* delete set */
3334 while (*av && isdigit(**av)) {
3335 i = strtol(*av, &sep, 10);
3338 j = strtol(sep + 1, NULL, 10);
3341 exitval = ipfw_delete_nat(i);
3342 } else if (g_co.do_pipe) {
3343 exitval = ipfw_delete_pipe(g_co.do_pipe, i);
3345 memset(&rt, 0, sizeof(rt));
3348 rt.flags = IPFW_RCFLAG_SET;
3350 rt.start_rule = i & 0xffff;
3351 rt.end_rule = j & 0xffff;
3352 if (rt.start_rule == 0 && rt.end_rule == 0)
3353 rt.flags |= IPFW_RCFLAG_ALL;
3355 rt.flags |= IPFW_RCFLAG_RANGE;
3356 if (g_co.use_set != 0) {
3357 rt.set = g_co.use_set - 1;
3358 rt.flags |= IPFW_RCFLAG_SET;
3361 if (g_co.do_dynamic == 2)
3362 rt.flags |= IPFW_RCFLAG_DYNAMIC;
3363 i = do_range_cmd(IP_FW_XDEL, &rt);
3365 exitval = EX_UNAVAILABLE;
3368 warn("rule %u: setsockopt(IP_FW_XDEL)",
3370 } else if (rt.new_set == 0 && do_set == 0 &&
3371 g_co.do_dynamic != 2) {
3372 exitval = EX_UNAVAILABLE;
3375 if (rt.start_rule != rt.end_rule)
3376 warnx("no rules rules in %u-%u range",
3377 rt.start_rule, rt.end_rule);
3379 warnx("rule %u not found",
3384 if (exitval != EX_OK && g_co.do_force == 0)
3390 * fill the interface structure. We do not check the name as we can
3391 * create interfaces dynamically, so checking them at insert time
3392 * makes relatively little sense.
3393 * Interface names containing '*', '?', or '[' are assumed to be shell
3394 * patterns which match interfaces.
3397 fill_iface(ipfw_insn_if *cmd, char *arg, int cblen, struct tidx *tstate)
3402 cmd->name[0] = '\0';
3403 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3407 /* Parse the interface or address */
3408 if (strcmp(arg, "any") == 0)
3409 cmd->o.len = 0; /* effectively ignore this command */
3410 else if (strncmp(arg, "table(", 6) == 0) {
3411 if ((p = strchr(arg + 6, ')')) == NULL)
3412 errx(EX_DATAERR, "forgotten parenthesis: '%s'", arg);
3414 p = strchr(arg + 6, ',');
3417 if ((uidx = pack_table(tstate, arg + 6)) == 0)
3418 errx(EX_DATAERR, "Invalid table name: %s", arg + 6);
3420 cmd->name[0] = '\1'; /* Special value indicating table */
3422 } else if (!isdigit(*arg)) {
3423 strlcpy(cmd->name, arg, sizeof(cmd->name));
3424 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3425 } else if (!inet_aton(arg, &cmd->p.ip))
3426 errx(EX_DATAERR, "bad ip address ``%s''", arg);
3430 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
3434 char *ap, *ptr, *optr;
3435 struct ether_addr *mac;
3436 const char *macset = "0123456789abcdefABCDEF:";
3438 if (strcmp(p, "any") == 0) {
3439 for (i = 0; i < ETHER_ADDR_LEN; i++)
3440 addr[i] = mask[i] = 0;
3444 optr = ptr = strdup(p);
3445 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
3447 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
3448 errx(EX_DATAERR, "Incorrect MAC address");
3449 bcopy(mac, addr, ETHER_ADDR_LEN);
3451 errx(EX_DATAERR, "Incorrect MAC address");
3453 if (ptr != NULL) { /* we have mask? */
3454 if (p[ptr - optr - 1] == '/') { /* mask len */
3455 long ml = strtol(ptr, &ap, 10);
3456 if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
3457 errx(EX_DATAERR, "Incorrect mask length");
3458 for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
3459 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
3462 if (strspn(ptr, macset) != l ||
3463 (mac = ether_aton(ptr)) == NULL)
3464 errx(EX_DATAERR, "Incorrect mask");
3465 bcopy(mac, mask, ETHER_ADDR_LEN);
3467 } else { /* default mask: ff:ff:ff:ff:ff:ff */
3468 for (i = 0; i < ETHER_ADDR_LEN; i++)
3471 for (i = 0; i < ETHER_ADDR_LEN; i++)
3478 * helper function, updates the pointer to cmd with the length
3479 * of the current command, and also cleans up the first word of
3480 * the new command in case it has been clobbered before.
3483 next_cmd(ipfw_insn *cmd, int *len)
3486 CHECK_LENGTH(*len, 0);
3488 bzero(cmd, sizeof(*cmd));
3493 * Takes arguments and copies them into a comment
3496 fill_comment(ipfw_insn *cmd, char **av, int cblen)
3499 char *p = (char *)(cmd + 1);
3501 cmd->opcode = O_NOP;
3502 cmd->len = (cmd->len & (F_NOT | F_OR));
3504 /* Compute length of comment string. */
3505 for (i = 0, l = 0; av[i] != NULL; i++)
3506 l += strlen(av[i]) + 1;
3511 "comment too long (max 80 chars)");
3513 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
3516 for (i = 0; av[i] != NULL; i++) {
3525 * A function to fill simple commands of size 1.
3526 * Existing flags are preserved.
3529 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3531 cmd->opcode = opcode;
3532 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3537 * Fetch and add the MAC address and type, with masks. This generates one or
3538 * two microinstructions, and returns the pointer to the last one.
3541 add_mac(ipfw_insn *cmd, char *av[], int cblen)
3545 if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
3546 errx(EX_DATAERR, "MAC dst src");
3548 cmd->opcode = O_MACADDR2;
3549 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3552 mac = (ipfw_insn_mac *)cmd;
3553 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
3554 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
3555 &(mac->mask[ETHER_ADDR_LEN])); /* src */
3560 add_mactype(ipfw_insn *cmd, char *av, int cblen)
3563 errx(EX_DATAERR, "missing MAC type");
3564 if (strcmp(av, "any") != 0) { /* we have a non-null type */
3565 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
3567 cmd->opcode = O_MAC_TYPE;
3574 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
3576 struct protoent *pe;
3580 proto = strtol(av, &ep, 10);
3581 if (*ep != '\0' || proto <= 0) {
3582 if ((pe = getprotobyname(av)) == NULL)
3584 proto = pe->p_proto;
3587 fill_cmd(cmd, O_PROTO, 0, proto);
3593 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
3595 u_char proto = IPPROTO_IP;
3597 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3598 ; /* do not set O_IP4 nor O_IP6 */
3599 else if (strcmp(av, "ip4") == 0)
3600 /* explicit "just IPv4" rule */
3601 fill_cmd(cmd, O_IP4, 0, 0);
3602 else if (strcmp(av, "ip6") == 0) {
3603 /* explicit "just IPv6" rule */
3604 proto = IPPROTO_IPV6;
3605 fill_cmd(cmd, O_IP6, 0, 0);
3607 return add_proto0(cmd, av, protop);
3614 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
3616 u_char proto = IPPROTO_IP;
3618 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3619 ; /* do not set O_IP4 nor O_IP6 */
3620 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3621 /* explicit "just IPv4" rule */
3622 fill_cmd(cmd, O_IP4, 0, 0);
3623 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3624 /* explicit "just IPv6" rule */
3625 proto = IPPROTO_IPV6;
3626 fill_cmd(cmd, O_IP6, 0, 0);
3628 return add_proto0(cmd, av, protop);
3635 add_srcip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3637 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3638 if (cmd->opcode == O_IP_DST_SET) /* set */
3639 cmd->opcode = O_IP_SRC_SET;
3640 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3641 cmd->opcode = O_IP_SRC_LOOKUP;
3642 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3643 cmd->opcode = O_IP_SRC_ME;
3644 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3645 cmd->opcode = O_IP_SRC;
3646 else /* addr/mask */
3647 cmd->opcode = O_IP_SRC_MASK;
3652 add_dstip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3654 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3655 if (cmd->opcode == O_IP_DST_SET) /* set */
3657 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3659 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3660 cmd->opcode = O_IP_DST_ME;
3661 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3662 cmd->opcode = O_IP_DST;
3663 else /* addr/mask */
3664 cmd->opcode = O_IP_DST_MASK;
3668 static struct _s_x f_reserved_keywords[] = {
3671 { "diverted", TOK_OR },
3672 { "dst-port", TOK_OR },
3673 { "src-port", TOK_OR },
3674 { "established", TOK_OR },
3675 { "keep-state", TOK_OR },
3677 { "icmptypes", TOK_OR },
3685 { NULL, 0 } /* terminator */
3689 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
3692 if (match_token(f_reserved_keywords, av) != -1)
3695 if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
3696 /* XXX todo: check that we have a protocol with ports */
3697 cmd->opcode = opcode;
3704 add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3707 char *host, *ch, buf[INET6_ADDRSTRLEN];
3708 ipfw_insn *ret = NULL;
3711 /* Copy first address in set if needed */
3712 if ((ch = strpbrk(av, "/,")) != NULL) {
3714 strlcpy(buf, av, sizeof(buf));
3715 if (len < sizeof(buf))
3721 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3722 inet_pton(AF_INET6, host, &a) == 1)
3723 ret = add_srcip6(cmd, av, cblen, tstate);
3724 /* XXX: should check for IPv4, not !IPv6 */
3725 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3726 inet_pton(AF_INET6, host, &a) != 1))
3727 ret = add_srcip(cmd, av, cblen, tstate);
3728 if (ret == NULL && strcmp(av, "any") != 0)
3735 add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3738 char *host, *ch, buf[INET6_ADDRSTRLEN];
3739 ipfw_insn *ret = NULL;
3742 /* Copy first address in set if needed */
3743 if ((ch = strpbrk(av, "/,")) != NULL) {
3745 strlcpy(buf, av, sizeof(buf));
3746 if (len < sizeof(buf))
3752 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3753 inet_pton(AF_INET6, host, &a) == 1)
3754 ret = add_dstip6(cmd, av, cblen, tstate);
3755 /* XXX: should check for IPv4, not !IPv6 */
3756 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3757 inet_pton(AF_INET6, host, &a) != 1))
3758 ret = add_dstip(cmd, av, cblen, tstate);
3759 if (ret == NULL && strcmp(av, "any") != 0)
3766 * Parse arguments and assemble the microinstructions which make up a rule.
3767 * Rules are added into the 'rulebuf' and then copied in the correct order
3768 * into the actual rule.
3770 * The syntax for a rule starts with the action, followed by
3771 * optional action parameters, and the various match patterns.
3772 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
3773 * (generated if the rule includes a keep-state option), then the
3774 * various match patterns, log/altq actions, and the actual action.
3778 compile_rule(char *av[], uint32_t *rbuf, int *rbufsize, struct tidx *tstate)
3781 * rules are added into the 'rulebuf' and then copied in
3782 * the correct order into the actual rule.
3783 * Some things that need to go out of order (prob, action etc.)
3786 static uint32_t actbuf[255], cmdbuf[255];
3787 int rblen, ablen, cblen;
3789 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
3790 ipfw_insn *first_cmd; /* first match pattern */
3792 struct ip_fw_rule *rule;
3795 * various flags used to record that we entered some fields.
3797 ipfw_insn *have_state = NULL; /* any state-related option */
3798 int have_rstate = 0;
3799 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
3800 ipfw_insn *have_skipcmd = NULL;
3805 int open_par = 0; /* open parenthesis ( */
3807 /* proto is here because it is used to fetch ports */
3808 u_char proto = IPPROTO_IP; /* default protocol */
3810 double match_prob = 1; /* match probability, default is always match */
3812 bzero(actbuf, sizeof(actbuf)); /* actions go here */
3813 bzero(cmdbuf, sizeof(cmdbuf));
3814 bzero(rbuf, *rbufsize);
3816 rule = (struct ip_fw_rule *)rbuf;
3817 cmd = (ipfw_insn *)cmdbuf;
3818 action = (ipfw_insn *)actbuf;
3820 rblen = *rbufsize / sizeof(uint32_t);
3821 rblen -= sizeof(struct ip_fw_rule) / sizeof(uint32_t);
3822 ablen = sizeof(actbuf) / sizeof(actbuf[0]);
3823 cblen = sizeof(cmdbuf) / sizeof(cmdbuf[0]);
3824 cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
3826 #define CHECK_RBUFLEN(len) { CHECK_LENGTH(rblen, len); rblen -= len; }
3827 #define CHECK_ACTLEN CHECK_LENGTH(ablen, action->len)
3831 /* [rule N] -- Rule number optional */
3832 if (av[0] && isdigit(**av)) {
3833 rule->rulenum = atoi(*av);
3837 /* [set N] -- set number (0..RESVD_SET), optional */
3838 if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
3839 int set = strtoul(av[1], NULL, 10);
3840 if (set < 0 || set > RESVD_SET)
3841 errx(EX_DATAERR, "illegal set %s", av[1]);
3847 /* [prob D] -- match probability, optional */
3848 if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
3849 match_prob = strtod(av[1], NULL);
3851 if (match_prob <= 0 || match_prob > 1)
3852 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
3856 /* action -- mandatory */
3857 NEED1("missing action");
3858 i = match_token(rule_actions, *av);
3860 action->len = 1; /* default */
3863 case TOK_CHECKSTATE:
3864 have_state = action;
3865 action->opcode = O_CHECK_STATE;
3867 match_token(rule_options, *av) == TOK_COMMENT) {
3868 action->arg1 = pack_object(tstate,
3869 default_state_name, IPFW_TLV_STATE_NAME);
3872 if (*av[0] == ':') {
3873 if (strcmp(*av + 1, "any") == 0)
3875 else if (state_check_name(*av + 1) == 0)
3876 action->arg1 = pack_object(tstate, *av + 1,
3877 IPFW_TLV_STATE_NAME);
3879 errx(EX_DATAERR, "Invalid state name %s",
3884 errx(EX_DATAERR, "Invalid state name %s", *av);
3888 action->opcode = O_REJECT;
3889 action->arg1 = ICMP_REJECT_ABORT;
3893 action->opcode = O_UNREACH6;
3894 action->arg1 = ICMP6_UNREACH_ABORT;
3898 action->opcode = O_ACCEPT;
3902 action->opcode = O_DENY;
3907 action->opcode = O_REJECT;
3908 action->arg1 = ICMP_UNREACH_HOST;
3912 action->opcode = O_REJECT;
3913 action->arg1 = ICMP_REJECT_RST;
3917 action->opcode = O_UNREACH6;
3918 action->arg1 = ICMP6_UNREACH_RST;
3922 action->opcode = O_REJECT;
3923 NEED1("missing reject code");
3924 fill_reject_code(&action->arg1, *av);
3929 action->opcode = O_UNREACH6;
3930 NEED1("missing unreach code");
3931 fill_unreach6_code(&action->arg1, *av);
3936 action->opcode = O_COUNT;
3940 action->opcode = O_NAT;
3941 action->len = F_INSN_SIZE(ipfw_insn_nat);
3943 if (*av != NULL && _substrcmp(*av, "global") == 0) {
3944 action->arg1 = IP_FW_NAT44_GLOBAL;
3950 action->opcode = O_QUEUE;
3953 action->opcode = O_PIPE;
3956 action->opcode = O_SKIPTO;
3959 action->opcode = O_NETGRAPH;
3962 action->opcode = O_NGTEE;
3965 action->opcode = O_DIVERT;
3968 action->opcode = O_TEE;
3971 action->opcode = O_CALLRETURN;
3974 errx(EX_USAGE, "missing argument for %s", *(av - 1));
3975 if (isdigit(**av)) {
3976 action->arg1 = strtoul(*av, NULL, 10);
3977 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
3978 errx(EX_DATAERR, "illegal argument for %s",
3980 } else if (_substrcmp(*av, "tablearg") == 0) {
3981 action->arg1 = IP_FW_TARG;
3982 } else if (i == TOK_DIVERT || i == TOK_TEE) {
3985 s = getservbyname(av[0], "divert");
3987 action->arg1 = ntohs(s->s_port);
3989 errx(EX_DATAERR, "illegal divert/tee port");
3991 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
3997 * Locate the address-port separator (':' or ',').
3998 * Could be one of the following:
4002 * IPv6 w:x:y::z,port
4003 * IPv6 [w:x:y::z]:port
4005 struct sockaddr_storage result;
4006 struct addrinfo *res;
4009 u_short port_number = 0;
4011 NEED1("missing forward address[:port]");
4013 if (_substrcmp(*av, "tablearg") == 0) {
4015 ((struct sockaddr_in*)&result)->sin_addr.s_addr =
4019 * Are we an bracket-enclosed IPv6 address?
4021 if (strchr(*av, '['))
4025 * locate the address-port separator (':' or ',')
4027 s = strchr(*av, ',');
4029 s = strchr(*av, ']');
4030 /* Prevent erroneous parsing on brackets. */
4036 /* Distinguish between IPv4:port and IPv6 cases. */
4038 if (s && strchr(s+1, ':'))
4039 s = NULL; /* no port */
4043 /* Terminate host portion and set s to start of port. */
4045 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
4048 "illegal forwarding port ``%s''", s);
4049 port_number = (u_short)i;
4053 * Resolve the host name or address to a family and a
4054 * network representation of the address.
4056 if (getaddrinfo(*av, NULL, NULL, &res))
4057 errx(EX_DATAERR, NULL);
4058 /* Just use the first host in the answer. */
4059 family = res->ai_family;
4060 memcpy(&result, res->ai_addr, res->ai_addrlen);
4064 if (family == PF_INET) {
4065 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
4067 action->opcode = O_FORWARD_IP;
4068 action->len = F_INSN_SIZE(ipfw_insn_sa);
4072 * In the kernel we assume AF_INET and use only
4073 * sin_port and sin_addr. Remember to set sin_len as
4074 * the routing code seems to use it too.
4076 p->sa.sin_len = sizeof(struct sockaddr_in);
4077 p->sa.sin_family = AF_INET;
4078 p->sa.sin_port = port_number;
4079 p->sa.sin_addr.s_addr =
4080 ((struct sockaddr_in *)&result)->sin_addr.s_addr;
4081 } else if (family == PF_INET6) {
4082 ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
4084 action->opcode = O_FORWARD_IP6;
4085 action->len = F_INSN_SIZE(ipfw_insn_sa6);
4088 p->sa.sin6_len = sizeof(struct sockaddr_in6);
4089 p->sa.sin6_family = AF_INET6;
4090 p->sa.sin6_port = port_number;
4091 p->sa.sin6_flowinfo = 0;
4092 p->sa.sin6_scope_id =
4093 ((struct sockaddr_in6 *)&result)->sin6_scope_id;
4094 bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
4095 &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
4097 errx(EX_DATAERR, "Invalid address family in forward action");
4103 /* pretend it is a 'count' rule followed by the comment */
4104 action->opcode = O_COUNT;
4105 av--; /* go back... */
4111 size_t intsize = sizeof(int);
4113 action->opcode = O_SETFIB;
4114 NEED1("missing fib number");
4115 if (_substrcmp(*av, "tablearg") == 0) {
4116 action->arg1 = IP_FW_TARG;
4118 action->arg1 = strtoul(*av, NULL, 10);
4119 if (sysctlbyname("net.fibs", &numfibs, &intsize,
4121 errx(EX_DATAERR, "fibs not suported.\n");
4122 if (action->arg1 >= numfibs) /* Temporary */
4123 errx(EX_DATAERR, "fib too large.\n");
4124 /* Add high-order bit to fib to make room for tablearg*/
4125 action->arg1 |= 0x8000;
4135 action->opcode = O_SETDSCP;
4136 NEED1("missing DSCP code");
4137 if (_substrcmp(*av, "tablearg") == 0) {
4138 action->arg1 = IP_FW_TARG;
4140 if (isalpha(*av[0])) {
4141 if ((code = match_token(f_ipdscp, *av)) == -1)
4142 errx(EX_DATAERR, "Unknown DSCP code");
4143 action->arg1 = code;
4145 action->arg1 = strtoul(*av, NULL, 10);
4147 * Add high-order bit to DSCP to make room
4150 action->arg1 |= 0x8000;
4157 action->opcode = O_REASS;
4161 fill_cmd(action, O_CALLRETURN, F_NOT, 0);
4164 case TOK_TCPSETMSS: {
4168 idx = pack_object(tstate, "tcp-setmss", IPFW_TLV_EACTION);
4170 errx(EX_DATAERR, "pack_object failed");
4171 fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4172 NEED1("Missing MSS value");
4173 action = next_cmd(action, &ablen);
4176 mss = strtoul(*av, NULL, 10);
4177 if (mss == 0 || mss > UINT16_MAX)
4178 errx(EX_USAGE, "invalid MSS value %s", *av);
4179 fill_cmd(action, O_EXTERNAL_DATA, 0, (uint16_t)mss);
4186 if (match_token(rule_eactions, *av) == -1)
4187 errx(EX_DATAERR, "invalid action %s\n", *av);
4189 * External actions support.
4190 * XXX: we support only syntax with instance name.
4191 * For known external actions (from rule_eactions list)
4192 * we can handle syntax directly. But with `eaction'
4193 * keyword we can use only `eaction <name> <instance>'
4199 NEED1("Missing eaction name");
4200 if (eaction_check_name(*av) != 0)
4201 errx(EX_DATAERR, "Invalid eaction name %s", *av);
4202 idx = pack_object(tstate, *av, IPFW_TLV_EACTION);
4204 errx(EX_DATAERR, "pack_object failed");
4205 fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4207 NEED1("Missing eaction instance name");
4208 action = next_cmd(action, &ablen);
4211 if (eaction_check_name(*av) != 0)
4212 errx(EX_DATAERR, "Invalid eaction instance name %s",
4215 * External action instance object has TLV type depended
4216 * from the external action name object index. Since we
4217 * currently don't know this index, use zero as TLV type.
4219 idx = pack_object(tstate, *av, 0);
4221 errx(EX_DATAERR, "pack_object failed");
4222 fill_cmd(action, O_EXTERNAL_INSTANCE, 0, idx);
4226 action = next_cmd(action, &ablen);
4229 * [altq queuename] -- altq tag, optional
4230 * [log [logamount N]] -- log, optional
4232 * If they exist, it go first in the cmdbuf, but then it is
4233 * skipped in the copy section to the end of the buffer.
4235 while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
4240 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
4245 "log cannot be specified more than once");
4246 have_log = (ipfw_insn *)c;
4247 cmd->len = F_INSN_SIZE(ipfw_insn_log);
4249 cmd->opcode = O_LOG;
4250 if (av[0] && _substrcmp(*av, "logamount") == 0) {
4252 NEED1("logamount requires argument");
4256 "logamount must be positive");
4260 len = sizeof(c->max_log);
4261 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
4262 &c->max_log, &len, NULL, 0) == -1) {
4263 if (g_co.test_only) {
4267 errx(1, "sysctlbyname(\"%s\")",
4268 "net.inet.ip.fw.verbose_limit");
4277 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
4279 NEED1("missing altq queue name");
4282 "altq cannot be specified more than once");
4283 have_altq = (ipfw_insn *)a;
4284 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
4286 cmd->opcode = O_ALTQ;
4287 a->qid = altq_name_to_qid(*av);
4298 errx(EX_USAGE, "tag and untag cannot be "
4299 "specified more than once");
4300 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
4301 rule_action_params);
4303 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
4311 cmd = next_cmd(cmd, &cblen);
4314 if (have_state) { /* must be a check-state, we are done */
4316 match_token(rule_options, *av) == TOK_COMMENT) {
4317 /* check-state has a comment */
4319 fill_comment(cmd, av, cblen);
4320 cmd = next_cmd(cmd, &cblen);
4326 #define OR_START(target) \
4327 if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
4329 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
4332 if ( (av[0])[1] == '\0') { \
4343 strcmp(*av, ")") == 0 || \
4344 strcmp(*av, "}") == 0)) { \
4349 errx(EX_USAGE, "missing \")\"\n"); \
4353 if (av[0] && _substrcmp(*av, "not") == 0) { \
4354 if (cmd->len & F_NOT) \
4355 errx(EX_USAGE, "double \"not\" not allowed\n"); \
4356 cmd->len |= F_NOT; \
4360 #define OR_BLOCK(target) \
4361 if (av[0] && _substrcmp(*av, "or") == 0) { \
4362 if (prev == NULL || open_par == 0) \
4363 errx(EX_DATAERR, "invalid OR block"); \
4364 prev->len |= F_OR; \
4374 * MAC addresses, optional.
4375 * If we have this, we skip the part "proto from src to dst"
4376 * and jump straight to the option parsing.
4379 NEED1("missing protocol");
4380 if (_substrcmp(*av, "MAC") == 0 ||
4381 _substrcmp(*av, "mac") == 0) {
4382 av++; /* the "MAC" keyword */
4383 add_mac(cmd, av); /* exits in case of errors */
4384 cmd = next_cmd(cmd);
4385 av += 2; /* dst-mac and src-mac */
4387 NEED1("missing mac type");
4388 if (add_mactype(cmd, av[0]))
4389 cmd = next_cmd(cmd);
4390 av++; /* any or mac-type */
4396 * protocol, mandatory
4398 OR_START(get_proto);
4400 NEED1("missing protocol");
4401 if (add_proto_compat(cmd, *av, &proto)) {
4403 if (F_LEN(cmd) != 0) {
4405 cmd = next_cmd(cmd, &cblen);
4407 } else if (first_cmd != cmd) {
4408 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
4410 rule->flags |= IPFW_RULE_JUSTOPTS;
4413 OR_BLOCK(get_proto);
4415 first_cmd = cmd; /* update pointer to use in compact form */
4420 if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
4421 errx(EX_USAGE, "missing ``from''");
4425 * source IP, mandatory
4427 OR_START(source_ip);
4428 NOT_BLOCK; /* optional "not" */
4429 NEED1("missing source address");
4430 if (add_src(cmd, *av, proto, cblen, tstate)) {
4432 if (F_LEN(cmd) != 0) { /* ! any */
4434 cmd = next_cmd(cmd, &cblen);
4437 errx(EX_USAGE, "bad source address %s", *av);
4438 OR_BLOCK(source_ip);
4441 * source ports, optional
4443 NOT_BLOCK; /* optional "not" */
4444 if ( av[0] != NULL ) {
4445 if (_substrcmp(*av, "any") == 0 ||
4446 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4448 if (F_LEN(cmd) != 0)
4449 cmd = next_cmd(cmd, &cblen);
4456 if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
4457 errx(EX_USAGE, "missing ``to''");
4461 * destination, mandatory
4464 NOT_BLOCK; /* optional "not" */
4465 NEED1("missing dst address");
4466 if (add_dst(cmd, *av, proto, cblen, tstate)) {
4468 if (F_LEN(cmd) != 0) { /* ! any */
4470 cmd = next_cmd(cmd, &cblen);
4473 errx( EX_USAGE, "bad destination address %s", *av);
4477 * dest. ports, optional
4479 NOT_BLOCK; /* optional "not" */
4481 if (_substrcmp(*av, "any") == 0 ||
4482 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4484 if (F_LEN(cmd) != 0)
4485 cmd = next_cmd(cmd, &cblen);
4488 if (first_cmd == cmd)
4489 rule->flags |= IPFW_RULE_NOOPT;
4493 while ( av[0] != NULL ) {
4495 ipfw_insn_u32 *cmd32; /* alias for cmd */
4498 cmd32 = (ipfw_insn_u32 *)cmd;
4500 if (*s == '!') { /* alternate syntax for NOT */
4501 if (cmd->len & F_NOT)
4502 errx(EX_USAGE, "double \"not\" not allowed\n");
4506 i = match_token(rule_options, s);
4510 if (cmd->len & F_NOT)
4511 errx(EX_USAGE, "double \"not\" not allowed\n");
4516 if (open_par == 0 || prev == NULL)
4517 errx(EX_USAGE, "invalid \"or\" block\n");
4521 case TOK_STARTBRACE:
4523 errx(EX_USAGE, "+nested \"(\" not allowed\n");
4529 errx(EX_USAGE, "+missing \")\"\n");
4535 fill_cmd(cmd, O_IN, 0, 0);
4539 cmd->len ^= F_NOT; /* toggle F_NOT */
4540 fill_cmd(cmd, O_IN, 0, 0);
4544 fill_cmd(cmd, O_DIVERTED, 0, 3);
4547 case TOK_DIVERTEDLOOPBACK:
4548 fill_cmd(cmd, O_DIVERTED, 0, 1);
4551 case TOK_DIVERTEDOUTPUT:
4552 fill_cmd(cmd, O_DIVERTED, 0, 2);
4556 fill_cmd(cmd, O_FRAG, 0, 0);
4560 fill_cmd(cmd, O_LAYER2, 0, 0);
4566 NEED1("recv, xmit, via require interface name"
4568 fill_iface((ipfw_insn_if *)cmd, av[0], cblen, tstate);
4570 if (F_LEN(cmd) == 0) /* not a valid address */
4573 cmd->opcode = O_XMIT;
4574 else if (i == TOK_RECV)
4575 cmd->opcode = O_RECV;
4576 else if (i == TOK_VIA)
4577 cmd->opcode = O_VIA;
4581 NEED1("icmptypes requires list of types");
4582 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
4586 case TOK_ICMP6TYPES:
4587 NEED1("icmptypes requires list of types");
4588 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
4593 NEED1("ipttl requires TTL");
4594 if (strpbrk(*av, "-,")) {
4595 if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
4596 errx(EX_DATAERR, "invalid ipttl %s", *av);
4598 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
4603 NEED1("ipid requires id");
4604 if (strpbrk(*av, "-,")) {
4605 if (!add_ports(cmd, *av, 0, O_IPID, cblen))
4606 errx(EX_DATAERR, "invalid ipid %s", *av);
4608 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
4613 NEED1("iplen requires length");
4614 if (strpbrk(*av, "-,")) {
4615 if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
4616 errx(EX_DATAERR, "invalid ip len %s", *av);
4618 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
4623 NEED1("ipver requires version");
4624 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
4628 case TOK_IPPRECEDENCE:
4629 NEED1("ipprecedence requires value");
4630 fill_cmd(cmd, O_IPPRECEDENCE, 0,
4631 (strtoul(*av, NULL, 0) & 7) << 5);
4636 NEED1("missing DSCP code");
4637 fill_dscp(cmd, *av, cblen);
4642 NEED1("missing argument for ipoptions");
4643 fill_flags_cmd(cmd, O_IPOPT, f_ipopts, *av);
4648 NEED1("missing argument for iptos");
4649 fill_flags_cmd(cmd, O_IPTOS, f_iptos, *av);
4654 NEED1("uid requires argument");
4660 cmd->opcode = O_UID;
4661 uid = strtoul(*av, &end, 0);
4662 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
4664 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
4665 cmd32->d[0] = pwd->pw_uid;
4666 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4672 NEED1("gid requires argument");
4678 cmd->opcode = O_GID;
4679 gid = strtoul(*av, &end, 0);
4680 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
4682 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
4683 cmd32->d[0] = grp->gr_gid;
4684 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4690 NEED1("jail requires argument");
4695 cmd->opcode = O_JAIL;
4697 * If av is a number, then we'll just pass it as-is. If
4698 * it's a name, try to resolve that to a jid.
4700 * We save the jail_getid(3) call for a fallback because
4701 * it entails an unconditional trip to the kernel to
4702 * either validate a jid or resolve a name to a jid.
4703 * This specific token doesn't currently require a
4704 * jid to be an active jail, so we save a transition
4705 * by simply using a number that we're given.
4707 jid = strtoul(*av, &end, 10);
4709 jid = jail_getid(*av);
4711 errx(EX_DATAERR, "%s", jail_errmsg);
4713 cmd32->d[0] = (uint32_t)jid;
4714 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4720 fill_cmd(cmd, O_ESTAB, 0, 0);
4724 fill_cmd(cmd, O_TCPFLAGS, 0,
4725 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
4728 case TOK_TCPDATALEN:
4729 NEED1("tcpdatalen requires length");
4730 if (strpbrk(*av, "-,")) {
4731 if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
4732 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
4734 fill_cmd(cmd, O_TCPDATALEN, 0,
4735 strtoul(*av, NULL, 0));
4740 NEED1("missing argument for tcpoptions");
4741 fill_flags_cmd(cmd, O_TCPOPTS, f_tcpopts, *av);
4747 NEED1("tcpseq/tcpack requires argument");
4748 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
4749 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
4750 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
4756 NEED1("tcpmss/tcpwin requires size");
4757 if (strpbrk(*av, "-,")) {
4758 if (add_ports(cmd, *av, 0,
4759 i == TOK_TCPWIN ? O_TCPWIN : O_TCPMSS,
4761 errx(EX_DATAERR, "invalid %s size %s",
4764 fill_cmd(cmd, i == TOK_TCPWIN ? O_TCPWIN :
4765 O_TCPMSS, 0, strtoul(*av, NULL, 0));
4770 NEED1("missing argument for tcpflags");
4771 cmd->opcode = O_TCPFLAGS;
4772 fill_flags_cmd(cmd, O_TCPFLAGS, f_tcpflags, *av);
4777 case TOK_RECORDSTATE: {
4781 errx(EX_USAGE, "keep-state or record-state cannot be part "
4784 errx(EX_USAGE, "only one of keep-state, record-state, "
4785 " limit and set-limit is allowed");
4786 if (*av != NULL && *av[0] == ':') {
4787 if (state_check_name(*av + 1) != 0)
4789 "Invalid state name %s", *av);
4790 uidx = pack_object(tstate, *av + 1,
4791 IPFW_TLV_STATE_NAME);
4794 uidx = pack_object(tstate, default_state_name,
4795 IPFW_TLV_STATE_NAME);
4797 have_rstate = i == TOK_RECORDSTATE;
4798 fill_cmd(cmd, O_KEEP_STATE, 0, uidx);
4803 case TOK_SETLIMIT: {
4804 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
4809 "limit or set-limit cannot be part of an or block");
4811 errx(EX_USAGE, "only one of keep-state, record-state, "
4812 " limit and set-limit is allowed");
4814 have_rstate = i == TOK_SETLIMIT;
4816 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
4818 cmd->opcode = O_LIMIT;
4819 c->limit_mask = c->conn_limit = 0;
4821 while ( av[0] != NULL ) {
4822 if ((val = match_token(limit_masks, *av)) <= 0)
4824 c->limit_mask |= val;
4828 if (c->limit_mask == 0)
4829 errx(EX_USAGE, "limit: missing limit mask");
4831 GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
4832 TOK_LIMIT, rule_options);
4835 if (*av != NULL && *av[0] == ':') {
4836 if (state_check_name(*av + 1) != 0)
4838 "Invalid state name %s", *av);
4839 cmd->arg1 = pack_object(tstate, *av + 1,
4840 IPFW_TLV_STATE_NAME);
4843 cmd->arg1 = pack_object(tstate,
4844 default_state_name, IPFW_TLV_STATE_NAME);
4849 NEED1("missing protocol");
4850 if (add_proto(cmd, *av, &proto)) {
4853 errx(EX_DATAERR, "invalid protocol ``%s''",
4858 NEED1("missing source IP");
4859 if (add_srcip(cmd, *av, cblen, tstate)) {
4865 NEED1("missing destination IP");
4866 if (add_dstip(cmd, *av, cblen, tstate)) {
4872 NEED1("missing source IP6");
4873 if (add_srcip6(cmd, *av, cblen, tstate)) {
4879 NEED1("missing destination IP6");
4880 if (add_dstip6(cmd, *av, cblen, tstate)) {
4886 NEED1("missing source port");
4887 if (_substrcmp(*av, "any") == 0 ||
4888 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4891 errx(EX_DATAERR, "invalid source port %s", *av);
4895 NEED1("missing destination port");
4896 if (_substrcmp(*av, "any") == 0 ||
4897 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4900 errx(EX_DATAERR, "invalid destination port %s",
4905 if (add_mac(cmd, av, cblen))
4910 NEED1("missing mac type");
4911 if (!add_mactype(cmd, *av, cblen))
4912 errx(EX_DATAERR, "invalid mac type %s", *av);
4916 case TOK_VERREVPATH:
4917 fill_cmd(cmd, O_VERREVPATH, 0, 0);
4920 case TOK_VERSRCREACH:
4921 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
4925 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
4929 fill_cmd(cmd, O_IPSEC, 0, 0);
4933 fill_cmd(cmd, O_IP6, 0, 0);
4937 fill_cmd(cmd, O_IP4, 0, 0);
4941 fill_ext6hdr( cmd, *av );
4946 if (proto != IPPROTO_IPV6 )
4947 errx( EX_USAGE, "flow-id filter is active "
4948 "only for ipv6 protocol\n");
4949 fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
4954 fill_comment(cmd, av, cblen);
4959 if (av[0] && strpbrk(*av, "-,")) {
4960 if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
4961 errx(EX_DATAERR, "tagged: invalid tag"
4967 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
4968 TOK_TAGGED, rule_options);
4969 fill_cmd(cmd, O_TAGGED, 0, tag);
4975 NEED1("fib requires fib number");
4976 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
4980 fill_cmd(cmd, O_SOCKARG, 0, 0);
4984 ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
4987 if (!av[0] || !av[1])
4988 errx(EX_USAGE, "format: lookup argument tablenum");
4989 cmd->opcode = O_IP_DST_LOOKUP;
4990 cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
4991 i = match_token(rule_options, *av);
4992 for (j = 0; lookup_key[j] >= 0 ; j++) {
4993 if (i == lookup_key[j])
4996 if (lookup_key[j] <= 0)
4997 errx(EX_USAGE, "format: cannot lookup on %s", *av);
4998 __PAST_END(c->d, 1) = j; // i converted to option
5001 if ((j = pack_table(tstate, *av)) == 0)
5002 errx(EX_DATAERR, "Invalid table name: %s", *av);
5009 NEED1("missing table name");
5010 if (strncmp(*av, "table(", 6) != 0)
5012 "enclose table name into \"table()\"");
5013 fill_table(cmd, *av, O_IP_FLOW_LOOKUP, tstate);
5017 case TOK_SKIPACTION:
5019 errx(EX_USAGE, "only one defer-action "
5022 fill_cmd(cmd, O_SKIP_ACTION, 0, 0);
5026 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
5028 if (F_LEN(cmd) > 0) { /* prepare to advance */
5030 cmd = next_cmd(cmd, &cblen);
5036 if (!have_state && have_skipcmd)
5037 warnx("Rule contains \"defer-immediate-action\" "
5038 "and doesn't contain any state-related options.");
5041 * Now copy stuff into the rule.
5042 * If we have a keep-state option, the first instruction
5043 * must be a PROBE_STATE (which is generated here).
5044 * If we have a LOG option, it was stored as the first command,
5045 * and now must be moved to the top of the action part.
5047 dst = (ipfw_insn *)rule->cmd;
5050 * First thing to write into the command stream is the match probability.
5052 if (match_prob != 1) { /* 1 means always match */
5053 dst->opcode = O_PROB;
5055 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
5060 * generate O_PROBE_STATE if necessary
5062 if (have_state && have_state->opcode != O_CHECK_STATE && !have_rstate) {
5063 fill_cmd(dst, O_PROBE_STATE, 0, have_state->arg1);
5064 dst = next_cmd(dst, &rblen);
5068 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG,
5071 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
5075 switch (src->opcode) {
5084 bcopy(src, dst, i * sizeof(uint32_t));
5090 * put back the have_state command as last opcode
5092 if (have_state && have_state->opcode != O_CHECK_STATE) {
5093 i = F_LEN(have_state);
5095 bcopy(have_state, dst, i * sizeof(uint32_t));
5100 * put back the have_skipcmd command as very last opcode
5103 i = F_LEN(have_skipcmd);
5105 bcopy(have_skipcmd, dst, i * sizeof(uint32_t));
5110 * start action section
5112 rule->act_ofs = dst - rule->cmd;
5114 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
5116 i = F_LEN(have_log);
5118 bcopy(have_log, dst, i * sizeof(uint32_t));
5122 i = F_LEN(have_altq);
5124 bcopy(have_altq, dst, i * sizeof(uint32_t));
5128 i = F_LEN(have_tag);
5130 bcopy(have_tag, dst, i * sizeof(uint32_t));
5135 * copy all other actions
5137 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
5140 bcopy(src, dst, i * sizeof(uint32_t));
5144 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
5145 *rbufsize = (char *)dst - (char *)rule;
5149 compare_ntlv(const void *_a, const void *_b)
5151 const ipfw_obj_ntlv *a, *b;
5153 a = (const ipfw_obj_ntlv *)_a;
5154 b = (const ipfw_obj_ntlv *)_b;
5156 if (a->set < b->set)
5158 else if (a->set > b->set)
5161 if (a->idx < b->idx)
5163 else if (a->idx > b->idx)
5166 if (a->head.type < b->head.type)
5168 else if (a->head.type > b->head.type)
5175 * Provide kernel with sorted list of referenced objects
5178 object_sort_ctlv(ipfw_obj_ctlv *ctlv)
5181 qsort(ctlv + 1, ctlv->count, ctlv->objsize, compare_ntlv);
5189 compare_object_kntlv(const void *k, const void *v)
5191 const ipfw_obj_ntlv *ntlv;
5192 struct object_kt key;
5194 key = *((const struct object_kt *)k);
5195 ntlv = (const ipfw_obj_ntlv *)v;
5197 if (key.uidx < ntlv->idx)
5199 else if (key.uidx > ntlv->idx)
5202 if (key.type < ntlv->head.type)
5204 else if (key.type > ntlv->head.type)
5211 * Finds object name in @ctlv by @idx and @type.
5212 * Uses the following facts:
5213 * 1) All TLVs are the same size
5214 * 2) Kernel implementation provides already sorted list.
5216 * Returns table name or NULL.
5219 object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx, uint16_t type)
5221 ipfw_obj_ntlv *ntlv;
5222 struct object_kt key;
5227 ntlv = bsearch(&key, (ctlv + 1), ctlv->count, ctlv->objsize,
5228 compare_object_kntlv);
5231 return (ntlv->name);
5237 table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx)
5240 return (object_search_ctlv(ctlv, idx, IPFW_TLV_TBL_NAME));
5244 * Adds one or more rules to ipfw chain.
5249 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
5250 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ] (*2) (*3)
5255 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
5256 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ]
5259 * Rules in reply are modified to store their actual ruleset number.
5261 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
5262 * according to their idx field and there has to be no duplicates.
5263 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
5264 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
5267 ipfw_add(char *av[])
5269 uint32_t rulebuf[1024];
5270 int rbufsize, default_off, tlen, rlen;
5273 struct ip_fw_rule *rule;
5275 ip_fw3_opheader *op3;
5276 ipfw_obj_ctlv *ctlv, *tstate;
5278 rbufsize = sizeof(rulebuf);
5279 memset(rulebuf, 0, rbufsize);
5280 memset(&ts, 0, sizeof(ts));
5282 /* Optimize case with no tables */
5283 default_off = sizeof(ipfw_obj_ctlv) + sizeof(ip_fw3_opheader);
5284 op3 = (ip_fw3_opheader *)rulebuf;
5285 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5286 rule = (struct ip_fw_rule *)(ctlv + 1);
5287 rbufsize -= default_off;
5289 compile_rule(av, (uint32_t *)rule, &rbufsize, &ts);
5290 /* Align rule size to u64 boundary */
5291 rlen = roundup2(rbufsize, sizeof(uint64_t));
5296 if (ts.count != 0) {
5297 /* Some tables. We have to alloc more data */
5298 tlen = ts.count * sizeof(ipfw_obj_ntlv);
5299 sz = default_off + sizeof(ipfw_obj_ctlv) + tlen + rlen;
5301 if ((tbuf = calloc(1, sz)) == NULL)
5302 err(EX_UNAVAILABLE, "malloc() failed for IP_FW_ADD");
5303 op3 = (ip_fw3_opheader *)tbuf;
5305 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5306 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
5307 ctlv->head.length = sizeof(ipfw_obj_ctlv) + tlen;
5308 ctlv->count = ts.count;
5309 ctlv->objsize = sizeof(ipfw_obj_ntlv);
5310 memcpy(ctlv + 1, ts.idx, tlen);
5311 object_sort_ctlv(ctlv);
5314 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
5315 ctlv->head.type = IPFW_TLV_RULE_LIST;
5316 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5318 memcpy(ctlv + 1, rule, rbufsize);
5320 /* Simply add header */
5321 sz = rlen + default_off;
5322 memset(ctlv, 0, sizeof(*ctlv));
5323 ctlv->head.type = IPFW_TLV_RULE_LIST;
5324 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5328 if (do_get3(IP_FW_XADD, op3, &sz) != 0)
5329 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_XADD");
5331 if (!g_co.do_quiet) {
5332 struct format_opts sfo;
5334 memset(&sfo, 0, sizeof(sfo));
5335 sfo.tstate = tstate;
5336 sfo.set_mask = (uint32_t)(-1);
5337 bp_alloc(&bp, 4096);
5338 show_static_rule(&g_co, &sfo, &bp, rule, NULL);
5339 printf("%s", bp.buf);
5351 * clear the counters or the log counters.
5352 * optname has the following values:
5353 * 0 (zero both counters and logging)
5354 * 1 (zero logging only)
5357 ipfw_zero(int ac, char *av[], int optname)
5361 char const *name = optname ? "RESETLOG" : "ZERO";
5365 optname = optname ? IP_FW_XRESETLOG : IP_FW_XZERO;
5369 /* clear all entries */
5370 memset(&rt, 0, sizeof(rt));
5371 rt.flags = IPFW_RCFLAG_ALL;
5372 if (do_range_cmd(optname, &rt) < 0)
5373 err(EX_UNAVAILABLE, "setsockopt(IP_FW_X%s)", name);
5375 printf("%s.\n", optname == IP_FW_XZERO ?
5376 "Accounting cleared":"Logging counts reset");
5383 if (isdigit(**av)) {
5384 arg = strtonum(*av, 0, 0xffff, &errstr);
5387 "invalid rule number %s\n", *av);
5388 memset(&rt, 0, sizeof(rt));
5389 rt.start_rule = arg;
5391 rt.flags |= IPFW_RCFLAG_RANGE;
5392 if (g_co.use_set != 0) {
5393 rt.set = g_co.use_set - 1;
5394 rt.flags |= IPFW_RCFLAG_SET;
5396 if (do_range_cmd(optname, &rt) != 0) {
5397 warn("rule %u: setsockopt(IP_FW_X%s)",
5399 failed = EX_UNAVAILABLE;
5400 } else if (rt.new_set == 0) {
5401 printf("Entry %d not found\n", arg);
5402 failed = EX_UNAVAILABLE;
5403 } else if (!g_co.do_quiet)
5404 printf("Entry %d %s.\n", arg,
5405 optname == IP_FW_XZERO ?
5406 "cleared" : "logging count reset");
5408 errx(EX_USAGE, "invalid rule number ``%s''", *av);
5412 if (failed != EX_OK)
5417 ipfw_flush(int force)
5421 if (!force && !g_co.do_quiet) { /* need to ask user */
5424 printf("Are you sure? [yn] ");
5427 c = toupper(getc(stdin));
5428 while (c != '\n' && getc(stdin) != '\n')
5430 return; /* and do not flush */
5431 } while (c != 'Y' && c != 'N');
5433 if (c == 'N') /* user said no */
5440 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
5441 memset(&rt, 0, sizeof(rt));
5442 if (g_co.use_set != 0) {
5443 rt.set = g_co.use_set - 1;
5444 rt.flags = IPFW_RCFLAG_SET;
5446 rt.flags = IPFW_RCFLAG_ALL;
5447 if (do_range_cmd(IP_FW_XDEL, &rt) != 0)
5448 err(EX_UNAVAILABLE, "setsockopt(IP_FW_XDEL)");
5450 printf("Flushed all %s.\n", g_co.do_pipe ? "pipes" : "rules");
5453 static struct _s_x intcmds[] = {
5454 { "talist", TOK_TALIST },
5455 { "iflist", TOK_IFLIST },
5456 { "olist", TOK_OLIST },
5457 { "vlist", TOK_VLIST },
5461 static struct _s_x otypes[] = {
5462 { "EACTION", IPFW_TLV_EACTION },
5463 { "DYNSTATE", IPFW_TLV_STATE_NAME },
5468 lookup_eaction_name(ipfw_obj_ntlv *ntlv, int cnt, uint16_t type)
5474 for (i = 0; i < cnt; i++) {
5475 if (ntlv[i].head.type != IPFW_TLV_EACTION)
5477 if (IPFW_TLV_EACTION_NAME(ntlv[i].idx) != type)
5479 name = ntlv[i].name;
5486 ipfw_list_objects(int ac __unused, char *av[] __unused)
5488 ipfw_obj_lheader req, *olh;
5489 ipfw_obj_ntlv *ntlv;
5494 memset(&req, 0, sizeof(req));
5496 if (do_get3(IP_FW_DUMP_SRVOBJECTS, &req.opheader, &sz) != 0)
5497 if (errno != ENOMEM)
5501 if ((olh = calloc(1, sz)) == NULL)
5505 if (do_get3(IP_FW_DUMP_SRVOBJECTS, &olh->opheader, &sz) != 0) {
5511 printf("Objects list:\n");
5513 printf("There are no objects\n");
5514 ntlv = (ipfw_obj_ntlv *)(olh + 1);
5515 for (i = 0; i < olh->count; i++) {
5516 name = match_value(otypes, ntlv->head.type);
5518 name = lookup_eaction_name(
5519 (ipfw_obj_ntlv *)(olh + 1), olh->count,
5522 printf(" kidx: %4d\ttype: %10d\tname: %s\n",
5523 ntlv->idx, ntlv->head.type, ntlv->name);
5525 printf(" kidx: %4d\ttype: %10s\tname: %s\n",
5526 ntlv->idx, name, ntlv->name);
5533 ipfw_internal_handler(int ac, char *av[])
5538 NEED1("internal cmd required");
5540 if ((tcmd = match_token(intcmds, *av)) == -1)
5541 errx(EX_USAGE, "invalid internal sub-cmd: %s", *av);
5545 ipfw_list_tifaces();
5548 ipfw_list_ta(ac, av);
5551 ipfw_list_objects(ac, av);
5554 ipfw_list_values(ac, av);
5560 ipfw_get_tracked_ifaces(ipfw_obj_lheader **polh)
5562 ipfw_obj_lheader req, *olh;
5565 memset(&req, 0, sizeof(req));
5568 if (do_get3(IP_FW_XIFLIST, &req.opheader, &sz) != 0) {
5569 if (errno != ENOMEM)
5574 if ((olh = calloc(1, sz)) == NULL)
5578 if (do_get3(IP_FW_XIFLIST, &olh->opheader, &sz) != 0) {
5588 ifinfo_cmp(const void *a, const void *b)
5590 const ipfw_iface_info *ia, *ib;
5592 ia = (const ipfw_iface_info *)a;
5593 ib = (const ipfw_iface_info *)b;
5595 return (stringnum_cmp(ia->ifname, ib->ifname));
5599 * Retrieves table list from kernel,
5600 * optionally sorts it and calls requested function for each table.
5601 * Returns 0 on success.
5604 ipfw_list_tifaces(void)
5606 ipfw_obj_lheader *olh = NULL;
5607 ipfw_iface_info *info;
5611 if ((error = ipfw_get_tracked_ifaces(&olh)) != 0)
5612 err(EX_OSERR, "Unable to request ipfw tracked interface list");
5614 qsort(olh + 1, olh->count, olh->objsize, ifinfo_cmp);
5616 info = (ipfw_iface_info *)(olh + 1);
5617 for (i = 0; i < olh->count; i++) {
5618 if (info->flags & IPFW_IFFLAG_RESOLVED)
5619 printf("%s ifindex: %d refcount: %u changes: %u\n",
5620 info->ifname, info->ifindex, info->refcnt,
5623 printf("%s ifindex: unresolved refcount: %u changes: %u\n",
5624 info->ifname, info->refcnt, info->gencnt);
5625 info = (ipfw_iface_info *)((caddr_t)info + olh->objsize);