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>
43 #include <time.h> /* ctime */
44 #include <timeconv.h> /* _long_to_time */
47 #include <stddef.h> /* offsetof */
49 #include <net/ethernet.h>
50 #include <net/if.h> /* only IFNAMSIZ */
51 #include <netinet/in.h>
52 #include <netinet/in_systm.h> /* only n_short, n_long */
53 #include <netinet/ip.h>
54 #include <netinet/ip_icmp.h>
55 #include <netinet/ip_fw.h>
56 #include <netinet/tcp.h>
57 #include <arpa/inet.h>
59 struct cmdline_opts co; /* global options */
65 int show_time; /* show timestamp */
66 uint32_t set_mask; /* enabled sets mask */
67 uint32_t flags; /* request flags */
68 uint32_t first; /* first rule to request */
69 uint32_t last; /* last rule to request */
70 uint32_t dcnt; /* number of dynamic states */
71 ipfw_obj_ctlv *tstate; /* table state data */
74 int resvd_set_number = RESVD_SET;
78 #define CHECK_LENGTH(v, len) do { \
80 errx(EX_DATAERR, "Rule too long"); \
83 * Check if we have enough space in cmd buffer. Note that since
84 * first 8? u32 words are reserved by reserved header, full cmd
85 * buffer can't be used, so we need to protect from buffer overrun
86 * only. At the beginning, cblen is less than actual buffer size by
87 * size of ipfw_insn_u32 instruction + 1 u32 work. This eliminates need
88 * for checking small instructions fitting in given range.
89 * We also (ab)use the fact that ipfw_insn is always the first field
90 * for any custom instruction.
92 #define CHECK_CMDLEN CHECK_LENGTH(cblen, F_LEN((ipfw_insn *)cmd))
94 #define GET_UINT_ARG(arg, min, max, tok, s_x) do { \
96 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
97 if (_substrcmp(*av, "tablearg") == 0) { \
106 _xval = strtol(*av, &end, 10); \
108 if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
109 errx(EX_DATAERR, "%s: invalid argument: %s", \
110 match_value(s_x, tok), *av); \
112 if (errno == ERANGE || _xval < min || _xval > max) \
113 errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
114 match_value(s_x, tok), min, max, *av); \
116 if (_xval == IP_FW_TARG) \
117 errx(EX_DATAERR, "%s: illegal argument value: %s", \
118 match_value(s_x, tok), *av); \
123 static struct _s_x f_tcpflags[] = {
134 static struct _s_x f_tcpopts[] = {
135 { "mss", IP_FW_TCPOPT_MSS },
136 { "maxseg", IP_FW_TCPOPT_MSS },
137 { "window", IP_FW_TCPOPT_WINDOW },
138 { "sack", IP_FW_TCPOPT_SACK },
139 { "ts", IP_FW_TCPOPT_TS },
140 { "timestamp", IP_FW_TCPOPT_TS },
141 { "cc", IP_FW_TCPOPT_CC },
147 * IP options span the range 0 to 255 so we need to remap them
148 * (though in fact only the low 5 bits are significant).
150 static struct _s_x f_ipopts[] = {
151 { "ssrr", IP_FW_IPOPT_SSRR},
152 { "lsrr", IP_FW_IPOPT_LSRR},
153 { "rr", IP_FW_IPOPT_RR},
154 { "ts", IP_FW_IPOPT_TS},
159 static struct _s_x f_iptos[] = {
160 { "lowdelay", IPTOS_LOWDELAY},
161 { "throughput", IPTOS_THROUGHPUT},
162 { "reliability", IPTOS_RELIABILITY},
163 { "mincost", IPTOS_MINCOST},
164 { "congestion", IPTOS_ECN_CE},
165 { "ecntransport", IPTOS_ECN_ECT0},
166 { "ip tos option", 0},
170 struct _s_x f_ipdscp[] = {
171 { "af11", IPTOS_DSCP_AF11 >> 2 }, /* 001010 */
172 { "af12", IPTOS_DSCP_AF12 >> 2 }, /* 001100 */
173 { "af13", IPTOS_DSCP_AF13 >> 2 }, /* 001110 */
174 { "af21", IPTOS_DSCP_AF21 >> 2 }, /* 010010 */
175 { "af22", IPTOS_DSCP_AF22 >> 2 }, /* 010100 */
176 { "af23", IPTOS_DSCP_AF23 >> 2 }, /* 010110 */
177 { "af31", IPTOS_DSCP_AF31 >> 2 }, /* 011010 */
178 { "af32", IPTOS_DSCP_AF32 >> 2 }, /* 011100 */
179 { "af33", IPTOS_DSCP_AF33 >> 2 }, /* 011110 */
180 { "af41", IPTOS_DSCP_AF41 >> 2 }, /* 100010 */
181 { "af42", IPTOS_DSCP_AF42 >> 2 }, /* 100100 */
182 { "af43", IPTOS_DSCP_AF43 >> 2 }, /* 100110 */
183 { "be", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
184 { "ef", IPTOS_DSCP_EF >> 2 }, /* 101110 */
185 { "cs0", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
186 { "cs1", IPTOS_DSCP_CS1 >> 2 }, /* 001000 */
187 { "cs2", IPTOS_DSCP_CS2 >> 2 }, /* 010000 */
188 { "cs3", IPTOS_DSCP_CS3 >> 2 }, /* 011000 */
189 { "cs4", IPTOS_DSCP_CS4 >> 2 }, /* 100000 */
190 { "cs5", IPTOS_DSCP_CS5 >> 2 }, /* 101000 */
191 { "cs6", IPTOS_DSCP_CS6 >> 2 }, /* 110000 */
192 { "cs7", IPTOS_DSCP_CS7 >> 2 }, /* 100000 */
196 static struct _s_x limit_masks[] = {
197 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
198 {"src-addr", DYN_SRC_ADDR},
199 {"src-port", DYN_SRC_PORT},
200 {"dst-addr", DYN_DST_ADDR},
201 {"dst-port", DYN_DST_PORT},
206 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
207 * This is only used in this code.
209 #define IPPROTO_ETHERTYPE 0x1000
210 static struct _s_x ether_types[] = {
212 * Note, we cannot use "-:&/" in the names because they are field
213 * separators in the type specifications. Also, we use s = NULL as
214 * end-delimiter, because a type of 0 can be legal.
227 { "pppoe_disc", 0x8863 },
228 { "pppoe_sess", 0x8864 },
229 { "ipx_8022", 0x00E0 },
230 { "ipx_8023", 0x0000 },
231 { "ipx_ii", 0x8137 },
232 { "ipx_snap", 0x8137 },
238 static struct _s_x rule_eactions[] = {
239 { "nat64lsn", TOK_NAT64LSN },
240 { "nat64stl", TOK_NAT64STL },
241 { "nptv6", TOK_NPTV6 },
242 { "tcp-setmss", TOK_TCPSETMSS },
243 { NULL, 0 } /* terminator */
246 static struct _s_x rule_actions[] = {
247 { "abort6", TOK_ABORT6 },
248 { "abort", TOK_ABORT },
249 { "accept", TOK_ACCEPT },
250 { "pass", TOK_ACCEPT },
251 { "allow", TOK_ACCEPT },
252 { "permit", TOK_ACCEPT },
253 { "count", TOK_COUNT },
254 { "pipe", TOK_PIPE },
255 { "queue", TOK_QUEUE },
256 { "divert", TOK_DIVERT },
258 { "netgraph", TOK_NETGRAPH },
259 { "ngtee", TOK_NGTEE },
260 { "fwd", TOK_FORWARD },
261 { "forward", TOK_FORWARD },
262 { "skipto", TOK_SKIPTO },
263 { "deny", TOK_DENY },
264 { "drop", TOK_DENY },
265 { "reject", TOK_REJECT },
266 { "reset6", TOK_RESET6 },
267 { "reset", TOK_RESET },
268 { "unreach6", TOK_UNREACH6 },
269 { "unreach", TOK_UNREACH },
270 { "check-state", TOK_CHECKSTATE },
271 { "//", TOK_COMMENT },
273 { "reass", TOK_REASS },
274 { "setfib", TOK_SETFIB },
275 { "setdscp", TOK_SETDSCP },
276 { "call", TOK_CALL },
277 { "return", TOK_RETURN },
278 { "eaction", TOK_EACTION },
279 { "tcp-setmss", TOK_TCPSETMSS },
280 { NULL, 0 } /* terminator */
283 static struct _s_x rule_action_params[] = {
284 { "altq", TOK_ALTQ },
287 { "untag", TOK_UNTAG },
288 { NULL, 0 } /* terminator */
292 * The 'lookup' instruction accepts one of the following arguments.
293 * -1 is a terminator for the list.
294 * Arguments are passed as v[1] in O_DST_LOOKUP options.
296 static int lookup_key[] = {
297 TOK_DSTIP, TOK_SRCIP, TOK_DSTPORT, TOK_SRCPORT,
298 TOK_UID, TOK_JAIL, TOK_DSCP, -1 };
300 static struct _s_x rule_options[] = {
301 { "tagged", TOK_TAGGED },
304 { "jail", TOK_JAIL },
306 { "limit", TOK_LIMIT },
307 { "keep-state", TOK_KEEPSTATE },
308 { "bridged", TOK_LAYER2 },
309 { "layer2", TOK_LAYER2 },
311 { "diverted", TOK_DIVERTED },
312 { "diverted-loopback", TOK_DIVERTEDLOOPBACK },
313 { "diverted-output", TOK_DIVERTEDOUTPUT },
314 { "xmit", TOK_XMIT },
315 { "recv", TOK_RECV },
317 { "fragment", TOK_FRAG },
318 { "frag", TOK_FRAG },
320 { "ipoptions", TOK_IPOPTS },
321 { "ipopts", TOK_IPOPTS },
322 { "iplen", TOK_IPLEN },
323 { "ipid", TOK_IPID },
324 { "ipprecedence", TOK_IPPRECEDENCE },
325 { "dscp", TOK_DSCP },
326 { "iptos", TOK_IPTOS },
327 { "ipttl", TOK_IPTTL },
328 { "ipversion", TOK_IPVER },
329 { "ipver", TOK_IPVER },
330 { "estab", TOK_ESTAB },
331 { "established", TOK_ESTAB },
332 { "setup", TOK_SETUP },
333 { "sockarg", TOK_SOCKARG },
334 { "tcpdatalen", TOK_TCPDATALEN },
335 { "tcpflags", TOK_TCPFLAGS },
336 { "tcpflgs", TOK_TCPFLAGS },
337 { "tcpoptions", TOK_TCPOPTS },
338 { "tcpopts", TOK_TCPOPTS },
339 { "tcpseq", TOK_TCPSEQ },
340 { "tcpack", TOK_TCPACK },
341 { "tcpwin", TOK_TCPWIN },
342 { "icmptype", TOK_ICMPTYPES },
343 { "icmptypes", TOK_ICMPTYPES },
344 { "dst-ip", TOK_DSTIP },
345 { "src-ip", TOK_SRCIP },
346 { "dst-port", TOK_DSTPORT },
347 { "src-port", TOK_SRCPORT },
348 { "proto", TOK_PROTO },
351 { "mac-type", TOK_MACTYPE },
352 { "verrevpath", TOK_VERREVPATH },
353 { "versrcreach", TOK_VERSRCREACH },
354 { "antispoof", TOK_ANTISPOOF },
355 { "ipsec", TOK_IPSEC },
356 { "icmp6type", TOK_ICMP6TYPES },
357 { "icmp6types", TOK_ICMP6TYPES },
358 { "ext6hdr", TOK_EXT6HDR},
359 { "flow-id", TOK_FLOWID},
364 { "dst-ipv6", TOK_DSTIP6},
365 { "dst-ip6", TOK_DSTIP6},
366 { "src-ipv6", TOK_SRCIP6},
367 { "src-ip6", TOK_SRCIP6},
368 { "lookup", TOK_LOOKUP},
370 { "//", TOK_COMMENT },
372 { "not", TOK_NOT }, /* pseudo option */
373 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
374 { "or", TOK_OR }, /* pseudo option */
375 { "|", /* escape */ TOK_OR }, /* pseudo option */
376 { "{", TOK_STARTBRACE }, /* pseudo option */
377 { "(", TOK_STARTBRACE }, /* pseudo option */
378 { "}", TOK_ENDBRACE }, /* pseudo option */
379 { ")", TOK_ENDBRACE }, /* pseudo option */
380 { NULL, 0 } /* terminator */
383 void bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg);
384 static int ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
385 ipfw_cfg_lheader **pcfg, size_t *psize);
386 static int ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
387 ipfw_cfg_lheader *cfg, size_t sz, int ac, char **av);
388 static void ipfw_list_tifaces(void);
391 static uint16_t pack_object(struct tidx *tstate, char *name, int otype);
392 static uint16_t pack_table(struct tidx *tstate, char *name);
394 static char *table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx);
395 static void object_sort_ctlv(ipfw_obj_ctlv *ctlv);
396 static char *object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx,
400 * Simple string buffer API.
401 * Used to simplify buffer passing between function and for
402 * transparent overrun handling.
406 * Allocates new buffer of given size @sz.
408 * Returns 0 on success.
411 bp_alloc(struct buf_pr *b, size_t size)
413 memset(b, 0, sizeof(struct buf_pr));
415 if ((b->buf = calloc(1, size)) == NULL)
426 bp_free(struct buf_pr *b)
433 * Flushes buffer so new writer start from beginning.
436 bp_flush(struct buf_pr *b)
445 * Print message specified by @format and args.
446 * Automatically manage buffer space and transparently handle
449 * Returns number of bytes that should have been printed.
452 bprintf(struct buf_pr *b, char *format, ...)
457 va_start(args, format);
459 i = vsnprintf(b->ptr, b->avail, format, args);
462 if (i > b->avail || i < 0) {
463 /* Overflow or print error */
476 * Special values printer for tablearg-aware opcodes.
479 bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg)
483 bprintf(bp, "%s", str);
484 if (arg == IP_FW_TARG)
485 bprintf(bp, "tablearg");
487 bprintf(bp, "%u", arg);
491 * Helper routine to print a possibly unaligned uint64_t on
492 * various platform. If width > 0, print the value with
493 * the desired width, followed by a space;
494 * otherwise, return the required width.
497 pr_u64(struct buf_pr *b, uint64_t *pd, int width)
500 #define U64_FMT "I64"
502 #define U64_FMT "llu"
505 unsigned long long d;
507 bcopy (pd, &u, sizeof(u));
510 bprintf(b, "%*" U64_FMT " ", width, d) :
511 snprintf(NULL, 0, "%" U64_FMT, d) ;
517 safe_calloc(size_t number, size_t size)
519 void *ret = calloc(number, size);
522 err(EX_OSERR, "calloc");
527 safe_realloc(void *ptr, size_t size)
529 void *ret = realloc(ptr, size);
532 err(EX_OSERR, "realloc");
537 * Compare things like interface or table names.
540 stringnum_cmp(const char *a, const char *b)
552 return (strcmp(a, b));
557 * conditionally runs the command.
558 * Selected options or negative -> getsockopt
561 do_cmd(int optname, void *optval, uintptr_t optlen)
568 if (ipfw_socket == -1)
569 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
571 err(EX_UNAVAILABLE, "socket");
573 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
574 optname == IP_FW_ADD || optname == IP_FW3 ||
575 optname == IP_FW_NAT_GET_CONFIG ||
577 optname == IP_FW_NAT_GET_LOG) {
580 i = getsockopt(ipfw_socket, IPPROTO_IP, optname, optval,
581 (socklen_t *)optlen);
583 i = setsockopt(ipfw_socket, IPPROTO_IP, optname, optval, optlen);
589 * do_set3 - pass ipfw control cmd to kernel
590 * @optname: option name
591 * @optval: pointer to option data
592 * @optlen: option length
594 * Assumes op3 header is already embedded.
595 * Calls setsockopt() with IP_FW3 as kernel-visible opcode.
596 * Returns 0 on success or errno otherwise.
599 do_set3(int optname, ip_fw3_opheader *op3, size_t optlen)
605 if (ipfw_socket == -1)
606 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
608 err(EX_UNAVAILABLE, "socket");
610 op3->opcode = optname;
612 return (setsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, optlen));
616 * do_get3 - pass ipfw control cmd to kernel
617 * @optname: option name
618 * @optval: pointer to option data
619 * @optlen: pointer to option length
621 * Assumes op3 header is already embedded.
622 * Calls getsockopt() with IP_FW3 as kernel-visible opcode.
623 * Returns 0 on success or errno otherwise.
626 do_get3(int optname, ip_fw3_opheader *op3, size_t *optlen)
634 if (ipfw_socket == -1)
635 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
637 err(EX_UNAVAILABLE, "socket");
639 op3->opcode = optname;
642 error = getsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, &len);
649 * match_token takes a table and a string, returns the value associated
650 * with the string (-1 in case of failure).
653 match_token(struct _s_x *table, const char *string)
656 uint i = strlen(string);
658 for (pt = table ; i && pt->s != NULL ; pt++)
659 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
665 * match_token_relaxed takes a table and a string, returns the value associated
666 * with the string for the best match.
669 * value from @table for matched records
670 * -1 for non-matched records
671 * -2 if more than one records match @string.
674 match_token_relaxed(struct _s_x *table, const char *string)
682 for (pt = table ; i != 0 && pt->s != NULL ; pt++) {
683 if (strncmp(pt->s, string, i) != 0)
692 return (c > 0 ? -2: -1);
696 get_token(struct _s_x *table, const char *string, const char *errbase)
700 if ((tcmd = match_token_relaxed(table, string)) < 0)
701 errx(EX_USAGE, "%s %s %s",
702 (tcmd == 0) ? "invalid" : "ambiguous", errbase, string);
708 * match_value takes a table and a value, returns the string associated
709 * with the value (NULL in case of failure).
712 match_value(struct _s_x *p, int value)
714 for (; p->s != NULL; p++)
721 concat_tokens(char *buf, size_t bufsize, struct _s_x *table, char *delimiter)
727 for (sz = 0, pt = table ; pt->s != NULL; pt++) {
728 l = snprintf(buf + sz, bufsize - sz, "%s%s",
729 (sz == 0) ? "" : delimiter, pt->s);
740 * helper function to process a set of flags and set bits in the
744 fill_flags(struct _s_x *flags, char *p, char **e, uint32_t *set,
747 char *q; /* points to the separator */
749 uint32_t *which; /* mask we are working on */
760 val = match_token(flags, p);
766 *which |= (uint32_t)val;
773 print_flags_buffer(char *buf, size_t sz, struct _s_x *list, uint32_t set)
775 char const *comma = "";
778 for (i = 0; list[i].x != 0; i++) {
779 if ((set & list[i].x) == 0)
783 l = snprintf(buf, sz, "%s%s", comma, list[i].s);
793 * _substrcmp takes two strings and returns 1 if they do not match,
794 * and 0 if they match exactly or the first string is a sub-string
795 * of the second. A warning is printed to stderr in the case that the
796 * first string is a sub-string of the second.
798 * This function will be removed in the future through the usual
799 * deprecation process.
802 _substrcmp(const char *str1, const char* str2)
805 if (strncmp(str1, str2, strlen(str1)) != 0)
808 if (strlen(str1) != strlen(str2))
809 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
815 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
816 * and 0 if they match exactly or the second string is a sub-string
817 * of the first. A warning is printed to stderr in the case that the
818 * first string does not match the third.
820 * This function exists to warn about the bizarre construction
821 * strncmp(str, "by", 2) which is used to allow people to use a shortcut
822 * for "bytes". The problem is that in addition to accepting "by",
823 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
824 * other string beginning with "by".
826 * This function will be removed in the future through the usual
827 * deprecation process.
830 _substrcmp2(const char *str1, const char* str2, const char* str3)
833 if (strncmp(str1, str2, strlen(str2)) != 0)
836 if (strcmp(str1, str3) != 0)
837 warnx("DEPRECATED: '%s' matched '%s'",
843 * prints one port, symbolic or numeric
846 print_port(struct buf_pr *bp, int proto, uint16_t port)
849 if (proto == IPPROTO_ETHERTYPE) {
852 if (co.do_resolv && (s = match_value(ether_types, port)) )
853 bprintf(bp, "%s", s);
855 bprintf(bp, "0x%04x", port);
857 struct servent *se = NULL;
859 struct protoent *pe = getprotobynumber(proto);
861 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
864 bprintf(bp, "%s", se->s_name);
866 bprintf(bp, "%d", port);
870 static struct _s_x _port_name[] = {
871 {"dst-port", O_IP_DSTPORT},
872 {"src-port", O_IP_SRCPORT},
876 {"mac-type", O_MAC_TYPE},
877 {"tcpdatalen", O_TCPDATALEN},
878 {"tcpwin", O_TCPWIN},
879 {"tagged", O_TAGGED},
884 * Print the values in a list 16-bit items of the types above.
885 * XXX todo: add support for mask.
888 print_newports(struct buf_pr *bp, ipfw_insn_u16 *cmd, int proto, int opcode)
890 uint16_t *p = cmd->ports;
895 sep = match_value(_port_name, opcode);
898 bprintf(bp, " %s", sep);
901 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
902 bprintf(bp, "%s", sep);
903 print_port(bp, proto, p[0]);
906 print_port(bp, proto, p[1]);
913 * Like strtol, but also translates service names into port numbers
914 * for some protocols.
916 * proto == -1 disables the protocol check;
917 * proto == IPPROTO_ETHERTYPE looks up an internal table
918 * proto == <some value in /etc/protocols> matches the values there.
919 * Returns *end == s in case the parameter is not found.
922 strtoport(char *s, char **end, int base, int proto)
928 *end = s; /* default - not found */
930 return 0; /* not found */
933 return strtol(s, end, base);
936 * find separator. '\\' escapes the next char.
938 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
939 if (*s1 == '\\' && s1[1] != '\0')
942 buf = safe_calloc(s1 - s + 1, 1);
945 * copy into a buffer skipping backslashes
947 for (p = s, i = 0; p != s1 ; p++)
952 if (proto == IPPROTO_ETHERTYPE) {
953 i = match_token(ether_types, buf);
955 if (i != -1) { /* found */
960 struct protoent *pe = NULL;
964 pe = getprotobynumber(proto);
966 se = getservbyname(buf, pe ? pe->p_name : NULL);
970 return ntohs(se->s_port);
973 return 0; /* not found */
977 * Fill the body of the command with the list of port ranges.
980 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
982 uint16_t a, b, *p = cmd->ports;
987 a = strtoport(av, &s, 0, proto);
988 if (s == av) /* empty or invalid argument */
991 CHECK_LENGTH(cblen, i + 2);
994 case '-': /* a range */
996 b = strtoport(av, &s, 0, proto);
997 /* Reject expressions like '1-abc' or '1-2-3'. */
998 if (s == av || (*s != ',' && *s != '\0'))
1003 case ',': /* comma separated list */
1008 warnx("port list: invalid separator <%c> in <%s>",
1018 if (i + 1 > F_LEN_MASK)
1019 errx(EX_DATAERR, "too many ports/ranges\n");
1020 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
1026 * Fill the body of the command with the list of DiffServ codepoints.
1029 fill_dscp(ipfw_insn *cmd, char *av, int cblen)
1031 uint32_t *low, *high;
1035 cmd->opcode = O_DSCP;
1036 cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
1040 low = (uint32_t *)(cmd + 1);
1053 if ((code = match_token(f_ipdscp, s)) == -1)
1054 errx(EX_DATAERR, "Unknown DSCP code");
1056 code = strtoul(s, NULL, 10);
1057 if (code < 0 || code > 63)
1058 errx(EX_DATAERR, "Invalid DSCP value");
1062 *high |= 1 << (code - 32);
1070 static struct _s_x icmpcodes[] = {
1071 { "net", ICMP_UNREACH_NET },
1072 { "host", ICMP_UNREACH_HOST },
1073 { "protocol", ICMP_UNREACH_PROTOCOL },
1074 { "port", ICMP_UNREACH_PORT },
1075 { "needfrag", ICMP_UNREACH_NEEDFRAG },
1076 { "srcfail", ICMP_UNREACH_SRCFAIL },
1077 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
1078 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
1079 { "isolated", ICMP_UNREACH_ISOLATED },
1080 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
1081 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
1082 { "tosnet", ICMP_UNREACH_TOSNET },
1083 { "toshost", ICMP_UNREACH_TOSHOST },
1084 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
1085 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
1086 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
1091 fill_reject_code(u_short *codep, char *str)
1096 val = strtoul(str, &s, 0);
1097 if (s == str || *s != '\0' || val >= 0x100)
1098 val = match_token(icmpcodes, str);
1100 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
1106 print_reject_code(struct buf_pr *bp, uint16_t code)
1110 if ((s = match_value(icmpcodes, code)) != NULL)
1111 bprintf(bp, "unreach %s", s);
1113 bprintf(bp, "unreach %u", code);
1117 * Returns the number of bits set (from left) in a contiguous bitmask,
1118 * or -1 if the mask is not contiguous.
1119 * XXX this needs a proper fix.
1120 * This effectively works on masks in big-endian (network) format.
1121 * when compiled on little endian architectures.
1123 * First bit is bit 7 of the first byte -- note, for MAC addresses,
1124 * the first bit on the wire is bit 0 of the first byte.
1125 * len is the max length in bits.
1128 contigmask(uint8_t *p, int len)
1132 for (i=0; i<len ; i++)
1133 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
1135 for (n=i+1; n < len; n++)
1136 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
1137 return -1; /* mask not contiguous */
1142 * print flags set/clear in the two bitmasks passed as parameters.
1143 * There is a specialized check for f_tcpflags.
1146 print_flags(struct buf_pr *bp, char const *name, ipfw_insn *cmd,
1149 char const *comma = "";
1151 uint8_t set = cmd->arg1 & 0xff;
1152 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
1154 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
1155 bprintf(bp, " setup");
1159 bprintf(bp, " %s ", name);
1160 for (i=0; list[i].x != 0; i++) {
1161 if (set & list[i].x) {
1163 bprintf(bp, "%s%s", comma, list[i].s);
1166 if (clear & list[i].x) {
1167 clear &= ~list[i].x;
1168 bprintf(bp, "%s!%s", comma, list[i].s);
1176 * Print the ip address contained in a command.
1179 print_ip(struct buf_pr *bp, const struct format_opts *fo, ipfw_insn_ip *cmd,
1182 struct hostent *he = NULL;
1184 uint32_t len = F_LEN((ipfw_insn *)cmd);
1185 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
1188 if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
1190 const char *arg = "<invalid>";
1192 if (d < sizeof(lookup_key)/sizeof(lookup_key[0]))
1193 arg = match_value(rule_options, lookup_key[d]);
1194 t = table_search_ctlv(fo->tstate, ((ipfw_insn *)cmd)->arg1);
1195 bprintf(bp, "%s lookup %s %s", cmd->o.len & F_NOT ? " not": "",
1199 bprintf(bp, "%s%s ", cmd->o.len & F_NOT ? " not": "", s);
1201 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
1205 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
1206 cmd->o.opcode == O_IP_DST_LOOKUP) {
1207 t = table_search_ctlv(fo->tstate, ((ipfw_insn *)cmd)->arg1);
1208 bprintf(bp, "table(%s", t);
1209 if (len == F_INSN_SIZE(ipfw_insn_u32))
1210 bprintf(bp, ",%u", *a);
1214 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
1215 uint32_t x, *map = (uint32_t *)&(cmd->mask);
1219 x = cmd->o.arg1 - 1;
1221 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1222 bprintf(bp, "%s/%d", inet_ntoa(cmd->addr),
1223 contigmask((uint8_t *)&x, 32));
1224 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1225 x &= 0xff; /* base */
1227 * Print bits and ranges.
1228 * Locate first bit set (i), then locate first bit unset (j).
1229 * If we have 3+ consecutive bits set, then print them as a
1230 * range, otherwise only print the initial bit and rescan.
1232 for (i=0; i < cmd->o.arg1; i++)
1233 if (map[i/32] & (1<<(i & 31))) {
1234 for (j=i+1; j < cmd->o.arg1; j++)
1235 if (!(map[ j/32] & (1<<(j & 31))))
1237 bprintf(bp, "%c%d", comma, i+x);
1238 if (j>i+2) { /* range has at least 3 elements */
1239 bprintf(bp, "-%d", j-1+x);
1248 * len == 2 indicates a single IP, whereas lists of 1 or more
1249 * addr/mask pairs have len = (2n+1). We convert len to n so we
1250 * use that to count the number of entries.
1252 for (len = len / 2; len > 0; len--, a += 2) {
1253 int mb = /* mask length */
1254 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1255 32 : contigmask((uint8_t *)&(a[1]), 32);
1256 if (mb == 32 && co.do_resolv)
1257 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
1258 if (he != NULL) /* resolved to name */
1259 bprintf(bp, "%s", he->h_name);
1260 else if (mb == 0) /* any */
1262 else { /* numeric IP followed by some kind of mask */
1263 ia = (struct in_addr *)&a[0];
1264 bprintf(bp, "%s", inet_ntoa(*ia));
1266 ia = (struct in_addr *)&a[1];
1267 bprintf(bp, ":%s", inet_ntoa(*ia));
1269 bprintf(bp, "/%d", mb);
1277 * prints a MAC address/mask pair
1280 format_mac(struct buf_pr *bp, uint8_t *addr, uint8_t *mask)
1282 int l = contigmask(mask, 48);
1285 bprintf(bp, " any");
1287 bprintf(bp, " %02x:%02x:%02x:%02x:%02x:%02x",
1288 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1290 bprintf(bp, "&%02x:%02x:%02x:%02x:%02x:%02x",
1291 mask[0], mask[1], mask[2],
1292 mask[3], mask[4], mask[5]);
1294 bprintf(bp, "/%d", l);
1299 print_mac(struct buf_pr *bp, ipfw_insn_mac *mac)
1302 bprintf(bp, " MAC");
1303 format_mac(bp, mac->addr, mac->mask);
1304 format_mac(bp, mac->addr + 6, mac->mask + 6);
1308 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1317 type = strtoul(av, &av, 0);
1319 if (*av != ',' && *av != '\0')
1320 errx(EX_DATAERR, "invalid ICMP type");
1323 errx(EX_DATAERR, "ICMP type out of range");
1325 cmd->d[0] |= 1 << type;
1327 cmd->o.opcode = O_ICMPTYPE;
1328 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1332 print_icmptypes(struct buf_pr *bp, ipfw_insn_u32 *cmd)
1337 bprintf(bp, " icmptypes");
1338 for (i = 0; i < 32; i++) {
1339 if ( (cmd->d[0] & (1 << (i))) == 0)
1341 bprintf(bp, "%c%d", sep, i);
1347 print_dscp(struct buf_pr *bp, ipfw_insn_u32 *cmd)
1354 bprintf(bp, " dscp");
1357 if (*v & (1 << i)) {
1358 if ((code = match_value(f_ipdscp, i)) != NULL)
1359 bprintf(bp, "%c%s", sep, code);
1361 bprintf(bp, "%c%d", sep, i);
1365 if ((++i % 32) == 0)
1370 #define insntod(cmd, type) ((ipfw_insn_ ## type *)(cmd))
1372 struct ip_fw_rule *rule;
1373 const ipfw_insn *eaction;
1376 #define HAVE_PROTO 0x0001
1377 #define HAVE_SRCIP 0x0002
1378 #define HAVE_DSTIP 0x0004
1384 init_show_state(struct show_state *state, struct ip_fw_rule *rule)
1387 state->printed = calloc(rule->cmd_len, sizeof(uint8_t));
1388 if (state->printed == NULL)
1391 state->eaction = NULL;
1394 state->or_block = 0;
1399 free_show_state(struct show_state *state)
1402 free(state->printed);
1406 is_printed_opcode(struct show_state *state, const ipfw_insn *cmd)
1409 return (state->printed[cmd - state->rule->cmd]);
1413 mark_printed(struct show_state *state, const ipfw_insn *cmd)
1416 state->printed[cmd - state->rule->cmd] = 1;
1420 print_limit(struct buf_pr *bp, const ipfw_insn_limit *limit)
1422 struct _s_x *p = limit_masks;
1423 char const *comma = " ";
1426 bprintf(bp, " limit");
1427 for (x = limit->limit_mask; p->x != 0; p++) {
1428 if ((x & p->x) == p->x) {
1430 bprintf(bp, "%s%s", comma, p->s);
1434 bprint_uint_arg(bp, " ", limit->conn_limit);
1438 print_instruction(struct buf_pr *bp, const struct format_opts *fo,
1439 struct show_state *state, ipfw_insn *cmd)
1441 struct protoent *pe;
1447 if (is_printed_opcode(state, cmd))
1449 if ((cmd->len & F_OR) != 0 && state->or_block == 0)
1451 if (cmd->opcode != O_IN && (cmd->len & F_NOT) != 0)
1452 bprintf(bp, " not");
1454 switch (cmd->opcode) {
1456 d = 1.0 * insntod(cmd, u32)->d[0] / 0x7fffffff;
1457 bprintf(bp, "prob %f ", d);
1459 case O_PROBE_STATE: /* no need to print anything here */
1462 case O_IP_SRC_LOOKUP:
1467 case O_IP_DST_LOOKUP:
1471 print_ip(bp, fo, insntod(cmd, ip), "");
1474 case O_IP6_SRC_MASK:
1477 case O_IP6_DST_MASK:
1479 print_ip6(bp, insntod(cmd, ip6), "");
1482 print_flow6id(bp, insntod(cmd, u32));
1486 print_newports(bp, insntod(cmd, u16), state->proto,
1487 (state->flags & (HAVE_SRCIP | HAVE_DSTIP)) ==
1488 (HAVE_SRCIP | HAVE_DSTIP) ? cmd->opcode: 0);
1491 pe = getprotobynumber(cmd->arg1);
1492 if (state->flags & HAVE_PROTO)
1493 bprintf(bp, " proto");
1495 bprintf(bp, " %s", pe->p_name);
1497 bprintf(bp, " %u", cmd->arg1);
1500 print_mac(bp, insntod(cmd, mac));
1503 print_newports(bp, insntod(cmd, u16),
1504 IPPROTO_ETHERTYPE, cmd->opcode);
1507 bprintf(bp, " frag");
1510 bprintf(bp, " fib %u", cmd->arg1);
1513 bprintf(bp, " sockarg");
1516 bprintf(bp, cmd->len & F_NOT ? " out" : " in");
1519 switch (cmd->arg1) {
1521 bprintf(bp, " diverted");
1524 bprintf(bp, " diverted-output");
1527 bprintf(bp, " diverted-loopback");
1530 bprintf(bp, " diverted-?<%u>", cmd->arg1);
1535 bprintf(bp, " layer2");
1540 if (cmd->opcode == O_XMIT)
1542 else if (cmd->opcode == O_RECV)
1544 else /* if (cmd->opcode == O_VIA) */
1546 switch (insntod(cmd, if)->name[0]) {
1548 bprintf(bp, " %s %s", s,
1549 inet_ntoa(insntod(cmd, if)->p.ip));
1552 bprintf(bp, " %s table(%s)", s,
1553 table_search_ctlv(fo->tstate,
1554 insntod(cmd, if)->p.kidx));
1557 bprintf(bp, " %s %s", s,
1558 insntod(cmd, if)->name);
1561 case O_IP_FLOW_LOOKUP:
1562 s = table_search_ctlv(fo->tstate, cmd->arg1);
1563 bprintf(bp, " flow table(%s", s);
1564 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))
1565 bprintf(bp, ",%u", insntod(cmd, u32)->d[0]);
1573 if (F_LEN(cmd) == 1) {
1574 switch (cmd->opcode) {
1591 bprintf(bp, " %s %u", s, cmd->arg1);
1593 print_newports(bp, insntod(cmd, u16), 0,
1597 bprintf(bp, " ipver %u", cmd->arg1);
1599 case O_IPPRECEDENCE:
1600 bprintf(bp, " ipprecedence %u", cmd->arg1 >> 5);
1603 print_dscp(bp, insntod(cmd, u32));
1606 print_flags(bp, "ipoptions", cmd, f_ipopts);
1609 print_flags(bp, "iptos", cmd, f_iptos);
1612 print_icmptypes(bp, insntod(cmd, u32));
1615 bprintf(bp, " established");
1618 print_flags(bp, "tcpflags", cmd, f_tcpflags);
1621 print_flags(bp, "tcpoptions", cmd, f_tcpopts);
1624 bprintf(bp, " tcpack %d",
1625 ntohl(insntod(cmd, u32)->d[0]));
1628 bprintf(bp, " tcpseq %d",
1629 ntohl(insntod(cmd, u32)->d[0]));
1632 pwd = getpwuid(insntod(cmd, u32)->d[0]);
1634 bprintf(bp, " uid %s", pwd->pw_name);
1636 bprintf(bp, " uid %u",
1637 insntod(cmd, u32)->d[0]);
1640 grp = getgrgid(insntod(cmd, u32)->d[0]);
1642 bprintf(bp, " gid %s", grp->gr_name);
1644 bprintf(bp, " gid %u",
1645 insntod(cmd, u32)->d[0]);
1648 bprintf(bp, " jail %d", insntod(cmd, u32)->d[0]);
1651 bprintf(bp, " verrevpath");
1654 bprintf(bp, " versrcreach");
1657 bprintf(bp, " antispoof");
1660 bprintf(bp, " ipsec");
1663 bprintf(bp, " // %s", (char *)(cmd + 1));
1666 bprintf(bp, " keep-state");
1668 object_search_ctlv(fo->tstate, cmd->arg1,
1669 IPFW_TLV_STATE_NAME));
1672 print_limit(bp, insntod(cmd, limit));
1674 object_search_ctlv(fo->tstate, cmd->arg1,
1675 IPFW_TLV_STATE_NAME));
1678 bprintf(bp, " ip6");
1681 bprintf(bp, " ip4");
1684 print_icmp6types(bp, insntod(cmd, u32));
1687 print_ext6hdr(bp, cmd);
1690 if (F_LEN(cmd) == 1)
1691 bprint_uint_arg(bp, " tagged ", cmd->arg1);
1693 print_newports(bp, insntod(cmd, u16),
1697 bprintf(bp, " [opcode %d len %d]", cmd->opcode,
1700 if (cmd->len & F_OR) {
1702 state->or_block = 1;
1703 } else if (state->or_block != 0) {
1705 state->or_block = 0;
1707 mark_printed(state, cmd);
1713 print_opcode(struct buf_pr *bp, struct format_opts *fo,
1714 struct show_state *state, uint8_t opcode)
1719 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
1720 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1721 /* We use zero opcode to print the rest of options */
1722 if (opcode != 0 && cmd->opcode != opcode)
1725 * Skip O_NOP, when we printing the rest
1726 * of options, it will be handled separately.
1728 if (cmd->opcode == O_NOP && opcode != O_NOP)
1730 if (!print_instruction(bp, fo, state, cmd))
1738 print_fwd(struct buf_pr *bp, const ipfw_insn *cmd)
1740 char buf[INET6_ADDRSTRLEN + IF_NAMESIZE + 2];
1745 if (cmd->opcode == O_FORWARD_IP) {
1746 sa = insntod(cmd, sa);
1747 port = sa->sa.sin_port;
1748 if (sa->sa.sin_addr.s_addr == INADDR_ANY)
1749 bprintf(bp, "fwd tablearg");
1751 bprintf(bp, "fwd %s", inet_ntoa(sa->sa.sin_addr));
1753 sa6 = insntod(cmd, sa6);
1754 port = sa6->sa.sin6_port;
1755 bprintf(bp, "fwd ");
1756 if (getnameinfo((const struct sockaddr *)&sa6->sa,
1757 sizeof(struct sockaddr_in6), buf, sizeof(buf), NULL, 0,
1758 NI_NUMERICHOST) == 0)
1759 bprintf(bp, "%s", buf);
1762 bprintf(bp, ",%u", port);
1766 print_action_instruction(struct buf_pr *bp, const struct format_opts *fo,
1767 struct show_state *state, const ipfw_insn *cmd)
1771 if (is_printed_opcode(state, cmd))
1773 switch (cmd->opcode) {
1775 bprintf(bp, "check-state");
1777 s = object_search_ctlv(fo->tstate, cmd->arg1,
1778 IPFW_TLV_STATE_NAME);
1781 bprintf(bp, " :%s", s ? s: "any");
1784 bprintf(bp, "allow");
1787 bprintf(bp, "count");
1790 bprintf(bp, "deny");
1793 if (cmd->arg1 == ICMP_REJECT_RST)
1794 bprintf(bp, "reset");
1795 else if (cmd->arg1 == ICMP_REJECT_ABORT)
1796 bprintf(bp, "abort");
1797 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1798 bprintf(bp, "reject");
1800 print_reject_code(bp, cmd->arg1);
1803 if (cmd->arg1 == ICMP6_UNREACH_RST)
1804 bprintf(bp, "reset6");
1805 else if (cmd->arg1 == ICMP6_UNREACH_ABORT)
1806 bprintf(bp, "abort6");
1808 print_unreach6_code(bp, cmd->arg1);
1811 bprint_uint_arg(bp, "skipto ", cmd->arg1);
1814 bprint_uint_arg(bp, "pipe ", cmd->arg1);
1817 bprint_uint_arg(bp, "queue ", cmd->arg1);
1820 bprint_uint_arg(bp, "divert ", cmd->arg1);
1823 bprint_uint_arg(bp, "tee ", cmd->arg1);
1826 bprint_uint_arg(bp, "netgraph ", cmd->arg1);
1829 bprint_uint_arg(bp, "ngtee ", cmd->arg1);
1836 if (insntod(cmd, log)->max_log > 0)
1837 bprintf(bp, " log logamount %d",
1838 insntod(cmd, log)->max_log);
1840 bprintf(bp, " log");
1844 print_altq_cmd(bp, insntod(cmd, altq));
1848 bprint_uint_arg(bp, cmd->len & F_NOT ? " untag ":
1849 " tag ", cmd->arg1);
1852 if (cmd->arg1 != IP_FW_NAT44_GLOBAL)
1853 bprint_uint_arg(bp, "nat ", cmd->arg1);
1855 bprintf(bp, "nat global");
1858 if (cmd->arg1 == IP_FW_TARG)
1859 bprint_uint_arg(bp, "setfib ", cmd->arg1);
1861 bprintf(bp, "setfib %u", cmd->arg1 & 0x7FFF);
1863 case O_EXTERNAL_ACTION:
1865 * The external action can consists of two following
1866 * each other opcodes - O_EXTERNAL_ACTION and
1867 * O_EXTERNAL_INSTANCE. The first contains the ID of
1868 * name of external action. The second contains the ID
1869 * of name of external action instance.
1870 * NOTE: in case when external action has no named
1871 * instances support, the second opcode isn't needed.
1873 state->eaction = cmd;
1874 s = object_search_ctlv(fo->tstate, cmd->arg1,
1876 if (match_token(rule_eactions, s) != -1)
1877 bprintf(bp, "%s", s);
1879 bprintf(bp, "eaction %s", s);
1881 case O_EXTERNAL_INSTANCE:
1882 if (state->eaction == NULL)
1885 * XXX: we need to teach ipfw(9) to rewrite opcodes
1886 * in the user buffer on rule addition. When we add
1887 * the rule, we specify zero TLV type for
1888 * O_EXTERNAL_INSTANCE object. To show correct
1889 * rule after `ipfw add` we need to search instance
1890 * name with zero type. But when we do `ipfw show`
1891 * we calculate TLV type using IPFW_TLV_EACTION_NAME()
1894 s = object_search_ctlv(fo->tstate, cmd->arg1, 0);
1896 s = object_search_ctlv(fo->tstate,
1897 cmd->arg1, IPFW_TLV_EACTION_NAME(
1898 state->eaction->arg1));
1899 bprintf(bp, " %s", s);
1901 case O_EXTERNAL_DATA:
1902 if (state->eaction == NULL)
1905 * Currently we support data formatting only for
1906 * external data with datalen u16. For unknown data
1907 * print its size in bytes.
1909 if (cmd->len == F_INSN_SIZE(ipfw_insn))
1910 bprintf(bp, " %u", cmd->arg1);
1912 bprintf(bp, " %ubytes",
1913 cmd->len * sizeof(uint32_t));
1916 if (cmd->arg1 == IP_FW_TARG) {
1917 bprintf(bp, "setdscp tablearg");
1920 s = match_value(f_ipdscp, cmd->arg1 & 0x3F);
1922 bprintf(bp, "setdscp %s", s);
1924 bprintf(bp, "setdscp %s", cmd->arg1 & 0x3F);
1927 bprintf(bp, "reass");
1930 if (cmd->len & F_NOT)
1931 bprintf(bp, "return");
1933 bprint_uint_arg(bp, "call ", cmd->arg1);
1936 bprintf(bp, "** unrecognized action %d len %d ",
1937 cmd->opcode, cmd->len);
1939 mark_printed(state, cmd);
1946 print_action(struct buf_pr *bp, struct format_opts *fo,
1947 struct show_state *state, uint8_t opcode)
1952 for (l = state->rule->cmd_len - state->rule->act_ofs,
1953 cmd = ACTION_PTR(state->rule); l > 0;
1954 l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1955 if (cmd->opcode != opcode)
1957 if (!print_action_instruction(bp, fo, state, cmd))
1965 print_proto(struct buf_pr *bp, struct format_opts *fo,
1966 struct show_state *state)
1969 int l, proto, ip4, ip6, tmp;
1971 /* Count all O_PROTO, O_IP4, O_IP6 instructions. */
1972 proto = tmp = ip4 = ip6 = 0;
1973 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
1974 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1975 switch (cmd->opcode) {
1981 if (cmd->len & F_OR)
1986 if (cmd->len & F_OR)
1993 if (proto == 0 && ip4 == 0 && ip6 == 0) {
1994 state->proto = IPPROTO_IP;
1995 state->flags |= HAVE_PROTO;
1999 /* To handle the case { ip4 or ip6 }, print opcode with F_OR first */
2002 cmd = print_opcode(bp, fo, state, ip4 > ip6 ? O_IP4: O_IP6);
2003 if (cmd != NULL && (cmd->len & F_OR))
2004 cmd = print_opcode(bp, fo, state, ip4 > ip6 ? O_IP6: O_IP4);
2005 if (cmd == NULL || (cmd->len & F_OR))
2006 for (l = proto; l > 0; l--) {
2007 cmd = print_opcode(bp, fo, state, O_PROTO);
2008 if (cmd != NULL && (cmd->len & F_OR) == 0)
2012 /* Initialize proto, it is used by print_newports() */
2016 state->proto = IPPROTO_IPV6;
2018 state->proto = IPPROTO_IP;
2019 state->flags |= HAVE_PROTO;
2023 match_opcode(int opcode, const int opcodes[], size_t nops)
2027 for (i = 0; i < nops; i++)
2028 if (opcode == opcodes[i])
2034 print_address(struct buf_pr *bp, struct format_opts *fo,
2035 struct show_state *state, const int opcodes[], size_t nops, int portop,
2039 int count, l, portcnt, pf;
2041 count = portcnt = 0;
2042 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2043 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2044 if (match_opcode(cmd->opcode, opcodes, nops))
2046 else if (cmd->opcode == portop)
2050 bprintf(bp, " any");
2051 for (l = state->rule->act_ofs, cmd = state->rule->cmd;
2052 l > 0 && count > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2053 if (!match_opcode(cmd->opcode, opcodes, nops))
2055 print_instruction(bp, fo, state, cmd);
2056 if ((cmd->len & F_OR) == 0)
2061 * If several O_IP_?PORT opcodes specified, leave them to the
2065 for (l = state->rule->act_ofs, cmd = state->rule->cmd, pf = 0;
2066 l > 0; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
2067 if (cmd->opcode != portop) {
2068 pf = (cmd->len & F_OR);
2071 /* Print opcode iff it is not in OR block. */
2072 if (pf == 0 && (cmd->len & F_OR) == 0)
2073 print_instruction(bp, fo, state, cmd);
2077 state->flags |= flag;
2080 static const int action_opcodes[] = {
2081 O_CHECK_STATE, O_ACCEPT, O_COUNT, O_DENY, O_REJECT,
2082 O_UNREACH6, O_SKIPTO, O_PIPE, O_QUEUE, O_DIVERT, O_TEE,
2083 O_NETGRAPH, O_NGTEE, O_FORWARD_IP, O_FORWARD_IP6, O_NAT,
2084 O_SETFIB, O_SETDSCP, O_REASS, O_CALLRETURN,
2085 /* keep the following opcodes at the end of the list */
2086 O_EXTERNAL_ACTION, O_EXTERNAL_INSTANCE, O_EXTERNAL_DATA
2089 static const int modifier_opcodes[] = {
2090 O_LOG, O_ALTQ, O_TAG
2093 static const int src_opcodes[] = {
2094 O_IP_SRC, O_IP_SRC_LOOKUP, O_IP_SRC_MASK, O_IP_SRC_ME,
2095 O_IP_SRC_SET, O_IP6_SRC, O_IP6_SRC_MASK, O_IP6_SRC_ME
2098 static const int dst_opcodes[] = {
2099 O_IP_DST, O_IP_DST_LOOKUP, O_IP_DST_MASK, O_IP_DST_ME,
2100 O_IP_DST_SET, O_IP6_DST, O_IP6_DST_MASK, O_IP6_DST_ME
2104 show_static_rule(struct cmdline_opts *co, struct format_opts *fo,
2105 struct buf_pr *bp, struct ip_fw_rule *rule, struct ip_fw_bcounter *cntr)
2107 struct show_state state;
2109 static int twidth = 0;
2112 /* Print # DISABLED or skip the rule */
2113 if ((fo->set_mask & (1 << rule->set)) == 0) {
2118 bprintf(bp, "# DISABLED ");
2120 if (init_show_state(&state, rule) != 0) {
2121 warn("init_show_state() failed");
2124 bprintf(bp, "%05u ", rule->rulenum);
2126 /* Print counters if enabled */
2127 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2128 pr_u64(bp, &cntr->pcnt, fo->pcwidth);
2129 pr_u64(bp, &cntr->bcnt, fo->bcwidth);
2132 /* Print timestamp */
2133 if (co->do_time == TIMESTAMP_NUMERIC)
2134 bprintf(bp, "%10u ", cntr->timestamp);
2135 else if (co->do_time == TIMESTAMP_STRING) {
2137 time_t t = (time_t)0;
2140 strcpy(timestr, ctime(&t));
2141 *strchr(timestr, '\n') = '\0';
2142 twidth = strlen(timestr);
2144 if (cntr->timestamp > 0) {
2145 t = _long_to_time(cntr->timestamp);
2147 strcpy(timestr, ctime(&t));
2148 *strchr(timestr, '\n') = '\0';
2149 bprintf(bp, "%s ", timestr);
2151 bprintf(bp, "%*s", twidth, " ");
2155 /* Print set number */
2157 bprintf(bp, "set %d ", rule->set);
2159 /* Print the optional "match probability" */
2160 cmd = print_opcode(bp, fo, &state, O_PROB);
2161 /* Print rule action */
2162 for (i = 0; i < nitems(action_opcodes); i++) {
2163 cmd = print_action(bp, fo, &state, action_opcodes[i]);
2166 /* Handle special cases */
2167 switch (cmd->opcode) {
2170 case O_EXTERNAL_ACTION:
2171 case O_EXTERNAL_INSTANCE:
2172 /* External action can have several instructions */
2177 /* Print rule modifiers */
2178 for (i = 0; i < nitems(modifier_opcodes); i++)
2179 print_action(bp, fo, &state, modifier_opcodes[i]);
2183 if (co->comment_only != 0)
2185 print_proto(bp, fo, &state);
2188 bprintf(bp, " from");
2189 print_address(bp, fo, &state, src_opcodes, nitems(src_opcodes),
2190 O_IP_SRCPORT, HAVE_SRCIP);
2192 /* Print destination */
2194 print_address(bp, fo, &state, dst_opcodes, nitems(dst_opcodes),
2195 O_IP_DSTPORT, HAVE_DSTIP);
2197 /* Print the rest of options */
2198 while (print_opcode(bp, fo, &state, 0))
2201 /* Print comment at the end */
2202 cmd = print_opcode(bp, fo, &state, O_NOP);
2203 if (co->comment_only != 0 && cmd == NULL)
2204 bprintf(bp, " // ...");
2206 free_show_state(&state);
2210 show_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2211 struct buf_pr *bp, ipfw_dyn_rule *d)
2213 struct protoent *pe;
2216 char buf[INET6_ADDRSTRLEN];
2218 if (!co->do_expired) {
2219 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
2222 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2223 bprintf(bp, "%05d", rulenum);
2224 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2226 pr_u64(bp, &d->pcnt, fo->pcwidth);
2227 pr_u64(bp, &d->bcnt, fo->bcwidth);
2228 bprintf(bp, "(%ds)", d->expire);
2230 switch (d->dyn_type) {
2231 case O_LIMIT_PARENT:
2232 bprintf(bp, " PARENT %d", d->count);
2235 bprintf(bp, " LIMIT");
2237 case O_KEEP_STATE: /* bidir, no mask */
2238 bprintf(bp, " STATE");
2242 if ((pe = getprotobynumber(d->id.proto)) != NULL)
2243 bprintf(bp, " %s", pe->p_name);
2245 bprintf(bp, " proto %u", d->id.proto);
2247 if (d->id.addr_type == 4) {
2248 a.s_addr = htonl(d->id.src_ip);
2249 bprintf(bp, " %s %d", inet_ntoa(a), d->id.src_port);
2251 a.s_addr = htonl(d->id.dst_ip);
2252 bprintf(bp, " <-> %s %d", inet_ntoa(a), d->id.dst_port);
2253 } else if (d->id.addr_type == 6) {
2254 bprintf(bp, " %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
2255 sizeof(buf)), d->id.src_port);
2256 bprintf(bp, " <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6,
2257 buf, sizeof(buf)), d->id.dst_port);
2259 bprintf(bp, " UNKNOWN <-> UNKNOWN");
2261 bprintf(bp, " :%s", object_search_ctlv(fo->tstate,
2262 d->kidx, IPFW_TLV_STATE_NAME));
2266 do_range_cmd(int cmd, ipfw_range_tlv *rt)
2268 ipfw_range_header rh;
2271 memset(&rh, 0, sizeof(rh));
2272 memcpy(&rh.range, rt, sizeof(*rt));
2273 rh.range.head.length = sizeof(*rt);
2274 rh.range.head.type = IPFW_TLV_RANGE;
2277 if (do_get3(cmd, &rh.opheader, &sz) != 0)
2279 /* Save number of matched objects */
2280 rt->new_set = rh.range.new_set;
2285 * This one handles all set-related commands
2286 * ipfw set { show | enable | disable }
2288 * ipfw set move X to Y
2289 * ipfw set move rule X to Y
2292 ipfw_sets_handler(char *av[])
2303 memset(&rt, 0, sizeof(rt));
2306 errx(EX_USAGE, "set needs command");
2307 if (_substrcmp(*av, "show") == 0) {
2308 struct format_opts fo;
2309 ipfw_cfg_lheader *cfg;
2311 memset(&fo, 0, sizeof(fo));
2312 if (ipfw_get_config(&co, &fo, &cfg, &size) != 0)
2313 err(EX_OSERR, "requesting config failed");
2315 for (i = 0, msg = "disable"; i < RESVD_SET; i++)
2316 if ((cfg->set_mask & (1<<i)) == 0) {
2317 printf("%s %d", msg, i);
2320 msg = (cfg->set_mask != (uint32_t)-1) ? " enable" : "enable";
2321 for (i = 0; i < RESVD_SET; i++)
2322 if ((cfg->set_mask & (1<<i)) != 0) {
2323 printf("%s %d", msg, i);
2328 } else if (_substrcmp(*av, "swap") == 0) {
2330 if ( av[0] == NULL || av[1] == NULL )
2331 errx(EX_USAGE, "set swap needs 2 set numbers\n");
2332 rt.set = atoi(av[0]);
2333 rt.new_set = atoi(av[1]);
2334 if (!isdigit(*(av[0])) || rt.set > RESVD_SET)
2335 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2336 if (!isdigit(*(av[1])) || rt.new_set > RESVD_SET)
2337 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2338 i = do_range_cmd(IP_FW_SET_SWAP, &rt);
2339 } else if (_substrcmp(*av, "move") == 0) {
2341 if (av[0] && _substrcmp(*av, "rule") == 0) {
2342 rt.flags = IPFW_RCFLAG_RANGE; /* move rules to new set */
2346 cmd = IP_FW_SET_MOVE; /* Move set to new one */
2347 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
2348 av[3] != NULL || _substrcmp(av[1], "to") != 0)
2349 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2350 rulenum = atoi(av[0]);
2351 rt.new_set = atoi(av[2]);
2352 if (cmd == IP_FW_XMOVE) {
2353 rt.start_rule = rulenum;
2354 rt.end_rule = rulenum;
2357 rt.new_set = atoi(av[2]);
2358 if (!isdigit(*(av[0])) || (cmd == 3 && rt.set > RESVD_SET) ||
2359 (cmd == 2 && rt.start_rule == IPFW_DEFAULT_RULE) )
2360 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2361 if (!isdigit(*(av[2])) || rt.new_set > RESVD_SET)
2362 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2363 i = do_range_cmd(cmd, &rt);
2365 err(EX_OSERR, "failed to move %s",
2366 cmd == IP_FW_SET_MOVE ? "set": "rule");
2367 } else if (_substrcmp(*av, "disable") == 0 ||
2368 _substrcmp(*av, "enable") == 0 ) {
2369 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2372 masks[0] = masks[1] = 0;
2375 if (isdigit(**av)) {
2377 if (i < 0 || i > RESVD_SET)
2379 "invalid set number %d\n", i);
2380 masks[which] |= (1<<i);
2381 } else if (_substrcmp(*av, "disable") == 0)
2383 else if (_substrcmp(*av, "enable") == 0)
2387 "invalid set command %s\n", *av);
2390 if ( (masks[0] & masks[1]) != 0 )
2392 "cannot enable and disable the same set\n");
2395 rt.new_set = masks[1];
2396 i = do_range_cmd(IP_FW_SET_ENABLE, &rt);
2398 warn("set enable/disable: setsockopt(IP_FW_SET_ENABLE)");
2400 errx(EX_USAGE, "invalid set command %s\n", *av);
2404 ipfw_sysctl_handler(char *av[], int which)
2408 if (av[0] == NULL) {
2409 warnx("missing keyword to enable/disable\n");
2410 } else if (_substrcmp(*av, "firewall") == 0) {
2411 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2412 &which, sizeof(which));
2413 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
2414 &which, sizeof(which));
2415 } else if (_substrcmp(*av, "one_pass") == 0) {
2416 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2417 &which, sizeof(which));
2418 } else if (_substrcmp(*av, "debug") == 0) {
2419 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2420 &which, sizeof(which));
2421 } else if (_substrcmp(*av, "verbose") == 0) {
2422 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2423 &which, sizeof(which));
2424 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2425 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2426 &which, sizeof(which));
2428 } else if (_substrcmp(*av, "altq") == 0) {
2429 altq_set_enabled(which);
2432 warnx("unrecognize enable/disable keyword: %s\n", *av);
2436 typedef void state_cb(struct cmdline_opts *co, struct format_opts *fo,
2437 void *arg, void *state);
2440 prepare_format_dyn(struct cmdline_opts *co, struct format_opts *fo,
2441 void *arg, void *_state)
2447 d = (ipfw_dyn_rule *)_state;
2448 /* Count _ALL_ states */
2451 if (fo->show_counters == 0)
2455 /* skip states from another set */
2456 bcopy((char *)&d->rule + sizeof(uint16_t), &set,
2458 if (set != co->use_set - 1)
2462 width = pr_u64(NULL, &d->pcnt, 0);
2463 if (width > fo->pcwidth)
2464 fo->pcwidth = width;
2466 width = pr_u64(NULL, &d->bcnt, 0);
2467 if (width > fo->bcwidth)
2468 fo->bcwidth = width;
2472 foreach_state(struct cmdline_opts *co, struct format_opts *fo,
2473 caddr_t base, size_t sz, state_cb dyn_bc, void *dyn_arg)
2479 ipfw_obj_ctlv *ctlv;
2485 ctlv = (ipfw_obj_ctlv *)base;
2486 switch (ctlv->head.type) {
2487 case IPFW_TLV_DYNSTATE_LIST:
2488 base += sizeof(*ctlv);
2489 sz -= sizeof(*ctlv);
2490 ttype = IPFW_TLV_DYN_ENT;
2499 tlv = (ipfw_obj_tlv *)base;
2500 if (tlv->type != ttype)
2503 fptr(co, fo, farg, tlv + 1);
2505 base += tlv->length;
2513 prepare_format_opts(struct cmdline_opts *co, struct format_opts *fo,
2514 ipfw_obj_tlv *rtlv, int rcnt, caddr_t dynbase, size_t dynsz)
2516 int bcwidth, pcwidth, width;
2518 struct ip_fw_bcounter *cntr;
2519 struct ip_fw_rule *r;
2523 if (fo->show_counters != 0) {
2524 for (n = 0; n < rcnt; n++,
2525 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2526 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2527 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2528 /* skip rules from another set */
2529 if (co->use_set && r->set != co->use_set - 1)
2532 /* packet counter */
2533 width = pr_u64(NULL, &cntr->pcnt, 0);
2534 if (width > pcwidth)
2538 width = pr_u64(NULL, &cntr->bcnt, 0);
2539 if (width > bcwidth)
2543 fo->bcwidth = bcwidth;
2544 fo->pcwidth = pcwidth;
2547 if (co->do_dynamic && dynsz > 0)
2548 foreach_state(co, fo, dynbase, dynsz, prepare_format_dyn, NULL);
2552 list_static_range(struct cmdline_opts *co, struct format_opts *fo,
2553 struct buf_pr *bp, ipfw_obj_tlv *rtlv, int rcnt)
2556 struct ip_fw_rule *r;
2557 struct ip_fw_bcounter *cntr;
2560 for (n = seen = 0; n < rcnt; n++,
2561 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2563 if ((fo->show_counters | fo->show_time) != 0) {
2564 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2565 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2568 r = (struct ip_fw_rule *)(rtlv + 1);
2570 if (r->rulenum > fo->last)
2572 if (co->use_set && r->set != co->use_set - 1)
2574 if (r->rulenum >= fo->first && r->rulenum <= fo->last) {
2575 show_static_rule(co, fo, bp, r, cntr);
2576 printf("%s", bp->buf);
2587 list_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2588 void *_arg, void *_state)
2595 d = (ipfw_dyn_rule *)_state;
2596 bp = (struct buf_pr *)_arg;
2598 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2599 if (rulenum > fo->last)
2602 bcopy((char *)&d->rule + sizeof(uint16_t),
2603 &set, sizeof(uint8_t));
2604 if (set != co->use_set - 1)
2607 if (rulenum >= fo->first) {
2608 show_dyn_state(co, fo, bp, d);
2609 printf("%s\n", bp->buf);
2615 list_dyn_range(struct cmdline_opts *co, struct format_opts *fo,
2616 struct buf_pr *bp, caddr_t base, size_t sz)
2619 sz = foreach_state(co, fo, base, sz, list_dyn_state, bp);
2624 ipfw_list(int ac, char *av[], int show_counters)
2626 ipfw_cfg_lheader *cfg;
2627 struct format_opts sfo;
2636 fprintf(stderr, "Testing only, list disabled\n");
2640 dummynet_list(ac, av, show_counters);
2646 memset(&sfo, 0, sizeof(sfo));
2648 /* Determine rule range to request */
2650 for (lac = ac, lav = av; lac != 0; lac--) {
2651 rnum = strtoul(*lav++, &endptr, 10);
2652 if (sfo.first == 0 || rnum < sfo.first)
2656 rnum = strtoul(endptr + 1, &endptr, 10);
2657 if (sfo.last == 0 || rnum > sfo.last)
2662 /* get configuraion from kernel */
2664 sfo.show_counters = show_counters;
2665 sfo.show_time = co.do_time;
2666 sfo.flags = IPFW_CFG_GET_STATIC;
2667 if (co.do_dynamic != 0)
2668 sfo.flags |= IPFW_CFG_GET_STATES;
2669 if ((sfo.show_counters | sfo.show_time) != 0)
2670 sfo.flags |= IPFW_CFG_GET_COUNTERS;
2671 if (ipfw_get_config(&co, &sfo, &cfg, &sz) != 0)
2672 err(EX_OSERR, "retrieving config failed");
2674 error = ipfw_show_config(&co, &sfo, cfg, sz, ac, av);
2683 ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
2684 ipfw_cfg_lheader *cfg, size_t sz, int ac, char *av[])
2689 int exitval = EX_OK;
2695 ipfw_obj_ctlv *ctlv, *tstate;
2696 ipfw_obj_tlv *rbase;
2699 * Handle tablenames TLV first, if any
2705 readsz = sizeof(*cfg);
2708 fo->set_mask = cfg->set_mask;
2710 ctlv = (ipfw_obj_ctlv *)(cfg + 1);
2712 if (cfg->flags & IPFW_CFG_GET_STATIC) {
2713 /* We've requested static rules */
2714 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2715 object_sort_ctlv(ctlv);
2717 readsz += ctlv->head.length;
2718 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2722 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2723 rbase = (ipfw_obj_tlv *)(ctlv + 1);
2725 readsz += ctlv->head.length;
2726 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2731 if ((cfg->flags & IPFW_CFG_GET_STATES) && (readsz != sz)) {
2732 /* We may have some dynamic states */
2733 dynsz = sz - readsz;
2734 /* Skip empty header */
2735 if (dynsz != sizeof(ipfw_obj_ctlv))
2736 dynbase = (caddr_t)ctlv;
2741 prepare_format_opts(co, fo, rbase, rcnt, dynbase, dynsz);
2742 bp_alloc(&bp, 4096);
2744 /* if no rule numbers were specified, list all rules */
2747 fo->last = IPFW_DEFAULT_RULE;
2748 list_static_range(co, fo, &bp, rbase, rcnt);
2750 if (co->do_dynamic && dynsz > 0) {
2751 printf("## Dynamic rules (%d %zu):\n", fo->dcnt, dynsz);
2752 list_dyn_range(co, fo, &bp, dynbase, dynsz);
2759 /* display specific rules requested on command line */
2760 for (lac = ac, lav = av; lac != 0; lac--) {
2761 /* convert command line rule # */
2762 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2764 fo->last = strtoul(endptr + 1, &endptr, 10);
2767 warnx("invalid rule number: %s", *(lav - 1));
2771 if (list_static_range(co, fo, &bp, rbase, rcnt) == 0) {
2772 /* give precedence to other error(s) */
2773 if (exitval == EX_OK)
2774 exitval = EX_UNAVAILABLE;
2775 if (fo->first == fo->last)
2776 warnx("rule %u does not exist", fo->first);
2778 warnx("no rules in range %u-%u",
2779 fo->first, fo->last);
2783 if (co->do_dynamic && dynsz > 0) {
2784 printf("## Dynamic rules:\n");
2785 for (lac = ac, lav = av; lac != 0; lac--) {
2786 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2788 fo->last = strtoul(endptr+1, &endptr, 10);
2790 /* already warned */
2792 list_dyn_range(co, fo, &bp, dynbase, dynsz);
2802 * Retrieves current ipfw configuration of given type
2803 * and stores its pointer to @pcfg.
2805 * Caller is responsible for freeing @pcfg.
2807 * Returns 0 on success.
2811 ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
2812 ipfw_cfg_lheader **pcfg, size_t *psize)
2814 ipfw_cfg_lheader *cfg;
2819 if (co->test_only != 0) {
2820 fprintf(stderr, "Testing only, list disabled\n");
2824 /* Start with some data size */
2828 for (i = 0; i < 16; i++) {
2831 if ((cfg = calloc(1, sz)) == NULL)
2834 cfg->flags = fo->flags;
2835 cfg->start_rule = fo->first;
2836 cfg->end_rule = fo->last;
2838 if (do_get3(IP_FW_XGET, &cfg->opheader, &sz) != 0) {
2839 if (errno != ENOMEM) {
2844 /* Buffer size is not enough. Try to increase */
2861 lookup_host (char *host, struct in_addr *ipaddr)
2865 if (!inet_aton(host, ipaddr)) {
2866 if ((he = gethostbyname(host)) == NULL)
2868 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2882 ipfw_check_object_name(const char *name)
2887 * Check that name is null-terminated and contains
2888 * valid symbols only. Valid mask is:
2889 * [a-zA-Z0-9\-_\.]{1,63}
2892 if (l == 0 || l >= 64)
2894 for (i = 0; i < l; i++) {
2896 if (isalpha(c) || isdigit(c) || c == '_' ||
2897 c == '-' || c == '.')
2904 static char *default_state_name = "default";
2906 state_check_name(const char *name)
2909 if (ipfw_check_object_name(name) != 0)
2911 if (strcmp(name, "any") == 0)
2917 eaction_check_name(const char *name)
2920 if (ipfw_check_object_name(name) != 0)
2922 /* Restrict some 'special' names */
2923 if (match_token(rule_actions, name) != -1 &&
2924 match_token(rule_action_params, name) != -1)
2930 pack_object(struct tidx *tstate, char *name, int otype)
2933 ipfw_obj_ntlv *ntlv;
2935 for (i = 0; i < tstate->count; i++) {
2936 if (strcmp(tstate->idx[i].name, name) != 0)
2938 if (tstate->idx[i].set != tstate->set)
2940 if (tstate->idx[i].head.type != otype)
2943 return (tstate->idx[i].idx);
2946 if (tstate->count + 1 > tstate->size) {
2948 tstate->idx = realloc(tstate->idx, tstate->size *
2949 sizeof(ipfw_obj_ntlv));
2950 if (tstate->idx == NULL)
2954 ntlv = &tstate->idx[i];
2955 memset(ntlv, 0, sizeof(ipfw_obj_ntlv));
2956 strlcpy(ntlv->name, name, sizeof(ntlv->name));
2957 ntlv->head.type = otype;
2958 ntlv->head.length = sizeof(ipfw_obj_ntlv);
2959 ntlv->set = tstate->set;
2960 ntlv->idx = ++tstate->counter;
2967 pack_table(struct tidx *tstate, char *name)
2970 if (table_check_name(name) != 0)
2973 return (pack_object(tstate, name, IPFW_TLV_TBL_NAME));
2977 fill_table(struct _ipfw_insn *cmd, char *av, uint8_t opcode,
2978 struct tidx *tstate)
2980 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2984 if ((p = strchr(av + 6, ')')) == NULL)
2985 errx(EX_DATAERR, "forgotten parenthesis: '%s'", av);
2987 p = strchr(av + 6, ',');
2991 if ((uidx = pack_table(tstate, av + 6)) == 0)
2992 errx(EX_DATAERR, "Invalid table name: %s", av + 6);
2994 cmd->opcode = opcode;
2997 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
2998 d[0] = strtoul(p, NULL, 0);
3000 cmd->len |= F_INSN_SIZE(ipfw_insn);
3005 * fills the addr and mask fields in the instruction as appropriate from av.
3006 * Update length as appropriate.
3007 * The following formats are allowed:
3008 * me returns O_IP_*_ME
3009 * 1.2.3.4 single IP address
3010 * 1.2.3.4:5.6.7.8 address:mask
3011 * 1.2.3.4/24 address/mask
3012 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
3013 * We can have multiple comma-separated address/mask entries.
3016 fill_ip(ipfw_insn_ip *cmd, char *av, int cblen, struct tidx *tstate)
3019 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
3021 cmd->o.len &= ~F_LEN_MASK; /* zero len */
3023 if (_substrcmp(av, "any") == 0)
3026 if (_substrcmp(av, "me") == 0) {
3027 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
3031 if (strncmp(av, "table(", 6) == 0) {
3032 fill_table(&cmd->o, av, O_IP_DST_LOOKUP, tstate);
3038 * After the address we can have '/' or ':' indicating a mask,
3039 * ',' indicating another address follows, '{' indicating a
3040 * set of addresses of unspecified size.
3042 char *t = NULL, *p = strpbrk(av, "/:,{");
3046 CHECK_LENGTH(cblen, F_INSN_SIZE(ipfw_insn) + 2 + len);
3051 if ((t = strpbrk(p, ",{")) != NULL) {
3058 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
3059 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
3062 if (!inet_aton(p, (struct in_addr *)&d[1]))
3063 errx(EX_DATAERR, "bad netmask ``%s''", p);
3068 d[1] = htonl(0U); /* mask */
3069 else if (masklen > 32)
3070 errx(EX_DATAERR, "bad width ``%s''", p);
3072 d[1] = htonl(~0U << (32 - masklen));
3074 case '{': /* no mask, assume /24 and put back the '{' */
3075 d[1] = htonl(~0U << (32 - 24));
3079 case ',': /* single address plus continuation */
3082 case 0: /* initialization value */
3084 d[1] = htonl(~0U); /* force /32 */
3087 d[0] &= d[1]; /* mask base address with mask */
3090 /* find next separator */
3092 p = strpbrk(p, ",{");
3093 if (p && *p == '{') {
3095 * We have a set of addresses. They are stored as follows:
3096 * arg1 is the set size (powers of 2, 2..256)
3097 * addr is the base address IN HOST FORMAT
3098 * mask.. is an array of arg1 bits (rounded up to
3099 * the next multiple of 32) with bits set
3100 * for each host in the map.
3102 uint32_t *map = (uint32_t *)&cmd->mask;
3104 int i = contigmask((uint8_t *)&(d[1]), 32);
3107 errx(EX_DATAERR, "address set cannot be in a list");
3108 if (i < 24 || i > 31)
3109 errx(EX_DATAERR, "invalid set with mask %d\n", i);
3110 cmd->o.arg1 = 1<<(32-i); /* map length */
3111 d[0] = ntohl(d[0]); /* base addr in host format */
3112 cmd->o.opcode = O_IP_DST_SET; /* default */
3113 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
3114 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
3115 map[i] = 0; /* clear map */
3119 high = low + cmd->o.arg1 - 1;
3121 * Here, i stores the previous value when we specify a range
3122 * of addresses within a mask, e.g. 45-63. i = -1 means we
3123 * have no previous value.
3125 i = -1; /* previous value in a range */
3126 while (isdigit(*av)) {
3128 int a = strtol(av, &s, 0);
3130 if (s == av) { /* no parameter */
3132 errx(EX_DATAERR, "set not closed\n");
3134 errx(EX_DATAERR, "incomplete range %d-", i);
3137 if (a < low || a > high)
3138 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
3141 if (i == -1) /* no previous in range */
3143 else { /* check that range is valid */
3145 errx(EX_DATAERR, "invalid range %d-%d",
3148 errx(EX_DATAERR, "double '-' in range");
3151 map[i/32] |= 1<<(i & 31);
3162 if (av) /* then *av must be a ',' */
3165 /* Check this entry */
3166 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
3168 * 'any' turns the entire list into a NOP.
3169 * 'not any' never matches, so it is removed from the
3170 * list unless it is the only item, in which case we
3173 if (cmd->o.len & F_NOT) { /* "not any" never matches */
3174 if (av == NULL && len == 0) /* only this entry */
3175 errx(EX_DATAERR, "not any never matches");
3177 /* else do nothing and skip this entry */
3180 /* A single IP can be stored in an optimized format */
3181 if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
3182 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
3185 len += 2; /* two words... */
3188 if (len + 1 > F_LEN_MASK)
3189 errx(EX_DATAERR, "address list too long");
3190 cmd->o.len |= len+1;
3194 /* n2mask sets n bits of the mask */
3196 n2mask(struct in6_addr *mask, int n)
3198 static int minimask[9] =
3199 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
3202 memset(mask, 0, sizeof(struct in6_addr));
3203 p = (u_char *) mask;
3204 for (; n > 0; p++, n -= 8) {
3214 fill_flags_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3215 struct _s_x *flags, char *p)
3218 uint32_t set = 0, clear = 0;
3220 if (fill_flags(flags, p, &e, &set, &clear) != 0)
3221 errx(EX_DATAERR, "invalid flag %s", e);
3223 cmd->opcode = opcode;
3224 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
3225 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3230 ipfw_delete(char *av[])
3235 int exitval = EX_OK;
3239 NEED1("missing rule specification");
3240 if ( *av && _substrcmp(*av, "set") == 0) {
3241 /* Do not allow using the following syntax:
3242 * ipfw set N delete set M
3245 errx(EX_DATAERR, "invalid syntax");
3246 do_set = 1; /* delete set */
3251 while (*av && isdigit(**av)) {
3252 i = strtol(*av, &sep, 10);
3255 j = strtol(sep + 1, NULL, 10);
3258 exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
3260 exitval = EX_UNAVAILABLE;
3261 warn("rule %u not available", i);
3263 } else if (co.do_pipe) {
3264 exitval = ipfw_delete_pipe(co.do_pipe, i);
3266 memset(&rt, 0, sizeof(rt));
3269 rt.flags = IPFW_RCFLAG_SET;
3271 rt.start_rule = i & 0xffff;
3272 rt.end_rule = j & 0xffff;
3273 if (rt.start_rule == 0 && rt.end_rule == 0)
3274 rt.flags |= IPFW_RCFLAG_ALL;
3276 rt.flags |= IPFW_RCFLAG_RANGE;
3277 if (co.use_set != 0) {
3278 rt.set = co.use_set - 1;
3279 rt.flags |= IPFW_RCFLAG_SET;
3282 i = do_range_cmd(IP_FW_XDEL, &rt);
3284 exitval = EX_UNAVAILABLE;
3285 warn("rule %u: setsockopt(IP_FW_XDEL)",
3287 } else if (rt.new_set == 0 && do_set == 0) {
3288 exitval = EX_UNAVAILABLE;
3289 if (rt.start_rule != rt.end_rule)
3290 warnx("no rules rules in %u-%u range",
3291 rt.start_rule, rt.end_rule);
3293 warnx("rule %u not found",
3298 if (exitval != EX_OK)
3304 * fill the interface structure. We do not check the name as we can
3305 * create interfaces dynamically, so checking them at insert time
3306 * makes relatively little sense.
3307 * Interface names containing '*', '?', or '[' are assumed to be shell
3308 * patterns which match interfaces.
3311 fill_iface(ipfw_insn_if *cmd, char *arg, int cblen, struct tidx *tstate)
3316 cmd->name[0] = '\0';
3317 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3321 /* Parse the interface or address */
3322 if (strcmp(arg, "any") == 0)
3323 cmd->o.len = 0; /* effectively ignore this command */
3324 else if (strncmp(arg, "table(", 6) == 0) {
3325 if ((p = strchr(arg + 6, ')')) == NULL)
3326 errx(EX_DATAERR, "forgotten parenthesis: '%s'", arg);
3328 p = strchr(arg + 6, ',');
3331 if ((uidx = pack_table(tstate, arg + 6)) == 0)
3332 errx(EX_DATAERR, "Invalid table name: %s", arg + 6);
3334 cmd->name[0] = '\1'; /* Special value indicating table */
3336 } else if (!isdigit(*arg)) {
3337 strlcpy(cmd->name, arg, sizeof(cmd->name));
3338 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3339 } else if (!inet_aton(arg, &cmd->p.ip))
3340 errx(EX_DATAERR, "bad ip address ``%s''", arg);
3344 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
3348 char *ap, *ptr, *optr;
3349 struct ether_addr *mac;
3350 const char *macset = "0123456789abcdefABCDEF:";
3352 if (strcmp(p, "any") == 0) {
3353 for (i = 0; i < ETHER_ADDR_LEN; i++)
3354 addr[i] = mask[i] = 0;
3358 optr = ptr = strdup(p);
3359 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
3361 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
3362 errx(EX_DATAERR, "Incorrect MAC address");
3363 bcopy(mac, addr, ETHER_ADDR_LEN);
3365 errx(EX_DATAERR, "Incorrect MAC address");
3367 if (ptr != NULL) { /* we have mask? */
3368 if (p[ptr - optr - 1] == '/') { /* mask len */
3369 long ml = strtol(ptr, &ap, 10);
3370 if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
3371 errx(EX_DATAERR, "Incorrect mask length");
3372 for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
3373 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
3376 if (strspn(ptr, macset) != l ||
3377 (mac = ether_aton(ptr)) == NULL)
3378 errx(EX_DATAERR, "Incorrect mask");
3379 bcopy(mac, mask, ETHER_ADDR_LEN);
3381 } else { /* default mask: ff:ff:ff:ff:ff:ff */
3382 for (i = 0; i < ETHER_ADDR_LEN; i++)
3385 for (i = 0; i < ETHER_ADDR_LEN; i++)
3392 * helper function, updates the pointer to cmd with the length
3393 * of the current command, and also cleans up the first word of
3394 * the new command in case it has been clobbered before.
3397 next_cmd(ipfw_insn *cmd, int *len)
3400 CHECK_LENGTH(*len, 0);
3402 bzero(cmd, sizeof(*cmd));
3407 * Takes arguments and copies them into a comment
3410 fill_comment(ipfw_insn *cmd, char **av, int cblen)
3413 char *p = (char *)(cmd + 1);
3415 cmd->opcode = O_NOP;
3416 cmd->len = (cmd->len & (F_NOT | F_OR));
3418 /* Compute length of comment string. */
3419 for (i = 0, l = 0; av[i] != NULL; i++)
3420 l += strlen(av[i]) + 1;
3425 "comment too long (max 80 chars)");
3427 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
3430 for (i = 0; av[i] != NULL; i++) {
3439 * A function to fill simple commands of size 1.
3440 * Existing flags are preserved.
3443 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3445 cmd->opcode = opcode;
3446 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3451 * Fetch and add the MAC address and type, with masks. This generates one or
3452 * two microinstructions, and returns the pointer to the last one.
3455 add_mac(ipfw_insn *cmd, char *av[], int cblen)
3459 if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
3460 errx(EX_DATAERR, "MAC dst src");
3462 cmd->opcode = O_MACADDR2;
3463 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3466 mac = (ipfw_insn_mac *)cmd;
3467 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
3468 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
3469 &(mac->mask[ETHER_ADDR_LEN])); /* src */
3474 add_mactype(ipfw_insn *cmd, char *av, int cblen)
3477 errx(EX_DATAERR, "missing MAC type");
3478 if (strcmp(av, "any") != 0) { /* we have a non-null type */
3479 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
3481 cmd->opcode = O_MAC_TYPE;
3488 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
3490 struct protoent *pe;
3494 proto = strtol(av, &ep, 10);
3495 if (*ep != '\0' || proto <= 0) {
3496 if ((pe = getprotobyname(av)) == NULL)
3498 proto = pe->p_proto;
3501 fill_cmd(cmd, O_PROTO, 0, proto);
3507 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
3509 u_char proto = IPPROTO_IP;
3511 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3512 ; /* do not set O_IP4 nor O_IP6 */
3513 else if (strcmp(av, "ip4") == 0)
3514 /* explicit "just IPv4" rule */
3515 fill_cmd(cmd, O_IP4, 0, 0);
3516 else if (strcmp(av, "ip6") == 0) {
3517 /* explicit "just IPv6" rule */
3518 proto = IPPROTO_IPV6;
3519 fill_cmd(cmd, O_IP6, 0, 0);
3521 return add_proto0(cmd, av, protop);
3528 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
3530 u_char proto = IPPROTO_IP;
3532 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3533 ; /* do not set O_IP4 nor O_IP6 */
3534 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3535 /* explicit "just IPv4" rule */
3536 fill_cmd(cmd, O_IP4, 0, 0);
3537 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3538 /* explicit "just IPv6" rule */
3539 proto = IPPROTO_IPV6;
3540 fill_cmd(cmd, O_IP6, 0, 0);
3542 return add_proto0(cmd, av, protop);
3549 add_srcip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3551 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3552 if (cmd->opcode == O_IP_DST_SET) /* set */
3553 cmd->opcode = O_IP_SRC_SET;
3554 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3555 cmd->opcode = O_IP_SRC_LOOKUP;
3556 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3557 cmd->opcode = O_IP_SRC_ME;
3558 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3559 cmd->opcode = O_IP_SRC;
3560 else /* addr/mask */
3561 cmd->opcode = O_IP_SRC_MASK;
3566 add_dstip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3568 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3569 if (cmd->opcode == O_IP_DST_SET) /* set */
3571 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3573 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3574 cmd->opcode = O_IP_DST_ME;
3575 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3576 cmd->opcode = O_IP_DST;
3577 else /* addr/mask */
3578 cmd->opcode = O_IP_DST_MASK;
3582 static struct _s_x f_reserved_keywords[] = {
3585 { "diverted", TOK_OR },
3586 { "dst-port", TOK_OR },
3587 { "src-port", TOK_OR },
3588 { "established", TOK_OR },
3589 { "keep-state", TOK_OR },
3591 { "icmptypes", TOK_OR },
3599 { NULL, 0 } /* terminator */
3603 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
3606 if (match_token(f_reserved_keywords, av) != -1)
3609 if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
3610 /* XXX todo: check that we have a protocol with ports */
3611 cmd->opcode = opcode;
3618 add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3621 char *host, *ch, buf[INET6_ADDRSTRLEN];
3622 ipfw_insn *ret = NULL;
3625 /* Copy first address in set if needed */
3626 if ((ch = strpbrk(av, "/,")) != NULL) {
3628 strlcpy(buf, av, sizeof(buf));
3629 if (len < sizeof(buf))
3635 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3636 inet_pton(AF_INET6, host, &a) == 1)
3637 ret = add_srcip6(cmd, av, cblen, tstate);
3638 /* XXX: should check for IPv4, not !IPv6 */
3639 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3640 inet_pton(AF_INET6, host, &a) != 1))
3641 ret = add_srcip(cmd, av, cblen, tstate);
3642 if (ret == NULL && strcmp(av, "any") != 0)
3649 add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3652 char *host, *ch, buf[INET6_ADDRSTRLEN];
3653 ipfw_insn *ret = NULL;
3656 /* Copy first address in set if needed */
3657 if ((ch = strpbrk(av, "/,")) != NULL) {
3659 strlcpy(buf, av, sizeof(buf));
3660 if (len < sizeof(buf))
3666 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3667 inet_pton(AF_INET6, host, &a) == 1)
3668 ret = add_dstip6(cmd, av, cblen, tstate);
3669 /* XXX: should check for IPv4, not !IPv6 */
3670 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3671 inet_pton(AF_INET6, host, &a) != 1))
3672 ret = add_dstip(cmd, av, cblen, tstate);
3673 if (ret == NULL && strcmp(av, "any") != 0)
3680 * Parse arguments and assemble the microinstructions which make up a rule.
3681 * Rules are added into the 'rulebuf' and then copied in the correct order
3682 * into the actual rule.
3684 * The syntax for a rule starts with the action, followed by
3685 * optional action parameters, and the various match patterns.
3686 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
3687 * (generated if the rule includes a keep-state option), then the
3688 * various match patterns, log/altq actions, and the actual action.
3692 compile_rule(char *av[], uint32_t *rbuf, int *rbufsize, struct tidx *tstate)
3695 * rules are added into the 'rulebuf' and then copied in
3696 * the correct order into the actual rule.
3697 * Some things that need to go out of order (prob, action etc.)
3700 static uint32_t actbuf[255], cmdbuf[255];
3701 int rblen, ablen, cblen;
3703 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
3704 ipfw_insn *first_cmd; /* first match pattern */
3706 struct ip_fw_rule *rule;
3709 * various flags used to record that we entered some fields.
3711 ipfw_insn *have_state = NULL; /* check-state or keep-state */
3712 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
3717 int open_par = 0; /* open parenthesis ( */
3719 /* proto is here because it is used to fetch ports */
3720 u_char proto = IPPROTO_IP; /* default protocol */
3722 double match_prob = 1; /* match probability, default is always match */
3724 bzero(actbuf, sizeof(actbuf)); /* actions go here */
3725 bzero(cmdbuf, sizeof(cmdbuf));
3726 bzero(rbuf, *rbufsize);
3728 rule = (struct ip_fw_rule *)rbuf;
3729 cmd = (ipfw_insn *)cmdbuf;
3730 action = (ipfw_insn *)actbuf;
3732 rblen = *rbufsize / sizeof(uint32_t);
3733 rblen -= sizeof(struct ip_fw_rule) / sizeof(uint32_t);
3734 ablen = sizeof(actbuf) / sizeof(actbuf[0]);
3735 cblen = sizeof(cmdbuf) / sizeof(cmdbuf[0]);
3736 cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
3738 #define CHECK_RBUFLEN(len) { CHECK_LENGTH(rblen, len); rblen -= len; }
3739 #define CHECK_ACTLEN CHECK_LENGTH(ablen, action->len)
3743 /* [rule N] -- Rule number optional */
3744 if (av[0] && isdigit(**av)) {
3745 rule->rulenum = atoi(*av);
3749 /* [set N] -- set number (0..RESVD_SET), optional */
3750 if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
3751 int set = strtoul(av[1], NULL, 10);
3752 if (set < 0 || set > RESVD_SET)
3753 errx(EX_DATAERR, "illegal set %s", av[1]);
3759 /* [prob D] -- match probability, optional */
3760 if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
3761 match_prob = strtod(av[1], NULL);
3763 if (match_prob <= 0 || match_prob > 1)
3764 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
3768 /* action -- mandatory */
3769 NEED1("missing action");
3770 i = match_token(rule_actions, *av);
3772 action->len = 1; /* default */
3775 case TOK_CHECKSTATE:
3776 have_state = action;
3777 action->opcode = O_CHECK_STATE;
3779 match_token(rule_options, *av) == TOK_COMMENT) {
3780 action->arg1 = pack_object(tstate,
3781 default_state_name, IPFW_TLV_STATE_NAME);
3784 if (*av[0] == ':') {
3785 if (strcmp(*av + 1, "any") == 0)
3787 else if (state_check_name(*av + 1) == 0)
3788 action->arg1 = pack_object(tstate, *av + 1,
3789 IPFW_TLV_STATE_NAME);
3791 errx(EX_DATAERR, "Invalid state name %s",
3796 errx(EX_DATAERR, "Invalid state name %s", *av);
3800 action->opcode = O_REJECT;
3801 action->arg1 = ICMP_REJECT_ABORT;
3805 action->opcode = O_UNREACH6;
3806 action->arg1 = ICMP6_UNREACH_ABORT;
3810 action->opcode = O_ACCEPT;
3814 action->opcode = O_DENY;
3819 action->opcode = O_REJECT;
3820 action->arg1 = ICMP_UNREACH_HOST;
3824 action->opcode = O_REJECT;
3825 action->arg1 = ICMP_REJECT_RST;
3829 action->opcode = O_UNREACH6;
3830 action->arg1 = ICMP6_UNREACH_RST;
3834 action->opcode = O_REJECT;
3835 NEED1("missing reject code");
3836 fill_reject_code(&action->arg1, *av);
3841 action->opcode = O_UNREACH6;
3842 NEED1("missing unreach code");
3843 fill_unreach6_code(&action->arg1, *av);
3848 action->opcode = O_COUNT;
3852 action->opcode = O_NAT;
3853 action->len = F_INSN_SIZE(ipfw_insn_nat);
3855 if (*av != NULL && _substrcmp(*av, "global") == 0) {
3856 action->arg1 = IP_FW_NAT44_GLOBAL;
3862 action->opcode = O_QUEUE;
3865 action->opcode = O_PIPE;
3868 action->opcode = O_SKIPTO;
3871 action->opcode = O_NETGRAPH;
3874 action->opcode = O_NGTEE;
3877 action->opcode = O_DIVERT;
3880 action->opcode = O_TEE;
3883 action->opcode = O_CALLRETURN;
3886 errx(EX_USAGE, "missing argument for %s", *(av - 1));
3887 if (isdigit(**av)) {
3888 action->arg1 = strtoul(*av, NULL, 10);
3889 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
3890 errx(EX_DATAERR, "illegal argument for %s",
3892 } else if (_substrcmp(*av, "tablearg") == 0) {
3893 action->arg1 = IP_FW_TARG;
3894 } else if (i == TOK_DIVERT || i == TOK_TEE) {
3897 s = getservbyname(av[0], "divert");
3899 action->arg1 = ntohs(s->s_port);
3901 errx(EX_DATAERR, "illegal divert/tee port");
3903 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
3909 * Locate the address-port separator (':' or ',').
3910 * Could be one of the following:
3914 * IPv6 w:x:y::z,port
3915 * The ':' can only be used with hostname and IPv4 address.
3916 * XXX-BZ Should we also support [w:x:y::z]:port?
3918 struct sockaddr_storage result;
3919 struct addrinfo *res;
3922 u_short port_number;
3924 NEED1("missing forward address[:port]");
3927 * locate the address-port separator (':' or ',')
3929 s = strchr(*av, ',');
3931 /* Distinguish between IPv4:port and IPv6 cases. */
3932 s = strchr(*av, ':');
3933 if (s && strchr(s+1, ':'))
3934 s = NULL; /* no port */
3939 /* Terminate host portion and set s to start of port. */
3941 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
3944 "illegal forwarding port ``%s''", s);
3945 port_number = (u_short)i;
3948 if (_substrcmp(*av, "tablearg") == 0) {
3950 ((struct sockaddr_in*)&result)->sin_addr.s_addr =
3954 * Resolve the host name or address to a family and a
3955 * network representation of the address.
3957 if (getaddrinfo(*av, NULL, NULL, &res))
3958 errx(EX_DATAERR, NULL);
3959 /* Just use the first host in the answer. */
3960 family = res->ai_family;
3961 memcpy(&result, res->ai_addr, res->ai_addrlen);
3965 if (family == PF_INET) {
3966 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
3968 action->opcode = O_FORWARD_IP;
3969 action->len = F_INSN_SIZE(ipfw_insn_sa);
3973 * In the kernel we assume AF_INET and use only
3974 * sin_port and sin_addr. Remember to set sin_len as
3975 * the routing code seems to use it too.
3977 p->sa.sin_len = sizeof(struct sockaddr_in);
3978 p->sa.sin_family = AF_INET;
3979 p->sa.sin_port = port_number;
3980 p->sa.sin_addr.s_addr =
3981 ((struct sockaddr_in *)&result)->sin_addr.s_addr;
3982 } else if (family == PF_INET6) {
3983 ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
3985 action->opcode = O_FORWARD_IP6;
3986 action->len = F_INSN_SIZE(ipfw_insn_sa6);
3989 p->sa.sin6_len = sizeof(struct sockaddr_in6);
3990 p->sa.sin6_family = AF_INET6;
3991 p->sa.sin6_port = port_number;
3992 p->sa.sin6_flowinfo = 0;
3993 p->sa.sin6_scope_id =
3994 ((struct sockaddr_in6 *)&result)->sin6_scope_id;
3995 bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
3996 &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
3998 errx(EX_DATAERR, "Invalid address family in forward action");
4004 /* pretend it is a 'count' rule followed by the comment */
4005 action->opcode = O_COUNT;
4006 av--; /* go back... */
4012 size_t intsize = sizeof(int);
4014 action->opcode = O_SETFIB;
4015 NEED1("missing fib number");
4016 if (_substrcmp(*av, "tablearg") == 0) {
4017 action->arg1 = IP_FW_TARG;
4019 action->arg1 = strtoul(*av, NULL, 10);
4020 if (sysctlbyname("net.fibs", &numfibs, &intsize,
4022 errx(EX_DATAERR, "fibs not suported.\n");
4023 if (action->arg1 >= numfibs) /* Temporary */
4024 errx(EX_DATAERR, "fib too large.\n");
4025 /* Add high-order bit to fib to make room for tablearg*/
4026 action->arg1 |= 0x8000;
4036 action->opcode = O_SETDSCP;
4037 NEED1("missing DSCP code");
4038 if (_substrcmp(*av, "tablearg") == 0) {
4039 action->arg1 = IP_FW_TARG;
4041 if (isalpha(*av[0])) {
4042 if ((code = match_token(f_ipdscp, *av)) == -1)
4043 errx(EX_DATAERR, "Unknown DSCP code");
4044 action->arg1 = code;
4046 action->arg1 = strtoul(*av, NULL, 10);
4048 * Add high-order bit to DSCP to make room
4051 action->arg1 |= 0x8000;
4058 action->opcode = O_REASS;
4062 fill_cmd(action, O_CALLRETURN, F_NOT, 0);
4065 case TOK_TCPSETMSS: {
4069 idx = pack_object(tstate, "tcp-setmss", IPFW_TLV_EACTION);
4071 errx(EX_DATAERR, "pack_object failed");
4072 fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4073 NEED1("Missing MSS value");
4074 action = next_cmd(action, &ablen);
4077 mss = strtoul(*av, NULL, 10);
4078 if (mss == 0 || mss > UINT16_MAX)
4079 errx(EX_USAGE, "invalid MSS value %s", *av);
4080 fill_cmd(action, O_EXTERNAL_DATA, 0, (uint16_t)mss);
4087 if (match_token(rule_eactions, *av) == -1)
4088 errx(EX_DATAERR, "invalid action %s\n", *av);
4090 * External actions support.
4091 * XXX: we support only syntax with instance name.
4092 * For known external actions (from rule_eactions list)
4093 * we can handle syntax directly. But with `eaction'
4094 * keyword we can use only `eaction <name> <instance>'
4100 NEED1("Missing eaction name");
4101 if (eaction_check_name(*av) != 0)
4102 errx(EX_DATAERR, "Invalid eaction name %s", *av);
4103 idx = pack_object(tstate, *av, IPFW_TLV_EACTION);
4105 errx(EX_DATAERR, "pack_object failed");
4106 fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4108 NEED1("Missing eaction instance name");
4109 action = next_cmd(action, &ablen);
4112 if (eaction_check_name(*av) != 0)
4113 errx(EX_DATAERR, "Invalid eaction instance name %s",
4116 * External action instance object has TLV type depended
4117 * from the external action name object index. Since we
4118 * currently don't know this index, use zero as TLV type.
4120 idx = pack_object(tstate, *av, 0);
4122 errx(EX_DATAERR, "pack_object failed");
4123 fill_cmd(action, O_EXTERNAL_INSTANCE, 0, idx);
4127 action = next_cmd(action, &ablen);
4130 * [altq queuename] -- altq tag, optional
4131 * [log [logamount N]] -- log, optional
4133 * If they exist, it go first in the cmdbuf, but then it is
4134 * skipped in the copy section to the end of the buffer.
4136 while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
4141 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
4146 "log cannot be specified more than once");
4147 have_log = (ipfw_insn *)c;
4148 cmd->len = F_INSN_SIZE(ipfw_insn_log);
4150 cmd->opcode = O_LOG;
4151 if (av[0] && _substrcmp(*av, "logamount") == 0) {
4153 NEED1("logamount requires argument");
4157 "logamount must be positive");
4161 len = sizeof(c->max_log);
4162 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
4163 &c->max_log, &len, NULL, 0) == -1) {
4168 errx(1, "sysctlbyname(\"%s\")",
4169 "net.inet.ip.fw.verbose_limit");
4178 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
4180 NEED1("missing altq queue name");
4183 "altq cannot be specified more than once");
4184 have_altq = (ipfw_insn *)a;
4185 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
4187 cmd->opcode = O_ALTQ;
4188 a->qid = altq_name_to_qid(*av);
4199 errx(EX_USAGE, "tag and untag cannot be "
4200 "specified more than once");
4201 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
4202 rule_action_params);
4204 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
4212 cmd = next_cmd(cmd, &cblen);
4215 if (have_state) { /* must be a check-state, we are done */
4217 match_token(rule_options, *av) == TOK_COMMENT) {
4218 /* check-state has a comment */
4220 fill_comment(cmd, av, cblen);
4221 cmd = next_cmd(cmd, &cblen);
4227 #define OR_START(target) \
4228 if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
4230 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
4233 if ( (av[0])[1] == '\0') { \
4244 strcmp(*av, ")") == 0 || \
4245 strcmp(*av, "}") == 0)) { \
4250 errx(EX_USAGE, "missing \")\"\n"); \
4254 if (av[0] && _substrcmp(*av, "not") == 0) { \
4255 if (cmd->len & F_NOT) \
4256 errx(EX_USAGE, "double \"not\" not allowed\n"); \
4257 cmd->len |= F_NOT; \
4261 #define OR_BLOCK(target) \
4262 if (av[0] && _substrcmp(*av, "or") == 0) { \
4263 if (prev == NULL || open_par == 0) \
4264 errx(EX_DATAERR, "invalid OR block"); \
4265 prev->len |= F_OR; \
4275 * MAC addresses, optional.
4276 * If we have this, we skip the part "proto from src to dst"
4277 * and jump straight to the option parsing.
4280 NEED1("missing protocol");
4281 if (_substrcmp(*av, "MAC") == 0 ||
4282 _substrcmp(*av, "mac") == 0) {
4283 av++; /* the "MAC" keyword */
4284 add_mac(cmd, av); /* exits in case of errors */
4285 cmd = next_cmd(cmd);
4286 av += 2; /* dst-mac and src-mac */
4288 NEED1("missing mac type");
4289 if (add_mactype(cmd, av[0]))
4290 cmd = next_cmd(cmd);
4291 av++; /* any or mac-type */
4297 * protocol, mandatory
4299 OR_START(get_proto);
4301 NEED1("missing protocol");
4302 if (add_proto_compat(cmd, *av, &proto)) {
4304 if (F_LEN(cmd) != 0) {
4306 cmd = next_cmd(cmd, &cblen);
4308 } else if (first_cmd != cmd) {
4309 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
4312 OR_BLOCK(get_proto);
4317 if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
4318 errx(EX_USAGE, "missing ``from''");
4322 * source IP, mandatory
4324 OR_START(source_ip);
4325 NOT_BLOCK; /* optional "not" */
4326 NEED1("missing source address");
4327 if (add_src(cmd, *av, proto, cblen, tstate)) {
4329 if (F_LEN(cmd) != 0) { /* ! any */
4331 cmd = next_cmd(cmd, &cblen);
4334 errx(EX_USAGE, "bad source address %s", *av);
4335 OR_BLOCK(source_ip);
4338 * source ports, optional
4340 NOT_BLOCK; /* optional "not" */
4341 if ( av[0] != NULL ) {
4342 if (_substrcmp(*av, "any") == 0 ||
4343 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4345 if (F_LEN(cmd) != 0)
4346 cmd = next_cmd(cmd, &cblen);
4353 if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
4354 errx(EX_USAGE, "missing ``to''");
4358 * destination, mandatory
4361 NOT_BLOCK; /* optional "not" */
4362 NEED1("missing dst address");
4363 if (add_dst(cmd, *av, proto, cblen, tstate)) {
4365 if (F_LEN(cmd) != 0) { /* ! any */
4367 cmd = next_cmd(cmd, &cblen);
4370 errx( EX_USAGE, "bad destination address %s", *av);
4374 * dest. ports, optional
4376 NOT_BLOCK; /* optional "not" */
4378 if (_substrcmp(*av, "any") == 0 ||
4379 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4381 if (F_LEN(cmd) != 0)
4382 cmd = next_cmd(cmd, &cblen);
4388 while ( av[0] != NULL ) {
4390 ipfw_insn_u32 *cmd32; /* alias for cmd */
4393 cmd32 = (ipfw_insn_u32 *)cmd;
4395 if (*s == '!') { /* alternate syntax for NOT */
4396 if (cmd->len & F_NOT)
4397 errx(EX_USAGE, "double \"not\" not allowed\n");
4401 i = match_token(rule_options, s);
4405 if (cmd->len & F_NOT)
4406 errx(EX_USAGE, "double \"not\" not allowed\n");
4411 if (open_par == 0 || prev == NULL)
4412 errx(EX_USAGE, "invalid \"or\" block\n");
4416 case TOK_STARTBRACE:
4418 errx(EX_USAGE, "+nested \"(\" not allowed\n");
4424 errx(EX_USAGE, "+missing \")\"\n");
4430 fill_cmd(cmd, O_IN, 0, 0);
4434 cmd->len ^= F_NOT; /* toggle F_NOT */
4435 fill_cmd(cmd, O_IN, 0, 0);
4439 fill_cmd(cmd, O_DIVERTED, 0, 3);
4442 case TOK_DIVERTEDLOOPBACK:
4443 fill_cmd(cmd, O_DIVERTED, 0, 1);
4446 case TOK_DIVERTEDOUTPUT:
4447 fill_cmd(cmd, O_DIVERTED, 0, 2);
4451 fill_cmd(cmd, O_FRAG, 0, 0);
4455 fill_cmd(cmd, O_LAYER2, 0, 0);
4461 NEED1("recv, xmit, via require interface name"
4463 fill_iface((ipfw_insn_if *)cmd, av[0], cblen, tstate);
4465 if (F_LEN(cmd) == 0) /* not a valid address */
4468 cmd->opcode = O_XMIT;
4469 else if (i == TOK_RECV)
4470 cmd->opcode = O_RECV;
4471 else if (i == TOK_VIA)
4472 cmd->opcode = O_VIA;
4476 NEED1("icmptypes requires list of types");
4477 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
4481 case TOK_ICMP6TYPES:
4482 NEED1("icmptypes requires list of types");
4483 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
4488 NEED1("ipttl requires TTL");
4489 if (strpbrk(*av, "-,")) {
4490 if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
4491 errx(EX_DATAERR, "invalid ipttl %s", *av);
4493 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
4498 NEED1("ipid requires id");
4499 if (strpbrk(*av, "-,")) {
4500 if (!add_ports(cmd, *av, 0, O_IPID, cblen))
4501 errx(EX_DATAERR, "invalid ipid %s", *av);
4503 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
4508 NEED1("iplen requires length");
4509 if (strpbrk(*av, "-,")) {
4510 if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
4511 errx(EX_DATAERR, "invalid ip len %s", *av);
4513 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
4518 NEED1("ipver requires version");
4519 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
4523 case TOK_IPPRECEDENCE:
4524 NEED1("ipprecedence requires value");
4525 fill_cmd(cmd, O_IPPRECEDENCE, 0,
4526 (strtoul(*av, NULL, 0) & 7) << 5);
4531 NEED1("missing DSCP code");
4532 fill_dscp(cmd, *av, cblen);
4537 NEED1("missing argument for ipoptions");
4538 fill_flags_cmd(cmd, O_IPOPT, f_ipopts, *av);
4543 NEED1("missing argument for iptos");
4544 fill_flags_cmd(cmd, O_IPTOS, f_iptos, *av);
4549 NEED1("uid requires argument");
4555 cmd->opcode = O_UID;
4556 uid = strtoul(*av, &end, 0);
4557 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
4559 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
4560 cmd32->d[0] = pwd->pw_uid;
4561 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4567 NEED1("gid requires argument");
4573 cmd->opcode = O_GID;
4574 gid = strtoul(*av, &end, 0);
4575 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
4577 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
4578 cmd32->d[0] = grp->gr_gid;
4579 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4585 NEED1("jail requires argument");
4590 cmd->opcode = O_JAIL;
4591 jid = (int)strtol(*av, &end, 0);
4592 if (jid < 0 || *end != '\0')
4593 errx(EX_DATAERR, "jail requires prison ID");
4594 cmd32->d[0] = (uint32_t)jid;
4595 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4601 fill_cmd(cmd, O_ESTAB, 0, 0);
4605 fill_cmd(cmd, O_TCPFLAGS, 0,
4606 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
4609 case TOK_TCPDATALEN:
4610 NEED1("tcpdatalen requires length");
4611 if (strpbrk(*av, "-,")) {
4612 if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
4613 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
4615 fill_cmd(cmd, O_TCPDATALEN, 0,
4616 strtoul(*av, NULL, 0));
4621 NEED1("missing argument for tcpoptions");
4622 fill_flags_cmd(cmd, O_TCPOPTS, f_tcpopts, *av);
4628 NEED1("tcpseq/tcpack requires argument");
4629 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
4630 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
4631 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
4636 NEED1("tcpwin requires length");
4637 if (strpbrk(*av, "-,")) {
4638 if (!add_ports(cmd, *av, 0, O_TCPWIN, cblen))
4639 errx(EX_DATAERR, "invalid tcpwin len %s", *av);
4641 fill_cmd(cmd, O_TCPWIN, 0,
4642 strtoul(*av, NULL, 0));
4647 NEED1("missing argument for tcpflags");
4648 cmd->opcode = O_TCPFLAGS;
4649 fill_flags_cmd(cmd, O_TCPFLAGS, f_tcpflags, *av);
4653 case TOK_KEEPSTATE: {
4657 errx(EX_USAGE, "keep-state cannot be part "
4660 errx(EX_USAGE, "only one of keep-state "
4661 "and limit is allowed");
4662 if (*av != NULL && *av[0] == ':') {
4663 if (state_check_name(*av + 1) != 0)
4665 "Invalid state name %s", *av);
4666 uidx = pack_object(tstate, *av + 1,
4667 IPFW_TLV_STATE_NAME);
4670 uidx = pack_object(tstate, default_state_name,
4671 IPFW_TLV_STATE_NAME);
4673 fill_cmd(cmd, O_KEEP_STATE, 0, uidx);
4678 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
4683 "limit cannot be part of an or block");
4685 errx(EX_USAGE, "only one of keep-state and "
4686 "limit is allowed");
4689 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
4691 cmd->opcode = O_LIMIT;
4692 c->limit_mask = c->conn_limit = 0;
4694 while ( av[0] != NULL ) {
4695 if ((val = match_token(limit_masks, *av)) <= 0)
4697 c->limit_mask |= val;
4701 if (c->limit_mask == 0)
4702 errx(EX_USAGE, "limit: missing limit mask");
4704 GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
4705 TOK_LIMIT, rule_options);
4708 if (*av != NULL && *av[0] == ':') {
4709 if (state_check_name(*av + 1) != 0)
4711 "Invalid state name %s", *av);
4712 cmd->arg1 = pack_object(tstate, *av + 1,
4713 IPFW_TLV_STATE_NAME);
4716 cmd->arg1 = pack_object(tstate,
4717 default_state_name, IPFW_TLV_STATE_NAME);
4722 NEED1("missing protocol");
4723 if (add_proto(cmd, *av, &proto)) {
4726 errx(EX_DATAERR, "invalid protocol ``%s''",
4731 NEED1("missing source IP");
4732 if (add_srcip(cmd, *av, cblen, tstate)) {
4738 NEED1("missing destination IP");
4739 if (add_dstip(cmd, *av, cblen, tstate)) {
4745 NEED1("missing source IP6");
4746 if (add_srcip6(cmd, *av, cblen, tstate)) {
4752 NEED1("missing destination IP6");
4753 if (add_dstip6(cmd, *av, cblen, tstate)) {
4759 NEED1("missing source port");
4760 if (_substrcmp(*av, "any") == 0 ||
4761 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4764 errx(EX_DATAERR, "invalid source port %s", *av);
4768 NEED1("missing destination port");
4769 if (_substrcmp(*av, "any") == 0 ||
4770 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4773 errx(EX_DATAERR, "invalid destination port %s",
4778 if (add_mac(cmd, av, cblen))
4783 NEED1("missing mac type");
4784 if (!add_mactype(cmd, *av, cblen))
4785 errx(EX_DATAERR, "invalid mac type %s", *av);
4789 case TOK_VERREVPATH:
4790 fill_cmd(cmd, O_VERREVPATH, 0, 0);
4793 case TOK_VERSRCREACH:
4794 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
4798 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
4802 fill_cmd(cmd, O_IPSEC, 0, 0);
4806 fill_cmd(cmd, O_IP6, 0, 0);
4810 fill_cmd(cmd, O_IP4, 0, 0);
4814 fill_ext6hdr( cmd, *av );
4819 if (proto != IPPROTO_IPV6 )
4820 errx( EX_USAGE, "flow-id filter is active "
4821 "only for ipv6 protocol\n");
4822 fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
4827 fill_comment(cmd, av, cblen);
4832 if (av[0] && strpbrk(*av, "-,")) {
4833 if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
4834 errx(EX_DATAERR, "tagged: invalid tag"
4840 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
4841 TOK_TAGGED, rule_options);
4842 fill_cmd(cmd, O_TAGGED, 0, tag);
4848 NEED1("fib requires fib number");
4849 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
4853 fill_cmd(cmd, O_SOCKARG, 0, 0);
4857 ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
4860 if (!av[0] || !av[1])
4861 errx(EX_USAGE, "format: lookup argument tablenum");
4862 cmd->opcode = O_IP_DST_LOOKUP;
4863 cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
4864 i = match_token(rule_options, *av);
4865 for (j = 0; lookup_key[j] >= 0 ; j++) {
4866 if (i == lookup_key[j])
4869 if (lookup_key[j] <= 0)
4870 errx(EX_USAGE, "format: cannot lookup on %s", *av);
4871 __PAST_END(c->d, 1) = j; // i converted to option
4874 if ((j = pack_table(tstate, *av)) == 0)
4875 errx(EX_DATAERR, "Invalid table name: %s", *av);
4882 NEED1("missing table name");
4883 if (strncmp(*av, "table(", 6) != 0)
4885 "enclose table name into \"table()\"");
4886 fill_table(cmd, *av, O_IP_FLOW_LOOKUP, tstate);
4891 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
4893 if (F_LEN(cmd) > 0) { /* prepare to advance */
4895 cmd = next_cmd(cmd, &cblen);
4901 * Now copy stuff into the rule.
4902 * If we have a keep-state option, the first instruction
4903 * must be a PROBE_STATE (which is generated here).
4904 * If we have a LOG option, it was stored as the first command,
4905 * and now must be moved to the top of the action part.
4907 dst = (ipfw_insn *)rule->cmd;
4910 * First thing to write into the command stream is the match probability.
4912 if (match_prob != 1) { /* 1 means always match */
4913 dst->opcode = O_PROB;
4915 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
4920 * generate O_PROBE_STATE if necessary
4922 if (have_state && have_state->opcode != O_CHECK_STATE) {
4923 fill_cmd(dst, O_PROBE_STATE, 0, have_state->arg1);
4924 dst = next_cmd(dst, &rblen);
4927 /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
4928 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
4932 switch (src->opcode) {
4940 bcopy(src, dst, i * sizeof(uint32_t));
4946 * put back the have_state command as last opcode
4948 if (have_state && have_state->opcode != O_CHECK_STATE) {
4949 i = F_LEN(have_state);
4951 bcopy(have_state, dst, i * sizeof(uint32_t));
4955 * start action section
4957 rule->act_ofs = dst - rule->cmd;
4959 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
4961 i = F_LEN(have_log);
4963 bcopy(have_log, dst, i * sizeof(uint32_t));
4967 i = F_LEN(have_altq);
4969 bcopy(have_altq, dst, i * sizeof(uint32_t));
4973 i = F_LEN(have_tag);
4975 bcopy(have_tag, dst, i * sizeof(uint32_t));
4980 * copy all other actions
4982 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
4985 bcopy(src, dst, i * sizeof(uint32_t));
4989 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
4990 *rbufsize = (char *)dst - (char *)rule;
4994 compare_ntlv(const void *_a, const void *_b)
4996 ipfw_obj_ntlv *a, *b;
4998 a = (ipfw_obj_ntlv *)_a;
4999 b = (ipfw_obj_ntlv *)_b;
5001 if (a->set < b->set)
5003 else if (a->set > b->set)
5006 if (a->idx < b->idx)
5008 else if (a->idx > b->idx)
5011 if (a->head.type < b->head.type)
5013 else if (a->head.type > b->head.type)
5020 * Provide kernel with sorted list of referenced objects
5023 object_sort_ctlv(ipfw_obj_ctlv *ctlv)
5026 qsort(ctlv + 1, ctlv->count, ctlv->objsize, compare_ntlv);
5034 compare_object_kntlv(const void *k, const void *v)
5036 ipfw_obj_ntlv *ntlv;
5037 struct object_kt key;
5039 key = *((struct object_kt *)k);
5040 ntlv = (ipfw_obj_ntlv *)v;
5042 if (key.uidx < ntlv->idx)
5044 else if (key.uidx > ntlv->idx)
5047 if (key.type < ntlv->head.type)
5049 else if (key.type > ntlv->head.type)
5056 * Finds object name in @ctlv by @idx and @type.
5057 * Uses the following facts:
5058 * 1) All TLVs are the same size
5059 * 2) Kernel implementation provides already sorted list.
5061 * Returns table name or NULL.
5064 object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx, uint16_t type)
5066 ipfw_obj_ntlv *ntlv;
5067 struct object_kt key;
5072 ntlv = bsearch(&key, (ctlv + 1), ctlv->count, ctlv->objsize,
5073 compare_object_kntlv);
5076 return (ntlv->name);
5082 table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx)
5085 return (object_search_ctlv(ctlv, idx, IPFW_TLV_TBL_NAME));
5089 * Adds one or more rules to ipfw chain.
5094 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
5095 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ] (*2) (*3)
5100 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
5101 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ]
5104 * Rules in reply are modified to store their actual ruleset number.
5106 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
5107 * according to their idx field and there has to be no duplicates.
5108 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
5109 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
5112 ipfw_add(char *av[])
5114 uint32_t rulebuf[1024];
5115 int rbufsize, default_off, tlen, rlen;
5118 struct ip_fw_rule *rule;
5120 ip_fw3_opheader *op3;
5121 ipfw_obj_ctlv *ctlv, *tstate;
5123 rbufsize = sizeof(rulebuf);
5124 memset(rulebuf, 0, rbufsize);
5125 memset(&ts, 0, sizeof(ts));
5127 /* Optimize case with no tables */
5128 default_off = sizeof(ipfw_obj_ctlv) + sizeof(ip_fw3_opheader);
5129 op3 = (ip_fw3_opheader *)rulebuf;
5130 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5131 rule = (struct ip_fw_rule *)(ctlv + 1);
5132 rbufsize -= default_off;
5134 compile_rule(av, (uint32_t *)rule, &rbufsize, &ts);
5135 /* Align rule size to u64 boundary */
5136 rlen = roundup2(rbufsize, sizeof(uint64_t));
5141 if (ts.count != 0) {
5142 /* Some tables. We have to alloc more data */
5143 tlen = ts.count * sizeof(ipfw_obj_ntlv);
5144 sz = default_off + sizeof(ipfw_obj_ctlv) + tlen + rlen;
5146 if ((tbuf = calloc(1, sz)) == NULL)
5147 err(EX_UNAVAILABLE, "malloc() failed for IP_FW_ADD");
5148 op3 = (ip_fw3_opheader *)tbuf;
5150 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5151 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
5152 ctlv->head.length = sizeof(ipfw_obj_ctlv) + tlen;
5153 ctlv->count = ts.count;
5154 ctlv->objsize = sizeof(ipfw_obj_ntlv);
5155 memcpy(ctlv + 1, ts.idx, tlen);
5156 object_sort_ctlv(ctlv);
5159 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
5160 ctlv->head.type = IPFW_TLV_RULE_LIST;
5161 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5163 memcpy(ctlv + 1, rule, rbufsize);
5165 /* Simply add header */
5166 sz = rlen + default_off;
5167 memset(ctlv, 0, sizeof(*ctlv));
5168 ctlv->head.type = IPFW_TLV_RULE_LIST;
5169 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5173 if (do_get3(IP_FW_XADD, op3, &sz) != 0)
5174 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_XADD");
5177 struct format_opts sfo;
5179 memset(&sfo, 0, sizeof(sfo));
5180 sfo.tstate = tstate;
5181 sfo.set_mask = (uint32_t)(-1);
5182 bp_alloc(&bp, 4096);
5183 show_static_rule(&co, &sfo, &bp, rule, NULL);
5184 printf("%s", bp.buf);
5196 * clear the counters or the log counters.
5197 * optname has the following values:
5198 * 0 (zero both counters and logging)
5199 * 1 (zero logging only)
5202 ipfw_zero(int ac, char *av[], int optname)
5206 char const *name = optname ? "RESETLOG" : "ZERO";
5210 optname = optname ? IP_FW_XRESETLOG : IP_FW_XZERO;
5214 /* clear all entries */
5215 memset(&rt, 0, sizeof(rt));
5216 rt.flags = IPFW_RCFLAG_ALL;
5217 if (do_range_cmd(optname, &rt) < 0)
5218 err(EX_UNAVAILABLE, "setsockopt(IP_FW_X%s)", name);
5220 printf("%s.\n", optname == IP_FW_XZERO ?
5221 "Accounting cleared":"Logging counts reset");
5228 if (isdigit(**av)) {
5229 arg = strtonum(*av, 0, 0xffff, &errstr);
5232 "invalid rule number %s\n", *av);
5233 memset(&rt, 0, sizeof(rt));
5234 rt.start_rule = arg;
5236 rt.flags |= IPFW_RCFLAG_RANGE;
5237 if (co.use_set != 0) {
5238 rt.set = co.use_set - 1;
5239 rt.flags |= IPFW_RCFLAG_SET;
5241 if (do_range_cmd(optname, &rt) != 0) {
5242 warn("rule %u: setsockopt(IP_FW_X%s)",
5244 failed = EX_UNAVAILABLE;
5245 } else if (rt.new_set == 0) {
5246 printf("Entry %d not found\n", arg);
5247 failed = EX_UNAVAILABLE;
5248 } else if (!co.do_quiet)
5249 printf("Entry %d %s.\n", arg,
5250 optname == IP_FW_XZERO ?
5251 "cleared" : "logging count reset");
5253 errx(EX_USAGE, "invalid rule number ``%s''", *av);
5257 if (failed != EX_OK)
5262 ipfw_flush(int force)
5266 if (!force && !co.do_quiet) { /* need to ask user */
5269 printf("Are you sure? [yn] ");
5272 c = toupper(getc(stdin));
5273 while (c != '\n' && getc(stdin) != '\n')
5275 return; /* and do not flush */
5276 } while (c != 'Y' && c != 'N');
5278 if (c == 'N') /* user said no */
5285 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
5286 memset(&rt, 0, sizeof(rt));
5287 if (co.use_set != 0) {
5288 rt.set = co.use_set - 1;
5289 rt.flags = IPFW_RCFLAG_SET;
5291 rt.flags = IPFW_RCFLAG_ALL;
5292 if (do_range_cmd(IP_FW_XDEL, &rt) != 0)
5293 err(EX_UNAVAILABLE, "setsockopt(IP_FW_XDEL)");
5295 printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
5298 static struct _s_x intcmds[] = {
5299 { "talist", TOK_TALIST },
5300 { "iflist", TOK_IFLIST },
5301 { "olist", TOK_OLIST },
5302 { "vlist", TOK_VLIST },
5306 static struct _s_x otypes[] = {
5307 { "EACTION", IPFW_TLV_EACTION },
5308 { "DYNSTATE", IPFW_TLV_STATE_NAME },
5313 lookup_eaction_name(ipfw_obj_ntlv *ntlv, int cnt, uint16_t type)
5319 for (i = 0; i < cnt; i++) {
5320 if (ntlv[i].head.type != IPFW_TLV_EACTION)
5322 if (IPFW_TLV_EACTION_NAME(ntlv[i].idx) != type)
5324 name = ntlv[i].name;
5331 ipfw_list_objects(int ac, char *av[])
5333 ipfw_obj_lheader req, *olh;
5334 ipfw_obj_ntlv *ntlv;
5339 memset(&req, 0, sizeof(req));
5341 if (do_get3(IP_FW_DUMP_SRVOBJECTS, &req.opheader, &sz) != 0)
5342 if (errno != ENOMEM)
5346 if ((olh = calloc(1, sz)) == NULL)
5350 if (do_get3(IP_FW_DUMP_SRVOBJECTS, &olh->opheader, &sz) != 0) {
5356 printf("Objects list:\n");
5358 printf("There are no objects\n");
5359 ntlv = (ipfw_obj_ntlv *)(olh + 1);
5360 for (i = 0; i < olh->count; i++) {
5361 name = match_value(otypes, ntlv->head.type);
5363 name = lookup_eaction_name(
5364 (ipfw_obj_ntlv *)(olh + 1), olh->count,
5367 printf(" kidx: %4d\ttype: %10d\tname: %s\n",
5368 ntlv->idx, ntlv->head.type, ntlv->name);
5370 printf(" kidx: %4d\ttype: %10s\tname: %s\n",
5371 ntlv->idx, name, ntlv->name);
5378 ipfw_internal_handler(int ac, char *av[])
5383 NEED1("internal cmd required");
5385 if ((tcmd = match_token(intcmds, *av)) == -1)
5386 errx(EX_USAGE, "invalid internal sub-cmd: %s", *av);
5390 ipfw_list_tifaces();
5393 ipfw_list_ta(ac, av);
5396 ipfw_list_objects(ac, av);
5399 ipfw_list_values(ac, av);
5405 ipfw_get_tracked_ifaces(ipfw_obj_lheader **polh)
5407 ipfw_obj_lheader req, *olh;
5410 memset(&req, 0, sizeof(req));
5413 if (do_get3(IP_FW_XIFLIST, &req.opheader, &sz) != 0) {
5414 if (errno != ENOMEM)
5419 if ((olh = calloc(1, sz)) == NULL)
5423 if (do_get3(IP_FW_XIFLIST, &olh->opheader, &sz) != 0) {
5433 ifinfo_cmp(const void *a, const void *b)
5435 ipfw_iface_info *ia, *ib;
5437 ia = (ipfw_iface_info *)a;
5438 ib = (ipfw_iface_info *)b;
5440 return (stringnum_cmp(ia->ifname, ib->ifname));
5444 * Retrieves table list from kernel,
5445 * optionally sorts it and calls requested function for each table.
5446 * Returns 0 on success.
5451 ipfw_obj_lheader *olh;
5452 ipfw_iface_info *info;
5455 if ((error = ipfw_get_tracked_ifaces(&olh)) != 0)
5456 err(EX_OSERR, "Unable to request ipfw tracked interface list");
5459 qsort(olh + 1, olh->count, olh->objsize, ifinfo_cmp);
5461 info = (ipfw_iface_info *)(olh + 1);
5462 for (i = 0; i < olh->count; i++) {
5463 if (info->flags & IPFW_IFFLAG_RESOLVED)
5464 printf("%s ifindex: %d refcount: %u changes: %u\n",
5465 info->ifname, info->ifindex, info->refcnt,
5468 printf("%s ifindex: unresolved refcount: %u changes: %u\n",
5469 info->ifname, info->refcnt, info->gencnt);
5470 info = (ipfw_iface_info *)((caddr_t)info + olh->objsize);