2 * Copyright (c) 2002-2003 Luigi Rizzo
3 * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
4 * Copyright (c) 1994 Ugen J.S.Antsilevich
6 * Idea and grammar partially left from:
7 * Copyright (c) 1993 Daniel Boulet
9 * Redistribution and use in source forms, with and without modification,
10 * are permitted provided that this entire comment appears intact.
12 * Redistribution in binary form may occur without any restrictions.
13 * Obviously, it would be nice if you gave credit where credit is due
14 * but requiring it would be too onerous.
16 * This software is provided ``AS IS'' without any warranties of any kind.
18 * NEW command line interface for IP firewall facility
23 #include <sys/types.h>
24 #include <sys/param.h>
25 #include <sys/socket.h>
26 #include <sys/sockio.h>
27 #include <sys/sysctl.h>
44 #include <time.h> /* ctime */
45 #include <timeconv.h> /* _long_to_time */
48 #include <stddef.h> /* offsetof */
50 #include <net/ethernet.h>
51 #include <net/if.h> /* only IFNAMSIZ */
52 #include <netinet/in.h>
53 #include <netinet/in_systm.h> /* only n_short, n_long */
54 #include <netinet/ip.h>
55 #include <netinet/ip_icmp.h>
56 #include <netinet/ip_fw.h>
57 #include <netinet/tcp.h>
58 #include <arpa/inet.h>
60 struct cmdline_opts g_co; /* global options */
66 int show_time; /* show timestamp */
67 uint32_t set_mask; /* enabled sets mask */
68 uint32_t flags; /* request flags */
69 uint32_t first; /* first rule to request */
70 uint32_t last; /* last rule to request */
71 uint32_t dcnt; /* number of dynamic states */
72 ipfw_obj_ctlv *tstate; /* table state data */
75 int resvd_set_number = RESVD_SET;
77 static int ipfw_socket = -1;
79 #define CHECK_LENGTH(v, len) do { \
81 errx(EX_DATAERR, "Rule too long"); \
84 * Check if we have enough space in cmd buffer. Note that since
85 * first 8? u32 words are reserved by reserved header, full cmd
86 * buffer can't be used, so we need to protect from buffer overrun
87 * only. At the beginning, cblen is less than actual buffer size by
88 * size of ipfw_insn_u32 instruction + 1 u32 work. This eliminates need
89 * for checking small instructions fitting in given range.
90 * We also (ab)use the fact that ipfw_insn is always the first field
91 * for any custom instruction.
93 #define CHECK_CMDLEN CHECK_LENGTH(cblen, F_LEN((ipfw_insn *)cmd))
95 #define GET_UINT_ARG(arg, min, max, tok, s_x) do { \
97 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
98 if (_substrcmp(*av, "tablearg") == 0) { \
107 _xval = strtol(*av, &end, 10); \
109 if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
110 errx(EX_DATAERR, "%s: invalid argument: %s", \
111 match_value(s_x, tok), *av); \
113 if (errno == ERANGE || _xval < min || _xval > max) \
114 errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
115 match_value(s_x, tok), min, max, *av); \
117 if (_xval == IP_FW_TARG) \
118 errx(EX_DATAERR, "%s: illegal argument value: %s", \
119 match_value(s_x, tok), *av); \
124 static struct _s_x f_tcpflags[] = {
135 static struct _s_x f_tcpopts[] = {
136 { "mss", IP_FW_TCPOPT_MSS },
137 { "maxseg", IP_FW_TCPOPT_MSS },
138 { "window", IP_FW_TCPOPT_WINDOW },
139 { "sack", IP_FW_TCPOPT_SACK },
140 { "ts", IP_FW_TCPOPT_TS },
141 { "timestamp", IP_FW_TCPOPT_TS },
142 { "cc", IP_FW_TCPOPT_CC },
148 * IP options span the range 0 to 255 so we need to remap them
149 * (though in fact only the low 5 bits are significant).
151 static struct _s_x f_ipopts[] = {
152 { "ssrr", IP_FW_IPOPT_SSRR},
153 { "lsrr", IP_FW_IPOPT_LSRR},
154 { "rr", IP_FW_IPOPT_RR},
155 { "ts", IP_FW_IPOPT_TS},
160 static struct _s_x f_iptos[] = {
161 { "lowdelay", IPTOS_LOWDELAY},
162 { "throughput", IPTOS_THROUGHPUT},
163 { "reliability", IPTOS_RELIABILITY},
164 { "mincost", IPTOS_MINCOST},
165 { "congestion", IPTOS_ECN_CE},
166 { "ecntransport", IPTOS_ECN_ECT0},
167 { "ip tos option", 0},
171 static struct _s_x f_ipoff[] = {
172 { "rf", IP_RF >> 8 },
173 { "df", IP_DF >> 8 },
174 { "mf", IP_MF >> 8 },
179 struct _s_x f_ipdscp[] = {
180 { "af11", IPTOS_DSCP_AF11 >> 2 }, /* 001010 */
181 { "af12", IPTOS_DSCP_AF12 >> 2 }, /* 001100 */
182 { "af13", IPTOS_DSCP_AF13 >> 2 }, /* 001110 */
183 { "af21", IPTOS_DSCP_AF21 >> 2 }, /* 010010 */
184 { "af22", IPTOS_DSCP_AF22 >> 2 }, /* 010100 */
185 { "af23", IPTOS_DSCP_AF23 >> 2 }, /* 010110 */
186 { "af31", IPTOS_DSCP_AF31 >> 2 }, /* 011010 */
187 { "af32", IPTOS_DSCP_AF32 >> 2 }, /* 011100 */
188 { "af33", IPTOS_DSCP_AF33 >> 2 }, /* 011110 */
189 { "af41", IPTOS_DSCP_AF41 >> 2 }, /* 100010 */
190 { "af42", IPTOS_DSCP_AF42 >> 2 }, /* 100100 */
191 { "af43", IPTOS_DSCP_AF43 >> 2 }, /* 100110 */
192 { "be", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
193 { "ef", IPTOS_DSCP_EF >> 2 }, /* 101110 */
194 { "cs0", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
195 { "cs1", IPTOS_DSCP_CS1 >> 2 }, /* 001000 */
196 { "cs2", IPTOS_DSCP_CS2 >> 2 }, /* 010000 */
197 { "cs3", IPTOS_DSCP_CS3 >> 2 }, /* 011000 */
198 { "cs4", IPTOS_DSCP_CS4 >> 2 }, /* 100000 */
199 { "cs5", IPTOS_DSCP_CS5 >> 2 }, /* 101000 */
200 { "cs6", IPTOS_DSCP_CS6 >> 2 }, /* 110000 */
201 { "cs7", IPTOS_DSCP_CS7 >> 2 }, /* 100000 */
205 static struct _s_x limit_masks[] = {
206 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
207 {"src-addr", DYN_SRC_ADDR},
208 {"src-port", DYN_SRC_PORT},
209 {"dst-addr", DYN_DST_ADDR},
210 {"dst-port", DYN_DST_PORT},
215 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
216 * This is only used in this code.
218 #define IPPROTO_ETHERTYPE 0x1000
219 static struct _s_x ether_types[] = {
221 * Note, we cannot use "-:&/" in the names because they are field
222 * separators in the type specifications. Also, we use s = NULL as
223 * end-delimiter, because a type of 0 can be legal.
236 { "pppoe_disc", 0x8863 },
237 { "pppoe_sess", 0x8864 },
238 { "ipx_8022", 0x00E0 },
239 { "ipx_8023", 0x0000 },
240 { "ipx_ii", 0x8137 },
241 { "ipx_snap", 0x8137 },
247 static struct _s_x rule_eactions[] = {
248 { "nat64clat", TOK_NAT64CLAT },
249 { "nat64lsn", TOK_NAT64LSN },
250 { "nat64stl", TOK_NAT64STL },
251 { "nptv6", TOK_NPTV6 },
252 { "tcp-setmss", TOK_TCPSETMSS },
253 { NULL, 0 } /* terminator */
256 static struct _s_x rule_actions[] = {
257 { "abort6", TOK_ABORT6 },
258 { "abort", TOK_ABORT },
259 { "accept", TOK_ACCEPT },
260 { "pass", TOK_ACCEPT },
261 { "allow", TOK_ACCEPT },
262 { "permit", TOK_ACCEPT },
263 { "count", TOK_COUNT },
264 { "pipe", TOK_PIPE },
265 { "queue", TOK_QUEUE },
266 { "divert", TOK_DIVERT },
268 { "netgraph", TOK_NETGRAPH },
269 { "ngtee", TOK_NGTEE },
270 { "fwd", TOK_FORWARD },
271 { "forward", TOK_FORWARD },
272 { "skipto", TOK_SKIPTO },
273 { "deny", TOK_DENY },
274 { "drop", TOK_DENY },
275 { "reject", TOK_REJECT },
276 { "reset6", TOK_RESET6 },
277 { "reset", TOK_RESET },
278 { "unreach6", TOK_UNREACH6 },
279 { "unreach", TOK_UNREACH },
280 { "check-state", TOK_CHECKSTATE },
281 { "//", TOK_COMMENT },
283 { "reass", TOK_REASS },
284 { "setfib", TOK_SETFIB },
285 { "setdscp", TOK_SETDSCP },
286 { "call", TOK_CALL },
287 { "return", TOK_RETURN },
288 { "eaction", TOK_EACTION },
289 { "tcp-setmss", TOK_TCPSETMSS },
290 { NULL, 0 } /* terminator */
293 static struct _s_x rule_action_params[] = {
294 { "altq", TOK_ALTQ },
297 { "untag", TOK_UNTAG },
298 { NULL, 0 } /* terminator */
302 * The 'lookup' instruction accepts one of the following arguments.
303 * -1 is a terminator for the list.
304 * Arguments are passed as v[1] in O_DST_LOOKUP options.
306 static int lookup_key[] = {
307 TOK_DSTIP, TOK_SRCIP, TOK_DSTPORT, TOK_SRCPORT,
308 TOK_UID, TOK_JAIL, TOK_DSCP, -1 };
310 static struct _s_x rule_options[] = {
311 { "tagged", TOK_TAGGED },
314 { "jail", TOK_JAIL },
316 { "limit", TOK_LIMIT },
317 { "set-limit", TOK_SETLIMIT },
318 { "keep-state", TOK_KEEPSTATE },
319 { "record-state", TOK_RECORDSTATE },
320 { "bridged", TOK_LAYER2 },
321 { "layer2", TOK_LAYER2 },
323 { "diverted", TOK_DIVERTED },
324 { "diverted-loopback", TOK_DIVERTEDLOOPBACK },
325 { "diverted-output", TOK_DIVERTEDOUTPUT },
326 { "xmit", TOK_XMIT },
327 { "recv", TOK_RECV },
329 { "fragment", TOK_FRAG },
330 { "frag", TOK_FRAG },
332 { "ipoptions", TOK_IPOPTS },
333 { "ipopts", TOK_IPOPTS },
334 { "iplen", TOK_IPLEN },
335 { "ipid", TOK_IPID },
336 { "ipprecedence", TOK_IPPRECEDENCE },
337 { "dscp", TOK_DSCP },
338 { "iptos", TOK_IPTOS },
339 { "ipttl", TOK_IPTTL },
340 { "ipversion", TOK_IPVER },
341 { "ipver", TOK_IPVER },
342 { "estab", TOK_ESTAB },
343 { "established", TOK_ESTAB },
344 { "setup", TOK_SETUP },
345 { "sockarg", TOK_SOCKARG },
346 { "tcpdatalen", TOK_TCPDATALEN },
347 { "tcpflags", TOK_TCPFLAGS },
348 { "tcpflgs", TOK_TCPFLAGS },
349 { "tcpmss", TOK_TCPMSS },
350 { "tcpoptions", TOK_TCPOPTS },
351 { "tcpopts", TOK_TCPOPTS },
352 { "tcpseq", TOK_TCPSEQ },
353 { "tcpack", TOK_TCPACK },
354 { "tcpwin", TOK_TCPWIN },
355 { "icmptype", TOK_ICMPTYPES },
356 { "icmptypes", TOK_ICMPTYPES },
357 { "dst-ip", TOK_DSTIP },
358 { "src-ip", TOK_SRCIP },
359 { "dst-port", TOK_DSTPORT },
360 { "src-port", TOK_SRCPORT },
361 { "proto", TOK_PROTO },
364 { "mac-type", TOK_MACTYPE },
365 { "verrevpath", TOK_VERREVPATH },
366 { "versrcreach", TOK_VERSRCREACH },
367 { "antispoof", TOK_ANTISPOOF },
368 { "ipsec", TOK_IPSEC },
369 { "icmp6type", TOK_ICMP6TYPES },
370 { "icmp6types", TOK_ICMP6TYPES },
371 { "ext6hdr", TOK_EXT6HDR},
372 { "flow-id", TOK_FLOWID},
377 { "dst-ipv6", TOK_DSTIP6},
378 { "dst-ip6", TOK_DSTIP6},
379 { "src-ipv6", TOK_SRCIP6},
380 { "src-ip6", TOK_SRCIP6},
381 { "lookup", TOK_LOOKUP},
383 { "defer-action", TOK_SKIPACTION },
384 { "defer-immediate-action", TOK_SKIPACTION },
385 { "//", TOK_COMMENT },
387 { "not", TOK_NOT }, /* pseudo option */
388 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
389 { "or", TOK_OR }, /* pseudo option */
390 { "|", /* escape */ TOK_OR }, /* pseudo option */
391 { "{", TOK_STARTBRACE }, /* pseudo option */
392 { "(", TOK_STARTBRACE }, /* pseudo option */
393 { "}", TOK_ENDBRACE }, /* pseudo option */
394 { ")", TOK_ENDBRACE }, /* pseudo option */
395 { NULL, 0 } /* terminator */
398 void bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg);
399 static int ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
400 ipfw_cfg_lheader **pcfg, size_t *psize);
401 static int ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
402 ipfw_cfg_lheader *cfg, size_t sz, int ac, char **av);
403 static void ipfw_list_tifaces(void);
406 static uint16_t pack_object(struct tidx *tstate, const char *name, int otype);
407 static uint16_t pack_table(struct tidx *tstate, const char *name);
409 static char *table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx);
410 static void object_sort_ctlv(ipfw_obj_ctlv *ctlv);
411 static char *object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx,
415 * Simple string buffer API.
416 * Used to simplify buffer passing between function and for
417 * transparent overrun handling.
421 * Allocates new buffer of given size @sz.
423 * Returns 0 on success.
426 bp_alloc(struct buf_pr *b, size_t size)
428 memset(b, 0, sizeof(struct buf_pr));
430 if ((b->buf = calloc(1, size)) == NULL)
441 bp_free(struct buf_pr *b)
448 * Flushes buffer so new writer start from beginning.
451 bp_flush(struct buf_pr *b)
460 * Print message specified by @format and args.
461 * Automatically manage buffer space and transparently handle
464 * Returns number of bytes that should have been printed.
467 bprintf(struct buf_pr *b, const char *format, ...)
472 va_start(args, format);
474 i = vsnprintf(b->ptr, b->avail, format, args);
477 if (i < 0 || (size_t)i > b->avail) {
478 /* Overflow or print error */
491 * Special values printer for tablearg-aware opcodes.
494 bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg)
498 bprintf(bp, "%s", str);
499 if (arg == IP_FW_TARG)
500 bprintf(bp, "tablearg");
502 bprintf(bp, "%u", arg);
506 * Helper routine to print a possibly unaligned uint64_t on
507 * various platform. If width > 0, print the value with
508 * the desired width, followed by a space;
509 * otherwise, return the required width.
512 pr_u64(struct buf_pr *b, void *pd, int width)
515 #define U64_FMT "I64"
517 #define U64_FMT "llu"
520 unsigned long long d;
522 bcopy (pd, &u, sizeof(u));
525 bprintf(b, "%*" U64_FMT " ", width, d) :
526 snprintf(NULL, 0, "%" U64_FMT, d) ;
532 safe_calloc(size_t number, size_t size)
534 void *ret = calloc(number, size);
537 err(EX_OSERR, "calloc");
542 safe_realloc(void *ptr, size_t size)
544 void *ret = realloc(ptr, size);
547 err(EX_OSERR, "realloc");
552 * Compare things like interface or table names.
555 stringnum_cmp(const char *a, const char *b)
567 return (strcmp(a, b));
572 * conditionally runs the command.
573 * Selected options or negative -> getsockopt
576 do_cmd(int optname, void *optval, uintptr_t optlen)
583 if (ipfw_socket == -1)
584 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
586 err(EX_UNAVAILABLE, "socket");
588 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
589 optname == IP_FW_ADD || optname == IP_FW3 ||
590 optname == IP_FW_NAT_GET_CONFIG ||
592 optname == IP_FW_NAT_GET_LOG) {
595 i = getsockopt(ipfw_socket, IPPROTO_IP, optname, optval,
596 (socklen_t *)optlen);
598 i = setsockopt(ipfw_socket, IPPROTO_IP, optname, optval, optlen);
604 * do_set3 - pass ipfw control cmd to kernel
605 * @optname: option name
606 * @optval: pointer to option data
607 * @optlen: option length
609 * Assumes op3 header is already embedded.
610 * Calls setsockopt() with IP_FW3 as kernel-visible opcode.
611 * Returns 0 on success or errno otherwise.
614 do_set3(int optname, ip_fw3_opheader *op3, size_t optlen)
620 if (ipfw_socket == -1)
621 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
623 err(EX_UNAVAILABLE, "socket");
625 op3->opcode = optname;
627 return (setsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, optlen));
631 * do_get3 - pass ipfw control cmd to kernel
632 * @optname: option name
633 * @optval: pointer to option data
634 * @optlen: pointer to option length
636 * Assumes op3 header is already embedded.
637 * Calls getsockopt() with IP_FW3 as kernel-visible opcode.
638 * Returns 0 on success or errno otherwise.
641 do_get3(int optname, ip_fw3_opheader *op3, size_t *optlen)
649 if (ipfw_socket == -1)
650 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
652 err(EX_UNAVAILABLE, "socket");
654 op3->opcode = optname;
657 error = getsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, &len);
664 * match_token takes a table and a string, returns the value associated
665 * with the string (-1 in case of failure).
668 match_token(struct _s_x *table, const char *string)
671 uint i = strlen(string);
673 for (pt = table ; i && pt->s != NULL ; pt++)
674 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
680 * match_token_relaxed takes a table and a string, returns the value associated
681 * with the string for the best match.
684 * value from @table for matched records
685 * -1 for non-matched records
686 * -2 if more than one records match @string.
689 match_token_relaxed(struct _s_x *table, const char *string)
697 for (pt = table ; i != 0 && pt->s != NULL ; pt++) {
698 if (strncmp(pt->s, string, i) != 0)
707 return (c > 0 ? -2: -1);
711 get_token(struct _s_x *table, const char *string, const char *errbase)
715 if ((tcmd = match_token_relaxed(table, string)) < 0)
716 errx(EX_USAGE, "%s %s %s",
717 (tcmd == 0) ? "invalid" : "ambiguous", errbase, string);
723 * match_value takes a table and a value, returns the string associated
724 * with the value (NULL in case of failure).
727 match_value(struct _s_x *p, int value)
729 for (; p->s != NULL; p++)
736 concat_tokens(char *buf, size_t bufsize, struct _s_x *table,
737 const char *delimiter)
743 for (sz = 0, pt = table ; pt->s != NULL; pt++) {
744 l = snprintf(buf + sz, bufsize - sz, "%s%s",
745 (sz == 0) ? "" : delimiter, pt->s);
756 * helper function to process a set of flags and set bits in the
760 fill_flags(struct _s_x *flags, char *p, char **e, uint32_t *set,
763 char *q; /* points to the separator */
765 uint32_t *which; /* mask we are working on */
776 val = match_token(flags, p);
782 *which |= (uint32_t)val;
789 print_flags_buffer(char *buf, size_t sz, struct _s_x *list, uint32_t set)
791 char const *comma = "";
794 for (i = 0; list[i].x != 0; i++) {
795 if ((set & list[i].x) == 0)
799 l = snprintf(buf, sz, "%s%s", comma, list[i].s);
800 if (l < 0 || (size_t)l >= sz)
809 * _substrcmp takes two strings and returns 1 if they do not match,
810 * and 0 if they match exactly or the first string is a sub-string
811 * of the second. A warning is printed to stderr in the case that the
812 * first string is a sub-string of the second.
814 * This function will be removed in the future through the usual
815 * deprecation process.
818 _substrcmp(const char *str1, const char* str2)
821 if (strncmp(str1, str2, strlen(str1)) != 0)
824 if (strlen(str1) != strlen(str2))
825 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
831 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
832 * and 0 if they match exactly or the second string is a sub-string
833 * of the first. A warning is printed to stderr in the case that the
834 * first string does not match the third.
836 * This function exists to warn about the bizarre construction
837 * strncmp(str, "by", 2) which is used to allow people to use a shortcut
838 * for "bytes". The problem is that in addition to accepting "by",
839 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
840 * other string beginning with "by".
842 * This function will be removed in the future through the usual
843 * deprecation process.
846 _substrcmp2(const char *str1, const char* str2, const char* str3)
849 if (strncmp(str1, str2, strlen(str2)) != 0)
852 if (strcmp(str1, str3) != 0)
853 warnx("DEPRECATED: '%s' matched '%s'",
859 * prints one port, symbolic or numeric
862 print_port(struct buf_pr *bp, int proto, uint16_t port)
865 if (proto == IPPROTO_ETHERTYPE) {
868 if (g_co.do_resolv && (s = match_value(ether_types, port)) )
869 bprintf(bp, "%s", s);
871 bprintf(bp, "0x%04x", port);
873 struct servent *se = NULL;
874 if (g_co.do_resolv) {
875 struct protoent *pe = getprotobynumber(proto);
877 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
880 bprintf(bp, "%s", se->s_name);
882 bprintf(bp, "%d", port);
886 static struct _s_x _port_name[] = {
887 {"dst-port", O_IP_DSTPORT},
888 {"src-port", O_IP_SRCPORT},
892 {"mac-type", O_MAC_TYPE},
893 {"tcpdatalen", O_TCPDATALEN},
894 {"tcpmss", O_TCPMSS},
895 {"tcpwin", O_TCPWIN},
896 {"tagged", O_TAGGED},
901 * Print the values in a list 16-bit items of the types above.
902 * XXX todo: add support for mask.
905 print_newports(struct buf_pr *bp, const ipfw_insn_u16 *cmd, int proto, int opcode)
907 const uint16_t *p = cmd->ports;
912 sep = match_value(_port_name, opcode);
915 bprintf(bp, " %s", sep);
918 for (i = F_LEN((const ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
919 bprintf(bp, "%s", sep);
920 print_port(bp, proto, p[0]);
923 print_port(bp, proto, p[1]);
930 * Like strtol, but also translates service names into port numbers
931 * for some protocols.
933 * proto == -1 disables the protocol check;
934 * proto == IPPROTO_ETHERTYPE looks up an internal table
935 * proto == <some value in /etc/protocols> matches the values there.
936 * Returns *end == s in case the parameter is not found.
939 strtoport(char *s, char **end, int base, int proto)
945 *end = s; /* default - not found */
947 return 0; /* not found */
950 return strtol(s, end, base);
953 * find separator. '\\' escapes the next char.
955 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\' ||
956 *s1 == '_' || *s1 == '.') ; s1++)
957 if (*s1 == '\\' && s1[1] != '\0')
960 buf = safe_calloc(s1 - s + 1, 1);
963 * copy into a buffer skipping backslashes
965 for (p = s, i = 0; p != s1 ; p++)
970 if (proto == IPPROTO_ETHERTYPE) {
971 i = match_token(ether_types, buf);
973 if (i != -1) { /* found */
978 struct protoent *pe = NULL;
982 pe = getprotobynumber(proto);
984 se = getservbyname(buf, pe ? pe->p_name : NULL);
988 return ntohs(se->s_port);
991 return 0; /* not found */
995 * Fill the body of the command with the list of port ranges.
998 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
1000 uint16_t a, b, *p = cmd->ports;
1005 a = strtoport(av, &s, 0, proto);
1006 if (s == av) /* empty or invalid argument */
1009 CHECK_LENGTH(cblen, i + 2);
1012 case '-': /* a range */
1014 b = strtoport(av, &s, 0, proto);
1015 /* Reject expressions like '1-abc' or '1-2-3'. */
1016 if (s == av || (*s != ',' && *s != '\0'))
1021 case ',': /* comma separated list */
1026 warnx("port list: invalid separator <%c> in <%s>",
1036 if (i + 1 > F_LEN_MASK)
1037 errx(EX_DATAERR, "too many ports/ranges\n");
1038 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
1044 * Fill the body of the command with the list of DiffServ codepoints.
1047 fill_dscp(ipfw_insn *cmd, char *av, int cblen)
1049 uint32_t *low, *high;
1053 cmd->opcode = O_DSCP;
1054 cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
1058 low = (uint32_t *)(cmd + 1);
1071 if ((code = match_token(f_ipdscp, s)) == -1)
1072 errx(EX_DATAERR, "Unknown DSCP code");
1074 code = strtoul(s, NULL, 10);
1075 if (code < 0 || code > 63)
1076 errx(EX_DATAERR, "Invalid DSCP value");
1080 *high |= 1 << (code - 32);
1088 static struct _s_x icmpcodes[] = {
1089 { "net", ICMP_UNREACH_NET },
1090 { "host", ICMP_UNREACH_HOST },
1091 { "protocol", ICMP_UNREACH_PROTOCOL },
1092 { "port", ICMP_UNREACH_PORT },
1093 { "needfrag", ICMP_UNREACH_NEEDFRAG },
1094 { "srcfail", ICMP_UNREACH_SRCFAIL },
1095 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
1096 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
1097 { "isolated", ICMP_UNREACH_ISOLATED },
1098 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
1099 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
1100 { "tosnet", ICMP_UNREACH_TOSNET },
1101 { "toshost", ICMP_UNREACH_TOSHOST },
1102 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
1103 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
1104 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
1109 fill_reject_code(u_short *codep, char *str)
1114 val = strtoul(str, &s, 0);
1115 if (s == str || *s != '\0' || val >= 0x100)
1116 val = match_token(icmpcodes, str);
1118 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
1124 print_reject_code(struct buf_pr *bp, uint16_t code)
1128 if ((s = match_value(icmpcodes, code)) != NULL)
1129 bprintf(bp, "unreach %s", s);
1131 bprintf(bp, "unreach %u", code);
1135 * Returns the number of bits set (from left) in a contiguous bitmask,
1136 * or -1 if the mask is not contiguous.
1137 * XXX this needs a proper fix.
1138 * This effectively works on masks in big-endian (network) format.
1139 * when compiled on little endian architectures.
1141 * First bit is bit 7 of the first byte -- note, for MAC addresses,
1142 * the first bit on the wire is bit 0 of the first byte.
1143 * len is the max length in bits.
1146 contigmask(const uint8_t *p, int len)
1150 for (i=0; i<len ; i++)
1151 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
1153 for (n=i+1; n < len; n++)
1154 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
1155 return -1; /* mask not contiguous */
1160 * print flags set/clear in the two bitmasks passed as parameters.
1161 * There is a specialized check for f_tcpflags.
1164 print_flags(struct buf_pr *bp, char const *name, const ipfw_insn *cmd,
1167 char const *comma = "";
1169 uint8_t set = cmd->arg1 & 0xff;
1170 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
1172 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
1173 bprintf(bp, " setup");
1177 bprintf(bp, " %s ", name);
1178 for (i=0; list[i].x != 0; i++) {
1179 if (set & list[i].x) {
1181 bprintf(bp, "%s%s", comma, list[i].s);
1184 if (clear & list[i].x) {
1185 clear &= ~list[i].x;
1186 bprintf(bp, "%s!%s", comma, list[i].s);
1194 * Print the ip address contained in a command.
1197 print_ip(struct buf_pr *bp, const struct format_opts *fo,
1198 const ipfw_insn_ip *cmd)
1200 struct hostent *he = NULL;
1201 const struct in_addr *ia;
1202 const uint32_t *a = ((const ipfw_insn_u32 *)cmd)->d;
1203 uint32_t len = F_LEN((const ipfw_insn *)cmd);
1207 if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
1209 const char *arg = "<invalid>";
1211 if (d < sizeof(lookup_key)/sizeof(lookup_key[0]))
1212 arg = match_value(rule_options, lookup_key[d]);
1213 t = table_search_ctlv(fo->tstate,
1214 ((const ipfw_insn *)cmd)->arg1);
1215 bprintf(bp, "lookup %s %s", arg, t);
1218 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
1222 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
1223 cmd->o.opcode == O_IP_DST_LOOKUP) {
1224 t = table_search_ctlv(fo->tstate,
1225 ((const ipfw_insn *)cmd)->arg1);
1226 bprintf(bp, "table(%s", t);
1227 if (len == F_INSN_SIZE(ipfw_insn_u32))
1228 bprintf(bp, ",%u", *a);
1232 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
1233 const uint32_t *map = (const uint32_t *)&cmd->mask;
1234 struct in_addr addr;
1239 x = cmd->o.arg1 - 1;
1241 addr.s_addr = htonl(cmd->addr.s_addr);
1242 bprintf(bp, "%s/%d", inet_ntoa(addr),
1243 contigmask((uint8_t *)&x, 32));
1244 x = cmd->addr.s_addr;
1245 x &= 0xff; /* base */
1247 * Print bits and ranges.
1248 * Locate first bit set (i), then locate first bit unset (j).
1249 * If we have 3+ consecutive bits set, then print them as a
1250 * range, otherwise only print the initial bit and rescan.
1252 for (i=0; i < cmd->o.arg1; i++)
1253 if (map[i/32] & (1<<(i & 31))) {
1254 for (j=i+1; j < cmd->o.arg1; j++)
1255 if (!(map[ j/32] & (1<<(j & 31))))
1257 bprintf(bp, "%c%d", comma, i+x);
1258 if (j>i+2) { /* range has at least 3 elements */
1259 bprintf(bp, "-%d", j-1+x);
1268 * len == 2 indicates a single IP, whereas lists of 1 or more
1269 * addr/mask pairs have len = (2n+1). We convert len to n so we
1270 * use that to count the number of entries.
1272 for (len = len / 2; len > 0; len--, a += 2) {
1273 int mb = /* mask length */
1274 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1275 32 : contigmask((const uint8_t *)&(a[1]), 32);
1276 if (mb == 32 && g_co.do_resolv)
1277 he = gethostbyaddr((const char *)&(a[0]), sizeof(in_addr_t),
1279 if (he != NULL) /* resolved to name */
1280 bprintf(bp, "%s", he->h_name);
1281 else if (mb == 0) /* any */
1283 else { /* numeric IP followed by some kind of mask */
1284 ia = (const struct in_addr *)&a[0];
1285 bprintf(bp, "%s", inet_ntoa(*ia));
1287 ia = (const struct in_addr *)&a[1];
1288 bprintf(bp, ":%s", inet_ntoa(*ia));
1290 bprintf(bp, "/%d", mb);
1298 * prints a MAC address/mask pair
1301 format_mac(struct buf_pr *bp, const uint8_t *addr, const uint8_t *mask)
1303 int l = contigmask(mask, 48);
1306 bprintf(bp, " any");
1308 bprintf(bp, " %02x:%02x:%02x:%02x:%02x:%02x",
1309 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1311 bprintf(bp, "&%02x:%02x:%02x:%02x:%02x:%02x",
1312 mask[0], mask[1], mask[2],
1313 mask[3], mask[4], mask[5]);
1315 bprintf(bp, "/%d", l);
1320 print_mac(struct buf_pr *bp, const ipfw_insn_mac *mac)
1323 bprintf(bp, " MAC");
1324 format_mac(bp, mac->addr, mac->mask);
1325 format_mac(bp, mac->addr + 6, mac->mask + 6);
1329 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1338 type = strtoul(av, &av, 0);
1340 if (*av != ',' && *av != '\0')
1341 errx(EX_DATAERR, "invalid ICMP type");
1344 errx(EX_DATAERR, "ICMP type out of range");
1346 cmd->d[0] |= 1 << type;
1348 cmd->o.opcode = O_ICMPTYPE;
1349 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1353 print_icmptypes(struct buf_pr *bp, const ipfw_insn_u32 *cmd)
1358 bprintf(bp, " icmptypes");
1359 for (i = 0; i < 32; i++) {
1360 if ( (cmd->d[0] & (1 << (i))) == 0)
1362 bprintf(bp, "%c%d", sep, i);
1368 print_dscp(struct buf_pr *bp, const ipfw_insn_u32 *cmd)
1375 bprintf(bp, " dscp");
1378 if (*v & (1 << i)) {
1379 if ((code = match_value(f_ipdscp, i)) != NULL)
1380 bprintf(bp, "%c%s", sep, code);
1382 bprintf(bp, "%c%d", sep, i);
1386 if ((++i % 32) == 0)
1391 #define insntod(cmd, type) ((const ipfw_insn_ ## type *)(cmd))
1393 struct ip_fw_rule *rule;
1394 const ipfw_insn *eaction;
1397 #define HAVE_PROTO 0x0001
1398 #define HAVE_SRCIP 0x0002
1399 #define HAVE_DSTIP 0x0004
1400 #define HAVE_PROBE_STATE 0x0008
1406 init_show_state(struct show_state *state, struct ip_fw_rule *rule)
1409 state->printed = calloc(rule->cmd_len, sizeof(uint8_t));
1410 if (state->printed == NULL)
1413 state->eaction = NULL;
1416 state->or_block = 0;
1421 free_show_state(struct show_state *state)
1424 free(state->printed);
1428 is_printed_opcode(struct show_state *state, const ipfw_insn *cmd)
1431 return (state->printed[cmd - state->rule->cmd]);
1435 mark_printed(struct show_state *state, const ipfw_insn *cmd)
1438 state->printed[cmd - state->rule->cmd] = 1;
1442 print_limit_mask(struct buf_pr *bp, const ipfw_insn_limit *limit)
1444 struct _s_x *p = limit_masks;
1445 char const *comma = " ";
1448 for (x = limit->limit_mask; p->x != 0; p++) {
1449 if ((x & p->x) == p->x) {
1451 bprintf(bp, "%s%s", comma, p->s);
1455 bprint_uint_arg(bp, " ", limit->conn_limit);
1459 print_instruction(struct buf_pr *bp, const struct format_opts *fo,
1460 struct show_state *state, const ipfw_insn *cmd)
1462 struct protoent *pe;
1468 if (is_printed_opcode(state, cmd))
1470 if ((cmd->len & F_OR) != 0 && state->or_block == 0)
1472 if (cmd->opcode != O_IN && (cmd->len & F_NOT) != 0)
1473 bprintf(bp, " not");
1475 switch (cmd->opcode) {
1477 d = 1.0 * insntod(cmd, u32)->d[0] / 0x7fffffff;
1478 bprintf(bp, "prob %f ", d);
1480 case O_PROBE_STATE: /* no need to print anything here */
1481 state->flags |= HAVE_PROBE_STATE;
1484 case O_IP_SRC_LOOKUP:
1488 if (state->flags & HAVE_SRCIP)
1489 bprintf(bp, " src-ip");
1490 print_ip(bp, fo, insntod(cmd, ip));
1493 case O_IP_DST_LOOKUP:
1497 if (state->flags & HAVE_DSTIP)
1498 bprintf(bp, " dst-ip");
1499 print_ip(bp, fo, insntod(cmd, ip));
1502 case O_IP6_SRC_MASK:
1504 if (state->flags & HAVE_SRCIP)
1505 bprintf(bp, " src-ip6");
1506 print_ip6(bp, insntod(cmd, ip6));
1509 case O_IP6_DST_MASK:
1511 if (state->flags & HAVE_DSTIP)
1512 bprintf(bp, " dst-ip6");
1513 print_ip6(bp, insntod(cmd, ip6));
1516 print_flow6id(bp, insntod(cmd, u32));
1520 print_newports(bp, insntod(cmd, u16), state->proto,
1521 (state->flags & (HAVE_SRCIP | HAVE_DSTIP)) ==
1522 (HAVE_SRCIP | HAVE_DSTIP) ? cmd->opcode: 0);
1525 pe = getprotobynumber(cmd->arg1);
1526 if (state->flags & HAVE_PROTO)
1527 bprintf(bp, " proto");
1529 bprintf(bp, " %s", pe->p_name);
1531 bprintf(bp, " %u", cmd->arg1);
1532 state->proto = cmd->arg1;
1535 print_mac(bp, insntod(cmd, mac));
1538 print_newports(bp, insntod(cmd, u16),
1539 IPPROTO_ETHERTYPE, cmd->opcode);
1542 print_flags(bp, "frag", cmd, f_ipoff);
1545 bprintf(bp, " fib %u", cmd->arg1);
1548 bprintf(bp, " sockarg");
1551 bprintf(bp, cmd->len & F_NOT ? " out" : " in");
1554 switch (cmd->arg1) {
1556 bprintf(bp, " diverted");
1559 bprintf(bp, " diverted-output");
1562 bprintf(bp, " diverted-loopback");
1565 bprintf(bp, " diverted-?<%u>", cmd->arg1);
1570 bprintf(bp, " layer2");
1575 if (cmd->opcode == O_XMIT)
1577 else if (cmd->opcode == O_RECV)
1579 else /* if (cmd->opcode == O_VIA) */
1581 switch (insntod(cmd, if)->name[0]) {
1583 bprintf(bp, " %s %s", s,
1584 inet_ntoa(insntod(cmd, if)->p.ip));
1587 bprintf(bp, " %s table(%s)", s,
1588 table_search_ctlv(fo->tstate,
1589 insntod(cmd, if)->p.kidx));
1592 bprintf(bp, " %s %s", s,
1593 insntod(cmd, if)->name);
1596 case O_IP_FLOW_LOOKUP:
1597 s = table_search_ctlv(fo->tstate, cmd->arg1);
1598 bprintf(bp, " flow table(%s", s);
1599 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))
1600 bprintf(bp, ",%u", insntod(cmd, u32)->d[0]);
1609 if (F_LEN(cmd) == 1) {
1610 switch (cmd->opcode) {
1633 bprintf(bp, " %s %u", s, cmd->arg1);
1635 print_newports(bp, insntod(cmd, u16), 0,
1639 bprintf(bp, " ipver %u", cmd->arg1);
1641 case O_IPPRECEDENCE:
1642 bprintf(bp, " ipprecedence %u", cmd->arg1 >> 5);
1645 print_dscp(bp, insntod(cmd, u32));
1648 print_flags(bp, "ipoptions", cmd, f_ipopts);
1651 print_flags(bp, "iptos", cmd, f_iptos);
1654 print_icmptypes(bp, insntod(cmd, u32));
1657 bprintf(bp, " established");
1660 print_flags(bp, "tcpflags", cmd, f_tcpflags);
1663 print_flags(bp, "tcpoptions", cmd, f_tcpopts);
1666 bprintf(bp, " tcpack %d",
1667 ntohl(insntod(cmd, u32)->d[0]));
1670 bprintf(bp, " tcpseq %d",
1671 ntohl(insntod(cmd, u32)->d[0]));
1674 pwd = getpwuid(insntod(cmd, u32)->d[0]);
1676 bprintf(bp, " uid %s", pwd->pw_name);
1678 bprintf(bp, " uid %u",
1679 insntod(cmd, u32)->d[0]);
1682 grp = getgrgid(insntod(cmd, u32)->d[0]);
1684 bprintf(bp, " gid %s", grp->gr_name);
1686 bprintf(bp, " gid %u",
1687 insntod(cmd, u32)->d[0]);
1690 bprintf(bp, " jail %d", insntod(cmd, u32)->d[0]);
1693 bprintf(bp, " verrevpath");
1696 bprintf(bp, " versrcreach");
1699 bprintf(bp, " antispoof");
1702 bprintf(bp, " ipsec");
1705 bprintf(bp, " // %s", (const char *)(cmd + 1));
1708 if (state->flags & HAVE_PROBE_STATE)
1709 bprintf(bp, " keep-state");
1711 bprintf(bp, " record-state");
1713 object_search_ctlv(fo->tstate, cmd->arg1,
1714 IPFW_TLV_STATE_NAME));
1717 if (state->flags & HAVE_PROBE_STATE)
1718 bprintf(bp, " limit");
1720 bprintf(bp, " set-limit");
1721 print_limit_mask(bp, insntod(cmd, limit));
1723 object_search_ctlv(fo->tstate, cmd->arg1,
1724 IPFW_TLV_STATE_NAME));
1727 if (state->flags & HAVE_PROTO)
1728 bprintf(bp, " proto");
1729 bprintf(bp, " ip6");
1732 if (state->flags & HAVE_PROTO)
1733 bprintf(bp, " proto");
1734 bprintf(bp, " ip4");
1737 print_icmp6types(bp, insntod(cmd, u32));
1740 print_ext6hdr(bp, cmd);
1743 if (F_LEN(cmd) == 1)
1744 bprint_uint_arg(bp, " tagged ", cmd->arg1);
1746 print_newports(bp, insntod(cmd, u16),
1750 bprintf(bp, " defer-immediate-action");
1753 bprintf(bp, " [opcode %d len %d]", cmd->opcode,
1756 if (cmd->len & F_OR) {
1758 state->or_block = 1;
1759 } else if (state->or_block != 0) {
1761 state->or_block = 0;
1763 mark_printed(state, cmd);
1769 print_opcode(struct buf_pr *bp, struct format_opts *fo,
1770 struct show_state *state, int opcode)
1775 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
1776 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1777 /* We use zero opcode to print the rest of options */
1778 if (opcode >= 0 && cmd->opcode != opcode)
1781 * Skip O_NOP, when we printing the rest
1782 * of options, it will be handled separately.
1784 if (cmd->opcode == O_NOP && opcode != O_NOP)
1786 if (!print_instruction(bp, fo, state, cmd))
1794 print_fwd(struct buf_pr *bp, const ipfw_insn *cmd)
1796 char buf[INET6_ADDRSTRLEN + IF_NAMESIZE + 2];
1797 const ipfw_insn_sa6 *sa6;
1798 const ipfw_insn_sa *sa;
1801 if (cmd->opcode == O_FORWARD_IP) {
1802 sa = insntod(cmd, sa);
1803 port = sa->sa.sin_port;
1804 if (sa->sa.sin_addr.s_addr == INADDR_ANY)
1805 bprintf(bp, "fwd tablearg");
1807 bprintf(bp, "fwd %s", inet_ntoa(sa->sa.sin_addr));
1809 sa6 = insntod(cmd, sa6);
1810 port = sa6->sa.sin6_port;
1811 bprintf(bp, "fwd ");
1812 if (getnameinfo((const struct sockaddr *)&sa6->sa,
1813 sizeof(struct sockaddr_in6), buf, sizeof(buf), NULL, 0,
1814 NI_NUMERICHOST) == 0)
1815 bprintf(bp, "%s", buf);
1818 bprintf(bp, ",%u", port);
1822 print_action_instruction(struct buf_pr *bp, const struct format_opts *fo,
1823 struct show_state *state, const ipfw_insn *cmd)
1827 if (is_printed_opcode(state, cmd))
1829 switch (cmd->opcode) {
1831 bprintf(bp, "check-state");
1833 s = object_search_ctlv(fo->tstate, cmd->arg1,
1834 IPFW_TLV_STATE_NAME);
1837 bprintf(bp, " :%s", s ? s: "any");
1840 bprintf(bp, "allow");
1843 bprintf(bp, "count");
1846 bprintf(bp, "deny");
1849 if (cmd->arg1 == ICMP_REJECT_RST)
1850 bprintf(bp, "reset");
1851 else if (cmd->arg1 == ICMP_REJECT_ABORT)
1852 bprintf(bp, "abort");
1853 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1854 bprintf(bp, "reject");
1856 print_reject_code(bp, cmd->arg1);
1859 if (cmd->arg1 == ICMP6_UNREACH_RST)
1860 bprintf(bp, "reset6");
1861 else if (cmd->arg1 == ICMP6_UNREACH_ABORT)
1862 bprintf(bp, "abort6");
1864 print_unreach6_code(bp, cmd->arg1);
1867 bprint_uint_arg(bp, "skipto ", cmd->arg1);
1870 bprint_uint_arg(bp, "pipe ", cmd->arg1);
1873 bprint_uint_arg(bp, "queue ", cmd->arg1);
1876 bprint_uint_arg(bp, "divert ", cmd->arg1);
1879 bprint_uint_arg(bp, "tee ", cmd->arg1);
1882 bprint_uint_arg(bp, "netgraph ", cmd->arg1);
1885 bprint_uint_arg(bp, "ngtee ", cmd->arg1);
1892 if (insntod(cmd, log)->max_log > 0)
1893 bprintf(bp, " log logamount %d",
1894 insntod(cmd, log)->max_log);
1896 bprintf(bp, " log");
1900 print_altq_cmd(bp, insntod(cmd, altq));
1904 bprint_uint_arg(bp, cmd->len & F_NOT ? " untag ":
1905 " tag ", cmd->arg1);
1908 if (cmd->arg1 != IP_FW_NAT44_GLOBAL)
1909 bprint_uint_arg(bp, "nat ", cmd->arg1);
1911 bprintf(bp, "nat global");
1914 if (cmd->arg1 == IP_FW_TARG)
1915 bprint_uint_arg(bp, "setfib ", cmd->arg1);
1917 bprintf(bp, "setfib %u", cmd->arg1 & 0x7FFF);
1919 case O_EXTERNAL_ACTION:
1921 * The external action can consists of two following
1922 * each other opcodes - O_EXTERNAL_ACTION and
1923 * O_EXTERNAL_INSTANCE. The first contains the ID of
1924 * name of external action. The second contains the ID
1925 * of name of external action instance.
1926 * NOTE: in case when external action has no named
1927 * instances support, the second opcode isn't needed.
1929 state->eaction = cmd;
1930 s = object_search_ctlv(fo->tstate, cmd->arg1,
1932 if (match_token(rule_eactions, s) != -1)
1933 bprintf(bp, "%s", s);
1935 bprintf(bp, "eaction %s", s);
1937 case O_EXTERNAL_INSTANCE:
1938 if (state->eaction == NULL)
1941 * XXX: we need to teach ipfw(9) to rewrite opcodes
1942 * in the user buffer on rule addition. When we add
1943 * the rule, we specify zero TLV type for
1944 * O_EXTERNAL_INSTANCE object. To show correct
1945 * rule after `ipfw add` we need to search instance
1946 * name with zero type. But when we do `ipfw show`
1947 * we calculate TLV type using IPFW_TLV_EACTION_NAME()
1950 s = object_search_ctlv(fo->tstate, cmd->arg1, 0);
1952 s = object_search_ctlv(fo->tstate,
1953 cmd->arg1, IPFW_TLV_EACTION_NAME(
1954 state->eaction->arg1));
1955 bprintf(bp, " %s", s);
1957 case O_EXTERNAL_DATA:
1958 if (state->eaction == NULL)
1961 * Currently we support data formatting only for
1962 * external data with datalen u16. For unknown data
1963 * print its size in bytes.
1965 if (cmd->len == F_INSN_SIZE(ipfw_insn))
1966 bprintf(bp, " %u", cmd->arg1);
1968 bprintf(bp, " %ubytes",
1969 cmd->len * sizeof(uint32_t));
1972 if (cmd->arg1 == IP_FW_TARG) {
1973 bprintf(bp, "setdscp tablearg");
1976 s = match_value(f_ipdscp, cmd->arg1 & 0x3F);
1978 bprintf(bp, "setdscp %s", s);
1980 bprintf(bp, "setdscp %u", cmd->arg1 & 0x3F);
1983 bprintf(bp, "reass");
1986 if (cmd->len & F_NOT)
1987 bprintf(bp, "return");
1989 bprint_uint_arg(bp, "call ", cmd->arg1);
1992 bprintf(bp, "** unrecognized action %d len %d ",
1993 cmd->opcode, cmd->len);
1995 mark_printed(state, cmd);
2002 print_action(struct buf_pr *bp, struct format_opts *fo,
2003 struct show_state *state, uint8_t opcode)
2008 for (l = state->rule->cmd_len - state->rule->act_ofs,
2009 cmd = ACTION_PTR(state->rule); l > 0;
2010 l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2011 if (cmd->opcode != opcode)
2013 if (!print_action_instruction(bp, fo, state, cmd))
2021 print_proto(struct buf_pr *bp, struct format_opts *fo,
2022 struct show_state *state)
2025 int l, proto, ip4, ip6;
2027 /* Count all O_PROTO, O_IP4, O_IP6 instructions. */
2028 proto = ip4 = ip6 = 0;
2029 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2030 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2031 switch (cmd->opcode) {
2037 if (cmd->len & F_OR)
2042 if (cmd->len & F_OR)
2049 if (proto == 0 && ip4 == 0 && ip6 == 0) {
2050 state->proto = IPPROTO_IP;
2051 state->flags |= HAVE_PROTO;
2055 /* To handle the case { ip4 or ip6 }, print opcode with F_OR first */
2058 cmd = print_opcode(bp, fo, state, ip4 > ip6 ? O_IP4: O_IP6);
2059 if (cmd != NULL && (cmd->len & F_OR))
2060 cmd = print_opcode(bp, fo, state, ip4 > ip6 ? O_IP6: O_IP4);
2061 if (cmd == NULL || (cmd->len & F_OR))
2062 for (l = proto; l > 0; l--) {
2063 cmd = print_opcode(bp, fo, state, O_PROTO);
2064 if (cmd == NULL || (cmd->len & F_OR) == 0)
2067 /* Initialize proto, it is used by print_newports() */
2068 state->flags |= HAVE_PROTO;
2069 if (state->proto == 0 && ip6 != 0)
2070 state->proto = IPPROTO_IPV6;
2074 match_opcode(int opcode, const int opcodes[], size_t nops)
2078 for (i = 0; i < nops; i++)
2079 if (opcode == opcodes[i])
2085 print_address(struct buf_pr *bp, struct format_opts *fo,
2086 struct show_state *state, const int opcodes[], size_t nops, int portop,
2090 int count, l, portcnt, pf;
2092 count = portcnt = 0;
2093 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2094 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2095 if (match_opcode(cmd->opcode, opcodes, nops))
2097 else if (cmd->opcode == portop)
2101 bprintf(bp, " any");
2102 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2103 l > 0 && count > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2104 if (!match_opcode(cmd->opcode, opcodes, nops))
2106 print_instruction(bp, fo, state, cmd);
2107 if ((cmd->len & F_OR) == 0)
2112 * If several O_IP_?PORT opcodes specified, leave them to the
2116 for (l = state->rule->act_ofs, cmd = state->rule->cmd, pf = 0;
2117 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2118 if (cmd->opcode != portop) {
2119 pf = (cmd->len & F_OR);
2122 /* Print opcode iff it is not in OR block. */
2123 if (pf == 0 && (cmd->len & F_OR) == 0)
2124 print_instruction(bp, fo, state, cmd);
2128 state->flags |= flag;
2131 static const int action_opcodes[] = {
2132 O_CHECK_STATE, O_ACCEPT, O_COUNT, O_DENY, O_REJECT,
2133 O_UNREACH6, O_SKIPTO, O_PIPE, O_QUEUE, O_DIVERT, O_TEE,
2134 O_NETGRAPH, O_NGTEE, O_FORWARD_IP, O_FORWARD_IP6, O_NAT,
2135 O_SETFIB, O_SETDSCP, O_REASS, O_CALLRETURN,
2136 /* keep the following opcodes at the end of the list */
2137 O_EXTERNAL_ACTION, O_EXTERNAL_INSTANCE, O_EXTERNAL_DATA
2140 static const int modifier_opcodes[] = {
2141 O_LOG, O_ALTQ, O_TAG
2144 static const int src_opcodes[] = {
2145 O_IP_SRC, O_IP_SRC_LOOKUP, O_IP_SRC_MASK, O_IP_SRC_ME,
2146 O_IP_SRC_SET, O_IP6_SRC, O_IP6_SRC_MASK, O_IP6_SRC_ME
2149 static const int dst_opcodes[] = {
2150 O_IP_DST, O_IP_DST_LOOKUP, O_IP_DST_MASK, O_IP_DST_ME,
2151 O_IP_DST_SET, O_IP6_DST, O_IP6_DST_MASK, O_IP6_DST_ME
2155 show_static_rule(struct cmdline_opts *co, struct format_opts *fo,
2156 struct buf_pr *bp, struct ip_fw_rule *rule, struct ip_fw_bcounter *cntr)
2158 static int twidth = 0;
2159 struct show_state state;
2163 /* Print # DISABLED or skip the rule */
2164 if ((fo->set_mask & (1 << rule->set)) == 0) {
2169 bprintf(bp, "# DISABLED ");
2171 if (init_show_state(&state, rule) != 0) {
2172 warn("init_show_state() failed");
2175 bprintf(bp, "%05u ", rule->rulenum);
2177 /* Print counters if enabled */
2178 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2179 pr_u64(bp, &cntr->pcnt, fo->pcwidth);
2180 pr_u64(bp, &cntr->bcnt, fo->bcwidth);
2183 /* Print timestamp */
2184 if (co->do_time == TIMESTAMP_NUMERIC)
2185 bprintf(bp, "%10u ", cntr->timestamp);
2186 else if (co->do_time == TIMESTAMP_STRING) {
2188 time_t t = (time_t)0;
2191 strcpy(timestr, ctime(&t));
2192 *strchr(timestr, '\n') = '\0';
2193 twidth = strlen(timestr);
2195 if (cntr->timestamp > 0) {
2196 t = _long_to_time(cntr->timestamp);
2198 strcpy(timestr, ctime(&t));
2199 *strchr(timestr, '\n') = '\0';
2200 bprintf(bp, "%s ", timestr);
2202 bprintf(bp, "%*s ", twidth, "");
2206 /* Print set number */
2208 bprintf(bp, "set %d ", rule->set);
2210 /* Print the optional "match probability" */
2211 cmd = print_opcode(bp, fo, &state, O_PROB);
2212 /* Print rule action */
2213 for (i = 0; i < nitems(action_opcodes); i++) {
2214 cmd = print_action(bp, fo, &state, action_opcodes[i]);
2217 /* Handle special cases */
2218 switch (cmd->opcode) {
2221 case O_EXTERNAL_ACTION:
2222 case O_EXTERNAL_INSTANCE:
2223 /* External action can have several instructions */
2228 /* Print rule modifiers */
2229 for (i = 0; i < nitems(modifier_opcodes); i++)
2230 print_action(bp, fo, &state, modifier_opcodes[i]);
2234 if (co->comment_only != 0)
2237 if (rule->flags & IPFW_RULE_JUSTOPTS) {
2238 state.flags |= HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP;
2242 print_proto(bp, fo, &state);
2243 if (co->do_compact != 0 && (rule->flags & IPFW_RULE_NOOPT))
2247 bprintf(bp, " from");
2248 print_address(bp, fo, &state, src_opcodes, nitems(src_opcodes),
2249 O_IP_SRCPORT, HAVE_SRCIP);
2251 /* Print destination */
2253 print_address(bp, fo, &state, dst_opcodes, nitems(dst_opcodes),
2254 O_IP_DSTPORT, HAVE_DSTIP);
2257 /* Print the rest of options */
2258 while (print_opcode(bp, fo, &state, -1))
2261 /* Print comment at the end */
2262 cmd = print_opcode(bp, fo, &state, O_NOP);
2263 if (co->comment_only != 0 && cmd == NULL)
2264 bprintf(bp, " // ...");
2266 free_show_state(&state);
2270 show_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2271 struct buf_pr *bp, ipfw_dyn_rule *d)
2273 struct protoent *pe;
2276 char buf[INET6_ADDRSTRLEN];
2278 if (d->expire == 0 && d->dyn_type != O_LIMIT_PARENT)
2281 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2282 bprintf(bp, "%05d", rulenum);
2283 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2285 pr_u64(bp, &d->pcnt, fo->pcwidth);
2286 pr_u64(bp, &d->bcnt, fo->bcwidth);
2287 bprintf(bp, "(%ds)", d->expire);
2289 switch (d->dyn_type) {
2290 case O_LIMIT_PARENT:
2291 bprintf(bp, " PARENT %d", d->count);
2294 bprintf(bp, " LIMIT");
2296 case O_KEEP_STATE: /* bidir, no mask */
2297 bprintf(bp, " STATE");
2301 if ((pe = getprotobynumber(d->id.proto)) != NULL)
2302 bprintf(bp, " %s", pe->p_name);
2304 bprintf(bp, " proto %u", d->id.proto);
2306 if (d->id.addr_type == 4) {
2307 a.s_addr = htonl(d->id.src_ip);
2308 bprintf(bp, " %s %d", inet_ntoa(a), d->id.src_port);
2310 a.s_addr = htonl(d->id.dst_ip);
2311 bprintf(bp, " <-> %s %d", inet_ntoa(a), d->id.dst_port);
2312 } else if (d->id.addr_type == 6) {
2313 bprintf(bp, " %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
2314 sizeof(buf)), d->id.src_port);
2315 bprintf(bp, " <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6,
2316 buf, sizeof(buf)), d->id.dst_port);
2318 bprintf(bp, " UNKNOWN <-> UNKNOWN");
2320 bprintf(bp, " :%s", object_search_ctlv(fo->tstate,
2321 d->kidx, IPFW_TLV_STATE_NAME));
2323 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
2324 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
2326 bprintf(bp, " state 0x%08x%s", d->state,
2327 d->state ? " ": ",");
2328 if (d->state & IPFW_DYN_ORPHANED)
2329 bprintf(bp, "ORPHANED,");
2330 if ((d->state & BOTH_SYN) == BOTH_SYN)
2331 bprintf(bp, "BOTH_SYN,");
2333 if (d->state & TH_SYN)
2334 bprintf(bp, "F_SYN,");
2335 if (d->state & (TH_SYN << 8))
2336 bprintf(bp, "R_SYN,");
2338 if ((d->state & BOTH_FIN) == BOTH_FIN)
2339 bprintf(bp, "BOTH_FIN,");
2341 if (d->state & TH_FIN)
2342 bprintf(bp, "F_FIN,");
2343 if (d->state & (TH_FIN << 8))
2344 bprintf(bp, "R_FIN,");
2346 bprintf(bp, " f_ack 0x%x, r_ack 0x%x", d->ack_fwd,
2352 do_range_cmd(int cmd, ipfw_range_tlv *rt)
2354 ipfw_range_header rh;
2357 memset(&rh, 0, sizeof(rh));
2358 memcpy(&rh.range, rt, sizeof(*rt));
2359 rh.range.head.length = sizeof(*rt);
2360 rh.range.head.type = IPFW_TLV_RANGE;
2363 if (do_get3(cmd, &rh.opheader, &sz) != 0)
2365 /* Save number of matched objects */
2366 rt->new_set = rh.range.new_set;
2371 * This one handles all set-related commands
2372 * ipfw set { show | enable | disable }
2374 * ipfw set move X to Y
2375 * ipfw set move rule X to Y
2378 ipfw_sets_handler(char *av[])
2389 memset(&rt, 0, sizeof(rt));
2392 errx(EX_USAGE, "set needs command");
2393 if (_substrcmp(*av, "show") == 0) {
2394 struct format_opts fo;
2395 ipfw_cfg_lheader *cfg;
2397 memset(&fo, 0, sizeof(fo));
2398 if (ipfw_get_config(&g_co, &fo, &cfg, &size) != 0)
2399 err(EX_OSERR, "requesting config failed");
2401 for (i = 0, msg = "disable"; i < RESVD_SET; i++)
2402 if ((cfg->set_mask & (1<<i)) == 0) {
2403 printf("%s %d", msg, i);
2406 msg = (cfg->set_mask != (uint32_t)-1) ? " enable" : "enable";
2407 for (i = 0; i < RESVD_SET; i++)
2408 if ((cfg->set_mask & (1<<i)) != 0) {
2409 printf("%s %d", msg, i);
2414 } else if (_substrcmp(*av, "swap") == 0) {
2416 if ( av[0] == NULL || av[1] == NULL )
2417 errx(EX_USAGE, "set swap needs 2 set numbers\n");
2418 rt.set = atoi(av[0]);
2419 rt.new_set = atoi(av[1]);
2420 if (!isdigit(*(av[0])) || rt.set > RESVD_SET)
2421 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2422 if (!isdigit(*(av[1])) || rt.new_set > RESVD_SET)
2423 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2424 i = do_range_cmd(IP_FW_SET_SWAP, &rt);
2425 } else if (_substrcmp(*av, "move") == 0) {
2427 if (av[0] && _substrcmp(*av, "rule") == 0) {
2428 rt.flags = IPFW_RCFLAG_RANGE; /* move rules to new set */
2432 cmd = IP_FW_SET_MOVE; /* Move set to new one */
2433 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
2434 av[3] != NULL || _substrcmp(av[1], "to") != 0)
2435 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2436 rulenum = atoi(av[0]);
2437 rt.new_set = atoi(av[2]);
2438 if (cmd == IP_FW_XMOVE) {
2439 rt.start_rule = rulenum;
2440 rt.end_rule = rulenum;
2443 rt.new_set = atoi(av[2]);
2444 if (!isdigit(*(av[0])) || (cmd == 3 && rt.set > RESVD_SET) ||
2445 (cmd == 2 && rt.start_rule == IPFW_DEFAULT_RULE) )
2446 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2447 if (!isdigit(*(av[2])) || rt.new_set > RESVD_SET)
2448 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2449 i = do_range_cmd(cmd, &rt);
2451 err(EX_OSERR, "failed to move %s",
2452 cmd == IP_FW_SET_MOVE ? "set": "rule");
2453 } else if (_substrcmp(*av, "disable") == 0 ||
2454 _substrcmp(*av, "enable") == 0 ) {
2455 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2458 masks[0] = masks[1] = 0;
2461 if (isdigit(**av)) {
2463 if (i < 0 || i > RESVD_SET)
2465 "invalid set number %d\n", i);
2466 masks[which] |= (1<<i);
2467 } else if (_substrcmp(*av, "disable") == 0)
2469 else if (_substrcmp(*av, "enable") == 0)
2473 "invalid set command %s\n", *av);
2476 if ( (masks[0] & masks[1]) != 0 )
2478 "cannot enable and disable the same set\n");
2481 rt.new_set = masks[1];
2482 i = do_range_cmd(IP_FW_SET_ENABLE, &rt);
2484 warn("set enable/disable: setsockopt(IP_FW_SET_ENABLE)");
2486 errx(EX_USAGE, "invalid set command %s\n", *av);
2490 ipfw_sysctl_handler(char *av[], int which)
2494 if (av[0] == NULL) {
2495 warnx("missing keyword to enable/disable\n");
2496 } else if (_substrcmp(*av, "firewall") == 0) {
2497 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2498 &which, sizeof(which));
2499 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
2500 &which, sizeof(which));
2501 } else if (_substrcmp(*av, "one_pass") == 0) {
2502 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2503 &which, sizeof(which));
2504 } else if (_substrcmp(*av, "debug") == 0) {
2505 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2506 &which, sizeof(which));
2507 } else if (_substrcmp(*av, "verbose") == 0) {
2508 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2509 &which, sizeof(which));
2510 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2511 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2512 &which, sizeof(which));
2514 } else if (_substrcmp(*av, "altq") == 0) {
2515 altq_set_enabled(which);
2518 warnx("unrecognize enable/disable keyword: %s\n", *av);
2522 typedef void state_cb(struct cmdline_opts *co, struct format_opts *fo,
2523 void *arg, void *state);
2526 prepare_format_dyn(struct cmdline_opts *co, struct format_opts *fo,
2527 void *arg __unused, void *_state)
2533 d = (ipfw_dyn_rule *)_state;
2534 /* Count _ALL_ states */
2537 if (fo->show_counters == 0)
2541 /* skip states from another set */
2542 bcopy((char *)&d->rule + sizeof(uint16_t), &set,
2544 if (set != co->use_set - 1)
2548 width = pr_u64(NULL, &d->pcnt, 0);
2549 if (width > fo->pcwidth)
2550 fo->pcwidth = width;
2552 width = pr_u64(NULL, &d->bcnt, 0);
2553 if (width > fo->bcwidth)
2554 fo->bcwidth = width;
2558 foreach_state(struct cmdline_opts *co, struct format_opts *fo,
2559 caddr_t base, size_t sz, state_cb dyn_bc, void *dyn_arg)
2565 ipfw_obj_ctlv *ctlv;
2571 ctlv = (ipfw_obj_ctlv *)base;
2572 switch (ctlv->head.type) {
2573 case IPFW_TLV_DYNSTATE_LIST:
2574 base += sizeof(*ctlv);
2575 sz -= sizeof(*ctlv);
2576 ttype = IPFW_TLV_DYN_ENT;
2585 tlv = (ipfw_obj_tlv *)base;
2586 if (tlv->type != ttype)
2589 fptr(co, fo, farg, tlv + 1);
2591 base += tlv->length;
2599 prepare_format_opts(struct cmdline_opts *co, struct format_opts *fo,
2600 ipfw_obj_tlv *rtlv, int rcnt, caddr_t dynbase, size_t dynsz)
2602 int bcwidth, pcwidth, width;
2604 struct ip_fw_bcounter *cntr;
2605 struct ip_fw_rule *r;
2609 if (fo->show_counters != 0) {
2610 for (n = 0; n < rcnt; n++,
2611 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2612 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2613 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2614 /* skip rules from another set */
2615 if (co->use_set && r->set != co->use_set - 1)
2618 /* packet counter */
2619 width = pr_u64(NULL, &cntr->pcnt, 0);
2620 if (width > pcwidth)
2624 width = pr_u64(NULL, &cntr->bcnt, 0);
2625 if (width > bcwidth)
2629 fo->bcwidth = bcwidth;
2630 fo->pcwidth = pcwidth;
2633 if (co->do_dynamic && dynsz > 0)
2634 foreach_state(co, fo, dynbase, dynsz, prepare_format_dyn, NULL);
2638 list_static_range(struct cmdline_opts *co, struct format_opts *fo,
2639 struct buf_pr *bp, ipfw_obj_tlv *rtlv, int rcnt)
2642 struct ip_fw_rule *r;
2643 struct ip_fw_bcounter *cntr;
2646 for (n = seen = 0; n < rcnt; n++,
2647 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2649 if ((fo->show_counters | fo->show_time) != 0) {
2650 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2651 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2654 r = (struct ip_fw_rule *)(rtlv + 1);
2656 if (r->rulenum > fo->last)
2658 if (co->use_set && r->set != co->use_set - 1)
2660 if (r->rulenum >= fo->first && r->rulenum <= fo->last) {
2661 show_static_rule(co, fo, bp, r, cntr);
2662 printf("%s", bp->buf);
2673 list_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2674 void *_arg, void *_state)
2681 d = (ipfw_dyn_rule *)_state;
2682 bp = (struct buf_pr *)_arg;
2684 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2685 if (rulenum > fo->last)
2688 bcopy((char *)&d->rule + sizeof(uint16_t),
2689 &set, sizeof(uint8_t));
2690 if (set != co->use_set - 1)
2693 if (rulenum >= fo->first) {
2694 show_dyn_state(co, fo, bp, d);
2695 printf("%s\n", bp->buf);
2701 list_dyn_range(struct cmdline_opts *co, struct format_opts *fo,
2702 struct buf_pr *bp, caddr_t base, size_t sz)
2705 sz = foreach_state(co, fo, base, sz, list_dyn_state, bp);
2710 ipfw_list(int ac, char *av[], int show_counters)
2712 ipfw_cfg_lheader *cfg;
2713 struct format_opts sfo;
2721 if (g_co.test_only) {
2722 fprintf(stderr, "Testing only, list disabled\n");
2726 dummynet_list(ac, av, show_counters);
2732 memset(&sfo, 0, sizeof(sfo));
2734 /* Determine rule range to request */
2736 for (lac = ac, lav = av; lac != 0; lac--) {
2737 rnum = strtoul(*lav++, &endptr, 10);
2738 if (sfo.first == 0 || rnum < sfo.first)
2742 rnum = strtoul(endptr + 1, &endptr, 10);
2743 if (sfo.last == 0 || rnum > sfo.last)
2748 /* get configuraion from kernel */
2750 sfo.show_counters = show_counters;
2751 sfo.show_time = g_co.do_time;
2752 if (g_co.do_dynamic != 2)
2753 sfo.flags |= IPFW_CFG_GET_STATIC;
2754 if (g_co.do_dynamic != 0)
2755 sfo.flags |= IPFW_CFG_GET_STATES;
2756 if ((sfo.show_counters | sfo.show_time) != 0)
2757 sfo.flags |= IPFW_CFG_GET_COUNTERS;
2758 if (ipfw_get_config(&g_co, &sfo, &cfg, &sz) != 0)
2759 err(EX_OSERR, "retrieving config failed");
2761 error = ipfw_show_config(&g_co, &sfo, cfg, sz, ac, av);
2770 ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
2771 ipfw_cfg_lheader *cfg, size_t sz, int ac, char *av[])
2776 int exitval = EX_OK;
2782 ipfw_obj_ctlv *ctlv, *tstate;
2783 ipfw_obj_tlv *rbase;
2786 * Handle tablenames TLV first, if any
2792 readsz = sizeof(*cfg);
2795 fo->set_mask = cfg->set_mask;
2797 ctlv = (ipfw_obj_ctlv *)(cfg + 1);
2798 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2799 object_sort_ctlv(ctlv);
2801 readsz += ctlv->head.length;
2802 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
2805 if (cfg->flags & IPFW_CFG_GET_STATIC) {
2806 /* We've requested static rules */
2807 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2808 rbase = (ipfw_obj_tlv *)(ctlv + 1);
2810 readsz += ctlv->head.length;
2811 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2816 if ((cfg->flags & IPFW_CFG_GET_STATES) && (readsz != sz)) {
2817 /* We may have some dynamic states */
2818 dynsz = sz - readsz;
2819 /* Skip empty header */
2820 if (dynsz != sizeof(ipfw_obj_ctlv))
2821 dynbase = (caddr_t)ctlv;
2826 prepare_format_opts(co, fo, rbase, rcnt, dynbase, dynsz);
2827 bp_alloc(&bp, 4096);
2829 /* if no rule numbers were specified, list all rules */
2832 fo->last = IPFW_DEFAULT_RULE;
2833 if (cfg->flags & IPFW_CFG_GET_STATIC)
2834 list_static_range(co, fo, &bp, rbase, rcnt);
2836 if (co->do_dynamic && dynsz > 0) {
2837 printf("## Dynamic rules (%d %zu):\n", fo->dcnt,
2839 list_dyn_range(co, fo, &bp, dynbase, dynsz);
2846 /* display specific rules requested on command line */
2847 for (lac = ac, lav = av; lac != 0; lac--) {
2848 /* convert command line rule # */
2849 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2851 fo->last = strtoul(endptr + 1, &endptr, 10);
2854 warnx("invalid rule number: %s", *(lav - 1));
2858 if ((cfg->flags & IPFW_CFG_GET_STATIC) == 0)
2861 if (list_static_range(co, fo, &bp, rbase, rcnt) == 0) {
2862 /* give precedence to other error(s) */
2863 if (exitval == EX_OK)
2864 exitval = EX_UNAVAILABLE;
2865 if (fo->first == fo->last)
2866 warnx("rule %u does not exist", fo->first);
2868 warnx("no rules in range %u-%u",
2869 fo->first, fo->last);
2873 if (co->do_dynamic && dynsz > 0) {
2874 printf("## Dynamic rules:\n");
2875 for (lac = ac, lav = av; lac != 0; lac--) {
2876 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2878 fo->last = strtoul(endptr+1, &endptr, 10);
2880 /* already warned */
2882 list_dyn_range(co, fo, &bp, dynbase, dynsz);
2892 * Retrieves current ipfw configuration of given type
2893 * and stores its pointer to @pcfg.
2895 * Caller is responsible for freeing @pcfg.
2897 * Returns 0 on success.
2901 ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
2902 ipfw_cfg_lheader **pcfg, size_t *psize)
2904 ipfw_cfg_lheader *cfg;
2909 if (co->test_only != 0) {
2910 fprintf(stderr, "Testing only, list disabled\n");
2914 /* Start with some data size */
2918 for (i = 0; i < 16; i++) {
2921 if ((cfg = calloc(1, sz)) == NULL)
2924 cfg->flags = fo->flags;
2925 cfg->start_rule = fo->first;
2926 cfg->end_rule = fo->last;
2928 if (do_get3(IP_FW_XGET, &cfg->opheader, &sz) != 0) {
2929 if (errno != ENOMEM) {
2934 /* Buffer size is not enough. Try to increase */
2951 lookup_host (char *host, struct in_addr *ipaddr)
2955 if (!inet_aton(host, ipaddr)) {
2956 if ((he = gethostbyname(host)) == NULL)
2958 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2972 ipfw_check_object_name(const char *name)
2977 * Check that name is null-terminated and contains
2978 * valid symbols only. Valid mask is:
2979 * [a-zA-Z0-9\-_\.]{1,63}
2982 if (l == 0 || l >= 64)
2984 for (i = 0; i < l; i++) {
2986 if (isalpha(c) || isdigit(c) || c == '_' ||
2987 c == '-' || c == '.')
2994 static const char *default_state_name = "default";
2997 state_check_name(const char *name)
3000 if (ipfw_check_object_name(name) != 0)
3002 if (strcmp(name, "any") == 0)
3008 eaction_check_name(const char *name)
3011 if (ipfw_check_object_name(name) != 0)
3013 /* Restrict some 'special' names */
3014 if (match_token(rule_actions, name) != -1 &&
3015 match_token(rule_action_params, name) != -1)
3021 pack_object(struct tidx *tstate, const char *name, int otype)
3023 ipfw_obj_ntlv *ntlv;
3026 for (i = 0; i < tstate->count; i++) {
3027 if (strcmp(tstate->idx[i].name, name) != 0)
3029 if (tstate->idx[i].set != tstate->set)
3031 if (tstate->idx[i].head.type != otype)
3034 return (tstate->idx[i].idx);
3037 if (tstate->count + 1 > tstate->size) {
3039 tstate->idx = realloc(tstate->idx, tstate->size *
3040 sizeof(ipfw_obj_ntlv));
3041 if (tstate->idx == NULL)
3045 ntlv = &tstate->idx[i];
3046 memset(ntlv, 0, sizeof(ipfw_obj_ntlv));
3047 strlcpy(ntlv->name, name, sizeof(ntlv->name));
3048 ntlv->head.type = otype;
3049 ntlv->head.length = sizeof(ipfw_obj_ntlv);
3050 ntlv->set = tstate->set;
3051 ntlv->idx = ++tstate->counter;
3058 pack_table(struct tidx *tstate, const char *name)
3061 if (table_check_name(name) != 0)
3064 return (pack_object(tstate, name, IPFW_TLV_TBL_NAME));
3068 fill_table(struct _ipfw_insn *cmd, char *av, uint8_t opcode,
3069 struct tidx *tstate)
3071 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
3075 if ((p = strchr(av + 6, ')')) == NULL)
3076 errx(EX_DATAERR, "forgotten parenthesis: '%s'", av);
3078 p = strchr(av + 6, ',');
3082 if ((uidx = pack_table(tstate, av + 6)) == 0)
3083 errx(EX_DATAERR, "Invalid table name: %s", av + 6);
3085 cmd->opcode = opcode;
3088 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3089 d[0] = strtoul(p, NULL, 0);
3091 cmd->len |= F_INSN_SIZE(ipfw_insn);
3096 * fills the addr and mask fields in the instruction as appropriate from av.
3097 * Update length as appropriate.
3098 * The following formats are allowed:
3099 * me returns O_IP_*_ME
3100 * 1.2.3.4 single IP address
3101 * 1.2.3.4:5.6.7.8 address:mask
3102 * 1.2.3.4/24 address/mask
3103 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
3104 * We can have multiple comma-separated address/mask entries.
3107 fill_ip(ipfw_insn_ip *cmd, char *av, int cblen, struct tidx *tstate)
3110 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
3112 cmd->o.len &= ~F_LEN_MASK; /* zero len */
3114 if (_substrcmp(av, "any") == 0)
3117 if (_substrcmp(av, "me") == 0) {
3118 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
3122 if (strncmp(av, "table(", 6) == 0) {
3123 fill_table(&cmd->o, av, O_IP_DST_LOOKUP, tstate);
3129 * After the address we can have '/' or ':' indicating a mask,
3130 * ',' indicating another address follows, '{' indicating a
3131 * set of addresses of unspecified size.
3133 char *t = NULL, *p = strpbrk(av, "/:,{");
3137 CHECK_LENGTH(cblen, (int)F_INSN_SIZE(ipfw_insn) + 2 + len);
3142 if ((t = strpbrk(p, ",{")) != NULL) {
3149 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
3150 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
3153 if (!inet_aton(p, (struct in_addr *)&d[1]))
3154 errx(EX_DATAERR, "bad netmask ``%s''", p);
3159 d[1] = htonl(0U); /* mask */
3160 else if (masklen > 32)
3161 errx(EX_DATAERR, "bad width ``%s''", p);
3163 d[1] = htonl(~0U << (32 - masklen));
3165 case '{': /* no mask, assume /24 and put back the '{' */
3166 d[1] = htonl(~0U << (32 - 24));
3170 case ',': /* single address plus continuation */
3173 case 0: /* initialization value */
3175 d[1] = htonl(~0U); /* force /32 */
3178 d[0] &= d[1]; /* mask base address with mask */
3181 /* find next separator */
3183 p = strpbrk(p, ",{");
3184 if (p && *p == '{') {
3186 * We have a set of addresses. They are stored as follows:
3187 * arg1 is the set size (powers of 2, 2..256)
3188 * addr is the base address IN HOST FORMAT
3189 * mask.. is an array of arg1 bits (rounded up to
3190 * the next multiple of 32) with bits set
3191 * for each host in the map.
3193 uint32_t *map = (uint32_t *)&cmd->mask;
3195 int i = contigmask((uint8_t *)&(d[1]), 32);
3198 errx(EX_DATAERR, "address set cannot be in a list");
3199 if (i < 24 || i > 31)
3200 errx(EX_DATAERR, "invalid set with mask %d\n", i);
3201 cmd->o.arg1 = 1<<(32-i); /* map length */
3202 d[0] = ntohl(d[0]); /* base addr in host format */
3203 cmd->o.opcode = O_IP_DST_SET; /* default */
3204 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
3205 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
3206 map[i] = 0; /* clear map */
3210 high = low + cmd->o.arg1 - 1;
3212 * Here, i stores the previous value when we specify a range
3213 * of addresses within a mask, e.g. 45-63. i = -1 means we
3214 * have no previous value.
3216 i = -1; /* previous value in a range */
3217 while (isdigit(*av)) {
3219 int a = strtol(av, &s, 0);
3221 if (s == av) { /* no parameter */
3223 errx(EX_DATAERR, "set not closed\n");
3225 errx(EX_DATAERR, "incomplete range %d-", i);
3228 if (a < low || a > high)
3229 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
3232 if (i == -1) /* no previous in range */
3234 else { /* check that range is valid */
3236 errx(EX_DATAERR, "invalid range %d-%d",
3239 errx(EX_DATAERR, "double '-' in range");
3242 map[i/32] |= 1<<(i & 31);
3253 if (av) /* then *av must be a ',' */
3256 /* Check this entry */
3257 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
3259 * 'any' turns the entire list into a NOP.
3260 * 'not any' never matches, so it is removed from the
3261 * list unless it is the only item, in which case we
3264 if (cmd->o.len & F_NOT) { /* "not any" never matches */
3265 if (av == NULL && len == 0) /* only this entry */
3266 errx(EX_DATAERR, "not any never matches");
3268 /* else do nothing and skip this entry */
3271 /* A single IP can be stored in an optimized format */
3272 if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
3273 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
3276 len += 2; /* two words... */
3279 if (len + 1 > F_LEN_MASK)
3280 errx(EX_DATAERR, "address list too long");
3281 cmd->o.len |= len+1;
3285 /* n2mask sets n bits of the mask */
3287 n2mask(struct in6_addr *mask, int n)
3289 static int minimask[9] =
3290 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
3293 memset(mask, 0, sizeof(struct in6_addr));
3294 p = (u_char *) mask;
3295 for (; n > 0; p++, n -= 8) {
3305 fill_flags_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3306 struct _s_x *flags, char *p)
3309 uint32_t set = 0, clear = 0;
3311 if (fill_flags(flags, p, &e, &set, &clear) != 0)
3312 errx(EX_DATAERR, "invalid flag %s", e);
3314 cmd->opcode = opcode;
3315 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
3316 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3321 ipfw_delete(char *av[])
3326 int exitval = EX_OK;
3330 NEED1("missing rule specification");
3331 if ( *av && _substrcmp(*av, "set") == 0) {
3332 /* Do not allow using the following syntax:
3333 * ipfw set N delete set M
3336 errx(EX_DATAERR, "invalid syntax");
3337 do_set = 1; /* delete set */
3342 while (*av && isdigit(**av)) {
3343 i = strtol(*av, &sep, 10);
3346 j = strtol(sep + 1, NULL, 10);
3349 exitval = ipfw_delete_nat(i);
3350 } else if (g_co.do_pipe) {
3351 exitval = ipfw_delete_pipe(g_co.do_pipe, i);
3353 memset(&rt, 0, sizeof(rt));
3356 rt.flags = IPFW_RCFLAG_SET;
3358 rt.start_rule = i & 0xffff;
3359 rt.end_rule = j & 0xffff;
3360 if (rt.start_rule == 0 && rt.end_rule == 0)
3361 rt.flags |= IPFW_RCFLAG_ALL;
3363 rt.flags |= IPFW_RCFLAG_RANGE;
3364 if (g_co.use_set != 0) {
3365 rt.set = g_co.use_set - 1;
3366 rt.flags |= IPFW_RCFLAG_SET;
3369 if (g_co.do_dynamic == 2)
3370 rt.flags |= IPFW_RCFLAG_DYNAMIC;
3371 i = do_range_cmd(IP_FW_XDEL, &rt);
3373 exitval = EX_UNAVAILABLE;
3376 warn("rule %u: setsockopt(IP_FW_XDEL)",
3378 } else if (rt.new_set == 0 && do_set == 0 &&
3379 g_co.do_dynamic != 2) {
3380 exitval = EX_UNAVAILABLE;
3383 if (rt.start_rule != rt.end_rule)
3384 warnx("no rules rules in %u-%u range",
3385 rt.start_rule, rt.end_rule);
3387 warnx("rule %u not found",
3392 if (exitval != EX_OK && g_co.do_force == 0)
3398 * fill the interface structure. We do not check the name as we can
3399 * create interfaces dynamically, so checking them at insert time
3400 * makes relatively little sense.
3401 * Interface names containing '*', '?', or '[' are assumed to be shell
3402 * patterns which match interfaces.
3405 fill_iface(ipfw_insn_if *cmd, char *arg, int cblen, struct tidx *tstate)
3410 cmd->name[0] = '\0';
3411 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3415 /* Parse the interface or address */
3416 if (strcmp(arg, "any") == 0)
3417 cmd->o.len = 0; /* effectively ignore this command */
3418 else if (strncmp(arg, "table(", 6) == 0) {
3419 if ((p = strchr(arg + 6, ')')) == NULL)
3420 errx(EX_DATAERR, "forgotten parenthesis: '%s'", arg);
3422 p = strchr(arg + 6, ',');
3425 if ((uidx = pack_table(tstate, arg + 6)) == 0)
3426 errx(EX_DATAERR, "Invalid table name: %s", arg + 6);
3428 cmd->name[0] = '\1'; /* Special value indicating table */
3430 } else if (!isdigit(*arg)) {
3431 strlcpy(cmd->name, arg, sizeof(cmd->name));
3432 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3433 } else if (!inet_aton(arg, &cmd->p.ip))
3434 errx(EX_DATAERR, "bad ip address ``%s''", arg);
3438 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
3442 char *ap, *ptr, *optr;
3443 struct ether_addr *mac;
3444 const char *macset = "0123456789abcdefABCDEF:";
3446 if (strcmp(p, "any") == 0) {
3447 for (i = 0; i < ETHER_ADDR_LEN; i++)
3448 addr[i] = mask[i] = 0;
3452 optr = ptr = strdup(p);
3453 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
3455 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
3456 errx(EX_DATAERR, "Incorrect MAC address");
3457 bcopy(mac, addr, ETHER_ADDR_LEN);
3459 errx(EX_DATAERR, "Incorrect MAC address");
3461 if (ptr != NULL) { /* we have mask? */
3462 if (p[ptr - optr - 1] == '/') { /* mask len */
3463 long ml = strtol(ptr, &ap, 10);
3464 if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
3465 errx(EX_DATAERR, "Incorrect mask length");
3466 for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
3467 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
3470 if (strspn(ptr, macset) != l ||
3471 (mac = ether_aton(ptr)) == NULL)
3472 errx(EX_DATAERR, "Incorrect mask");
3473 bcopy(mac, mask, ETHER_ADDR_LEN);
3475 } else { /* default mask: ff:ff:ff:ff:ff:ff */
3476 for (i = 0; i < ETHER_ADDR_LEN; i++)
3479 for (i = 0; i < ETHER_ADDR_LEN; i++)
3486 * helper function, updates the pointer to cmd with the length
3487 * of the current command, and also cleans up the first word of
3488 * the new command in case it has been clobbered before.
3491 next_cmd(ipfw_insn *cmd, int *len)
3494 CHECK_LENGTH(*len, 0);
3496 bzero(cmd, sizeof(*cmd));
3501 * Takes arguments and copies them into a comment
3504 fill_comment(ipfw_insn *cmd, char **av, int cblen)
3507 char *p = (char *)(cmd + 1);
3509 cmd->opcode = O_NOP;
3510 cmd->len = (cmd->len & (F_NOT | F_OR));
3512 /* Compute length of comment string. */
3513 for (i = 0, l = 0; av[i] != NULL; i++)
3514 l += strlen(av[i]) + 1;
3519 "comment too long (max 80 chars)");
3521 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
3524 for (i = 0; av[i] != NULL; i++) {
3533 * A function to fill simple commands of size 1.
3534 * Existing flags are preserved.
3537 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3539 cmd->opcode = opcode;
3540 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3545 * Fetch and add the MAC address and type, with masks. This generates one or
3546 * two microinstructions, and returns the pointer to the last one.
3549 add_mac(ipfw_insn *cmd, char *av[], int cblen)
3553 if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
3554 errx(EX_DATAERR, "MAC dst src");
3556 cmd->opcode = O_MACADDR2;
3557 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3560 mac = (ipfw_insn_mac *)cmd;
3561 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
3562 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
3563 &(mac->mask[ETHER_ADDR_LEN])); /* src */
3568 add_mactype(ipfw_insn *cmd, char *av, int cblen)
3571 errx(EX_DATAERR, "missing MAC type");
3572 if (strcmp(av, "any") != 0) { /* we have a non-null type */
3573 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
3575 cmd->opcode = O_MAC_TYPE;
3582 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
3584 struct protoent *pe;
3588 proto = strtol(av, &ep, 10);
3589 if (*ep != '\0' || proto <= 0) {
3590 if ((pe = getprotobyname(av)) == NULL)
3592 proto = pe->p_proto;
3595 fill_cmd(cmd, O_PROTO, 0, proto);
3601 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
3603 u_char proto = IPPROTO_IP;
3605 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3606 ; /* do not set O_IP4 nor O_IP6 */
3607 else if (strcmp(av, "ip4") == 0)
3608 /* explicit "just IPv4" rule */
3609 fill_cmd(cmd, O_IP4, 0, 0);
3610 else if (strcmp(av, "ip6") == 0) {
3611 /* explicit "just IPv6" rule */
3612 proto = IPPROTO_IPV6;
3613 fill_cmd(cmd, O_IP6, 0, 0);
3615 return add_proto0(cmd, av, protop);
3622 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
3624 u_char proto = IPPROTO_IP;
3626 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3627 ; /* do not set O_IP4 nor O_IP6 */
3628 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3629 /* explicit "just IPv4" rule */
3630 fill_cmd(cmd, O_IP4, 0, 0);
3631 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3632 /* explicit "just IPv6" rule */
3633 proto = IPPROTO_IPV6;
3634 fill_cmd(cmd, O_IP6, 0, 0);
3636 return add_proto0(cmd, av, protop);
3643 add_srcip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3645 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3646 if (cmd->opcode == O_IP_DST_SET) /* set */
3647 cmd->opcode = O_IP_SRC_SET;
3648 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3649 cmd->opcode = O_IP_SRC_LOOKUP;
3650 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3651 cmd->opcode = O_IP_SRC_ME;
3652 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3653 cmd->opcode = O_IP_SRC;
3654 else /* addr/mask */
3655 cmd->opcode = O_IP_SRC_MASK;
3660 add_dstip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3662 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3663 if (cmd->opcode == O_IP_DST_SET) /* set */
3665 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3667 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3668 cmd->opcode = O_IP_DST_ME;
3669 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3670 cmd->opcode = O_IP_DST;
3671 else /* addr/mask */
3672 cmd->opcode = O_IP_DST_MASK;
3676 static struct _s_x f_reserved_keywords[] = {
3679 { "diverted", TOK_OR },
3680 { "dst-port", TOK_OR },
3681 { "src-port", TOK_OR },
3682 { "established", TOK_OR },
3683 { "keep-state", TOK_OR },
3685 { "icmptypes", TOK_OR },
3693 { NULL, 0 } /* terminator */
3697 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
3700 if (match_token(f_reserved_keywords, av) != -1)
3703 if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
3704 /* XXX todo: check that we have a protocol with ports */
3705 cmd->opcode = opcode;
3712 add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3715 char *host, *ch, buf[INET6_ADDRSTRLEN];
3716 ipfw_insn *ret = NULL;
3719 /* Copy first address in set if needed */
3720 if ((ch = strpbrk(av, "/,")) != NULL) {
3722 strlcpy(buf, av, sizeof(buf));
3723 if (len < sizeof(buf))
3729 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3730 inet_pton(AF_INET6, host, &a) == 1)
3731 ret = add_srcip6(cmd, av, cblen, tstate);
3732 /* XXX: should check for IPv4, not !IPv6 */
3733 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3734 inet_pton(AF_INET6, host, &a) != 1))
3735 ret = add_srcip(cmd, av, cblen, tstate);
3736 if (ret == NULL && strcmp(av, "any") != 0)
3743 add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3746 char *host, *ch, buf[INET6_ADDRSTRLEN];
3747 ipfw_insn *ret = NULL;
3750 /* Copy first address in set if needed */
3751 if ((ch = strpbrk(av, "/,")) != NULL) {
3753 strlcpy(buf, av, sizeof(buf));
3754 if (len < sizeof(buf))
3760 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3761 inet_pton(AF_INET6, host, &a) == 1)
3762 ret = add_dstip6(cmd, av, cblen, tstate);
3763 /* XXX: should check for IPv4, not !IPv6 */
3764 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3765 inet_pton(AF_INET6, host, &a) != 1))
3766 ret = add_dstip(cmd, av, cblen, tstate);
3767 if (ret == NULL && strcmp(av, "any") != 0)
3774 * Parse arguments and assemble the microinstructions which make up a rule.
3775 * Rules are added into the 'rulebuf' and then copied in the correct order
3776 * into the actual rule.
3778 * The syntax for a rule starts with the action, followed by
3779 * optional action parameters, and the various match patterns.
3780 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
3781 * (generated if the rule includes a keep-state option), then the
3782 * various match patterns, log/altq actions, and the actual action.
3786 compile_rule(char *av[], uint32_t *rbuf, int *rbufsize, struct tidx *tstate)
3789 * rules are added into the 'rulebuf' and then copied in
3790 * the correct order into the actual rule.
3791 * Some things that need to go out of order (prob, action etc.)
3794 static uint32_t actbuf[255], cmdbuf[255];
3795 int rblen, ablen, cblen;
3797 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
3798 ipfw_insn *first_cmd; /* first match pattern */
3800 struct ip_fw_rule *rule;
3803 * various flags used to record that we entered some fields.
3805 ipfw_insn *have_state = NULL; /* any state-related option */
3806 int have_rstate = 0;
3807 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
3808 ipfw_insn *have_skipcmd = NULL;
3813 int open_par = 0; /* open parenthesis ( */
3815 /* proto is here because it is used to fetch ports */
3816 u_char proto = IPPROTO_IP; /* default protocol */
3818 double match_prob = 1; /* match probability, default is always match */
3820 bzero(actbuf, sizeof(actbuf)); /* actions go here */
3821 bzero(cmdbuf, sizeof(cmdbuf));
3822 bzero(rbuf, *rbufsize);
3824 rule = (struct ip_fw_rule *)rbuf;
3825 cmd = (ipfw_insn *)cmdbuf;
3826 action = (ipfw_insn *)actbuf;
3828 rblen = *rbufsize / sizeof(uint32_t);
3829 rblen -= sizeof(struct ip_fw_rule) / sizeof(uint32_t);
3830 ablen = sizeof(actbuf) / sizeof(actbuf[0]);
3831 cblen = sizeof(cmdbuf) / sizeof(cmdbuf[0]);
3832 cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
3834 #define CHECK_RBUFLEN(len) { CHECK_LENGTH(rblen, len); rblen -= len; }
3835 #define CHECK_ACTLEN CHECK_LENGTH(ablen, action->len)
3839 /* [rule N] -- Rule number optional */
3840 if (av[0] && isdigit(**av)) {
3841 rule->rulenum = atoi(*av);
3845 /* [set N] -- set number (0..RESVD_SET), optional */
3846 if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
3847 int set = strtoul(av[1], NULL, 10);
3848 if (set < 0 || set > RESVD_SET)
3849 errx(EX_DATAERR, "illegal set %s", av[1]);
3855 /* [prob D] -- match probability, optional */
3856 if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
3857 match_prob = strtod(av[1], NULL);
3859 if (match_prob <= 0 || match_prob > 1)
3860 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
3864 /* action -- mandatory */
3865 NEED1("missing action");
3866 i = match_token(rule_actions, *av);
3868 action->len = 1; /* default */
3871 case TOK_CHECKSTATE:
3872 have_state = action;
3873 action->opcode = O_CHECK_STATE;
3875 match_token(rule_options, *av) == TOK_COMMENT) {
3876 action->arg1 = pack_object(tstate,
3877 default_state_name, IPFW_TLV_STATE_NAME);
3880 if (*av[0] == ':') {
3881 if (strcmp(*av + 1, "any") == 0)
3883 else if (state_check_name(*av + 1) == 0)
3884 action->arg1 = pack_object(tstate, *av + 1,
3885 IPFW_TLV_STATE_NAME);
3887 errx(EX_DATAERR, "Invalid state name %s",
3892 errx(EX_DATAERR, "Invalid state name %s", *av);
3896 action->opcode = O_REJECT;
3897 action->arg1 = ICMP_REJECT_ABORT;
3901 action->opcode = O_UNREACH6;
3902 action->arg1 = ICMP6_UNREACH_ABORT;
3906 action->opcode = O_ACCEPT;
3910 action->opcode = O_DENY;
3915 action->opcode = O_REJECT;
3916 action->arg1 = ICMP_UNREACH_HOST;
3920 action->opcode = O_REJECT;
3921 action->arg1 = ICMP_REJECT_RST;
3925 action->opcode = O_UNREACH6;
3926 action->arg1 = ICMP6_UNREACH_RST;
3930 action->opcode = O_REJECT;
3931 NEED1("missing reject code");
3932 fill_reject_code(&action->arg1, *av);
3937 action->opcode = O_UNREACH6;
3938 NEED1("missing unreach code");
3939 fill_unreach6_code(&action->arg1, *av);
3944 action->opcode = O_COUNT;
3948 action->opcode = O_NAT;
3949 action->len = F_INSN_SIZE(ipfw_insn_nat);
3951 if (*av != NULL && _substrcmp(*av, "global") == 0) {
3952 action->arg1 = IP_FW_NAT44_GLOBAL;
3958 action->opcode = O_QUEUE;
3961 action->opcode = O_PIPE;
3964 action->opcode = O_SKIPTO;
3967 action->opcode = O_NETGRAPH;
3970 action->opcode = O_NGTEE;
3973 action->opcode = O_DIVERT;
3976 action->opcode = O_TEE;
3979 action->opcode = O_CALLRETURN;
3982 errx(EX_USAGE, "missing argument for %s", *(av - 1));
3983 if (isdigit(**av)) {
3984 action->arg1 = strtoul(*av, NULL, 10);
3985 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
3986 errx(EX_DATAERR, "illegal argument for %s",
3988 } else if (_substrcmp(*av, "tablearg") == 0) {
3989 action->arg1 = IP_FW_TARG;
3990 } else if (i == TOK_DIVERT || i == TOK_TEE) {
3993 s = getservbyname(av[0], "divert");
3995 action->arg1 = ntohs(s->s_port);
3997 errx(EX_DATAERR, "illegal divert/tee port");
3999 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
4005 * Locate the address-port separator (':' or ',').
4006 * Could be one of the following:
4010 * IPv6 w:x:y::z,port
4011 * IPv6 [w:x:y::z]:port
4013 struct sockaddr_storage result;
4014 struct addrinfo *res;
4017 u_short port_number = 0;
4019 NEED1("missing forward address[:port]");
4021 if (_substrcmp(*av, "tablearg") == 0) {
4023 ((struct sockaddr_in*)&result)->sin_addr.s_addr =
4027 * Are we an bracket-enclosed IPv6 address?
4029 if (strchr(*av, '['))
4033 * locate the address-port separator (':' or ',')
4035 s = strchr(*av, ',');
4037 s = strchr(*av, ']');
4038 /* Prevent erroneous parsing on brackets. */
4044 /* Distinguish between IPv4:port and IPv6 cases. */
4046 if (s && strchr(s+1, ':'))
4047 s = NULL; /* no port */
4051 /* Terminate host portion and set s to start of port. */
4053 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
4056 "illegal forwarding port ``%s''", s);
4057 port_number = (u_short)i;
4061 * Resolve the host name or address to a family and a
4062 * network representation of the address.
4064 if (getaddrinfo(*av, NULL, NULL, &res))
4065 errx(EX_DATAERR, NULL);
4066 /* Just use the first host in the answer. */
4067 family = res->ai_family;
4068 memcpy(&result, res->ai_addr, res->ai_addrlen);
4072 if (family == PF_INET) {
4073 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
4075 action->opcode = O_FORWARD_IP;
4076 action->len = F_INSN_SIZE(ipfw_insn_sa);
4080 * In the kernel we assume AF_INET and use only
4081 * sin_port and sin_addr. Remember to set sin_len as
4082 * the routing code seems to use it too.
4084 p->sa.sin_len = sizeof(struct sockaddr_in);
4085 p->sa.sin_family = AF_INET;
4086 p->sa.sin_port = port_number;
4087 p->sa.sin_addr.s_addr =
4088 ((struct sockaddr_in *)&result)->sin_addr.s_addr;
4089 } else if (family == PF_INET6) {
4090 ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
4092 action->opcode = O_FORWARD_IP6;
4093 action->len = F_INSN_SIZE(ipfw_insn_sa6);
4096 p->sa.sin6_len = sizeof(struct sockaddr_in6);
4097 p->sa.sin6_family = AF_INET6;
4098 p->sa.sin6_port = port_number;
4099 p->sa.sin6_flowinfo = 0;
4100 p->sa.sin6_scope_id =
4101 ((struct sockaddr_in6 *)&result)->sin6_scope_id;
4102 bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
4103 &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
4105 errx(EX_DATAERR, "Invalid address family in forward action");
4111 /* pretend it is a 'count' rule followed by the comment */
4112 action->opcode = O_COUNT;
4113 av--; /* go back... */
4119 size_t intsize = sizeof(int);
4121 action->opcode = O_SETFIB;
4122 NEED1("missing fib number");
4123 if (_substrcmp(*av, "tablearg") == 0) {
4124 action->arg1 = IP_FW_TARG;
4126 action->arg1 = strtoul(*av, NULL, 10);
4127 if (sysctlbyname("net.fibs", &numfibs, &intsize,
4129 errx(EX_DATAERR, "fibs not suported.\n");
4130 if (action->arg1 >= numfibs) /* Temporary */
4131 errx(EX_DATAERR, "fib too large.\n");
4132 /* Add high-order bit to fib to make room for tablearg*/
4133 action->arg1 |= 0x8000;
4143 action->opcode = O_SETDSCP;
4144 NEED1("missing DSCP code");
4145 if (_substrcmp(*av, "tablearg") == 0) {
4146 action->arg1 = IP_FW_TARG;
4148 if (isalpha(*av[0])) {
4149 if ((code = match_token(f_ipdscp, *av)) == -1)
4150 errx(EX_DATAERR, "Unknown DSCP code");
4151 action->arg1 = code;
4153 action->arg1 = strtoul(*av, NULL, 10);
4155 * Add high-order bit to DSCP to make room
4158 action->arg1 |= 0x8000;
4165 action->opcode = O_REASS;
4169 fill_cmd(action, O_CALLRETURN, F_NOT, 0);
4172 case TOK_TCPSETMSS: {
4176 idx = pack_object(tstate, "tcp-setmss", IPFW_TLV_EACTION);
4178 errx(EX_DATAERR, "pack_object failed");
4179 fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4180 NEED1("Missing MSS value");
4181 action = next_cmd(action, &ablen);
4184 mss = strtoul(*av, NULL, 10);
4185 if (mss == 0 || mss > UINT16_MAX)
4186 errx(EX_USAGE, "invalid MSS value %s", *av);
4187 fill_cmd(action, O_EXTERNAL_DATA, 0, (uint16_t)mss);
4194 if (match_token(rule_eactions, *av) == -1)
4195 errx(EX_DATAERR, "invalid action %s\n", *av);
4197 * External actions support.
4198 * XXX: we support only syntax with instance name.
4199 * For known external actions (from rule_eactions list)
4200 * we can handle syntax directly. But with `eaction'
4201 * keyword we can use only `eaction <name> <instance>'
4207 NEED1("Missing eaction name");
4208 if (eaction_check_name(*av) != 0)
4209 errx(EX_DATAERR, "Invalid eaction name %s", *av);
4210 idx = pack_object(tstate, *av, IPFW_TLV_EACTION);
4212 errx(EX_DATAERR, "pack_object failed");
4213 fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4215 NEED1("Missing eaction instance name");
4216 action = next_cmd(action, &ablen);
4219 if (eaction_check_name(*av) != 0)
4220 errx(EX_DATAERR, "Invalid eaction instance name %s",
4223 * External action instance object has TLV type depended
4224 * from the external action name object index. Since we
4225 * currently don't know this index, use zero as TLV type.
4227 idx = pack_object(tstate, *av, 0);
4229 errx(EX_DATAERR, "pack_object failed");
4230 fill_cmd(action, O_EXTERNAL_INSTANCE, 0, idx);
4234 action = next_cmd(action, &ablen);
4237 * [altq queuename] -- altq tag, optional
4238 * [log [logamount N]] -- log, optional
4240 * If they exist, it go first in the cmdbuf, but then it is
4241 * skipped in the copy section to the end of the buffer.
4243 while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
4248 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
4253 "log cannot be specified more than once");
4254 have_log = (ipfw_insn *)c;
4255 cmd->len = F_INSN_SIZE(ipfw_insn_log);
4257 cmd->opcode = O_LOG;
4258 if (av[0] && _substrcmp(*av, "logamount") == 0) {
4260 NEED1("logamount requires argument");
4264 "logamount must be positive");
4268 len = sizeof(c->max_log);
4269 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
4270 &c->max_log, &len, NULL, 0) == -1) {
4271 if (g_co.test_only) {
4275 errx(1, "sysctlbyname(\"%s\")",
4276 "net.inet.ip.fw.verbose_limit");
4285 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
4287 NEED1("missing altq queue name");
4290 "altq cannot be specified more than once");
4291 have_altq = (ipfw_insn *)a;
4292 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
4294 cmd->opcode = O_ALTQ;
4295 a->qid = altq_name_to_qid(*av);
4306 errx(EX_USAGE, "tag and untag cannot be "
4307 "specified more than once");
4308 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
4309 rule_action_params);
4311 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
4319 cmd = next_cmd(cmd, &cblen);
4322 if (have_state) { /* must be a check-state, we are done */
4324 match_token(rule_options, *av) == TOK_COMMENT) {
4325 /* check-state has a comment */
4327 fill_comment(cmd, av, cblen);
4328 cmd = next_cmd(cmd, &cblen);
4334 #define OR_START(target) \
4335 if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
4337 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
4340 if ( (av[0])[1] == '\0') { \
4351 strcmp(*av, ")") == 0 || \
4352 strcmp(*av, "}") == 0)) { \
4357 errx(EX_USAGE, "missing \")\"\n"); \
4361 if (av[0] && _substrcmp(*av, "not") == 0) { \
4362 if (cmd->len & F_NOT) \
4363 errx(EX_USAGE, "double \"not\" not allowed\n"); \
4364 cmd->len |= F_NOT; \
4368 #define OR_BLOCK(target) \
4369 if (av[0] && _substrcmp(*av, "or") == 0) { \
4370 if (prev == NULL || open_par == 0) \
4371 errx(EX_DATAERR, "invalid OR block"); \
4372 prev->len |= F_OR; \
4382 * MAC addresses, optional.
4383 * If we have this, we skip the part "proto from src to dst"
4384 * and jump straight to the option parsing.
4387 NEED1("missing protocol");
4388 if (_substrcmp(*av, "MAC") == 0 ||
4389 _substrcmp(*av, "mac") == 0) {
4390 av++; /* the "MAC" keyword */
4391 add_mac(cmd, av); /* exits in case of errors */
4392 cmd = next_cmd(cmd);
4393 av += 2; /* dst-mac and src-mac */
4395 NEED1("missing mac type");
4396 if (add_mactype(cmd, av[0]))
4397 cmd = next_cmd(cmd);
4398 av++; /* any or mac-type */
4404 * protocol, mandatory
4406 OR_START(get_proto);
4408 NEED1("missing protocol");
4409 if (add_proto_compat(cmd, *av, &proto)) {
4411 if (F_LEN(cmd) != 0) {
4413 cmd = next_cmd(cmd, &cblen);
4415 } else if (first_cmd != cmd) {
4416 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
4418 rule->flags |= IPFW_RULE_JUSTOPTS;
4421 OR_BLOCK(get_proto);
4423 first_cmd = cmd; /* update pointer to use in compact form */
4428 if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
4429 errx(EX_USAGE, "missing ``from''");
4433 * source IP, mandatory
4435 OR_START(source_ip);
4436 NOT_BLOCK; /* optional "not" */
4437 NEED1("missing source address");
4438 if (add_src(cmd, *av, proto, cblen, tstate)) {
4440 if (F_LEN(cmd) != 0) { /* ! any */
4442 cmd = next_cmd(cmd, &cblen);
4445 errx(EX_USAGE, "bad source address %s", *av);
4446 OR_BLOCK(source_ip);
4449 * source ports, optional
4451 NOT_BLOCK; /* optional "not" */
4452 if ( av[0] != NULL ) {
4453 if (_substrcmp(*av, "any") == 0 ||
4454 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4456 if (F_LEN(cmd) != 0)
4457 cmd = next_cmd(cmd, &cblen);
4464 if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
4465 errx(EX_USAGE, "missing ``to''");
4469 * destination, mandatory
4472 NOT_BLOCK; /* optional "not" */
4473 NEED1("missing dst address");
4474 if (add_dst(cmd, *av, proto, cblen, tstate)) {
4476 if (F_LEN(cmd) != 0) { /* ! any */
4478 cmd = next_cmd(cmd, &cblen);
4481 errx( EX_USAGE, "bad destination address %s", *av);
4485 * dest. ports, optional
4487 NOT_BLOCK; /* optional "not" */
4489 if (_substrcmp(*av, "any") == 0 ||
4490 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4492 if (F_LEN(cmd) != 0)
4493 cmd = next_cmd(cmd, &cblen);
4496 if (first_cmd == cmd)
4497 rule->flags |= IPFW_RULE_NOOPT;
4501 while ( av[0] != NULL ) {
4503 ipfw_insn_u32 *cmd32; /* alias for cmd */
4506 cmd32 = (ipfw_insn_u32 *)cmd;
4508 if (*s == '!') { /* alternate syntax for NOT */
4509 if (cmd->len & F_NOT)
4510 errx(EX_USAGE, "double \"not\" not allowed\n");
4514 i = match_token(rule_options, s);
4518 if (cmd->len & F_NOT)
4519 errx(EX_USAGE, "double \"not\" not allowed\n");
4524 if (open_par == 0 || prev == NULL)
4525 errx(EX_USAGE, "invalid \"or\" block\n");
4529 case TOK_STARTBRACE:
4531 errx(EX_USAGE, "+nested \"(\" not allowed\n");
4537 errx(EX_USAGE, "+missing \")\"\n");
4543 fill_cmd(cmd, O_IN, 0, 0);
4547 cmd->len ^= F_NOT; /* toggle F_NOT */
4548 fill_cmd(cmd, O_IN, 0, 0);
4552 fill_cmd(cmd, O_DIVERTED, 0, 3);
4555 case TOK_DIVERTEDLOOPBACK:
4556 fill_cmd(cmd, O_DIVERTED, 0, 1);
4559 case TOK_DIVERTEDOUTPUT:
4560 fill_cmd(cmd, O_DIVERTED, 0, 2);
4564 uint32_t set = 0, clear = 0;
4566 if (*av != NULL && fill_flags(f_ipoff, *av, NULL,
4571 * Compatibility: no argument after "frag"
4572 * keyword equals to "frag offset".
4577 fill_cmd(cmd, O_FRAG, 0,
4578 (set & 0xff) | ( (clear & 0xff) << 8));
4583 fill_cmd(cmd, O_LAYER2, 0, 0);
4589 NEED1("recv, xmit, via require interface name"
4591 fill_iface((ipfw_insn_if *)cmd, av[0], cblen, tstate);
4593 if (F_LEN(cmd) == 0) /* not a valid address */
4596 cmd->opcode = O_XMIT;
4597 else if (i == TOK_RECV)
4598 cmd->opcode = O_RECV;
4599 else if (i == TOK_VIA)
4600 cmd->opcode = O_VIA;
4604 NEED1("icmptypes requires list of types");
4605 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
4609 case TOK_ICMP6TYPES:
4610 NEED1("icmptypes requires list of types");
4611 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
4616 NEED1("ipttl requires TTL");
4617 if (strpbrk(*av, "-,")) {
4618 if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
4619 errx(EX_DATAERR, "invalid ipttl %s", *av);
4621 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
4626 NEED1("ipid requires id");
4627 if (strpbrk(*av, "-,")) {
4628 if (!add_ports(cmd, *av, 0, O_IPID, cblen))
4629 errx(EX_DATAERR, "invalid ipid %s", *av);
4631 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
4636 NEED1("iplen requires length");
4637 if (strpbrk(*av, "-,")) {
4638 if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
4639 errx(EX_DATAERR, "invalid ip len %s", *av);
4641 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
4646 NEED1("ipver requires version");
4647 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
4651 case TOK_IPPRECEDENCE:
4652 NEED1("ipprecedence requires value");
4653 fill_cmd(cmd, O_IPPRECEDENCE, 0,
4654 (strtoul(*av, NULL, 0) & 7) << 5);
4659 NEED1("missing DSCP code");
4660 fill_dscp(cmd, *av, cblen);
4665 NEED1("missing argument for ipoptions");
4666 fill_flags_cmd(cmd, O_IPOPT, f_ipopts, *av);
4671 NEED1("missing argument for iptos");
4672 fill_flags_cmd(cmd, O_IPTOS, f_iptos, *av);
4677 NEED1("uid requires argument");
4683 cmd->opcode = O_UID;
4684 uid = strtoul(*av, &end, 0);
4685 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
4687 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
4688 cmd32->d[0] = pwd->pw_uid;
4689 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4695 NEED1("gid requires argument");
4701 cmd->opcode = O_GID;
4702 gid = strtoul(*av, &end, 0);
4703 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
4705 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
4706 cmd32->d[0] = grp->gr_gid;
4707 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4713 NEED1("jail requires argument");
4718 cmd->opcode = O_JAIL;
4720 * If av is a number, then we'll just pass it as-is. If
4721 * it's a name, try to resolve that to a jid.
4723 * We save the jail_getid(3) call for a fallback because
4724 * it entails an unconditional trip to the kernel to
4725 * either validate a jid or resolve a name to a jid.
4726 * This specific token doesn't currently require a
4727 * jid to be an active jail, so we save a transition
4728 * by simply using a number that we're given.
4730 jid = strtoul(*av, &end, 10);
4732 jid = jail_getid(*av);
4734 errx(EX_DATAERR, "%s", jail_errmsg);
4736 cmd32->d[0] = (uint32_t)jid;
4737 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4743 fill_cmd(cmd, O_ESTAB, 0, 0);
4747 fill_cmd(cmd, O_TCPFLAGS, 0,
4748 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
4751 case TOK_TCPDATALEN:
4752 NEED1("tcpdatalen requires length");
4753 if (strpbrk(*av, "-,")) {
4754 if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
4755 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
4757 fill_cmd(cmd, O_TCPDATALEN, 0,
4758 strtoul(*av, NULL, 0));
4763 NEED1("missing argument for tcpoptions");
4764 fill_flags_cmd(cmd, O_TCPOPTS, f_tcpopts, *av);
4770 NEED1("tcpseq/tcpack requires argument");
4771 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
4772 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
4773 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
4779 NEED1("tcpmss/tcpwin requires size");
4780 if (strpbrk(*av, "-,")) {
4781 if (add_ports(cmd, *av, 0,
4782 i == TOK_TCPWIN ? O_TCPWIN : O_TCPMSS,
4784 errx(EX_DATAERR, "invalid %s size %s",
4787 fill_cmd(cmd, i == TOK_TCPWIN ? O_TCPWIN :
4788 O_TCPMSS, 0, strtoul(*av, NULL, 0));
4793 NEED1("missing argument for tcpflags");
4794 cmd->opcode = O_TCPFLAGS;
4795 fill_flags_cmd(cmd, O_TCPFLAGS, f_tcpflags, *av);
4800 case TOK_RECORDSTATE: {
4804 errx(EX_USAGE, "keep-state or record-state cannot be part "
4807 errx(EX_USAGE, "only one of keep-state, record-state, "
4808 " limit and set-limit is allowed");
4809 if (*av != NULL && *av[0] == ':') {
4810 if (state_check_name(*av + 1) != 0)
4812 "Invalid state name %s", *av);
4813 uidx = pack_object(tstate, *av + 1,
4814 IPFW_TLV_STATE_NAME);
4817 uidx = pack_object(tstate, default_state_name,
4818 IPFW_TLV_STATE_NAME);
4820 have_rstate = i == TOK_RECORDSTATE;
4821 fill_cmd(cmd, O_KEEP_STATE, 0, uidx);
4826 case TOK_SETLIMIT: {
4827 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
4832 "limit or set-limit cannot be part of an or block");
4834 errx(EX_USAGE, "only one of keep-state, record-state, "
4835 " limit and set-limit is allowed");
4837 have_rstate = i == TOK_SETLIMIT;
4839 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
4841 cmd->opcode = O_LIMIT;
4842 c->limit_mask = c->conn_limit = 0;
4844 while ( av[0] != NULL ) {
4845 if ((val = match_token(limit_masks, *av)) <= 0)
4847 c->limit_mask |= val;
4851 if (c->limit_mask == 0)
4852 errx(EX_USAGE, "limit: missing limit mask");
4854 GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
4855 TOK_LIMIT, rule_options);
4858 if (*av != NULL && *av[0] == ':') {
4859 if (state_check_name(*av + 1) != 0)
4861 "Invalid state name %s", *av);
4862 cmd->arg1 = pack_object(tstate, *av + 1,
4863 IPFW_TLV_STATE_NAME);
4866 cmd->arg1 = pack_object(tstate,
4867 default_state_name, IPFW_TLV_STATE_NAME);
4872 NEED1("missing protocol");
4873 if (add_proto(cmd, *av, &proto)) {
4876 errx(EX_DATAERR, "invalid protocol ``%s''",
4881 NEED1("missing source IP");
4882 if (add_srcip(cmd, *av, cblen, tstate)) {
4888 NEED1("missing destination IP");
4889 if (add_dstip(cmd, *av, cblen, tstate)) {
4895 NEED1("missing source IP6");
4896 if (add_srcip6(cmd, *av, cblen, tstate)) {
4902 NEED1("missing destination IP6");
4903 if (add_dstip6(cmd, *av, cblen, tstate)) {
4909 NEED1("missing source port");
4910 if (_substrcmp(*av, "any") == 0 ||
4911 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4914 errx(EX_DATAERR, "invalid source port %s", *av);
4918 NEED1("missing destination port");
4919 if (_substrcmp(*av, "any") == 0 ||
4920 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4923 errx(EX_DATAERR, "invalid destination port %s",
4928 if (add_mac(cmd, av, cblen))
4933 NEED1("missing mac type");
4934 if (!add_mactype(cmd, *av, cblen))
4935 errx(EX_DATAERR, "invalid mac type %s", *av);
4939 case TOK_VERREVPATH:
4940 fill_cmd(cmd, O_VERREVPATH, 0, 0);
4943 case TOK_VERSRCREACH:
4944 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
4948 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
4952 fill_cmd(cmd, O_IPSEC, 0, 0);
4956 fill_cmd(cmd, O_IP6, 0, 0);
4960 fill_cmd(cmd, O_IP4, 0, 0);
4964 fill_ext6hdr( cmd, *av );
4969 if (proto != IPPROTO_IPV6 )
4970 errx( EX_USAGE, "flow-id filter is active "
4971 "only for ipv6 protocol\n");
4972 fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
4977 fill_comment(cmd, av, cblen);
4982 if (av[0] && strpbrk(*av, "-,")) {
4983 if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
4984 errx(EX_DATAERR, "tagged: invalid tag"
4990 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
4991 TOK_TAGGED, rule_options);
4992 fill_cmd(cmd, O_TAGGED, 0, tag);
4998 NEED1("fib requires fib number");
4999 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
5003 fill_cmd(cmd, O_SOCKARG, 0, 0);
5007 ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
5010 if (!av[0] || !av[1])
5011 errx(EX_USAGE, "format: lookup argument tablenum");
5012 cmd->opcode = O_IP_DST_LOOKUP;
5013 cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
5014 i = match_token(rule_options, *av);
5015 for (j = 0; lookup_key[j] >= 0 ; j++) {
5016 if (i == lookup_key[j])
5019 if (lookup_key[j] <= 0)
5020 errx(EX_USAGE, "format: cannot lookup on %s", *av);
5021 __PAST_END(c->d, 1) = j; // i converted to option
5024 if ((j = pack_table(tstate, *av)) == 0)
5025 errx(EX_DATAERR, "Invalid table name: %s", *av);
5032 NEED1("missing table name");
5033 if (strncmp(*av, "table(", 6) != 0)
5035 "enclose table name into \"table()\"");
5036 fill_table(cmd, *av, O_IP_FLOW_LOOKUP, tstate);
5040 case TOK_SKIPACTION:
5042 errx(EX_USAGE, "only one defer-action "
5045 fill_cmd(cmd, O_SKIP_ACTION, 0, 0);
5049 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
5051 if (F_LEN(cmd) > 0) { /* prepare to advance */
5053 cmd = next_cmd(cmd, &cblen);
5059 if (!have_state && have_skipcmd)
5060 warnx("Rule contains \"defer-immediate-action\" "
5061 "and doesn't contain any state-related options.");
5064 * Now copy stuff into the rule.
5065 * If we have a keep-state option, the first instruction
5066 * must be a PROBE_STATE (which is generated here).
5067 * If we have a LOG option, it was stored as the first command,
5068 * and now must be moved to the top of the action part.
5070 dst = (ipfw_insn *)rule->cmd;
5073 * First thing to write into the command stream is the match probability.
5075 if (match_prob != 1) { /* 1 means always match */
5076 dst->opcode = O_PROB;
5078 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
5083 * generate O_PROBE_STATE if necessary
5085 if (have_state && have_state->opcode != O_CHECK_STATE && !have_rstate) {
5086 fill_cmd(dst, O_PROBE_STATE, 0, have_state->arg1);
5087 dst = next_cmd(dst, &rblen);
5091 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG,
5094 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
5098 switch (src->opcode) {
5107 bcopy(src, dst, i * sizeof(uint32_t));
5113 * put back the have_state command as last opcode
5115 if (have_state && have_state->opcode != O_CHECK_STATE) {
5116 i = F_LEN(have_state);
5118 bcopy(have_state, dst, i * sizeof(uint32_t));
5123 * put back the have_skipcmd command as very last opcode
5126 i = F_LEN(have_skipcmd);
5128 bcopy(have_skipcmd, dst, i * sizeof(uint32_t));
5133 * start action section
5135 rule->act_ofs = dst - rule->cmd;
5137 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
5139 i = F_LEN(have_log);
5141 bcopy(have_log, dst, i * sizeof(uint32_t));
5145 i = F_LEN(have_altq);
5147 bcopy(have_altq, dst, i * sizeof(uint32_t));
5151 i = F_LEN(have_tag);
5153 bcopy(have_tag, dst, i * sizeof(uint32_t));
5158 * copy all other actions
5160 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
5163 bcopy(src, dst, i * sizeof(uint32_t));
5167 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
5168 *rbufsize = (char *)dst - (char *)rule;
5172 compare_ntlv(const void *_a, const void *_b)
5174 const ipfw_obj_ntlv *a, *b;
5176 a = (const ipfw_obj_ntlv *)_a;
5177 b = (const ipfw_obj_ntlv *)_b;
5179 if (a->set < b->set)
5181 else if (a->set > b->set)
5184 if (a->idx < b->idx)
5186 else if (a->idx > b->idx)
5189 if (a->head.type < b->head.type)
5191 else if (a->head.type > b->head.type)
5198 * Provide kernel with sorted list of referenced objects
5201 object_sort_ctlv(ipfw_obj_ctlv *ctlv)
5204 qsort(ctlv + 1, ctlv->count, ctlv->objsize, compare_ntlv);
5212 compare_object_kntlv(const void *k, const void *v)
5214 const ipfw_obj_ntlv *ntlv;
5215 struct object_kt key;
5217 key = *((const struct object_kt *)k);
5218 ntlv = (const ipfw_obj_ntlv *)v;
5220 if (key.uidx < ntlv->idx)
5222 else if (key.uidx > ntlv->idx)
5225 if (key.type < ntlv->head.type)
5227 else if (key.type > ntlv->head.type)
5234 * Finds object name in @ctlv by @idx and @type.
5235 * Uses the following facts:
5236 * 1) All TLVs are the same size
5237 * 2) Kernel implementation provides already sorted list.
5239 * Returns table name or NULL.
5242 object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx, uint16_t type)
5244 ipfw_obj_ntlv *ntlv;
5245 struct object_kt key;
5250 ntlv = bsearch(&key, (ctlv + 1), ctlv->count, ctlv->objsize,
5251 compare_object_kntlv);
5254 return (ntlv->name);
5260 table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx)
5263 return (object_search_ctlv(ctlv, idx, IPFW_TLV_TBL_NAME));
5267 * Adds one or more rules to ipfw chain.
5272 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
5273 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ] (*2) (*3)
5278 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
5279 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ]
5282 * Rules in reply are modified to store their actual ruleset number.
5284 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
5285 * according to their idx field and there has to be no duplicates.
5286 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
5287 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
5290 ipfw_add(char *av[])
5292 uint32_t rulebuf[1024];
5293 int rbufsize, default_off, tlen, rlen;
5296 struct ip_fw_rule *rule;
5298 ip_fw3_opheader *op3;
5299 ipfw_obj_ctlv *ctlv, *tstate;
5301 rbufsize = sizeof(rulebuf);
5302 memset(rulebuf, 0, rbufsize);
5303 memset(&ts, 0, sizeof(ts));
5305 /* Optimize case with no tables */
5306 default_off = sizeof(ipfw_obj_ctlv) + sizeof(ip_fw3_opheader);
5307 op3 = (ip_fw3_opheader *)rulebuf;
5308 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5309 rule = (struct ip_fw_rule *)(ctlv + 1);
5310 rbufsize -= default_off;
5312 compile_rule(av, (uint32_t *)rule, &rbufsize, &ts);
5313 /* Align rule size to u64 boundary */
5314 rlen = roundup2(rbufsize, sizeof(uint64_t));
5319 if (ts.count != 0) {
5320 /* Some tables. We have to alloc more data */
5321 tlen = ts.count * sizeof(ipfw_obj_ntlv);
5322 sz = default_off + sizeof(ipfw_obj_ctlv) + tlen + rlen;
5324 if ((tbuf = calloc(1, sz)) == NULL)
5325 err(EX_UNAVAILABLE, "malloc() failed for IP_FW_ADD");
5326 op3 = (ip_fw3_opheader *)tbuf;
5328 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5329 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
5330 ctlv->head.length = sizeof(ipfw_obj_ctlv) + tlen;
5331 ctlv->count = ts.count;
5332 ctlv->objsize = sizeof(ipfw_obj_ntlv);
5333 memcpy(ctlv + 1, ts.idx, tlen);
5334 object_sort_ctlv(ctlv);
5337 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
5338 ctlv->head.type = IPFW_TLV_RULE_LIST;
5339 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5341 memcpy(ctlv + 1, rule, rbufsize);
5343 /* Simply add header */
5344 sz = rlen + default_off;
5345 memset(ctlv, 0, sizeof(*ctlv));
5346 ctlv->head.type = IPFW_TLV_RULE_LIST;
5347 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5351 if (do_get3(IP_FW_XADD, op3, &sz) != 0)
5352 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_XADD");
5354 if (!g_co.do_quiet) {
5355 struct format_opts sfo;
5357 memset(&sfo, 0, sizeof(sfo));
5358 sfo.tstate = tstate;
5359 sfo.set_mask = (uint32_t)(-1);
5360 bp_alloc(&bp, 4096);
5361 show_static_rule(&g_co, &sfo, &bp, rule, NULL);
5362 printf("%s", bp.buf);
5374 * clear the counters or the log counters.
5375 * optname has the following values:
5376 * 0 (zero both counters and logging)
5377 * 1 (zero logging only)
5380 ipfw_zero(int ac, char *av[], int optname)
5384 char const *name = optname ? "RESETLOG" : "ZERO";
5388 optname = optname ? IP_FW_XRESETLOG : IP_FW_XZERO;
5392 /* clear all entries */
5393 memset(&rt, 0, sizeof(rt));
5394 rt.flags = IPFW_RCFLAG_ALL;
5395 if (do_range_cmd(optname, &rt) < 0)
5396 err(EX_UNAVAILABLE, "setsockopt(IP_FW_X%s)", name);
5398 printf("%s.\n", optname == IP_FW_XZERO ?
5399 "Accounting cleared":"Logging counts reset");
5406 if (isdigit(**av)) {
5407 arg = strtonum(*av, 0, 0xffff, &errstr);
5410 "invalid rule number %s\n", *av);
5411 memset(&rt, 0, sizeof(rt));
5412 rt.start_rule = arg;
5414 rt.flags |= IPFW_RCFLAG_RANGE;
5415 if (g_co.use_set != 0) {
5416 rt.set = g_co.use_set - 1;
5417 rt.flags |= IPFW_RCFLAG_SET;
5419 if (do_range_cmd(optname, &rt) != 0) {
5420 warn("rule %u: setsockopt(IP_FW_X%s)",
5422 failed = EX_UNAVAILABLE;
5423 } else if (rt.new_set == 0) {
5424 printf("Entry %d not found\n", arg);
5425 failed = EX_UNAVAILABLE;
5426 } else if (!g_co.do_quiet)
5427 printf("Entry %d %s.\n", arg,
5428 optname == IP_FW_XZERO ?
5429 "cleared" : "logging count reset");
5431 errx(EX_USAGE, "invalid rule number ``%s''", *av);
5435 if (failed != EX_OK)
5440 ipfw_flush(int force)
5444 if (!force && !g_co.do_quiet) { /* need to ask user */
5447 printf("Are you sure? [yn] ");
5450 c = toupper(getc(stdin));
5451 while (c != '\n' && getc(stdin) != '\n')
5453 return; /* and do not flush */
5454 } while (c != 'Y' && c != 'N');
5456 if (c == 'N') /* user said no */
5463 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
5464 memset(&rt, 0, sizeof(rt));
5465 if (g_co.use_set != 0) {
5466 rt.set = g_co.use_set - 1;
5467 rt.flags = IPFW_RCFLAG_SET;
5469 rt.flags = IPFW_RCFLAG_ALL;
5470 if (do_range_cmd(IP_FW_XDEL, &rt) != 0)
5471 err(EX_UNAVAILABLE, "setsockopt(IP_FW_XDEL)");
5473 printf("Flushed all %s.\n", g_co.do_pipe ? "pipes" : "rules");
5476 static struct _s_x intcmds[] = {
5477 { "talist", TOK_TALIST },
5478 { "iflist", TOK_IFLIST },
5479 { "olist", TOK_OLIST },
5480 { "vlist", TOK_VLIST },
5484 static struct _s_x otypes[] = {
5485 { "EACTION", IPFW_TLV_EACTION },
5486 { "DYNSTATE", IPFW_TLV_STATE_NAME },
5491 lookup_eaction_name(ipfw_obj_ntlv *ntlv, int cnt, uint16_t type)
5497 for (i = 0; i < cnt; i++) {
5498 if (ntlv[i].head.type != IPFW_TLV_EACTION)
5500 if (IPFW_TLV_EACTION_NAME(ntlv[i].idx) != type)
5502 name = ntlv[i].name;
5509 ipfw_list_objects(int ac __unused, char *av[] __unused)
5511 ipfw_obj_lheader req, *olh;
5512 ipfw_obj_ntlv *ntlv;
5517 memset(&req, 0, sizeof(req));
5519 if (do_get3(IP_FW_DUMP_SRVOBJECTS, &req.opheader, &sz) != 0)
5520 if (errno != ENOMEM)
5524 if ((olh = calloc(1, sz)) == NULL)
5528 if (do_get3(IP_FW_DUMP_SRVOBJECTS, &olh->opheader, &sz) != 0) {
5534 printf("Objects list:\n");
5536 printf("There are no objects\n");
5537 ntlv = (ipfw_obj_ntlv *)(olh + 1);
5538 for (i = 0; i < olh->count; i++) {
5539 name = match_value(otypes, ntlv->head.type);
5541 name = lookup_eaction_name(
5542 (ipfw_obj_ntlv *)(olh + 1), olh->count,
5545 printf(" kidx: %4d\ttype: %10d\tname: %s\n",
5546 ntlv->idx, ntlv->head.type, ntlv->name);
5548 printf(" kidx: %4d\ttype: %10s\tname: %s\n",
5549 ntlv->idx, name, ntlv->name);
5556 ipfw_internal_handler(int ac, char *av[])
5561 NEED1("internal cmd required");
5563 if ((tcmd = match_token(intcmds, *av)) == -1)
5564 errx(EX_USAGE, "invalid internal sub-cmd: %s", *av);
5568 ipfw_list_tifaces();
5571 ipfw_list_ta(ac, av);
5574 ipfw_list_objects(ac, av);
5577 ipfw_list_values(ac, av);
5583 ipfw_get_tracked_ifaces(ipfw_obj_lheader **polh)
5585 ipfw_obj_lheader req, *olh;
5588 memset(&req, 0, sizeof(req));
5591 if (do_get3(IP_FW_XIFLIST, &req.opheader, &sz) != 0) {
5592 if (errno != ENOMEM)
5597 if ((olh = calloc(1, sz)) == NULL)
5601 if (do_get3(IP_FW_XIFLIST, &olh->opheader, &sz) != 0) {
5611 ifinfo_cmp(const void *a, const void *b)
5613 const ipfw_iface_info *ia, *ib;
5615 ia = (const ipfw_iface_info *)a;
5616 ib = (const ipfw_iface_info *)b;
5618 return (stringnum_cmp(ia->ifname, ib->ifname));
5622 * Retrieves table list from kernel,
5623 * optionally sorts it and calls requested function for each table.
5624 * Returns 0 on success.
5627 ipfw_list_tifaces(void)
5629 ipfw_obj_lheader *olh = NULL;
5630 ipfw_iface_info *info;
5634 if ((error = ipfw_get_tracked_ifaces(&olh)) != 0)
5635 err(EX_OSERR, "Unable to request ipfw tracked interface list");
5637 qsort(olh + 1, olh->count, olh->objsize, ifinfo_cmp);
5639 info = (ipfw_iface_info *)(olh + 1);
5640 for (i = 0; i < olh->count; i++) {
5641 if (info->flags & IPFW_IFFLAG_RESOLVED)
5642 printf("%s ifindex: %d refcount: %u changes: %u\n",
5643 info->ifname, info->ifindex, info->refcnt,
5646 printf("%s ifindex: unresolved refcount: %u changes: %u\n",
5647 info->ifname, info->refcnt, info->gencnt);
5648 info = (ipfw_iface_info *)((caddr_t)info + olh->objsize);