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
20 * $FreeBSD: head/sbin/ipfw/ipfw2.c 187983 2009-02-01 16:00:49Z luigi $
23 #include <sys/types.h>
24 #include <sys/socket.h>
25 #include <sys/sockio.h>
26 #include <sys/sysctl.h>
40 #include <time.h> /* ctime */
41 #include <timeconv.h> /* _long_to_time */
45 #include <net/ethernet.h>
46 #include <net/if.h> /* only IFNAMSIZ */
47 #include <netinet/in.h>
48 #include <netinet/in_systm.h> /* only n_short, n_long */
49 #include <netinet/ip.h>
50 #include <netinet/ip_icmp.h>
51 #include <netinet/ip_fw.h>
52 #include <netinet/tcp.h>
53 #include <arpa/inet.h>
55 struct cmdline_opts co; /* global options */
57 int resvd_set_number = RESVD_SET;
59 #define GET_UINT_ARG(arg, min, max, tok, s_x) do { \
61 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
62 if (_substrcmp(*av, "tablearg") == 0) { \
63 arg = IP_FW_TABLEARG; \
71 val = strtol(*av, &end, 10); \
73 if (!isdigit(**av) || *end != '\0' || (val == 0 && errno == EINVAL)) \
74 errx(EX_DATAERR, "%s: invalid argument: %s", \
75 match_value(s_x, tok), *av); \
77 if (errno == ERANGE || val < min || val > max) \
78 errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
79 match_value(s_x, tok), min, max, *av); \
81 if (val == IP_FW_TABLEARG) \
82 errx(EX_DATAERR, "%s: illegal argument value: %s", \
83 match_value(s_x, tok), *av); \
89 PRINT_UINT_ARG(const char *str, uint32_t arg)
93 if (arg == IP_FW_TABLEARG)
99 static struct _s_x f_tcpflags[] = {
110 static struct _s_x f_tcpopts[] = {
111 { "mss", IP_FW_TCPOPT_MSS },
112 { "maxseg", IP_FW_TCPOPT_MSS },
113 { "window", IP_FW_TCPOPT_WINDOW },
114 { "sack", IP_FW_TCPOPT_SACK },
115 { "ts", IP_FW_TCPOPT_TS },
116 { "timestamp", IP_FW_TCPOPT_TS },
117 { "cc", IP_FW_TCPOPT_CC },
123 * IP options span the range 0 to 255 so we need to remap them
124 * (though in fact only the low 5 bits are significant).
126 static struct _s_x f_ipopts[] = {
127 { "ssrr", IP_FW_IPOPT_SSRR},
128 { "lsrr", IP_FW_IPOPT_LSRR},
129 { "rr", IP_FW_IPOPT_RR},
130 { "ts", IP_FW_IPOPT_TS},
135 static struct _s_x f_iptos[] = {
136 { "lowdelay", IPTOS_LOWDELAY},
137 { "throughput", IPTOS_THROUGHPUT},
138 { "reliability", IPTOS_RELIABILITY},
139 { "mincost", IPTOS_MINCOST},
140 { "congestion", IPTOS_ECN_CE},
141 { "ecntransport", IPTOS_ECN_ECT0},
142 { "ip tos option", 0},
146 static struct _s_x limit_masks[] = {
147 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
148 {"src-addr", DYN_SRC_ADDR},
149 {"src-port", DYN_SRC_PORT},
150 {"dst-addr", DYN_DST_ADDR},
151 {"dst-port", DYN_DST_PORT},
156 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
157 * This is only used in this code.
159 #define IPPROTO_ETHERTYPE 0x1000
160 static struct _s_x ether_types[] = {
162 * Note, we cannot use "-:&/" in the names because they are field
163 * separators in the type specifications. Also, we use s = NULL as
164 * end-delimiter, because a type of 0 can be legal.
177 { "pppoe_disc", 0x8863 },
178 { "pppoe_sess", 0x8864 },
179 { "ipx_8022", 0x00E0 },
180 { "ipx_8023", 0x0000 },
181 { "ipx_ii", 0x8137 },
182 { "ipx_snap", 0x8137 },
189 static struct _s_x rule_actions[] = {
190 { "accept", TOK_ACCEPT },
191 { "pass", TOK_ACCEPT },
192 { "allow", TOK_ACCEPT },
193 { "permit", TOK_ACCEPT },
194 { "count", TOK_COUNT },
195 { "pipe", TOK_PIPE },
196 { "queue", TOK_QUEUE },
197 { "divert", TOK_DIVERT },
199 { "netgraph", TOK_NETGRAPH },
200 { "ngtee", TOK_NGTEE },
201 { "fwd", TOK_FORWARD },
202 { "forward", TOK_FORWARD },
203 { "skipto", TOK_SKIPTO },
204 { "deny", TOK_DENY },
205 { "drop", TOK_DENY },
206 { "reject", TOK_REJECT },
207 { "reset6", TOK_RESET6 },
208 { "reset", TOK_RESET },
209 { "unreach6", TOK_UNREACH6 },
210 { "unreach", TOK_UNREACH },
211 { "check-state", TOK_CHECKSTATE },
212 { "//", TOK_COMMENT },
214 { "reass", TOK_REASS },
215 { "setfib", TOK_SETFIB },
216 { NULL, 0 } /* terminator */
219 static struct _s_x rule_action_params[] = {
220 { "altq", TOK_ALTQ },
223 { "untag", TOK_UNTAG },
224 { NULL, 0 } /* terminator */
227 static struct _s_x rule_options[] = {
228 { "tagged", TOK_TAGGED },
231 { "jail", TOK_JAIL },
233 { "limit", TOK_LIMIT },
234 { "keep-state", TOK_KEEPSTATE },
235 { "bridged", TOK_LAYER2 },
236 { "layer2", TOK_LAYER2 },
238 { "diverted", TOK_DIVERTED },
239 { "diverted-loopback", TOK_DIVERTEDLOOPBACK },
240 { "diverted-output", TOK_DIVERTEDOUTPUT },
241 { "xmit", TOK_XMIT },
242 { "recv", TOK_RECV },
244 { "fragment", TOK_FRAG },
245 { "frag", TOK_FRAG },
247 { "ipoptions", TOK_IPOPTS },
248 { "ipopts", TOK_IPOPTS },
249 { "iplen", TOK_IPLEN },
250 { "ipid", TOK_IPID },
251 { "ipprecedence", TOK_IPPRECEDENCE },
252 { "iptos", TOK_IPTOS },
253 { "ipttl", TOK_IPTTL },
254 { "ipversion", TOK_IPVER },
255 { "ipver", TOK_IPVER },
256 { "estab", TOK_ESTAB },
257 { "established", TOK_ESTAB },
258 { "setup", TOK_SETUP },
259 { "tcpdatalen", TOK_TCPDATALEN },
260 { "tcpflags", TOK_TCPFLAGS },
261 { "tcpflgs", TOK_TCPFLAGS },
262 { "tcpoptions", TOK_TCPOPTS },
263 { "tcpopts", TOK_TCPOPTS },
264 { "tcpseq", TOK_TCPSEQ },
265 { "tcpack", TOK_TCPACK },
266 { "tcpwin", TOK_TCPWIN },
267 { "icmptype", TOK_ICMPTYPES },
268 { "icmptypes", TOK_ICMPTYPES },
269 { "dst-ip", TOK_DSTIP },
270 { "src-ip", TOK_SRCIP },
271 { "dst-port", TOK_DSTPORT },
272 { "src-port", TOK_SRCPORT },
273 { "proto", TOK_PROTO },
276 { "mac-type", TOK_MACTYPE },
277 { "verrevpath", TOK_VERREVPATH },
278 { "versrcreach", TOK_VERSRCREACH },
279 { "antispoof", TOK_ANTISPOOF },
280 { "ipsec", TOK_IPSEC },
281 { "icmp6type", TOK_ICMP6TYPES },
282 { "icmp6types", TOK_ICMP6TYPES },
283 { "ext6hdr", TOK_EXT6HDR},
284 { "flow-id", TOK_FLOWID},
289 { "dst-ipv6", TOK_DSTIP6},
290 { "dst-ip6", TOK_DSTIP6},
291 { "src-ipv6", TOK_SRCIP6},
292 { "src-ip6", TOK_SRCIP6},
293 { "//", TOK_COMMENT },
295 { "not", TOK_NOT }, /* pseudo option */
296 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
297 { "or", TOK_OR }, /* pseudo option */
298 { "|", /* escape */ TOK_OR }, /* pseudo option */
299 { "{", TOK_STARTBRACE }, /* pseudo option */
300 { "(", TOK_STARTBRACE }, /* pseudo option */
301 { "}", TOK_ENDBRACE }, /* pseudo option */
302 { ")", TOK_ENDBRACE }, /* pseudo option */
303 { NULL, 0 } /* terminator */
307 * The following is used to generate a printable argument for
308 * 64-bit numbers, irrespective of platform alignment and bit size.
309 * Because all the printf in this program use %llu as a format,
310 * we just return an unsigned long long, which is larger than
311 * we need in certain cases, but saves the hassle of using
312 * PRIu64 as a format specifier.
313 * We don't care about inlining, this is not performance critical code.
316 align_uint64(const uint64_t *pll)
320 bcopy (pll, &ret, sizeof(ret));
325 safe_calloc(size_t number, size_t size)
327 void *ret = calloc(number, size);
330 err(EX_OSERR, "calloc");
335 safe_realloc(void *ptr, size_t size)
337 void *ret = realloc(ptr, size);
340 err(EX_OSERR, "realloc");
345 * conditionally runs the command.
348 do_cmd(int optname, void *optval, uintptr_t optlen)
350 static int s = -1; /* the socket */
357 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
359 err(EX_UNAVAILABLE, "socket");
361 if (optname == IP_FW_GET || optname == IP_FW_DYN_GET ||
362 optname == IP_DUMMYNET_GET ||
363 optname == IP_FW_ADD || optname == IP_FW_TABLE_LIST ||
364 optname == IP_FW_TABLE_GETSIZE ||
365 optname == IP_FW_NAT_GET_CONFIG ||
366 optname == IP_FW_NAT_GET_LOG)
367 i = getsockopt(s, IPPROTO_IP, optname, optval,
368 (socklen_t *)optlen);
370 i = setsockopt(s, IPPROTO_IP, optname, optval, optlen);
375 * match_token takes a table and a string, returns the value associated
376 * with the string (-1 in case of failure).
379 match_token(struct _s_x *table, char *string)
382 uint i = strlen(string);
384 for (pt = table ; i && pt->s != NULL ; pt++)
385 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
391 * match_value takes a table and a value, returns the string associated
392 * with the value (NULL in case of failure).
395 match_value(struct _s_x *p, int value)
397 for (; p->s != NULL; p++)
404 * _substrcmp takes two strings and returns 1 if they do not match,
405 * and 0 if they match exactly or the first string is a sub-string
406 * of the second. A warning is printed to stderr in the case that the
407 * first string is a sub-string of the second.
409 * This function will be removed in the future through the usual
410 * deprecation process.
413 _substrcmp(const char *str1, const char* str2)
416 if (strncmp(str1, str2, strlen(str1)) != 0)
419 if (strlen(str1) != strlen(str2))
420 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
426 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
427 * and 0 if they match exactly or the second string is a sub-string
428 * of the first. A warning is printed to stderr in the case that the
429 * first string does not match the third.
431 * This function exists to warn about the bizzare construction
432 * strncmp(str, "by", 2) which is used to allow people to use a shotcut
433 * for "bytes". The problem is that in addition to accepting "by",
434 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
435 * other string beginning with "by".
437 * This function will be removed in the future through the usual
438 * deprecation process.
441 _substrcmp2(const char *str1, const char* str2, const char* str3)
444 if (strncmp(str1, str2, strlen(str2)) != 0)
447 if (strcmp(str1, str3) != 0)
448 warnx("DEPRECATED: '%s' matched '%s'",
454 * prints one port, symbolic or numeric
457 print_port(int proto, uint16_t port)
460 if (proto == IPPROTO_ETHERTYPE) {
463 if (co.do_resolv && (s = match_value(ether_types, port)) )
466 printf("0x%04x", port);
468 struct servent *se = NULL;
470 struct protoent *pe = getprotobynumber(proto);
472 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
475 printf("%s", se->s_name);
481 static struct _s_x _port_name[] = {
482 {"dst-port", O_IP_DSTPORT},
483 {"src-port", O_IP_SRCPORT},
487 {"mac-type", O_MAC_TYPE},
488 {"tcpdatalen", O_TCPDATALEN},
489 {"tagged", O_TAGGED},
494 * Print the values in a list 16-bit items of the types above.
495 * XXX todo: add support for mask.
498 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode)
500 uint16_t *p = cmd->ports;
505 sep = match_value(_port_name, opcode);
511 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
513 print_port(proto, p[0]);
516 print_port(proto, p[1]);
523 * Like strtol, but also translates service names into port numbers
524 * for some protocols.
526 * proto == -1 disables the protocol check;
527 * proto == IPPROTO_ETHERTYPE looks up an internal table
528 * proto == <some value in /etc/protocols> matches the values there.
529 * Returns *end == s in case the parameter is not found.
532 strtoport(char *s, char **end, int base, int proto)
538 *end = s; /* default - not found */
540 return 0; /* not found */
543 return strtol(s, end, base);
546 * find separator. '\\' escapes the next char.
548 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
549 if (*s1 == '\\' && s1[1] != '\0')
552 buf = safe_calloc(s1 - s + 1, 1);
555 * copy into a buffer skipping backslashes
557 for (p = s, i = 0; p != s1 ; p++)
562 if (proto == IPPROTO_ETHERTYPE) {
563 i = match_token(ether_types, buf);
565 if (i != -1) { /* found */
570 struct protoent *pe = NULL;
574 pe = getprotobynumber(proto);
576 se = getservbyname(buf, pe ? pe->p_name : NULL);
580 return ntohs(se->s_port);
583 return 0; /* not found */
587 * Fill the body of the command with the list of port ranges.
590 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto)
592 uint16_t a, b, *p = cmd->ports;
597 a = strtoport(av, &s, 0, proto);
598 if (s == av) /* empty or invalid argument */
602 case '-': /* a range */
604 b = strtoport(av, &s, 0, proto);
605 /* Reject expressions like '1-abc' or '1-2-3'. */
606 if (s == av || (*s != ',' && *s != '\0'))
611 case ',': /* comma separated list */
616 warnx("port list: invalid separator <%c> in <%s>",
626 if (i + 1 > F_LEN_MASK)
627 errx(EX_DATAERR, "too many ports/ranges\n");
628 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
633 static struct _s_x icmpcodes[] = {
634 { "net", ICMP_UNREACH_NET },
635 { "host", ICMP_UNREACH_HOST },
636 { "protocol", ICMP_UNREACH_PROTOCOL },
637 { "port", ICMP_UNREACH_PORT },
638 { "needfrag", ICMP_UNREACH_NEEDFRAG },
639 { "srcfail", ICMP_UNREACH_SRCFAIL },
640 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
641 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
642 { "isolated", ICMP_UNREACH_ISOLATED },
643 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
644 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
645 { "tosnet", ICMP_UNREACH_TOSNET },
646 { "toshost", ICMP_UNREACH_TOSHOST },
647 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
648 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
649 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
654 fill_reject_code(u_short *codep, char *str)
659 val = strtoul(str, &s, 0);
660 if (s == str || *s != '\0' || val >= 0x100)
661 val = match_token(icmpcodes, str);
663 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
669 print_reject_code(uint16_t code)
671 char const *s = match_value(icmpcodes, code);
674 printf("unreach %s", s);
676 printf("unreach %u", code);
680 * Returns the number of bits set (from left) in a contiguous bitmask,
681 * or -1 if the mask is not contiguous.
682 * XXX this needs a proper fix.
683 * This effectively works on masks in big-endian (network) format.
684 * when compiled on little endian architectures.
686 * First bit is bit 7 of the first byte -- note, for MAC addresses,
687 * the first bit on the wire is bit 0 of the first byte.
688 * len is the max length in bits.
691 contigmask(uint8_t *p, int len)
695 for (i=0; i<len ; i++)
696 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
698 for (n=i+1; n < len; n++)
699 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
700 return -1; /* mask not contiguous */
705 * print flags set/clear in the two bitmasks passed as parameters.
706 * There is a specialized check for f_tcpflags.
709 print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list)
711 char const *comma = "";
713 uint8_t set = cmd->arg1 & 0xff;
714 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
716 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
721 printf(" %s ", name);
722 for (i=0; list[i].x != 0; i++) {
723 if (set & list[i].x) {
725 printf("%s%s", comma, list[i].s);
728 if (clear & list[i].x) {
730 printf("%s!%s", comma, list[i].s);
737 * Print the ip address contained in a command.
740 print_ip(ipfw_insn_ip *cmd, char const *s)
742 struct hostent *he = NULL;
743 int len = F_LEN((ipfw_insn *)cmd);
744 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
746 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
748 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
752 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
753 cmd->o.opcode == O_IP_DST_LOOKUP) {
754 printf("table(%u", ((ipfw_insn *)cmd)->arg1);
755 if (len == F_INSN_SIZE(ipfw_insn_u32))
760 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
761 uint32_t x, *map = (uint32_t *)&(cmd->mask);
767 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
768 printf("%s/%d", inet_ntoa(cmd->addr),
769 contigmask((uint8_t *)&x, 32));
770 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
771 x &= 0xff; /* base */
773 * Print bits and ranges.
774 * Locate first bit set (i), then locate first bit unset (j).
775 * If we have 3+ consecutive bits set, then print them as a
776 * range, otherwise only print the initial bit and rescan.
778 for (i=0; i < cmd->o.arg1; i++)
779 if (map[i/32] & (1<<(i & 31))) {
780 for (j=i+1; j < cmd->o.arg1; j++)
781 if (!(map[ j/32] & (1<<(j & 31))))
783 printf("%c%d", comma, i+x);
784 if (j>i+2) { /* range has at least 3 elements */
785 printf("-%d", j-1+x);
794 * len == 2 indicates a single IP, whereas lists of 1 or more
795 * addr/mask pairs have len = (2n+1). We convert len to n so we
796 * use that to count the number of entries.
798 for (len = len / 2; len > 0; len--, a += 2) {
799 int mb = /* mask length */
800 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
801 32 : contigmask((uint8_t *)&(a[1]), 32);
802 if (mb == 32 && co.do_resolv)
803 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
804 if (he != NULL) /* resolved to name */
805 printf("%s", he->h_name);
806 else if (mb == 0) /* any */
808 else { /* numeric IP followed by some kind of mask */
809 printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) );
811 printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) );
821 * prints a MAC address/mask pair
824 print_mac(uint8_t *addr, uint8_t *mask)
826 int l = contigmask(mask, 48);
831 printf(" %02x:%02x:%02x:%02x:%02x:%02x",
832 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
834 printf("&%02x:%02x:%02x:%02x:%02x:%02x",
835 mask[0], mask[1], mask[2],
836 mask[3], mask[4], mask[5]);
843 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
852 type = strtoul(av, &av, 0);
854 if (*av != ',' && *av != '\0')
855 errx(EX_DATAERR, "invalid ICMP type");
858 errx(EX_DATAERR, "ICMP type out of range");
860 cmd->d[0] |= 1 << type;
862 cmd->o.opcode = O_ICMPTYPE;
863 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
867 print_icmptypes(ipfw_insn_u32 *cmd)
872 printf(" icmptypes");
873 for (i = 0; i < 32; i++) {
874 if ( (cmd->d[0] & (1 << (i))) == 0)
876 printf("%c%d", sep, i);
882 * show_ipfw() prints the body of an ipfw rule.
883 * Because the standard rule has at least proto src_ip dst_ip, we use
884 * a helper function to produce these entries if not provided explicitly.
885 * The first argument is the list of fields we have, the second is
886 * the list of fields we want to be printed.
888 * Special cases if we have provided a MAC header:
889 * + if the rule does not contain IP addresses/ports, do not print them;
890 * + if the rule does not contain an IP proto, print "all" instead of "ip";
892 * Once we have 'have_options', IP header fields are printed as options.
894 #define HAVE_PROTO 0x0001
895 #define HAVE_SRCIP 0x0002
896 #define HAVE_DSTIP 0x0004
897 #define HAVE_PROTO4 0x0008
898 #define HAVE_PROTO6 0x0010
899 #define HAVE_OPTIONS 0x8000
901 #define HAVE_IP (HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP)
903 show_prerequisites(int *flags, int want, int cmd __unused)
907 if ( (*flags & HAVE_IP) == HAVE_IP)
908 *flags |= HAVE_OPTIONS;
910 if ( !(*flags & HAVE_OPTIONS)) {
911 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) {
912 if ( (*flags & HAVE_PROTO4))
914 else if ( (*flags & HAVE_PROTO6))
919 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
921 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
928 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth)
930 static int twidth = 0;
932 ipfw_insn *cmd, *tagptr = NULL;
933 const char *comment = NULL; /* ptr to comment if we have one */
934 int proto = 0; /* default */
935 int flags = 0; /* prerequisites */
936 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
937 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
938 int or_block = 0; /* we are in an or block */
939 uint32_t set_disable;
941 bcopy(&rule->next_rule, &set_disable, sizeof(set_disable));
943 if (set_disable & (1 << rule->set)) { /* disabled */
947 printf("# DISABLED ");
949 printf("%05u ", rule->rulenum);
951 if (pcwidth>0 || bcwidth>0)
952 printf("%*llu %*llu ", pcwidth, align_uint64(&rule->pcnt),
953 bcwidth, align_uint64(&rule->bcnt));
956 printf("%10u ", rule->timestamp);
957 else if (co.do_time == 1) {
959 time_t t = (time_t)0;
962 strcpy(timestr, ctime(&t));
963 *strchr(timestr, '\n') = '\0';
964 twidth = strlen(timestr);
966 if (rule->timestamp) {
967 t = _long_to_time(rule->timestamp);
969 strcpy(timestr, ctime(&t));
970 *strchr(timestr, '\n') = '\0';
971 printf("%s ", timestr);
973 printf("%*s", twidth, " ");
978 printf("set %d ", rule->set);
981 * print the optional "match probability"
983 if (rule->cmd_len > 0) {
985 if (cmd->opcode == O_PROB) {
986 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
987 double d = 1.0 * p->d[0];
989 d = (d / 0x7fffffff);
990 printf("prob %f ", d);
995 * first print actions
997 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
998 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
999 switch(cmd->opcode) {
1001 printf("check-state");
1002 flags = HAVE_IP; /* avoid printing anything else */
1018 if (cmd->arg1 == ICMP_REJECT_RST)
1020 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1023 print_reject_code(cmd->arg1);
1027 if (cmd->arg1 == ICMP6_UNREACH_RST)
1030 print_unreach6_code(cmd->arg1);
1034 PRINT_UINT_ARG("skipto ", cmd->arg1);
1038 PRINT_UINT_ARG("pipe ", cmd->arg1);
1042 PRINT_UINT_ARG("queue ", cmd->arg1);
1046 PRINT_UINT_ARG("divert ", cmd->arg1);
1050 PRINT_UINT_ARG("tee ", cmd->arg1);
1054 PRINT_UINT_ARG("netgraph ", cmd->arg1);
1058 PRINT_UINT_ARG("ngtee ", cmd->arg1);
1063 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1065 if (s->sa.sin_addr.s_addr == INADDR_ANY) {
1066 printf("fwd tablearg");
1068 printf("fwd %s", inet_ntoa(s->sa.sin_addr));
1071 printf(",%d", s->sa.sin_port);
1075 case O_LOG: /* O_LOG is printed last */
1076 logptr = (ipfw_insn_log *)cmd;
1079 case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1080 altqptr = (ipfw_insn_altq *)cmd;
1088 PRINT_UINT_ARG("nat ", cmd->arg1);
1092 PRINT_UINT_ARG("setfib ", cmd->arg1);
1100 printf("** unrecognized action %d len %d ",
1101 cmd->opcode, cmd->len);
1105 if (logptr->max_log > 0)
1106 printf(" log logamount %d", logptr->max_log);
1111 print_altq_cmd(altqptr);
1114 if (tagptr->len & F_NOT)
1115 PRINT_UINT_ARG(" untag ", tagptr->arg1);
1117 PRINT_UINT_ARG(" tag ", tagptr->arg1);
1121 * then print the body.
1123 for (l = rule->act_ofs, cmd = rule->cmd ;
1124 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1125 if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1127 if (cmd->opcode == O_IP4) {
1128 flags |= HAVE_PROTO4;
1130 } else if (cmd->opcode == O_IP6) {
1131 flags |= HAVE_PROTO6;
1135 if (rule->_pad & 1) { /* empty rules before options */
1136 if (!co.do_compact) {
1137 show_prerequisites(&flags, HAVE_PROTO, 0);
1138 printf(" from any to any");
1140 flags |= HAVE_IP | HAVE_OPTIONS;
1143 if (co.comment_only)
1146 for (l = rule->act_ofs, cmd = rule->cmd ;
1147 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1149 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1151 if (co.comment_only) {
1152 if (cmd->opcode != O_NOP)
1154 printf(" // %s\n", (char *)(cmd + 1));
1158 show_prerequisites(&flags, 0, cmd->opcode);
1160 switch(cmd->opcode) {
1162 break; /* done already */
1165 break; /* no need to print anything here */
1168 case O_IP_SRC_LOOKUP:
1172 show_prerequisites(&flags, HAVE_PROTO, 0);
1173 if (!(flags & HAVE_SRCIP))
1175 if ((cmd->len & F_OR) && !or_block)
1177 print_ip((ipfw_insn_ip *)cmd,
1178 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1179 flags |= HAVE_SRCIP;
1183 case O_IP_DST_LOOKUP:
1187 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1188 if (!(flags & HAVE_DSTIP))
1190 if ((cmd->len & F_OR) && !or_block)
1192 print_ip((ipfw_insn_ip *)cmd,
1193 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1194 flags |= HAVE_DSTIP;
1198 case O_IP6_SRC_MASK:
1200 show_prerequisites(&flags, HAVE_PROTO, 0);
1201 if (!(flags & HAVE_SRCIP))
1203 if ((cmd->len & F_OR) && !or_block)
1205 print_ip6((ipfw_insn_ip6 *)cmd,
1206 (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1207 flags |= HAVE_SRCIP | HAVE_PROTO;
1211 case O_IP6_DST_MASK:
1213 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1214 if (!(flags & HAVE_DSTIP))
1216 if ((cmd->len & F_OR) && !or_block)
1218 print_ip6((ipfw_insn_ip6 *)cmd,
1219 (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1220 flags |= HAVE_DSTIP;
1224 print_flow6id( (ipfw_insn_u32 *) cmd );
1225 flags |= HAVE_OPTIONS;
1229 show_prerequisites(&flags, HAVE_IP, 0);
1231 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1232 if ((cmd->len & F_OR) && !or_block)
1234 if (cmd->len & F_NOT)
1236 print_newports((ipfw_insn_u16 *)cmd, proto,
1237 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1241 struct protoent *pe = NULL;
1243 if ((cmd->len & F_OR) && !or_block)
1245 if (cmd->len & F_NOT)
1248 pe = getprotobynumber(cmd->arg1);
1249 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1250 !(flags & HAVE_PROTO))
1251 show_prerequisites(&flags,
1252 HAVE_IP | HAVE_OPTIONS, 0);
1253 if (flags & HAVE_OPTIONS)
1256 printf(" %s", pe->p_name);
1258 printf(" %u", cmd->arg1);
1260 flags |= HAVE_PROTO;
1263 default: /*options ... */
1264 if (!(cmd->len & (F_OR|F_NOT)))
1265 if (((cmd->opcode == O_IP6) &&
1266 (flags & HAVE_PROTO6)) ||
1267 ((cmd->opcode == O_IP4) &&
1268 (flags & HAVE_PROTO4)))
1270 show_prerequisites(&flags, HAVE_IP | HAVE_OPTIONS, 0);
1271 if ((cmd->len & F_OR) && !or_block)
1273 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1275 switch(cmd->opcode) {
1277 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1280 print_mac(m->addr, m->mask);
1281 print_mac(m->addr + 6, m->mask + 6);
1286 print_newports((ipfw_insn_u16 *)cmd,
1287 IPPROTO_ETHERTYPE, cmd->opcode);
1296 printf(" fib %u", cmd->arg1 );
1300 printf(cmd->len & F_NOT ? " out" : " in");
1304 switch (cmd->arg1) {
1306 printf(" diverted");
1309 printf(" diverted-loopback");
1312 printf(" diverted-output");
1315 printf(" diverted-?<%u>", cmd->arg1);
1328 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1330 if (cmd->opcode == O_XMIT)
1332 else if (cmd->opcode == O_RECV)
1334 else /* if (cmd->opcode == O_VIA) */
1336 if (cmdif->name[0] == '\0')
1338 inet_ntoa(cmdif->p.ip));
1340 printf(" %s %s", s, cmdif->name);
1345 if (F_LEN(cmd) == 1)
1346 printf(" ipid %u", cmd->arg1 );
1348 print_newports((ipfw_insn_u16 *)cmd, 0,
1353 if (F_LEN(cmd) == 1)
1354 printf(" ipttl %u", cmd->arg1 );
1356 print_newports((ipfw_insn_u16 *)cmd, 0,
1361 printf(" ipver %u", cmd->arg1 );
1364 case O_IPPRECEDENCE:
1365 printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1369 if (F_LEN(cmd) == 1)
1370 printf(" iplen %u", cmd->arg1 );
1372 print_newports((ipfw_insn_u16 *)cmd, 0,
1377 print_flags("ipoptions", cmd, f_ipopts);
1381 print_flags("iptos", cmd, f_iptos);
1385 print_icmptypes((ipfw_insn_u32 *)cmd);
1389 printf(" established");
1393 if (F_LEN(cmd) == 1)
1394 printf(" tcpdatalen %u", cmd->arg1 );
1396 print_newports((ipfw_insn_u16 *)cmd, 0,
1401 print_flags("tcpflags", cmd, f_tcpflags);
1405 print_flags("tcpoptions", cmd, f_tcpopts);
1409 printf(" tcpwin %d", ntohs(cmd->arg1));
1413 printf(" tcpack %d", ntohl(cmd32->d[0]));
1417 printf(" tcpseq %d", ntohl(cmd32->d[0]));
1422 struct passwd *pwd = getpwuid(cmd32->d[0]);
1425 printf(" uid %s", pwd->pw_name);
1427 printf(" uid %u", cmd32->d[0]);
1433 struct group *grp = getgrgid(cmd32->d[0]);
1436 printf(" gid %s", grp->gr_name);
1438 printf(" gid %u", cmd32->d[0]);
1443 printf(" jail %d", cmd32->d[0]);
1447 printf(" verrevpath");
1451 printf(" versrcreach");
1455 printf(" antispoof");
1463 comment = (char *)(cmd + 1);
1467 printf(" keep-state");
1471 struct _s_x *p = limit_masks;
1472 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1473 uint8_t x = c->limit_mask;
1474 char const *comma = " ";
1477 for (; p->x != 0 ; p++)
1478 if ((x & p->x) == p->x) {
1480 printf("%s%s", comma, p->s);
1483 PRINT_UINT_ARG(" ", c->conn_limit);
1496 print_icmp6types((ipfw_insn_u32 *)cmd);
1500 print_ext6hdr( (ipfw_insn *) cmd );
1504 if (F_LEN(cmd) == 1)
1505 PRINT_UINT_ARG(" tagged ", cmd->arg1);
1507 print_newports((ipfw_insn_u16 *)cmd, 0,
1512 printf(" [opcode %d len %d]",
1513 cmd->opcode, cmd->len);
1516 if (cmd->len & F_OR) {
1519 } else if (or_block) {
1524 show_prerequisites(&flags, HAVE_IP, 0);
1526 printf(" // %s", comment);
1531 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth)
1533 struct protoent *pe;
1536 char buf[INET6_ADDRSTRLEN];
1538 if (!co.do_expired) {
1539 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1542 bcopy(&d->rule, &rulenum, sizeof(rulenum));
1543 printf("%05d", rulenum);
1544 if (pcwidth>0 || bcwidth>0)
1545 printf(" %*llu %*llu (%ds)", pcwidth,
1546 align_uint64(&d->pcnt), bcwidth,
1547 align_uint64(&d->bcnt), d->expire);
1548 switch (d->dyn_type) {
1549 case O_LIMIT_PARENT:
1550 printf(" PARENT %d", d->count);
1555 case O_KEEP_STATE: /* bidir, no mask */
1560 if ((pe = getprotobynumber(d->id.proto)) != NULL)
1561 printf(" %s", pe->p_name);
1563 printf(" proto %u", d->id.proto);
1565 if (d->id.addr_type == 4) {
1566 a.s_addr = htonl(d->id.src_ip);
1567 printf(" %s %d", inet_ntoa(a), d->id.src_port);
1569 a.s_addr = htonl(d->id.dst_ip);
1570 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
1571 } else if (d->id.addr_type == 6) {
1572 printf(" %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
1573 sizeof(buf)), d->id.src_port);
1574 printf(" <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6, buf,
1575 sizeof(buf)), d->id.dst_port);
1577 printf(" UNKNOWN <-> UNKNOWN\n");
1583 * This one handles all set-related commands
1584 * ipfw set { show | enable | disable }
1586 * ipfw set move X to Y
1587 * ipfw set move rule X to Y
1590 ipfw_sets_handler(int ac, char *av[])
1592 uint32_t set_disable, masks[2];
1595 uint8_t cmd, new_set;
1601 errx(EX_USAGE, "set needs command");
1602 if (_substrcmp(*av, "show") == 0) {
1606 nbytes = sizeof(struct ip_fw);
1607 data = safe_calloc(1, nbytes);
1608 if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0)
1609 err(EX_OSERR, "getsockopt(IP_FW_GET)");
1610 bcopy(&((struct ip_fw *)data)->next_rule,
1611 &set_disable, sizeof(set_disable));
1613 for (i = 0, msg = "disable" ; i < RESVD_SET; i++)
1614 if ((set_disable & (1<<i))) {
1615 printf("%s %d", msg, i);
1618 msg = (set_disable) ? " enable" : "enable";
1619 for (i = 0; i < RESVD_SET; i++)
1620 if (!(set_disable & (1<<i))) {
1621 printf("%s %d", msg, i);
1625 } else if (_substrcmp(*av, "swap") == 0) {
1628 errx(EX_USAGE, "set swap needs 2 set numbers\n");
1629 rulenum = atoi(av[0]);
1630 new_set = atoi(av[1]);
1631 if (!isdigit(*(av[0])) || rulenum > RESVD_SET)
1632 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
1633 if (!isdigit(*(av[1])) || new_set > RESVD_SET)
1634 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
1635 masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
1636 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
1637 } else if (_substrcmp(*av, "move") == 0) {
1639 if (ac && _substrcmp(*av, "rule") == 0) {
1644 if (ac != 3 || _substrcmp(av[1], "to") != 0)
1645 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
1646 rulenum = atoi(av[0]);
1647 new_set = atoi(av[2]);
1648 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) ||
1649 (cmd == 2 && rulenum == IPFW_DEFAULT_RULE) )
1650 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
1651 if (!isdigit(*(av[2])) || new_set > RESVD_SET)
1652 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
1653 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
1654 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
1655 } else if (_substrcmp(*av, "disable") == 0 ||
1656 _substrcmp(*av, "enable") == 0 ) {
1657 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
1660 masks[0] = masks[1] = 0;
1663 if (isdigit(**av)) {
1665 if (i < 0 || i > RESVD_SET)
1667 "invalid set number %d\n", i);
1668 masks[which] |= (1<<i);
1669 } else if (_substrcmp(*av, "disable") == 0)
1671 else if (_substrcmp(*av, "enable") == 0)
1675 "invalid set command %s\n", *av);
1678 if ( (masks[0] & masks[1]) != 0 )
1680 "cannot enable and disable the same set\n");
1682 i = do_cmd(IP_FW_DEL, masks, sizeof(masks));
1684 warn("set enable/disable: setsockopt(IP_FW_DEL)");
1686 errx(EX_USAGE, "invalid set command %s\n", *av);
1690 ipfw_sysctl_handler(int ac, char *av[], int which)
1696 warnx("missing keyword to enable/disable\n");
1697 } else if (_substrcmp(*av, "firewall") == 0) {
1698 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
1699 &which, sizeof(which));
1700 } else if (_substrcmp(*av, "one_pass") == 0) {
1701 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
1702 &which, sizeof(which));
1703 } else if (_substrcmp(*av, "debug") == 0) {
1704 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
1705 &which, sizeof(which));
1706 } else if (_substrcmp(*av, "verbose") == 0) {
1707 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
1708 &which, sizeof(which));
1709 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
1710 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
1711 &which, sizeof(which));
1712 } else if (_substrcmp(*av, "altq") == 0) {
1713 altq_set_enabled(which);
1715 warnx("unrecognize enable/disable keyword: %s\n", *av);
1720 ipfw_list(int ac, char *av[], int show_counters)
1723 ipfw_dyn_rule *dynrules = NULL;
1726 #define NEXT(r) ((struct ip_fw *)((char *)r + RULESIZE(r)))
1729 int bcwidth, n, nbytes, pcwidth, width, nstat;
1731 int exitval = EX_OK;
1738 int ocmd = IP_FW_GET;
1741 ocmd = IP_DUMMYNET_GET;
1742 else if (co.do_dynamic)
1743 ocmd = IP_FW_DYN_GET;
1745 int nalloc = 1024; /* start somewhere... */
1750 fprintf(stderr, "Testing only, list disabled\n");
1757 /* get rules or pipes from kernel, resizing array as necessary */
1760 while (nbytes >= nalloc) {
1761 nalloc = nalloc * 2 + 200;
1763 data = safe_realloc(data, nbytes);
1764 if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0)
1765 err(EX_OSERR, "getsockopt(IP_%s_GET)",
1766 co.do_pipe ? "DUMMYNET" : "FW");
1770 ipfw_list_pipes(data, nbytes, ac, av);
1775 * Count static rules. They have variable size so we
1776 * need to scan the list to count them.
1781 if (!co.do_dynamic) {
1782 for (nstat = 1, r = data, lim = (char *)data + nbytes;
1783 r->rulenum < IPFW_DEFAULT_RULE && (char *)r < lim;
1784 ++nstat, r = NEXT(r) )
1789 * Count dynamic rules. This is easier as they have
1792 if (co.do_dynamic) {
1793 dynrules = (ipfw_dyn_rule *)r ;
1794 n = (char *)r - (char *)data;
1795 ndyn = (nbytes - n) / sizeof *dynrules;
1798 /* if showing stats, figure out column widths ahead of time */
1799 bcwidth = pcwidth = 0;
1800 if (show_counters) {
1801 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
1802 /* skip rules from another set */
1803 if (co.use_set && r->set != co.use_set - 1)
1806 /* packet counter */
1807 width = snprintf(NULL, 0, "%llu",
1808 align_uint64(&r->pcnt));
1809 if (width > pcwidth)
1813 width = snprintf(NULL, 0, "%llu",
1814 align_uint64(&r->bcnt));
1815 if (width > bcwidth)
1820 if (co.do_dynamic && ndyn) {
1821 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1823 /* skip rules from another set */
1824 bcopy((char *)&d->rule + sizeof(uint16_t),
1825 &set, sizeof(uint8_t));
1826 if (set != co.use_set - 1)
1829 width = snprintf(NULL, 0, "%llu",
1830 align_uint64(&d->pcnt));
1831 if (width > pcwidth)
1834 width = snprintf(NULL, 0, "%llu",
1835 align_uint64(&d->bcnt));
1836 if (width > bcwidth)
1841 /* if no rule numbers were specified, list all rules */
1843 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
1844 if (co.use_set && r->set != co.use_set - 1)
1846 show_ipfw(r, pcwidth, bcwidth);
1849 if (co.do_dynamic && ndyn) {
1850 printf("## Dynamic rules (%d):\n", ndyn);
1851 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1853 bcopy((char *)&d->rule + sizeof(uint16_t),
1854 &set, sizeof(uint8_t));
1855 if (set != co.use_set - 1)
1858 show_dyn_ipfw(d, pcwidth, bcwidth);
1864 /* display specific rules requested on command line */
1866 if (!co.do_dynamic) {
1867 for (lac = ac, lav = av; lac != 0; lac--) {
1868 /* convert command line rule # */
1869 last = rnum = strtoul(*lav++, &endptr, 10);
1871 last = strtoul(endptr+1, &endptr, 10);
1874 warnx("invalid rule number: %s", *(lav - 1));
1877 for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) {
1878 if (r->rulenum > last)
1880 if (co.use_set && r->set != co.use_set - 1)
1882 if (r->rulenum >= rnum && r->rulenum <= last) {
1883 show_ipfw(r, pcwidth, bcwidth);
1888 /* give precedence to other error(s) */
1889 if (exitval == EX_OK)
1890 exitval = EX_UNAVAILABLE;
1891 warnx("rule %lu does not exist", rnum);
1896 if (co.do_dynamic && ndyn) {
1897 printf("## Dynamic rules:\n");
1898 for (lac = ac, lav = av; lac != 0; lac--) {
1899 last = rnum = strtoul(*lav++, &endptr, 10);
1901 last = strtoul(endptr+1, &endptr, 10);
1903 /* already warned */
1905 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1908 bcopy(&d->rule, &rulenum, sizeof(rulenum));
1912 bcopy((char *)&d->rule + sizeof(uint16_t),
1913 &set, sizeof(uint8_t));
1914 if (set != co.use_set - 1)
1917 if (r->rulenum >= rnum && r->rulenum <= last)
1918 show_dyn_ipfw(d, pcwidth, bcwidth);
1928 if (exitval != EX_OK)
1934 lookup_host (char *host, struct in_addr *ipaddr)
1938 if (!inet_aton(host, ipaddr)) {
1939 if ((he = gethostbyname(host)) == NULL)
1941 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
1947 * fills the addr and mask fields in the instruction as appropriate from av.
1948 * Update length as appropriate.
1949 * The following formats are allowed:
1950 * me returns O_IP_*_ME
1951 * 1.2.3.4 single IP address
1952 * 1.2.3.4:5.6.7.8 address:mask
1953 * 1.2.3.4/24 address/mask
1954 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
1955 * We can have multiple comma-separated address/mask entries.
1958 fill_ip(ipfw_insn_ip *cmd, char *av)
1961 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
1963 cmd->o.len &= ~F_LEN_MASK; /* zero len */
1965 if (_substrcmp(av, "any") == 0)
1968 if (_substrcmp(av, "me") == 0) {
1969 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
1973 if (strncmp(av, "table(", 6) == 0) {
1974 char *p = strchr(av + 6, ',');
1978 cmd->o.opcode = O_IP_DST_LOOKUP;
1979 cmd->o.arg1 = strtoul(av + 6, NULL, 0);
1981 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1982 d[0] = strtoul(p, NULL, 0);
1984 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
1990 * After the address we can have '/' or ':' indicating a mask,
1991 * ',' indicating another address follows, '{' indicating a
1992 * set of addresses of unspecified size.
1994 char *t = NULL, *p = strpbrk(av, "/:,{");
2001 if ((t = strpbrk(p, ",{")) != NULL) {
2008 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2009 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2012 if (!inet_aton(p, (struct in_addr *)&d[1]))
2013 errx(EX_DATAERR, "bad netmask ``%s''", p);
2018 d[1] = htonl(0); /* mask */
2019 else if (masklen > 32)
2020 errx(EX_DATAERR, "bad width ``%s''", p);
2022 d[1] = htonl(~0 << (32 - masklen));
2024 case '{': /* no mask, assume /24 and put back the '{' */
2025 d[1] = htonl(~0 << (32 - 24));
2029 case ',': /* single address plus continuation */
2032 case 0: /* initialization value */
2034 d[1] = htonl(~0); /* force /32 */
2037 d[0] &= d[1]; /* mask base address with mask */
2040 /* find next separator */
2042 p = strpbrk(p, ",{");
2043 if (p && *p == '{') {
2045 * We have a set of addresses. They are stored as follows:
2046 * arg1 is the set size (powers of 2, 2..256)
2047 * addr is the base address IN HOST FORMAT
2048 * mask.. is an array of arg1 bits (rounded up to
2049 * the next multiple of 32) with bits set
2050 * for each host in the map.
2052 uint32_t *map = (uint32_t *)&cmd->mask;
2054 int i = contigmask((uint8_t *)&(d[1]), 32);
2057 errx(EX_DATAERR, "address set cannot be in a list");
2058 if (i < 24 || i > 31)
2059 errx(EX_DATAERR, "invalid set with mask %d\n", i);
2060 cmd->o.arg1 = 1<<(32-i); /* map length */
2061 d[0] = ntohl(d[0]); /* base addr in host format */
2062 cmd->o.opcode = O_IP_DST_SET; /* default */
2063 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2064 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2065 map[i] = 0; /* clear map */
2069 high = low + cmd->o.arg1 - 1;
2071 * Here, i stores the previous value when we specify a range
2072 * of addresses within a mask, e.g. 45-63. i = -1 means we
2073 * have no previous value.
2075 i = -1; /* previous value in a range */
2076 while (isdigit(*av)) {
2078 int a = strtol(av, &s, 0);
2080 if (s == av) { /* no parameter */
2082 errx(EX_DATAERR, "set not closed\n");
2084 errx(EX_DATAERR, "incomplete range %d-", i);
2087 if (a < low || a > high)
2088 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
2091 if (i == -1) /* no previous in range */
2093 else { /* check that range is valid */
2095 errx(EX_DATAERR, "invalid range %d-%d",
2098 errx(EX_DATAERR, "double '-' in range");
2101 map[i/32] |= 1<<(i & 31);
2112 if (av) /* then *av must be a ',' */
2115 /* Check this entry */
2116 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2118 * 'any' turns the entire list into a NOP.
2119 * 'not any' never matches, so it is removed from the
2120 * list unless it is the only item, in which case we
2123 if (cmd->o.len & F_NOT) { /* "not any" never matches */
2124 if (av == NULL && len == 0) /* only this entry */
2125 errx(EX_DATAERR, "not any never matches");
2127 /* else do nothing and skip this entry */
2130 /* A single IP can be stored in an optimized format */
2131 if (d[1] == ~0 && av == NULL && len == 0) {
2132 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2135 len += 2; /* two words... */
2138 if (len + 1 > F_LEN_MASK)
2139 errx(EX_DATAERR, "address list too long");
2140 cmd->o.len |= len+1;
2144 /* n2mask sets n bits of the mask */
2146 n2mask(struct in6_addr *mask, int n)
2148 static int minimask[9] =
2149 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
2152 memset(mask, 0, sizeof(struct in6_addr));
2153 p = (u_char *) mask;
2154 for (; n > 0; p++, n -= 8) {
2165 * helper function to process a set of flags and set bits in the
2166 * appropriate masks.
2169 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
2170 struct _s_x *flags, char *p)
2172 uint8_t set=0, clear=0;
2175 char *q; /* points to the separator */
2177 uint8_t *which; /* mask we are working on */
2187 val = match_token(flags, p);
2189 errx(EX_DATAERR, "invalid flag %s", p);
2190 *which |= (uint8_t)val;
2193 cmd->opcode = opcode;
2194 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
2195 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
2200 ipfw_delete(int ac, char *av[])
2204 int exitval = EX_OK;
2209 NEED1("missing rule specification");
2210 if (ac > 0 && _substrcmp(*av, "set") == 0) {
2211 /* Do not allow using the following syntax:
2212 * ipfw set N delete set M
2215 errx(EX_DATAERR, "invalid syntax");
2216 do_set = 1; /* delete set */
2221 while (ac && isdigit(**av)) {
2222 i = atoi(*av); av++; ac--;
2224 exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
2226 exitval = EX_UNAVAILABLE;
2227 warn("rule %u not available", i);
2229 } else if (co.do_pipe) {
2230 exitval = ipfw_delete_pipe(co.do_pipe, i);
2233 rulenum = (i & 0xffff) | (5 << 24) |
2234 ((co.use_set - 1) << 16);
2236 rulenum = (i & 0xffff) | (do_set << 24);
2237 i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum);
2239 exitval = EX_UNAVAILABLE;
2240 warn("rule %u: setsockopt(IP_FW_DEL)",
2245 if (exitval != EX_OK)
2251 * fill the interface structure. We do not check the name as we can
2252 * create interfaces dynamically, so checking them at insert time
2253 * makes relatively little sense.
2254 * Interface names containing '*', '?', or '[' are assumed to be shell
2255 * patterns which match interfaces.
2258 fill_iface(ipfw_insn_if *cmd, char *arg)
2260 cmd->name[0] = '\0';
2261 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
2263 /* Parse the interface or address */
2264 if (strcmp(arg, "any") == 0)
2265 cmd->o.len = 0; /* effectively ignore this command */
2266 else if (!isdigit(*arg)) {
2267 strlcpy(cmd->name, arg, sizeof(cmd->name));
2268 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
2269 } else if (!inet_aton(arg, &cmd->p.ip))
2270 errx(EX_DATAERR, "bad ip address ``%s''", arg);
2274 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
2277 char *ap, *ptr, *optr;
2278 struct ether_addr *mac;
2279 const char *macset = "0123456789abcdefABCDEF:";
2281 if (strcmp(p, "any") == 0) {
2282 for (i = 0; i < ETHER_ADDR_LEN; i++)
2283 addr[i] = mask[i] = 0;
2287 optr = ptr = strdup(p);
2288 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
2290 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
2291 errx(EX_DATAERR, "Incorrect MAC address");
2292 bcopy(mac, addr, ETHER_ADDR_LEN);
2294 errx(EX_DATAERR, "Incorrect MAC address");
2296 if (ptr != NULL) { /* we have mask? */
2297 if (p[ptr - optr - 1] == '/') { /* mask len */
2298 l = strtol(ptr, &ap, 10);
2299 if (*ap != 0 || l > ETHER_ADDR_LEN * 8 || l < 0)
2300 errx(EX_DATAERR, "Incorrect mask length");
2301 for (i = 0; l > 0 && i < ETHER_ADDR_LEN; l -= 8, i++)
2302 mask[i] = (l >= 8) ? 0xff: (~0) << (8 - l);
2305 if (strspn(ptr, macset) != l ||
2306 (mac = ether_aton(ptr)) == NULL)
2307 errx(EX_DATAERR, "Incorrect mask");
2308 bcopy(mac, mask, ETHER_ADDR_LEN);
2310 } else { /* default mask: ff:ff:ff:ff:ff:ff */
2311 for (i = 0; i < ETHER_ADDR_LEN; i++)
2314 for (i = 0; i < ETHER_ADDR_LEN; i++)
2321 * helper function, updates the pointer to cmd with the length
2322 * of the current command, and also cleans up the first word of
2323 * the new command in case it has been clobbered before.
2326 next_cmd(ipfw_insn *cmd)
2329 bzero(cmd, sizeof(*cmd));
2334 * Takes arguments and copies them into a comment
2337 fill_comment(ipfw_insn *cmd, int ac, char **av)
2340 char *p = (char *)(cmd + 1);
2342 cmd->opcode = O_NOP;
2343 cmd->len = (cmd->len & (F_NOT | F_OR));
2345 /* Compute length of comment string. */
2346 for (i = 0, l = 0; i < ac; i++)
2347 l += strlen(av[i]) + 1;
2352 "comment too long (max 80 chars)");
2354 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
2355 for (i = 0; i < ac; i++) {
2364 * A function to fill simple commands of size 1.
2365 * Existing flags are preserved.
2368 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
2370 cmd->opcode = opcode;
2371 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
2376 * Fetch and add the MAC address and type, with masks. This generates one or
2377 * two microinstructions, and returns the pointer to the last one.
2380 add_mac(ipfw_insn *cmd, int ac, char *av[])
2385 errx(EX_DATAERR, "MAC dst src");
2387 cmd->opcode = O_MACADDR2;
2388 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
2390 mac = (ipfw_insn_mac *)cmd;
2391 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
2392 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
2393 &(mac->mask[ETHER_ADDR_LEN])); /* src */
2398 add_mactype(ipfw_insn *cmd, int ac, char *av)
2401 errx(EX_DATAERR, "missing MAC type");
2402 if (strcmp(av, "any") != 0) { /* we have a non-null type */
2403 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE);
2404 cmd->opcode = O_MAC_TYPE;
2411 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
2413 struct protoent *pe;
2417 proto = strtol(av, &ep, 10);
2418 if (*ep != '\0' || proto <= 0) {
2419 if ((pe = getprotobyname(av)) == NULL)
2421 proto = pe->p_proto;
2424 fill_cmd(cmd, O_PROTO, 0, proto);
2430 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
2432 u_char proto = IPPROTO_IP;
2434 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2435 ; /* do not set O_IP4 nor O_IP6 */
2436 else if (strcmp(av, "ip4") == 0)
2437 /* explicit "just IPv4" rule */
2438 fill_cmd(cmd, O_IP4, 0, 0);
2439 else if (strcmp(av, "ip6") == 0) {
2440 /* explicit "just IPv6" rule */
2441 proto = IPPROTO_IPV6;
2442 fill_cmd(cmd, O_IP6, 0, 0);
2444 return add_proto0(cmd, av, protop);
2451 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
2453 u_char proto = IPPROTO_IP;
2455 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2456 ; /* do not set O_IP4 nor O_IP6 */
2457 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
2458 /* explicit "just IPv4" rule */
2459 fill_cmd(cmd, O_IP4, 0, 0);
2460 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
2461 /* explicit "just IPv6" rule */
2462 proto = IPPROTO_IPV6;
2463 fill_cmd(cmd, O_IP6, 0, 0);
2465 return add_proto0(cmd, av, protop);
2472 add_srcip(ipfw_insn *cmd, char *av)
2474 fill_ip((ipfw_insn_ip *)cmd, av);
2475 if (cmd->opcode == O_IP_DST_SET) /* set */
2476 cmd->opcode = O_IP_SRC_SET;
2477 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
2478 cmd->opcode = O_IP_SRC_LOOKUP;
2479 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2480 cmd->opcode = O_IP_SRC_ME;
2481 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2482 cmd->opcode = O_IP_SRC;
2483 else /* addr/mask */
2484 cmd->opcode = O_IP_SRC_MASK;
2489 add_dstip(ipfw_insn *cmd, char *av)
2491 fill_ip((ipfw_insn_ip *)cmd, av);
2492 if (cmd->opcode == O_IP_DST_SET) /* set */
2494 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
2496 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2497 cmd->opcode = O_IP_DST_ME;
2498 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2499 cmd->opcode = O_IP_DST;
2500 else /* addr/mask */
2501 cmd->opcode = O_IP_DST_MASK;
2506 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode)
2508 if (_substrcmp(av, "any") == 0) {
2510 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) {
2511 /* XXX todo: check that we have a protocol with ports */
2512 cmd->opcode = opcode;
2519 add_src(ipfw_insn *cmd, char *av, u_char proto)
2523 ipfw_insn *ret = NULL;
2525 if ((host = strdup(av)) == NULL)
2527 if ((ch = strrchr(host, '/')) != NULL)
2530 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
2531 inet_pton(AF_INET6, host, &a))
2532 ret = add_srcip6(cmd, av);
2533 /* XXX: should check for IPv4, not !IPv6 */
2534 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2535 !inet_pton(AF_INET6, host, &a)))
2536 ret = add_srcip(cmd, av);
2537 if (ret == NULL && strcmp(av, "any") != 0)
2545 add_dst(ipfw_insn *cmd, char *av, u_char proto)
2549 ipfw_insn *ret = NULL;
2551 if ((host = strdup(av)) == NULL)
2553 if ((ch = strrchr(host, '/')) != NULL)
2556 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
2557 inet_pton(AF_INET6, host, &a))
2558 ret = add_dstip6(cmd, av);
2559 /* XXX: should check for IPv4, not !IPv6 */
2560 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2561 !inet_pton(AF_INET6, host, &a)))
2562 ret = add_dstip(cmd, av);
2563 if (ret == NULL && strcmp(av, "any") != 0)
2571 * Parse arguments and assemble the microinstructions which make up a rule.
2572 * Rules are added into the 'rulebuf' and then copied in the correct order
2573 * into the actual rule.
2575 * The syntax for a rule starts with the action, followed by
2576 * optional action parameters, and the various match patterns.
2577 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
2578 * (generated if the rule includes a keep-state option), then the
2579 * various match patterns, log/altq actions, and the actual action.
2583 ipfw_add(int ac, char *av[])
2586 * rules are added into the 'rulebuf' and then copied in
2587 * the correct order into the actual rule.
2588 * Some things that need to go out of order (prob, action etc.)
2591 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255];
2593 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
2594 ipfw_insn *first_cmd; /* first match pattern */
2599 * various flags used to record that we entered some fields.
2601 ipfw_insn *have_state = NULL; /* check-state or keep-state */
2602 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
2607 int open_par = 0; /* open parenthesis ( */
2609 /* proto is here because it is used to fetch ports */
2610 u_char proto = IPPROTO_IP; /* default protocol */
2612 double match_prob = 1; /* match probability, default is always match */
2614 bzero(actbuf, sizeof(actbuf)); /* actions go here */
2615 bzero(cmdbuf, sizeof(cmdbuf));
2616 bzero(rulebuf, sizeof(rulebuf));
2618 rule = (struct ip_fw *)rulebuf;
2619 cmd = (ipfw_insn *)cmdbuf;
2620 action = (ipfw_insn *)actbuf;
2624 /* [rule N] -- Rule number optional */
2625 if (ac && isdigit(**av)) {
2626 rule->rulenum = atoi(*av);
2631 /* [set N] -- set number (0..RESVD_SET), optional */
2632 if (ac > 1 && _substrcmp(*av, "set") == 0) {
2633 int set = strtoul(av[1], NULL, 10);
2634 if (set < 0 || set > RESVD_SET)
2635 errx(EX_DATAERR, "illegal set %s", av[1]);
2640 /* [prob D] -- match probability, optional */
2641 if (ac > 1 && _substrcmp(*av, "prob") == 0) {
2642 match_prob = strtod(av[1], NULL);
2644 if (match_prob <= 0 || match_prob > 1)
2645 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
2649 /* action -- mandatory */
2650 NEED1("missing action");
2651 i = match_token(rule_actions, *av);
2653 action->len = 1; /* default */
2655 case TOK_CHECKSTATE:
2656 have_state = action;
2657 action->opcode = O_CHECK_STATE;
2661 action->opcode = O_ACCEPT;
2665 action->opcode = O_DENY;
2670 action->opcode = O_REJECT;
2671 action->arg1 = ICMP_UNREACH_HOST;
2675 action->opcode = O_REJECT;
2676 action->arg1 = ICMP_REJECT_RST;
2680 action->opcode = O_UNREACH6;
2681 action->arg1 = ICMP6_UNREACH_RST;
2685 action->opcode = O_REJECT;
2686 NEED1("missing reject code");
2687 fill_reject_code(&action->arg1, *av);
2692 action->opcode = O_UNREACH6;
2693 NEED1("missing unreach code");
2694 fill_unreach6_code(&action->arg1, *av);
2699 action->opcode = O_COUNT;
2703 action->opcode = O_NAT;
2704 action->len = F_INSN_SIZE(ipfw_insn_nat);
2708 action->opcode = O_QUEUE;
2711 action->opcode = O_PIPE;
2714 action->opcode = O_SKIPTO;
2717 action->opcode = O_NETGRAPH;
2720 action->opcode = O_NGTEE;
2723 action->opcode = O_DIVERT;
2726 action->opcode = O_TEE;
2729 errx(EX_USAGE, "missing argument for %s", *(av - 1));
2730 if (isdigit(**av)) {
2731 action->arg1 = strtoul(*av, NULL, 10);
2732 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
2733 errx(EX_DATAERR, "illegal argument for %s",
2735 } else if (_substrcmp(*av, "tablearg") == 0) {
2736 action->arg1 = IP_FW_TABLEARG;
2737 } else if (i == TOK_DIVERT || i == TOK_TEE) {
2740 s = getservbyname(av[0], "divert");
2742 action->arg1 = ntohs(s->s_port);
2744 errx(EX_DATAERR, "illegal divert/tee port");
2746 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
2751 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
2754 NEED1("missing forward address[:port]");
2756 action->opcode = O_FORWARD_IP;
2757 action->len = F_INSN_SIZE(ipfw_insn_sa);
2760 * In the kernel we assume AF_INET and use only
2761 * sin_port and sin_addr.
2763 p->sa.sin_family = AF_INET;
2766 * locate the address-port separator (':' or ',')
2768 s = strchr(*av, ':');
2770 s = strchr(*av, ',');
2773 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
2776 "illegal forwarding port ``%s''", s);
2777 p->sa.sin_port = (u_short)i;
2779 if (_substrcmp(*av, "tablearg") == 0)
2780 p->sa.sin_addr.s_addr = INADDR_ANY;
2782 lookup_host(*av, &(p->sa.sin_addr));
2787 /* pretend it is a 'count' rule followed by the comment */
2788 action->opcode = O_COUNT;
2789 ac++; av--; /* go back... */
2795 size_t intsize = sizeof(int);
2797 action->opcode = O_SETFIB;
2798 NEED1("missing fib number");
2799 action->arg1 = strtoul(*av, NULL, 10);
2800 if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
2801 errx(EX_DATAERR, "fibs not suported.\n");
2802 if (action->arg1 >= numfibs) /* Temporary */
2803 errx(EX_DATAERR, "fib too large.\n");
2809 action->opcode = O_REASS;
2813 errx(EX_DATAERR, "invalid action %s\n", av[-1]);
2815 action = next_cmd(action);
2818 * [altq queuename] -- altq tag, optional
2819 * [log [logamount N]] -- log, optional
2821 * If they exist, it go first in the cmdbuf, but then it is
2822 * skipped in the copy section to the end of the buffer.
2824 while (ac != 0 && (i = match_token(rule_action_params, *av)) != -1) {
2829 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
2834 "log cannot be specified more than once");
2835 have_log = (ipfw_insn *)c;
2836 cmd->len = F_INSN_SIZE(ipfw_insn_log);
2837 cmd->opcode = O_LOG;
2838 if (ac && _substrcmp(*av, "logamount") == 0) {
2840 NEED1("logamount requires argument");
2844 "logamount must be positive");
2848 len = sizeof(c->max_log);
2849 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
2850 &c->max_log, &len, NULL, 0) == -1)
2851 errx(1, "sysctlbyname(\"%s\")",
2852 "net.inet.ip.fw.verbose_limit");
2859 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
2861 NEED1("missing altq queue name");
2864 "altq cannot be specified more than once");
2865 have_altq = (ipfw_insn *)a;
2866 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
2867 cmd->opcode = O_ALTQ;
2868 a->qid = altq_name_to_qid(*av);
2878 errx(EX_USAGE, "tag and untag cannot be "
2879 "specified more than once");
2880 GET_UINT_ARG(tag, 1, IPFW_DEFAULT_RULE - 1, i,
2881 rule_action_params);
2883 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
2891 cmd = next_cmd(cmd);
2894 if (have_state) /* must be a check-state, we are done */
2897 #define OR_START(target) \
2898 if (ac && (*av[0] == '(' || *av[0] == '{')) { \
2900 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
2903 if ( (av[0])[1] == '\0') { \
2914 strcmp(*av, ")") == 0 || \
2915 strcmp(*av, "}") == 0)) { \
2920 errx(EX_USAGE, "missing \")\"\n"); \
2924 if (ac && _substrcmp(*av, "not") == 0) { \
2925 if (cmd->len & F_NOT) \
2926 errx(EX_USAGE, "double \"not\" not allowed\n"); \
2927 cmd->len |= F_NOT; \
2931 #define OR_BLOCK(target) \
2932 if (ac && _substrcmp(*av, "or") == 0) { \
2933 if (prev == NULL || open_par == 0) \
2934 errx(EX_DATAERR, "invalid OR block"); \
2935 prev->len |= F_OR; \
2945 * MAC addresses, optional.
2946 * If we have this, we skip the part "proto from src to dst"
2947 * and jump straight to the option parsing.
2950 NEED1("missing protocol");
2951 if (_substrcmp(*av, "MAC") == 0 ||
2952 _substrcmp(*av, "mac") == 0) {
2953 ac--; av++; /* the "MAC" keyword */
2954 add_mac(cmd, ac, av); /* exits in case of errors */
2955 cmd = next_cmd(cmd);
2956 ac -= 2; av += 2; /* dst-mac and src-mac */
2958 NEED1("missing mac type");
2959 if (add_mactype(cmd, ac, av[0]))
2960 cmd = next_cmd(cmd);
2961 ac--; av++; /* any or mac-type */
2967 * protocol, mandatory
2969 OR_START(get_proto);
2971 NEED1("missing protocol");
2972 if (add_proto_compat(cmd, *av, &proto)) {
2974 if (F_LEN(cmd) != 0) {
2976 cmd = next_cmd(cmd);
2978 } else if (first_cmd != cmd) {
2979 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
2982 OR_BLOCK(get_proto);
2987 if (!ac || _substrcmp(*av, "from") != 0)
2988 errx(EX_USAGE, "missing ``from''");
2992 * source IP, mandatory
2994 OR_START(source_ip);
2995 NOT_BLOCK; /* optional "not" */
2996 NEED1("missing source address");
2997 if (add_src(cmd, *av, proto)) {
2999 if (F_LEN(cmd) != 0) { /* ! any */
3001 cmd = next_cmd(cmd);
3004 errx(EX_USAGE, "bad source address %s", *av);
3005 OR_BLOCK(source_ip);
3008 * source ports, optional
3010 NOT_BLOCK; /* optional "not" */
3012 if (_substrcmp(*av, "any") == 0 ||
3013 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
3015 if (F_LEN(cmd) != 0)
3016 cmd = next_cmd(cmd);
3023 if (!ac || _substrcmp(*av, "to") != 0)
3024 errx(EX_USAGE, "missing ``to''");
3028 * destination, mandatory
3031 NOT_BLOCK; /* optional "not" */
3032 NEED1("missing dst address");
3033 if (add_dst(cmd, *av, proto)) {
3035 if (F_LEN(cmd) != 0) { /* ! any */
3037 cmd = next_cmd(cmd);
3040 errx( EX_USAGE, "bad destination address %s", *av);
3044 * dest. ports, optional
3046 NOT_BLOCK; /* optional "not" */
3048 if (_substrcmp(*av, "any") == 0 ||
3049 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
3051 if (F_LEN(cmd) != 0)
3052 cmd = next_cmd(cmd);
3057 if (ac && first_cmd == cmd) {
3059 * nothing specified so far, store in the rule to ease
3067 ipfw_insn_u32 *cmd32; /* alias for cmd */
3070 cmd32 = (ipfw_insn_u32 *)cmd;
3072 if (*s == '!') { /* alternate syntax for NOT */
3073 if (cmd->len & F_NOT)
3074 errx(EX_USAGE, "double \"not\" not allowed\n");
3078 i = match_token(rule_options, s);
3082 if (cmd->len & F_NOT)
3083 errx(EX_USAGE, "double \"not\" not allowed\n");
3088 if (open_par == 0 || prev == NULL)
3089 errx(EX_USAGE, "invalid \"or\" block\n");
3093 case TOK_STARTBRACE:
3095 errx(EX_USAGE, "+nested \"(\" not allowed\n");
3101 errx(EX_USAGE, "+missing \")\"\n");
3107 fill_cmd(cmd, O_IN, 0, 0);
3111 cmd->len ^= F_NOT; /* toggle F_NOT */
3112 fill_cmd(cmd, O_IN, 0, 0);
3116 fill_cmd(cmd, O_DIVERTED, 0, 3);
3119 case TOK_DIVERTEDLOOPBACK:
3120 fill_cmd(cmd, O_DIVERTED, 0, 1);
3123 case TOK_DIVERTEDOUTPUT:
3124 fill_cmd(cmd, O_DIVERTED, 0, 2);
3128 fill_cmd(cmd, O_FRAG, 0, 0);
3132 fill_cmd(cmd, O_LAYER2, 0, 0);
3138 NEED1("recv, xmit, via require interface name"
3140 fill_iface((ipfw_insn_if *)cmd, av[0]);
3142 if (F_LEN(cmd) == 0) /* not a valid address */
3145 cmd->opcode = O_XMIT;
3146 else if (i == TOK_RECV)
3147 cmd->opcode = O_RECV;
3148 else if (i == TOK_VIA)
3149 cmd->opcode = O_VIA;
3153 NEED1("icmptypes requires list of types");
3154 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
3158 case TOK_ICMP6TYPES:
3159 NEED1("icmptypes requires list of types");
3160 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av);
3165 NEED1("ipttl requires TTL");
3166 if (strpbrk(*av, "-,")) {
3167 if (!add_ports(cmd, *av, 0, O_IPTTL))
3168 errx(EX_DATAERR, "invalid ipttl %s", *av);
3170 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
3175 NEED1("ipid requires id");
3176 if (strpbrk(*av, "-,")) {
3177 if (!add_ports(cmd, *av, 0, O_IPID))
3178 errx(EX_DATAERR, "invalid ipid %s", *av);
3180 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
3185 NEED1("iplen requires length");
3186 if (strpbrk(*av, "-,")) {
3187 if (!add_ports(cmd, *av, 0, O_IPLEN))
3188 errx(EX_DATAERR, "invalid ip len %s", *av);
3190 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
3195 NEED1("ipver requires version");
3196 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
3200 case TOK_IPPRECEDENCE:
3201 NEED1("ipprecedence requires value");
3202 fill_cmd(cmd, O_IPPRECEDENCE, 0,
3203 (strtoul(*av, NULL, 0) & 7) << 5);
3208 NEED1("missing argument for ipoptions");
3209 fill_flags(cmd, O_IPOPT, f_ipopts, *av);
3214 NEED1("missing argument for iptos");
3215 fill_flags(cmd, O_IPTOS, f_iptos, *av);
3220 NEED1("uid requires argument");
3226 cmd->opcode = O_UID;
3227 uid = strtoul(*av, &end, 0);
3228 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
3230 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
3231 cmd32->d[0] = pwd->pw_uid;
3232 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3238 NEED1("gid requires argument");
3244 cmd->opcode = O_GID;
3245 gid = strtoul(*av, &end, 0);
3246 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
3248 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
3249 cmd32->d[0] = grp->gr_gid;
3250 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3256 NEED1("jail requires argument");
3261 cmd->opcode = O_JAIL;
3262 jid = (int)strtol(*av, &end, 0);
3263 if (jid < 0 || *end != '\0')
3264 errx(EX_DATAERR, "jail requires prison ID");
3265 cmd32->d[0] = (uint32_t)jid;
3266 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3272 fill_cmd(cmd, O_ESTAB, 0, 0);
3276 fill_cmd(cmd, O_TCPFLAGS, 0,
3277 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
3280 case TOK_TCPDATALEN:
3281 NEED1("tcpdatalen requires length");
3282 if (strpbrk(*av, "-,")) {
3283 if (!add_ports(cmd, *av, 0, O_TCPDATALEN))
3284 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
3286 fill_cmd(cmd, O_TCPDATALEN, 0,
3287 strtoul(*av, NULL, 0));
3292 NEED1("missing argument for tcpoptions");
3293 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
3299 NEED1("tcpseq/tcpack requires argument");
3300 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3301 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
3302 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
3307 NEED1("tcpwin requires length");
3308 fill_cmd(cmd, O_TCPWIN, 0,
3309 htons(strtoul(*av, NULL, 0)));
3314 NEED1("missing argument for tcpflags");
3315 cmd->opcode = O_TCPFLAGS;
3316 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
3322 errx(EX_USAGE, "keep-state cannot be part "
3325 errx(EX_USAGE, "only one of keep-state "
3326 "and limit is allowed");
3328 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
3332 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
3337 "limit cannot be part of an or block");
3339 errx(EX_USAGE, "only one of keep-state and "
3340 "limit is allowed");
3343 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
3344 cmd->opcode = O_LIMIT;
3345 c->limit_mask = c->conn_limit = 0;
3348 if ((val = match_token(limit_masks, *av)) <= 0)
3350 c->limit_mask |= val;
3354 if (c->limit_mask == 0)
3355 errx(EX_USAGE, "limit: missing limit mask");
3357 GET_UINT_ARG(c->conn_limit, 1, IPFW_DEFAULT_RULE - 1,
3358 TOK_LIMIT, rule_options);
3365 NEED1("missing protocol");
3366 if (add_proto(cmd, *av, &proto)) {
3369 errx(EX_DATAERR, "invalid protocol ``%s''",
3374 NEED1("missing source IP");
3375 if (add_srcip(cmd, *av)) {
3381 NEED1("missing destination IP");
3382 if (add_dstip(cmd, *av)) {
3388 NEED1("missing source IP6");
3389 if (add_srcip6(cmd, *av)) {
3395 NEED1("missing destination IP6");
3396 if (add_dstip6(cmd, *av)) {
3402 NEED1("missing source port");
3403 if (_substrcmp(*av, "any") == 0 ||
3404 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
3407 errx(EX_DATAERR, "invalid source port %s", *av);
3411 NEED1("missing destination port");
3412 if (_substrcmp(*av, "any") == 0 ||
3413 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
3416 errx(EX_DATAERR, "invalid destination port %s",
3421 if (add_mac(cmd, ac, av)) {
3427 NEED1("missing mac type");
3428 if (!add_mactype(cmd, ac, *av))
3429 errx(EX_DATAERR, "invalid mac type %s", *av);
3433 case TOK_VERREVPATH:
3434 fill_cmd(cmd, O_VERREVPATH, 0, 0);
3437 case TOK_VERSRCREACH:
3438 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
3442 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
3446 fill_cmd(cmd, O_IPSEC, 0, 0);
3450 fill_cmd(cmd, O_IP6, 0, 0);
3454 fill_cmd(cmd, O_IP4, 0, 0);
3458 fill_ext6hdr( cmd, *av );
3463 if (proto != IPPROTO_IPV6 )
3464 errx( EX_USAGE, "flow-id filter is active "
3465 "only for ipv6 protocol\n");
3466 fill_flow6( (ipfw_insn_u32 *) cmd, *av );
3471 fill_comment(cmd, ac, av);
3477 if (ac > 0 && strpbrk(*av, "-,")) {
3478 if (!add_ports(cmd, *av, 0, O_TAGGED))
3479 errx(EX_DATAERR, "tagged: invalid tag"
3485 GET_UINT_ARG(tag, 1, IPFW_DEFAULT_RULE - 1,
3486 TOK_TAGGED, rule_options);
3487 fill_cmd(cmd, O_TAGGED, 0, tag);
3493 NEED1("fib requires fib number");
3494 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
3499 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
3501 if (F_LEN(cmd) > 0) { /* prepare to advance */
3503 cmd = next_cmd(cmd);
3509 * Now copy stuff into the rule.
3510 * If we have a keep-state option, the first instruction
3511 * must be a PROBE_STATE (which is generated here).
3512 * If we have a LOG option, it was stored as the first command,
3513 * and now must be moved to the top of the action part.
3515 dst = (ipfw_insn *)rule->cmd;
3518 * First thing to write into the command stream is the match probability.
3520 if (match_prob != 1) { /* 1 means always match */
3521 dst->opcode = O_PROB;
3523 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
3528 * generate O_PROBE_STATE if necessary
3530 if (have_state && have_state->opcode != O_CHECK_STATE) {
3531 fill_cmd(dst, O_PROBE_STATE, 0, 0);
3532 dst = next_cmd(dst);
3535 /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
3536 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
3539 switch (src->opcode) {
3547 bcopy(src, dst, i * sizeof(uint32_t));
3553 * put back the have_state command as last opcode
3555 if (have_state && have_state->opcode != O_CHECK_STATE) {
3556 i = F_LEN(have_state);
3557 bcopy(have_state, dst, i * sizeof(uint32_t));
3561 * start action section
3563 rule->act_ofs = dst - rule->cmd;
3565 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
3567 i = F_LEN(have_log);
3568 bcopy(have_log, dst, i * sizeof(uint32_t));
3572 i = F_LEN(have_altq);
3573 bcopy(have_altq, dst, i * sizeof(uint32_t));
3577 i = F_LEN(have_tag);
3578 bcopy(have_tag, dst, i * sizeof(uint32_t));
3582 * copy all other actions
3584 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
3586 bcopy(src, dst, i * sizeof(uint32_t));
3590 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
3591 i = (char *)dst - (char *)rule;
3592 if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1)
3593 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
3595 show_ipfw(rule, 0, 0);
3599 * clear the counters or the log counters.
3602 ipfw_zero(int ac, char *av[], int optname /* 0 = IP_FW_ZERO, 1 = IP_FW_RESETLOG */)
3604 uint32_t arg, saved_arg;
3607 char const *name = optname ? "RESETLOG" : "ZERO";
3609 optname = optname ? IP_FW_RESETLOG : IP_FW_ZERO;
3614 /* clear all entries */
3615 if (do_cmd(optname, NULL, 0) < 0)
3616 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name);
3618 printf("%s.\n", optname == IP_FW_ZERO ?
3619 "Accounting cleared":"Logging counts reset");
3626 if (isdigit(**av)) {
3627 arg = strtonum(*av, 0, 0xffff, &errstr);
3630 "invalid rule number %s\n", *av);
3633 arg |= (1 << 24) | ((co.use_set - 1) << 16);
3636 if (do_cmd(optname, &arg, sizeof(arg))) {
3637 warn("rule %u: setsockopt(IP_FW_%s)",
3639 failed = EX_UNAVAILABLE;
3640 } else if (!co.do_quiet)
3641 printf("Entry %d %s.\n", saved_arg,
3642 optname == IP_FW_ZERO ?
3643 "cleared" : "logging count reset");
3645 errx(EX_USAGE, "invalid rule number ``%s''", *av);
3648 if (failed != EX_OK)
3653 ipfw_flush(int force)
3655 int cmd = co.do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
3657 if (!force && !co.do_quiet) { /* need to ask user */
3660 printf("Are you sure? [yn] ");
3663 c = toupper(getc(stdin));
3664 while (c != '\n' && getc(stdin) != '\n')
3666 return; /* and do not flush */
3667 } while (c != 'Y' && c != 'N');
3669 if (c == 'N') /* user said no */
3672 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
3674 uint32_t arg = ((co.use_set - 1) & 0xffff) | (1 << 24);
3675 if (do_cmd(IP_FW_DEL, &arg, sizeof(arg)) < 0)
3676 err(EX_UNAVAILABLE, "setsockopt(IP_FW_DEL)");
3677 } else if (do_cmd(cmd, NULL, 0) < 0)
3678 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
3679 co.do_pipe ? "DUMMYNET" : "FW");
3681 printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
3685 static void table_list(ipfw_table_entry ent, int need_header);
3688 * This one handles all table-related commands
3689 * ipfw table N add addr[/masklen] [value]
3690 * ipfw table N delete addr[/masklen]
3691 * ipfw table {N | all} flush
3692 * ipfw table {N | all} list
3695 ipfw_table_handler(int ac, char *av[])
3697 ipfw_table_entry ent;
3703 uint32_t tables_max;
3705 len = sizeof(tables_max);
3706 if (sysctlbyname("net.inet.ip.fw.tables_max", &tables_max, &len,
3708 #ifdef IPFW_TABLES_MAX
3709 warn("Warn: Failed to get the max tables number via sysctl. "
3710 "Using the compiled in defaults. \nThe reason was");
3711 tables_max = IPFW_TABLES_MAX;
3713 errx(1, "Failed sysctlbyname(\"net.inet.ip.fw.tables_max\")");
3718 if (ac && isdigit(**av)) {
3719 ent.tbl = atoi(*av);
3722 } else if (ac && _substrcmp(*av, "all") == 0) {
3727 errx(EX_USAGE, "table number or 'all' keyword required");
3728 if (ent.tbl >= tables_max)
3729 errx(EX_USAGE, "The table number exceeds the maximum allowed "
3730 "value (%d)", tables_max - 1);
3731 NEED1("table needs command");
3732 if (is_all && _substrcmp(*av, "list") != 0
3733 && _substrcmp(*av, "flush") != 0)
3734 errx(EX_USAGE, "table number required");
3736 if (_substrcmp(*av, "add") == 0 ||
3737 _substrcmp(*av, "delete") == 0) {
3738 do_add = **av == 'a';
3741 errx(EX_USAGE, "IP address required");
3742 p = strchr(*av, '/');
3745 ent.masklen = atoi(p);
3746 if (ent.masklen > 32)
3747 errx(EX_DATAERR, "bad width ``%s''", p);
3750 if (lookup_host(*av, (struct in_addr *)&ent.addr) != 0)
3751 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
3755 /* isdigit is a bit of a hack here.. */
3756 if (strchr(*av, (int)'.') == NULL && isdigit(**av)) {
3757 ent.value = strtoul(*av, NULL, 0);
3759 if (lookup_host(*av, (struct in_addr *)&tval) == 0) {
3760 /* The value must be stored in host order *
3761 * so that the values < 65k can be distinguished */
3762 ent.value = ntohl(tval);
3764 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
3769 if (do_cmd(do_add ? IP_FW_TABLE_ADD : IP_FW_TABLE_DEL,
3770 &ent, sizeof(ent)) < 0) {
3771 /* If running silent, don't bomb out on these errors. */
3772 if (!(co.do_quiet && (errno == (do_add ? EEXIST : ESRCH))))
3773 err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)",
3774 do_add ? "ADD" : "DEL");
3775 /* In silent mode, react to a failed add by deleting */
3777 do_cmd(IP_FW_TABLE_DEL, &ent, sizeof(ent));
3778 if (do_cmd(IP_FW_TABLE_ADD,
3779 &ent, sizeof(ent)) < 0)
3781 "setsockopt(IP_FW_TABLE_ADD)");
3784 } else if (_substrcmp(*av, "flush") == 0) {
3785 a = is_all ? tables_max : (ent.tbl + 1);
3787 if (do_cmd(IP_FW_TABLE_FLUSH, &ent.tbl,
3788 sizeof(ent.tbl)) < 0)
3789 err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)");
3790 } while (++ent.tbl < a);
3791 } else if (_substrcmp(*av, "list") == 0) {
3792 a = is_all ? tables_max : (ent.tbl + 1);
3794 table_list(ent, is_all);
3795 } while (++ent.tbl < a);
3797 errx(EX_USAGE, "invalid table command %s", *av);
3801 table_list(ipfw_table_entry ent, int need_header)
3809 if (do_cmd(IP_FW_TABLE_GETSIZE, &a, (uintptr_t)&l) < 0)
3810 err(EX_OSERR, "getsockopt(IP_FW_TABLE_GETSIZE)");
3812 /* If a is zero we have nothing to do, the table is empty. */
3816 l = sizeof(*tbl) + a * sizeof(ipfw_table_entry);
3817 tbl = safe_calloc(1, l);
3819 if (do_cmd(IP_FW_TABLE_LIST, tbl, (uintptr_t)&l) < 0)
3820 err(EX_OSERR, "getsockopt(IP_FW_TABLE_LIST)");
3821 if (tbl->cnt && need_header)
3822 printf("---table(%d)---\n", tbl->tbl);
3823 for (a = 0; a < tbl->cnt; a++) {
3825 tval = tbl->ent[a].value;
3826 if (co.do_value_as_ip) {
3828 strncpy(tbuf, inet_ntoa(*(struct in_addr *)
3829 &tbl->ent[a].addr), 127);
3830 /* inet_ntoa expects network order */
3832 printf("%s/%u %s\n", tbuf, tbl->ent[a].masklen,
3833 inet_ntoa(*(struct in_addr *)&tval));
3835 printf("%s/%u %u\n",
3836 inet_ntoa(*(struct in_addr *)&tbl->ent[a].addr),
3837 tbl->ent[a].masklen, tval);