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/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 _xval = strtol(*av, &end, 10); \
73 if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
74 errx(EX_DATAERR, "%s: invalid argument: %s", \
75 match_value(s_x, tok), *av); \
77 if (errno == ERANGE || _xval < min || _xval > 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 (_xval == 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 */
228 * The 'lookup' instruction accepts one of the following arguments.
229 * -1 is a terminator for the list.
230 * Arguments are passed as v[1] in O_DST_LOOKUP options.
232 static int lookup_key[] = {
233 TOK_DSTIP, TOK_SRCIP, TOK_DSTPORT, TOK_SRCPORT,
234 TOK_UID, TOK_JAIL, TOK_DSCP, -1 };
236 static struct _s_x rule_options[] = {
237 { "tagged", TOK_TAGGED },
240 { "jail", TOK_JAIL },
242 { "limit", TOK_LIMIT },
243 { "keep-state", TOK_KEEPSTATE },
244 { "bridged", TOK_LAYER2 },
245 { "layer2", TOK_LAYER2 },
247 { "diverted", TOK_DIVERTED },
248 { "diverted-loopback", TOK_DIVERTEDLOOPBACK },
249 { "diverted-output", TOK_DIVERTEDOUTPUT },
250 { "xmit", TOK_XMIT },
251 { "recv", TOK_RECV },
253 { "fragment", TOK_FRAG },
254 { "frag", TOK_FRAG },
256 { "ipoptions", TOK_IPOPTS },
257 { "ipopts", TOK_IPOPTS },
258 { "iplen", TOK_IPLEN },
259 { "ipid", TOK_IPID },
260 { "ipprecedence", TOK_IPPRECEDENCE },
261 { "dscp", TOK_DSCP },
262 { "iptos", TOK_IPTOS },
263 { "ipttl", TOK_IPTTL },
264 { "ipversion", TOK_IPVER },
265 { "ipver", TOK_IPVER },
266 { "estab", TOK_ESTAB },
267 { "established", TOK_ESTAB },
268 { "setup", TOK_SETUP },
269 { "tcpdatalen", TOK_TCPDATALEN },
270 { "tcpflags", TOK_TCPFLAGS },
271 { "tcpflgs", TOK_TCPFLAGS },
272 { "tcpoptions", TOK_TCPOPTS },
273 { "tcpopts", TOK_TCPOPTS },
274 { "tcpseq", TOK_TCPSEQ },
275 { "tcpack", TOK_TCPACK },
276 { "tcpwin", TOK_TCPWIN },
277 { "icmptype", TOK_ICMPTYPES },
278 { "icmptypes", TOK_ICMPTYPES },
279 { "dst-ip", TOK_DSTIP },
280 { "src-ip", TOK_SRCIP },
281 { "dst-port", TOK_DSTPORT },
282 { "src-port", TOK_SRCPORT },
283 { "proto", TOK_PROTO },
286 { "mac-type", TOK_MACTYPE },
287 { "verrevpath", TOK_VERREVPATH },
288 { "versrcreach", TOK_VERSRCREACH },
289 { "antispoof", TOK_ANTISPOOF },
290 { "ipsec", TOK_IPSEC },
291 { "icmp6type", TOK_ICMP6TYPES },
292 { "icmp6types", TOK_ICMP6TYPES },
293 { "ext6hdr", TOK_EXT6HDR},
294 { "flow-id", TOK_FLOWID},
299 { "dst-ipv6", TOK_DSTIP6},
300 { "dst-ip6", TOK_DSTIP6},
301 { "src-ipv6", TOK_SRCIP6},
302 { "src-ip6", TOK_SRCIP6},
303 { "lookup", TOK_LOOKUP},
304 { "//", TOK_COMMENT },
306 { "not", TOK_NOT }, /* pseudo option */
307 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
308 { "or", TOK_OR }, /* pseudo option */
309 { "|", /* escape */ TOK_OR }, /* pseudo option */
310 { "{", TOK_STARTBRACE }, /* pseudo option */
311 { "(", TOK_STARTBRACE }, /* pseudo option */
312 { "}", TOK_ENDBRACE }, /* pseudo option */
313 { ")", TOK_ENDBRACE }, /* pseudo option */
314 { NULL, 0 } /* terminator */
318 * The following is used to generate a printable argument for
319 * 64-bit numbers, irrespective of platform alignment and bit size.
320 * Because all the printf in this program use %llu as a format,
321 * we just return an unsigned long long, which is larger than
322 * we need in certain cases, but saves the hassle of using
323 * PRIu64 as a format specifier.
324 * We don't care about inlining, this is not performance critical code.
327 align_uint64(const uint64_t *pll)
331 bcopy (pll, &ret, sizeof(ret));
336 safe_calloc(size_t number, size_t size)
338 void *ret = calloc(number, size);
341 err(EX_OSERR, "calloc");
346 safe_realloc(void *ptr, size_t size)
348 void *ret = realloc(ptr, size);
351 err(EX_OSERR, "realloc");
356 * conditionally runs the command.
357 * Selected options or negative -> getsockopt
360 do_cmd(int optname, void *optval, uintptr_t optlen)
362 static int s = -1; /* the socket */
369 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
371 err(EX_UNAVAILABLE, "socket");
373 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
374 optname == IP_FW_ADD || optname == IP_FW_TABLE_LIST ||
375 optname == IP_FW_TABLE_GETSIZE ||
376 optname == IP_FW_NAT_GET_CONFIG ||
378 optname == IP_FW_NAT_GET_LOG) {
381 i = getsockopt(s, IPPROTO_IP, optname, optval,
382 (socklen_t *)optlen);
384 i = setsockopt(s, IPPROTO_IP, optname, optval, optlen);
390 * match_token takes a table and a string, returns the value associated
391 * with the string (-1 in case of failure).
394 match_token(struct _s_x *table, char *string)
397 uint i = strlen(string);
399 for (pt = table ; i && pt->s != NULL ; pt++)
400 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
406 * match_value takes a table and a value, returns the string associated
407 * with the value (NULL in case of failure).
410 match_value(struct _s_x *p, int value)
412 for (; p->s != NULL; p++)
419 * _substrcmp takes two strings and returns 1 if they do not match,
420 * and 0 if they match exactly or the first string is a sub-string
421 * of the second. A warning is printed to stderr in the case that the
422 * first string is a sub-string of the second.
424 * This function will be removed in the future through the usual
425 * deprecation process.
428 _substrcmp(const char *str1, const char* str2)
431 if (strncmp(str1, str2, strlen(str1)) != 0)
434 if (strlen(str1) != strlen(str2))
435 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
441 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
442 * and 0 if they match exactly or the second string is a sub-string
443 * of the first. A warning is printed to stderr in the case that the
444 * first string does not match the third.
446 * This function exists to warn about the bizzare construction
447 * strncmp(str, "by", 2) which is used to allow people to use a shotcut
448 * for "bytes". The problem is that in addition to accepting "by",
449 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
450 * other string beginning with "by".
452 * This function will be removed in the future through the usual
453 * deprecation process.
456 _substrcmp2(const char *str1, const char* str2, const char* str3)
459 if (strncmp(str1, str2, strlen(str2)) != 0)
462 if (strcmp(str1, str3) != 0)
463 warnx("DEPRECATED: '%s' matched '%s'",
469 * prints one port, symbolic or numeric
472 print_port(int proto, uint16_t port)
475 if (proto == IPPROTO_ETHERTYPE) {
478 if (co.do_resolv && (s = match_value(ether_types, port)) )
481 printf("0x%04x", port);
483 struct servent *se = NULL;
485 struct protoent *pe = getprotobynumber(proto);
487 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
490 printf("%s", se->s_name);
496 static struct _s_x _port_name[] = {
497 {"dst-port", O_IP_DSTPORT},
498 {"src-port", O_IP_SRCPORT},
502 {"mac-type", O_MAC_TYPE},
503 {"tcpdatalen", O_TCPDATALEN},
504 {"tagged", O_TAGGED},
509 * Print the values in a list 16-bit items of the types above.
510 * XXX todo: add support for mask.
513 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode)
515 uint16_t *p = cmd->ports;
520 sep = match_value(_port_name, opcode);
526 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
528 print_port(proto, p[0]);
531 print_port(proto, p[1]);
538 * Like strtol, but also translates service names into port numbers
539 * for some protocols.
541 * proto == -1 disables the protocol check;
542 * proto == IPPROTO_ETHERTYPE looks up an internal table
543 * proto == <some value in /etc/protocols> matches the values there.
544 * Returns *end == s in case the parameter is not found.
547 strtoport(char *s, char **end, int base, int proto)
553 *end = s; /* default - not found */
555 return 0; /* not found */
558 return strtol(s, end, base);
561 * find separator. '\\' escapes the next char.
563 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
564 if (*s1 == '\\' && s1[1] != '\0')
567 buf = safe_calloc(s1 - s + 1, 1);
570 * copy into a buffer skipping backslashes
572 for (p = s, i = 0; p != s1 ; p++)
577 if (proto == IPPROTO_ETHERTYPE) {
578 i = match_token(ether_types, buf);
580 if (i != -1) { /* found */
585 struct protoent *pe = NULL;
589 pe = getprotobynumber(proto);
591 se = getservbyname(buf, pe ? pe->p_name : NULL);
595 return ntohs(se->s_port);
598 return 0; /* not found */
602 * Fill the body of the command with the list of port ranges.
605 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto)
607 uint16_t a, b, *p = cmd->ports;
612 a = strtoport(av, &s, 0, proto);
613 if (s == av) /* empty or invalid argument */
617 case '-': /* a range */
619 b = strtoport(av, &s, 0, proto);
620 /* Reject expressions like '1-abc' or '1-2-3'. */
621 if (s == av || (*s != ',' && *s != '\0'))
626 case ',': /* comma separated list */
631 warnx("port list: invalid separator <%c> in <%s>",
641 if (i + 1 > F_LEN_MASK)
642 errx(EX_DATAERR, "too many ports/ranges\n");
643 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
648 static struct _s_x icmpcodes[] = {
649 { "net", ICMP_UNREACH_NET },
650 { "host", ICMP_UNREACH_HOST },
651 { "protocol", ICMP_UNREACH_PROTOCOL },
652 { "port", ICMP_UNREACH_PORT },
653 { "needfrag", ICMP_UNREACH_NEEDFRAG },
654 { "srcfail", ICMP_UNREACH_SRCFAIL },
655 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
656 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
657 { "isolated", ICMP_UNREACH_ISOLATED },
658 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
659 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
660 { "tosnet", ICMP_UNREACH_TOSNET },
661 { "toshost", ICMP_UNREACH_TOSHOST },
662 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
663 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
664 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
669 fill_reject_code(u_short *codep, char *str)
674 val = strtoul(str, &s, 0);
675 if (s == str || *s != '\0' || val >= 0x100)
676 val = match_token(icmpcodes, str);
678 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
684 print_reject_code(uint16_t code)
686 char const *s = match_value(icmpcodes, code);
689 printf("unreach %s", s);
691 printf("unreach %u", code);
695 * Returns the number of bits set (from left) in a contiguous bitmask,
696 * or -1 if the mask is not contiguous.
697 * XXX this needs a proper fix.
698 * This effectively works on masks in big-endian (network) format.
699 * when compiled on little endian architectures.
701 * First bit is bit 7 of the first byte -- note, for MAC addresses,
702 * the first bit on the wire is bit 0 of the first byte.
703 * len is the max length in bits.
706 contigmask(uint8_t *p, int len)
710 for (i=0; i<len ; i++)
711 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
713 for (n=i+1; n < len; n++)
714 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
715 return -1; /* mask not contiguous */
720 * print flags set/clear in the two bitmasks passed as parameters.
721 * There is a specialized check for f_tcpflags.
724 print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list)
726 char const *comma = "";
728 uint8_t set = cmd->arg1 & 0xff;
729 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
731 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
736 printf(" %s ", name);
737 for (i=0; list[i].x != 0; i++) {
738 if (set & list[i].x) {
740 printf("%s%s", comma, list[i].s);
743 if (clear & list[i].x) {
745 printf("%s!%s", comma, list[i].s);
752 * Print the ip address contained in a command.
755 print_ip(ipfw_insn_ip *cmd, char const *s)
757 struct hostent *he = NULL;
758 uint32_t len = F_LEN((ipfw_insn *)cmd);
759 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
761 if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
763 const char *arg = "<invalid>";
765 if (d < sizeof(lookup_key)/sizeof(lookup_key[0]))
766 arg = match_value(rule_options, lookup_key[d]);
767 printf("%s lookup %s %d", cmd->o.len & F_NOT ? " not": "",
771 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
773 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
777 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
778 cmd->o.opcode == O_IP_DST_LOOKUP) {
779 printf("table(%u", ((ipfw_insn *)cmd)->arg1);
780 if (len == F_INSN_SIZE(ipfw_insn_u32))
785 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
786 uint32_t x, *map = (uint32_t *)&(cmd->mask);
792 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
793 printf("%s/%d", inet_ntoa(cmd->addr),
794 contigmask((uint8_t *)&x, 32));
795 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
796 x &= 0xff; /* base */
798 * Print bits and ranges.
799 * Locate first bit set (i), then locate first bit unset (j).
800 * If we have 3+ consecutive bits set, then print them as a
801 * range, otherwise only print the initial bit and rescan.
803 for (i=0; i < cmd->o.arg1; i++)
804 if (map[i/32] & (1<<(i & 31))) {
805 for (j=i+1; j < cmd->o.arg1; j++)
806 if (!(map[ j/32] & (1<<(j & 31))))
808 printf("%c%d", comma, i+x);
809 if (j>i+2) { /* range has at least 3 elements */
810 printf("-%d", j-1+x);
819 * len == 2 indicates a single IP, whereas lists of 1 or more
820 * addr/mask pairs have len = (2n+1). We convert len to n so we
821 * use that to count the number of entries.
823 for (len = len / 2; len > 0; len--, a += 2) {
824 int mb = /* mask length */
825 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
826 32 : contigmask((uint8_t *)&(a[1]), 32);
827 if (mb == 32 && co.do_resolv)
828 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
829 if (he != NULL) /* resolved to name */
830 printf("%s", he->h_name);
831 else if (mb == 0) /* any */
833 else { /* numeric IP followed by some kind of mask */
834 printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) );
836 printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) );
846 * prints a MAC address/mask pair
849 print_mac(uint8_t *addr, uint8_t *mask)
851 int l = contigmask(mask, 48);
856 printf(" %02x:%02x:%02x:%02x:%02x:%02x",
857 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
859 printf("&%02x:%02x:%02x:%02x:%02x:%02x",
860 mask[0], mask[1], mask[2],
861 mask[3], mask[4], mask[5]);
868 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
877 type = strtoul(av, &av, 0);
879 if (*av != ',' && *av != '\0')
880 errx(EX_DATAERR, "invalid ICMP type");
883 errx(EX_DATAERR, "ICMP type out of range");
885 cmd->d[0] |= 1 << type;
887 cmd->o.opcode = O_ICMPTYPE;
888 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
892 print_icmptypes(ipfw_insn_u32 *cmd)
897 printf(" icmptypes");
898 for (i = 0; i < 32; i++) {
899 if ( (cmd->d[0] & (1 << (i))) == 0)
901 printf("%c%d", sep, i);
907 * show_ipfw() prints the body of an ipfw rule.
908 * Because the standard rule has at least proto src_ip dst_ip, we use
909 * a helper function to produce these entries if not provided explicitly.
910 * The first argument is the list of fields we have, the second is
911 * the list of fields we want to be printed.
913 * Special cases if we have provided a MAC header:
914 * + if the rule does not contain IP addresses/ports, do not print them;
915 * + if the rule does not contain an IP proto, print "all" instead of "ip";
917 * Once we have 'have_options', IP header fields are printed as options.
919 #define HAVE_PROTO 0x0001
920 #define HAVE_SRCIP 0x0002
921 #define HAVE_DSTIP 0x0004
922 #define HAVE_PROTO4 0x0008
923 #define HAVE_PROTO6 0x0010
924 #define HAVE_IP 0x0100
925 #define HAVE_OPTIONS 0x8000
928 show_prerequisites(int *flags, int want, int cmd __unused)
932 if ( (*flags & HAVE_IP) == HAVE_IP)
933 *flags |= HAVE_OPTIONS;
935 if ( !(*flags & HAVE_OPTIONS)) {
936 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) {
937 if ( (*flags & HAVE_PROTO4))
939 else if ( (*flags & HAVE_PROTO6))
944 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
946 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
953 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth)
955 static int twidth = 0;
957 ipfw_insn *cmd, *tagptr = NULL;
958 const char *comment = NULL; /* ptr to comment if we have one */
959 int proto = 0; /* default */
960 int flags = 0; /* prerequisites */
961 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
962 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
963 int or_block = 0; /* we are in an or block */
964 uint32_t set_disable;
966 bcopy(&rule->next_rule, &set_disable, sizeof(set_disable));
968 if (set_disable & (1 << rule->set)) { /* disabled */
972 printf("# DISABLED ");
974 printf("%05u ", rule->rulenum);
976 if (pcwidth>0 || bcwidth>0)
977 printf("%*llu %*llu ", pcwidth, align_uint64(&rule->pcnt),
978 bcwidth, align_uint64(&rule->bcnt));
981 printf("%10u ", rule->timestamp);
982 else if (co.do_time == 1) {
984 time_t t = (time_t)0;
987 strcpy(timestr, ctime(&t));
988 *strchr(timestr, '\n') = '\0';
989 twidth = strlen(timestr);
991 if (rule->timestamp) {
992 t = _long_to_time(rule->timestamp);
994 strcpy(timestr, ctime(&t));
995 *strchr(timestr, '\n') = '\0';
996 printf("%s ", timestr);
998 printf("%*s", twidth, " ");
1003 printf("set %d ", rule->set);
1006 * print the optional "match probability"
1008 if (rule->cmd_len > 0) {
1010 if (cmd->opcode == O_PROB) {
1011 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1012 double d = 1.0 * p->d[0];
1014 d = (d / 0x7fffffff);
1015 printf("prob %f ", d);
1020 * first print actions
1022 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1023 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1024 switch(cmd->opcode) {
1026 printf("check-state");
1027 /* avoid printing anything else */
1028 flags = HAVE_PROTO | HAVE_SRCIP |
1029 HAVE_DSTIP | HAVE_IP;
1045 if (cmd->arg1 == ICMP_REJECT_RST)
1047 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1050 print_reject_code(cmd->arg1);
1054 if (cmd->arg1 == ICMP6_UNREACH_RST)
1057 print_unreach6_code(cmd->arg1);
1061 PRINT_UINT_ARG("skipto ", cmd->arg1);
1065 PRINT_UINT_ARG("pipe ", cmd->arg1);
1069 PRINT_UINT_ARG("queue ", cmd->arg1);
1073 PRINT_UINT_ARG("divert ", cmd->arg1);
1077 PRINT_UINT_ARG("tee ", cmd->arg1);
1081 PRINT_UINT_ARG("netgraph ", cmd->arg1);
1085 PRINT_UINT_ARG("ngtee ", cmd->arg1);
1090 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1092 if (s->sa.sin_addr.s_addr == INADDR_ANY) {
1093 printf("fwd tablearg");
1095 printf("fwd %s", inet_ntoa(s->sa.sin_addr));
1098 printf(",%d", s->sa.sin_port);
1102 case O_LOG: /* O_LOG is printed last */
1103 logptr = (ipfw_insn_log *)cmd;
1106 case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1107 altqptr = (ipfw_insn_altq *)cmd;
1116 PRINT_UINT_ARG("nat ", cmd->arg1);
1118 printf("nat global");
1122 PRINT_UINT_ARG("setfib ", cmd->arg1);
1130 printf("** unrecognized action %d len %d ",
1131 cmd->opcode, cmd->len);
1135 if (logptr->max_log > 0)
1136 printf(" log logamount %d", logptr->max_log);
1142 print_altq_cmd(altqptr);
1146 if (tagptr->len & F_NOT)
1147 PRINT_UINT_ARG(" untag ", tagptr->arg1);
1149 PRINT_UINT_ARG(" tag ", tagptr->arg1);
1153 * then print the body.
1155 for (l = rule->act_ofs, cmd = rule->cmd ;
1156 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1157 if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1159 if (cmd->opcode == O_IP4) {
1160 flags |= HAVE_PROTO4;
1162 } else if (cmd->opcode == O_IP6) {
1163 flags |= HAVE_PROTO6;
1167 if (rule->_pad & 1) { /* empty rules before options */
1168 if (!co.do_compact) {
1169 show_prerequisites(&flags, HAVE_PROTO, 0);
1170 printf(" from any to any");
1172 flags |= HAVE_IP | HAVE_OPTIONS | HAVE_PROTO |
1173 HAVE_SRCIP | HAVE_DSTIP;
1176 if (co.comment_only)
1179 for (l = rule->act_ofs, cmd = rule->cmd ;
1180 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1182 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1184 if (co.comment_only) {
1185 if (cmd->opcode != O_NOP)
1187 printf(" // %s\n", (char *)(cmd + 1));
1191 show_prerequisites(&flags, 0, cmd->opcode);
1193 switch(cmd->opcode) {
1195 break; /* done already */
1198 break; /* no need to print anything here */
1201 case O_IP_SRC_LOOKUP:
1205 show_prerequisites(&flags, HAVE_PROTO, 0);
1206 if (!(flags & HAVE_SRCIP))
1208 if ((cmd->len & F_OR) && !or_block)
1210 print_ip((ipfw_insn_ip *)cmd,
1211 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1212 flags |= HAVE_SRCIP;
1216 case O_IP_DST_LOOKUP:
1220 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1221 if (!(flags & HAVE_DSTIP))
1223 if ((cmd->len & F_OR) && !or_block)
1225 print_ip((ipfw_insn_ip *)cmd,
1226 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1227 flags |= HAVE_DSTIP;
1231 case O_IP6_SRC_MASK:
1233 show_prerequisites(&flags, HAVE_PROTO, 0);
1234 if (!(flags & HAVE_SRCIP))
1236 if ((cmd->len & F_OR) && !or_block)
1238 print_ip6((ipfw_insn_ip6 *)cmd,
1239 (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1240 flags |= HAVE_SRCIP | HAVE_PROTO;
1244 case O_IP6_DST_MASK:
1246 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1247 if (!(flags & HAVE_DSTIP))
1249 if ((cmd->len & F_OR) && !or_block)
1251 print_ip6((ipfw_insn_ip6 *)cmd,
1252 (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1253 flags |= HAVE_DSTIP;
1257 print_flow6id( (ipfw_insn_u32 *) cmd );
1258 flags |= HAVE_OPTIONS;
1262 show_prerequisites(&flags,
1263 HAVE_PROTO | HAVE_SRCIP |
1264 HAVE_DSTIP | HAVE_IP, 0);
1266 show_prerequisites(&flags,
1267 HAVE_PROTO | HAVE_SRCIP, 0);
1268 if ((cmd->len & F_OR) && !or_block)
1270 if (cmd->len & F_NOT)
1272 print_newports((ipfw_insn_u16 *)cmd, proto,
1273 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1277 struct protoent *pe = NULL;
1279 if ((cmd->len & F_OR) && !or_block)
1281 if (cmd->len & F_NOT)
1284 pe = getprotobynumber(cmd->arg1);
1285 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1286 !(flags & HAVE_PROTO))
1287 show_prerequisites(&flags,
1288 HAVE_PROTO | HAVE_IP | HAVE_SRCIP |
1289 HAVE_DSTIP | HAVE_OPTIONS, 0);
1290 if (flags & HAVE_OPTIONS)
1293 printf(" %s", pe->p_name);
1295 printf(" %u", cmd->arg1);
1297 flags |= HAVE_PROTO;
1300 default: /*options ... */
1301 if (!(cmd->len & (F_OR|F_NOT)))
1302 if (((cmd->opcode == O_IP6) &&
1303 (flags & HAVE_PROTO6)) ||
1304 ((cmd->opcode == O_IP4) &&
1305 (flags & HAVE_PROTO4)))
1307 show_prerequisites(&flags, HAVE_PROTO | HAVE_SRCIP |
1308 HAVE_DSTIP | HAVE_IP | HAVE_OPTIONS, 0);
1309 if ((cmd->len & F_OR) && !or_block)
1311 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1313 switch(cmd->opcode) {
1315 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1318 print_mac(m->addr, m->mask);
1319 print_mac(m->addr + 6, m->mask + 6);
1324 print_newports((ipfw_insn_u16 *)cmd,
1325 IPPROTO_ETHERTYPE, cmd->opcode);
1334 printf(" fib %u", cmd->arg1 );
1338 printf(cmd->len & F_NOT ? " out" : " in");
1342 switch (cmd->arg1) {
1344 printf(" diverted");
1347 printf(" diverted-loopback");
1350 printf(" diverted-output");
1353 printf(" diverted-?<%u>", cmd->arg1);
1366 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1368 if (cmd->opcode == O_XMIT)
1370 else if (cmd->opcode == O_RECV)
1372 else /* if (cmd->opcode == O_VIA) */
1374 if (cmdif->name[0] == '\0')
1376 inet_ntoa(cmdif->p.ip));
1378 printf(" %s %s", s, cmdif->name);
1383 if (F_LEN(cmd) == 1)
1384 printf(" ipid %u", cmd->arg1 );
1386 print_newports((ipfw_insn_u16 *)cmd, 0,
1391 if (F_LEN(cmd) == 1)
1392 printf(" ipttl %u", cmd->arg1 );
1394 print_newports((ipfw_insn_u16 *)cmd, 0,
1399 printf(" ipver %u", cmd->arg1 );
1402 case O_IPPRECEDENCE:
1403 printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1407 if (F_LEN(cmd) == 1)
1408 printf(" iplen %u", cmd->arg1 );
1410 print_newports((ipfw_insn_u16 *)cmd, 0,
1415 print_flags("ipoptions", cmd, f_ipopts);
1419 print_flags("iptos", cmd, f_iptos);
1423 print_icmptypes((ipfw_insn_u32 *)cmd);
1427 printf(" established");
1431 if (F_LEN(cmd) == 1)
1432 printf(" tcpdatalen %u", cmd->arg1 );
1434 print_newports((ipfw_insn_u16 *)cmd, 0,
1439 print_flags("tcpflags", cmd, f_tcpflags);
1443 print_flags("tcpoptions", cmd, f_tcpopts);
1447 printf(" tcpwin %d", ntohs(cmd->arg1));
1451 printf(" tcpack %d", ntohl(cmd32->d[0]));
1455 printf(" tcpseq %d", ntohl(cmd32->d[0]));
1460 struct passwd *pwd = getpwuid(cmd32->d[0]);
1463 printf(" uid %s", pwd->pw_name);
1465 printf(" uid %u", cmd32->d[0]);
1471 struct group *grp = getgrgid(cmd32->d[0]);
1474 printf(" gid %s", grp->gr_name);
1476 printf(" gid %u", cmd32->d[0]);
1481 printf(" jail %d", cmd32->d[0]);
1485 printf(" verrevpath");
1489 printf(" versrcreach");
1493 printf(" antispoof");
1501 comment = (char *)(cmd + 1);
1505 printf(" keep-state");
1509 struct _s_x *p = limit_masks;
1510 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1511 uint8_t x = c->limit_mask;
1512 char const *comma = " ";
1515 for (; p->x != 0 ; p++)
1516 if ((x & p->x) == p->x) {
1518 printf("%s%s", comma, p->s);
1521 PRINT_UINT_ARG(" ", c->conn_limit);
1534 print_icmp6types((ipfw_insn_u32 *)cmd);
1538 print_ext6hdr( (ipfw_insn *) cmd );
1542 if (F_LEN(cmd) == 1)
1543 PRINT_UINT_ARG(" tagged ", cmd->arg1);
1545 print_newports((ipfw_insn_u16 *)cmd, 0,
1550 printf(" [opcode %d len %d]",
1551 cmd->opcode, cmd->len);
1554 if (cmd->len & F_OR) {
1557 } else if (or_block) {
1562 show_prerequisites(&flags, HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP
1565 printf(" // %s", comment);
1570 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth)
1572 struct protoent *pe;
1575 char buf[INET6_ADDRSTRLEN];
1577 if (!co.do_expired) {
1578 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1581 bcopy(&d->rule, &rulenum, sizeof(rulenum));
1582 printf("%05d", rulenum);
1583 if (pcwidth>0 || bcwidth>0)
1584 printf(" %*llu %*llu (%ds)", pcwidth,
1585 align_uint64(&d->pcnt), bcwidth,
1586 align_uint64(&d->bcnt), d->expire);
1587 switch (d->dyn_type) {
1588 case O_LIMIT_PARENT:
1589 printf(" PARENT %d", d->count);
1594 case O_KEEP_STATE: /* bidir, no mask */
1599 if ((pe = getprotobynumber(d->id.proto)) != NULL)
1600 printf(" %s", pe->p_name);
1602 printf(" proto %u", d->id.proto);
1604 if (d->id.addr_type == 4) {
1605 a.s_addr = htonl(d->id.src_ip);
1606 printf(" %s %d", inet_ntoa(a), d->id.src_port);
1608 a.s_addr = htonl(d->id.dst_ip);
1609 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
1610 } else if (d->id.addr_type == 6) {
1611 printf(" %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
1612 sizeof(buf)), d->id.src_port);
1613 printf(" <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6, buf,
1614 sizeof(buf)), d->id.dst_port);
1616 printf(" UNKNOWN <-> UNKNOWN\n");
1622 * This one handles all set-related commands
1623 * ipfw set { show | enable | disable }
1625 * ipfw set move X to Y
1626 * ipfw set move rule X to Y
1629 ipfw_sets_handler(char *av[])
1631 uint32_t set_disable, masks[2];
1634 uint8_t cmd, new_set;
1639 errx(EX_USAGE, "set needs command");
1640 if (_substrcmp(*av, "show") == 0) {
1645 nalloc = nbytes = sizeof(struct ip_fw);
1646 while (nbytes >= nalloc) {
1649 nalloc = nalloc * 2 + 200;
1651 data = safe_calloc(1, nbytes);
1652 if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0)
1653 err(EX_OSERR, "getsockopt(IP_FW_GET)");
1656 bcopy(&((struct ip_fw *)data)->next_rule,
1657 &set_disable, sizeof(set_disable));
1659 for (i = 0, msg = "disable" ; i < RESVD_SET; i++)
1660 if ((set_disable & (1<<i))) {
1661 printf("%s %d", msg, i);
1664 msg = (set_disable) ? " enable" : "enable";
1665 for (i = 0; i < RESVD_SET; i++)
1666 if (!(set_disable & (1<<i))) {
1667 printf("%s %d", msg, i);
1671 } else if (_substrcmp(*av, "swap") == 0) {
1673 if ( av[0] == NULL || av[1] == NULL )
1674 errx(EX_USAGE, "set swap needs 2 set numbers\n");
1675 rulenum = atoi(av[0]);
1676 new_set = atoi(av[1]);
1677 if (!isdigit(*(av[0])) || rulenum > RESVD_SET)
1678 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
1679 if (!isdigit(*(av[1])) || new_set > RESVD_SET)
1680 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
1681 masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
1682 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
1683 } else if (_substrcmp(*av, "move") == 0) {
1685 if (av[0] && _substrcmp(*av, "rule") == 0) {
1690 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
1691 av[3] != NULL || _substrcmp(av[1], "to") != 0)
1692 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
1693 rulenum = atoi(av[0]);
1694 new_set = atoi(av[2]);
1695 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) ||
1696 (cmd == 2 && rulenum == IPFW_DEFAULT_RULE) )
1697 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
1698 if (!isdigit(*(av[2])) || new_set > RESVD_SET)
1699 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
1700 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
1701 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
1702 } else if (_substrcmp(*av, "disable") == 0 ||
1703 _substrcmp(*av, "enable") == 0 ) {
1704 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
1707 masks[0] = masks[1] = 0;
1710 if (isdigit(**av)) {
1712 if (i < 0 || i > RESVD_SET)
1714 "invalid set number %d\n", i);
1715 masks[which] |= (1<<i);
1716 } else if (_substrcmp(*av, "disable") == 0)
1718 else if (_substrcmp(*av, "enable") == 0)
1722 "invalid set command %s\n", *av);
1725 if ( (masks[0] & masks[1]) != 0 )
1727 "cannot enable and disable the same set\n");
1729 i = do_cmd(IP_FW_DEL, masks, sizeof(masks));
1731 warn("set enable/disable: setsockopt(IP_FW_DEL)");
1733 errx(EX_USAGE, "invalid set command %s\n", *av);
1737 ipfw_sysctl_handler(char *av[], int which)
1741 if (av[0] == NULL) {
1742 warnx("missing keyword to enable/disable\n");
1743 } else if (_substrcmp(*av, "firewall") == 0) {
1744 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
1745 &which, sizeof(which));
1746 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
1747 &which, sizeof(which));
1748 } else if (_substrcmp(*av, "one_pass") == 0) {
1749 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
1750 &which, sizeof(which));
1751 } else if (_substrcmp(*av, "debug") == 0) {
1752 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
1753 &which, sizeof(which));
1754 } else if (_substrcmp(*av, "verbose") == 0) {
1755 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
1756 &which, sizeof(which));
1757 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
1758 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
1759 &which, sizeof(which));
1761 } else if (_substrcmp(*av, "altq") == 0) {
1762 altq_set_enabled(which);
1765 warnx("unrecognize enable/disable keyword: %s\n", *av);
1770 ipfw_list(int ac, char *av[], int show_counters)
1773 ipfw_dyn_rule *dynrules, *d;
1775 #define NEXT(r) ((struct ip_fw *)((char *)r + RULESIZE(r)))
1778 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
1779 int exitval = EX_OK;
1787 const int ocmd = co.do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
1788 int nalloc = 1024; /* start somewhere... */
1793 fprintf(stderr, "Testing only, list disabled\n");
1797 dummynet_list(ac, av, show_counters);
1804 /* get rules or pipes from kernel, resizing array as necessary */
1807 while (nbytes >= nalloc) {
1808 nalloc = nalloc * 2 + 200;
1810 data = safe_realloc(data, nbytes);
1811 if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0)
1812 err(EX_OSERR, "getsockopt(IP_%s_GET)",
1813 co.do_pipe ? "DUMMYNET" : "FW");
1817 * Count static rules. They have variable size so we
1818 * need to scan the list to count them.
1820 for (nstat = 1, r = data, lim = (char *)data + nbytes;
1821 r->rulenum < IPFW_DEFAULT_RULE && (char *)r < lim;
1822 ++nstat, r = NEXT(r) )
1826 * Count dynamic rules. This is easier as they have
1830 dynrules = (ipfw_dyn_rule *)r ;
1831 n = (char *)r - (char *)data;
1832 ndyn = (nbytes - n) / sizeof *dynrules;
1834 /* if showing stats, figure out column widths ahead of time */
1835 bcwidth = pcwidth = 0;
1836 if (show_counters) {
1837 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
1838 /* skip rules from another set */
1839 if (co.use_set && r->set != co.use_set - 1)
1842 /* packet counter */
1843 width = snprintf(NULL, 0, "%llu",
1844 align_uint64(&r->pcnt));
1845 if (width > pcwidth)
1849 width = snprintf(NULL, 0, "%llu",
1850 align_uint64(&r->bcnt));
1851 if (width > bcwidth)
1855 if (co.do_dynamic && ndyn) {
1856 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1858 /* skip rules from another set */
1859 bcopy((char *)&d->rule + sizeof(uint16_t),
1860 &set, sizeof(uint8_t));
1861 if (set != co.use_set - 1)
1864 width = snprintf(NULL, 0, "%llu",
1865 align_uint64(&d->pcnt));
1866 if (width > pcwidth)
1869 width = snprintf(NULL, 0, "%llu",
1870 align_uint64(&d->bcnt));
1871 if (width > bcwidth)
1875 /* if no rule numbers were specified, list all rules */
1877 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
1878 if (co.use_set && r->set != co.use_set - 1)
1880 show_ipfw(r, pcwidth, bcwidth);
1883 if (co.do_dynamic && ndyn) {
1884 printf("## Dynamic rules (%d):\n", ndyn);
1885 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1887 bcopy((char *)&d->rule + sizeof(uint16_t),
1888 &set, sizeof(uint8_t));
1889 if (set != co.use_set - 1)
1892 show_dyn_ipfw(d, pcwidth, bcwidth);
1898 /* display specific rules requested on command line */
1900 for (lac = ac, lav = av; lac != 0; lac--) {
1901 /* convert command line rule # */
1902 last = rnum = strtoul(*lav++, &endptr, 10);
1904 last = strtoul(endptr+1, &endptr, 10);
1907 warnx("invalid rule number: %s", *(lav - 1));
1910 for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) {
1911 if (r->rulenum > last)
1913 if (co.use_set && r->set != co.use_set - 1)
1915 if (r->rulenum >= rnum && r->rulenum <= last) {
1916 show_ipfw(r, pcwidth, bcwidth);
1921 /* give precedence to other error(s) */
1922 if (exitval == EX_OK)
1923 exitval = EX_UNAVAILABLE;
1924 warnx("rule %lu does not exist", rnum);
1928 if (co.do_dynamic && ndyn) {
1929 printf("## Dynamic rules:\n");
1930 for (lac = ac, lav = av; lac != 0; lac--) {
1931 last = rnum = strtoul(*lav++, &endptr, 10);
1933 last = strtoul(endptr+1, &endptr, 10);
1935 /* already warned */
1937 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1940 bcopy(&d->rule, &rulenum, sizeof(rulenum));
1944 bcopy((char *)&d->rule + sizeof(uint16_t),
1945 &set, sizeof(uint8_t));
1946 if (set != co.use_set - 1)
1949 if (r->rulenum >= rnum && r->rulenum <= last)
1950 show_dyn_ipfw(d, pcwidth, bcwidth);
1960 if (exitval != EX_OK)
1966 lookup_host (char *host, struct in_addr *ipaddr)
1970 if (!inet_aton(host, ipaddr)) {
1971 if ((he = gethostbyname(host)) == NULL)
1973 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
1979 * fills the addr and mask fields in the instruction as appropriate from av.
1980 * Update length as appropriate.
1981 * The following formats are allowed:
1982 * me returns O_IP_*_ME
1983 * 1.2.3.4 single IP address
1984 * 1.2.3.4:5.6.7.8 address:mask
1985 * 1.2.3.4/24 address/mask
1986 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
1987 * We can have multiple comma-separated address/mask entries.
1990 fill_ip(ipfw_insn_ip *cmd, char *av)
1993 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
1995 cmd->o.len &= ~F_LEN_MASK; /* zero len */
1997 if (_substrcmp(av, "any") == 0)
2000 if (_substrcmp(av, "me") == 0) {
2001 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2005 if (strncmp(av, "table(", 6) == 0) {
2006 char *p = strchr(av + 6, ',');
2010 cmd->o.opcode = O_IP_DST_LOOKUP;
2011 cmd->o.arg1 = strtoul(av + 6, NULL, 0);
2013 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2014 d[0] = strtoul(p, NULL, 0);
2016 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2022 * After the address we can have '/' or ':' indicating a mask,
2023 * ',' indicating another address follows, '{' indicating a
2024 * set of addresses of unspecified size.
2026 char *t = NULL, *p = strpbrk(av, "/:,{");
2033 if ((t = strpbrk(p, ",{")) != NULL) {
2040 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2041 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2044 if (!inet_aton(p, (struct in_addr *)&d[1]))
2045 errx(EX_DATAERR, "bad netmask ``%s''", p);
2050 d[1] = htonl(0); /* mask */
2051 else if (masklen > 32)
2052 errx(EX_DATAERR, "bad width ``%s''", p);
2054 d[1] = htonl(~0 << (32 - masklen));
2056 case '{': /* no mask, assume /24 and put back the '{' */
2057 d[1] = htonl(~0 << (32 - 24));
2061 case ',': /* single address plus continuation */
2064 case 0: /* initialization value */
2066 d[1] = htonl(~0); /* force /32 */
2069 d[0] &= d[1]; /* mask base address with mask */
2072 /* find next separator */
2074 p = strpbrk(p, ",{");
2075 if (p && *p == '{') {
2077 * We have a set of addresses. They are stored as follows:
2078 * arg1 is the set size (powers of 2, 2..256)
2079 * addr is the base address IN HOST FORMAT
2080 * mask.. is an array of arg1 bits (rounded up to
2081 * the next multiple of 32) with bits set
2082 * for each host in the map.
2084 uint32_t *map = (uint32_t *)&cmd->mask;
2086 int i = contigmask((uint8_t *)&(d[1]), 32);
2089 errx(EX_DATAERR, "address set cannot be in a list");
2090 if (i < 24 || i > 31)
2091 errx(EX_DATAERR, "invalid set with mask %d\n", i);
2092 cmd->o.arg1 = 1<<(32-i); /* map length */
2093 d[0] = ntohl(d[0]); /* base addr in host format */
2094 cmd->o.opcode = O_IP_DST_SET; /* default */
2095 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2096 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2097 map[i] = 0; /* clear map */
2101 high = low + cmd->o.arg1 - 1;
2103 * Here, i stores the previous value when we specify a range
2104 * of addresses within a mask, e.g. 45-63. i = -1 means we
2105 * have no previous value.
2107 i = -1; /* previous value in a range */
2108 while (isdigit(*av)) {
2110 int a = strtol(av, &s, 0);
2112 if (s == av) { /* no parameter */
2114 errx(EX_DATAERR, "set not closed\n");
2116 errx(EX_DATAERR, "incomplete range %d-", i);
2119 if (a < low || a > high)
2120 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
2123 if (i == -1) /* no previous in range */
2125 else { /* check that range is valid */
2127 errx(EX_DATAERR, "invalid range %d-%d",
2130 errx(EX_DATAERR, "double '-' in range");
2133 map[i/32] |= 1<<(i & 31);
2144 if (av) /* then *av must be a ',' */
2147 /* Check this entry */
2148 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2150 * 'any' turns the entire list into a NOP.
2151 * 'not any' never matches, so it is removed from the
2152 * list unless it is the only item, in which case we
2155 if (cmd->o.len & F_NOT) { /* "not any" never matches */
2156 if (av == NULL && len == 0) /* only this entry */
2157 errx(EX_DATAERR, "not any never matches");
2159 /* else do nothing and skip this entry */
2162 /* A single IP can be stored in an optimized format */
2163 if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
2164 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2167 len += 2; /* two words... */
2170 if (len + 1 > F_LEN_MASK)
2171 errx(EX_DATAERR, "address list too long");
2172 cmd->o.len |= len+1;
2176 /* n2mask sets n bits of the mask */
2178 n2mask(struct in6_addr *mask, int n)
2180 static int minimask[9] =
2181 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
2184 memset(mask, 0, sizeof(struct in6_addr));
2185 p = (u_char *) mask;
2186 for (; n > 0; p++, n -= 8) {
2196 * helper function to process a set of flags and set bits in the
2197 * appropriate masks.
2200 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
2201 struct _s_x *flags, char *p)
2203 uint8_t set=0, clear=0;
2206 char *q; /* points to the separator */
2208 uint8_t *which; /* mask we are working on */
2218 val = match_token(flags, p);
2220 errx(EX_DATAERR, "invalid flag %s", p);
2221 *which |= (uint8_t)val;
2224 cmd->opcode = opcode;
2225 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
2226 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
2231 ipfw_delete(char *av[])
2235 int exitval = EX_OK;
2239 NEED1("missing rule specification");
2240 if ( *av && _substrcmp(*av, "set") == 0) {
2241 /* Do not allow using the following syntax:
2242 * ipfw set N delete set M
2245 errx(EX_DATAERR, "invalid syntax");
2246 do_set = 1; /* delete set */
2251 while (*av && isdigit(**av)) {
2252 i = atoi(*av); av++;
2254 exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
2256 exitval = EX_UNAVAILABLE;
2257 warn("rule %u not available", i);
2259 } else if (co.do_pipe) {
2260 exitval = ipfw_delete_pipe(co.do_pipe, i);
2263 rulenum = (i & 0xffff) | (5 << 24) |
2264 ((co.use_set - 1) << 16);
2266 rulenum = (i & 0xffff) | (do_set << 24);
2267 i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum);
2269 exitval = EX_UNAVAILABLE;
2270 warn("rule %u: setsockopt(IP_FW_DEL)",
2275 if (exitval != EX_OK)
2281 * fill the interface structure. We do not check the name as we can
2282 * create interfaces dynamically, so checking them at insert time
2283 * makes relatively little sense.
2284 * Interface names containing '*', '?', or '[' are assumed to be shell
2285 * patterns which match interfaces.
2288 fill_iface(ipfw_insn_if *cmd, char *arg)
2290 cmd->name[0] = '\0';
2291 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
2293 /* Parse the interface or address */
2294 if (strcmp(arg, "any") == 0)
2295 cmd->o.len = 0; /* effectively ignore this command */
2296 else if (!isdigit(*arg)) {
2297 strlcpy(cmd->name, arg, sizeof(cmd->name));
2298 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
2299 } else if (!inet_aton(arg, &cmd->p.ip))
2300 errx(EX_DATAERR, "bad ip address ``%s''", arg);
2304 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
2308 char *ap, *ptr, *optr;
2309 struct ether_addr *mac;
2310 const char *macset = "0123456789abcdefABCDEF:";
2312 if (strcmp(p, "any") == 0) {
2313 for (i = 0; i < ETHER_ADDR_LEN; i++)
2314 addr[i] = mask[i] = 0;
2318 optr = ptr = strdup(p);
2319 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
2321 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
2322 errx(EX_DATAERR, "Incorrect MAC address");
2323 bcopy(mac, addr, ETHER_ADDR_LEN);
2325 errx(EX_DATAERR, "Incorrect MAC address");
2327 if (ptr != NULL) { /* we have mask? */
2328 if (p[ptr - optr - 1] == '/') { /* mask len */
2329 long ml = strtol(ptr, &ap, 10);
2330 if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
2331 errx(EX_DATAERR, "Incorrect mask length");
2332 for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
2333 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
2336 if (strspn(ptr, macset) != l ||
2337 (mac = ether_aton(ptr)) == NULL)
2338 errx(EX_DATAERR, "Incorrect mask");
2339 bcopy(mac, mask, ETHER_ADDR_LEN);
2341 } else { /* default mask: ff:ff:ff:ff:ff:ff */
2342 for (i = 0; i < ETHER_ADDR_LEN; i++)
2345 for (i = 0; i < ETHER_ADDR_LEN; i++)
2352 * helper function, updates the pointer to cmd with the length
2353 * of the current command, and also cleans up the first word of
2354 * the new command in case it has been clobbered before.
2357 next_cmd(ipfw_insn *cmd)
2360 bzero(cmd, sizeof(*cmd));
2365 * Takes arguments and copies them into a comment
2368 fill_comment(ipfw_insn *cmd, char **av)
2371 char *p = (char *)(cmd + 1);
2373 cmd->opcode = O_NOP;
2374 cmd->len = (cmd->len & (F_NOT | F_OR));
2376 /* Compute length of comment string. */
2377 for (i = 0, l = 0; av[i] != NULL; i++)
2378 l += strlen(av[i]) + 1;
2383 "comment too long (max 80 chars)");
2385 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
2386 for (i = 0; av[i] != NULL; i++) {
2395 * A function to fill simple commands of size 1.
2396 * Existing flags are preserved.
2399 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
2401 cmd->opcode = opcode;
2402 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
2407 * Fetch and add the MAC address and type, with masks. This generates one or
2408 * two microinstructions, and returns the pointer to the last one.
2411 add_mac(ipfw_insn *cmd, char *av[])
2415 if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
2416 errx(EX_DATAERR, "MAC dst src");
2418 cmd->opcode = O_MACADDR2;
2419 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
2421 mac = (ipfw_insn_mac *)cmd;
2422 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
2423 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
2424 &(mac->mask[ETHER_ADDR_LEN])); /* src */
2429 add_mactype(ipfw_insn *cmd, char *av)
2432 errx(EX_DATAERR, "missing MAC type");
2433 if (strcmp(av, "any") != 0) { /* we have a non-null type */
2434 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE);
2435 cmd->opcode = O_MAC_TYPE;
2442 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
2444 struct protoent *pe;
2448 proto = strtol(av, &ep, 10);
2449 if (*ep != '\0' || proto <= 0) {
2450 if ((pe = getprotobyname(av)) == NULL)
2452 proto = pe->p_proto;
2455 fill_cmd(cmd, O_PROTO, 0, proto);
2461 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
2463 u_char proto = IPPROTO_IP;
2465 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2466 ; /* do not set O_IP4 nor O_IP6 */
2467 else if (strcmp(av, "ip4") == 0)
2468 /* explicit "just IPv4" rule */
2469 fill_cmd(cmd, O_IP4, 0, 0);
2470 else if (strcmp(av, "ip6") == 0) {
2471 /* explicit "just IPv6" rule */
2472 proto = IPPROTO_IPV6;
2473 fill_cmd(cmd, O_IP6, 0, 0);
2475 return add_proto0(cmd, av, protop);
2482 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
2484 u_char proto = IPPROTO_IP;
2486 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2487 ; /* do not set O_IP4 nor O_IP6 */
2488 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
2489 /* explicit "just IPv4" rule */
2490 fill_cmd(cmd, O_IP4, 0, 0);
2491 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
2492 /* explicit "just IPv6" rule */
2493 proto = IPPROTO_IPV6;
2494 fill_cmd(cmd, O_IP6, 0, 0);
2496 return add_proto0(cmd, av, protop);
2503 add_srcip(ipfw_insn *cmd, char *av)
2505 fill_ip((ipfw_insn_ip *)cmd, av);
2506 if (cmd->opcode == O_IP_DST_SET) /* set */
2507 cmd->opcode = O_IP_SRC_SET;
2508 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
2509 cmd->opcode = O_IP_SRC_LOOKUP;
2510 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2511 cmd->opcode = O_IP_SRC_ME;
2512 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2513 cmd->opcode = O_IP_SRC;
2514 else /* addr/mask */
2515 cmd->opcode = O_IP_SRC_MASK;
2520 add_dstip(ipfw_insn *cmd, char *av)
2522 fill_ip((ipfw_insn_ip *)cmd, av);
2523 if (cmd->opcode == O_IP_DST_SET) /* set */
2525 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
2527 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2528 cmd->opcode = O_IP_DST_ME;
2529 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2530 cmd->opcode = O_IP_DST;
2531 else /* addr/mask */
2532 cmd->opcode = O_IP_DST_MASK;
2537 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode)
2539 /* XXX "any" is trapped before. Perhaps "to" */
2540 if (_substrcmp(av, "any") == 0) {
2542 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) {
2543 /* XXX todo: check that we have a protocol with ports */
2544 cmd->opcode = opcode;
2551 add_src(ipfw_insn *cmd, char *av, u_char proto)
2555 ipfw_insn *ret = NULL;
2557 if ((host = strdup(av)) == NULL)
2559 if ((ch = strrchr(host, '/')) != NULL)
2562 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
2563 inet_pton(AF_INET6, host, &a) == 1)
2564 ret = add_srcip6(cmd, av);
2565 /* XXX: should check for IPv4, not !IPv6 */
2566 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2567 inet_pton(AF_INET6, host, &a) != 1))
2568 ret = add_srcip(cmd, av);
2569 if (ret == NULL && strcmp(av, "any") != 0)
2577 add_dst(ipfw_insn *cmd, char *av, u_char proto)
2581 ipfw_insn *ret = NULL;
2583 if ((host = strdup(av)) == NULL)
2585 if ((ch = strrchr(host, '/')) != NULL)
2588 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
2589 inet_pton(AF_INET6, host, &a) == 1)
2590 ret = add_dstip6(cmd, av);
2591 /* XXX: should check for IPv4, not !IPv6 */
2592 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2593 inet_pton(AF_INET6, host, &a) != 1))
2594 ret = add_dstip(cmd, av);
2595 if (ret == NULL && strcmp(av, "any") != 0)
2603 * Parse arguments and assemble the microinstructions which make up a rule.
2604 * Rules are added into the 'rulebuf' and then copied in the correct order
2605 * into the actual rule.
2607 * The syntax for a rule starts with the action, followed by
2608 * optional action parameters, and the various match patterns.
2609 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
2610 * (generated if the rule includes a keep-state option), then the
2611 * various match patterns, log/altq actions, and the actual action.
2615 ipfw_add(char *av[])
2618 * rules are added into the 'rulebuf' and then copied in
2619 * the correct order into the actual rule.
2620 * Some things that need to go out of order (prob, action etc.)
2623 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255];
2625 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
2626 ipfw_insn *first_cmd; /* first match pattern */
2631 * various flags used to record that we entered some fields.
2633 ipfw_insn *have_state = NULL; /* check-state or keep-state */
2634 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
2639 int open_par = 0; /* open parenthesis ( */
2641 /* proto is here because it is used to fetch ports */
2642 u_char proto = IPPROTO_IP; /* default protocol */
2644 double match_prob = 1; /* match probability, default is always match */
2646 bzero(actbuf, sizeof(actbuf)); /* actions go here */
2647 bzero(cmdbuf, sizeof(cmdbuf));
2648 bzero(rulebuf, sizeof(rulebuf));
2650 rule = (struct ip_fw *)rulebuf;
2651 cmd = (ipfw_insn *)cmdbuf;
2652 action = (ipfw_insn *)actbuf;
2656 /* [rule N] -- Rule number optional */
2657 if (av[0] && isdigit(**av)) {
2658 rule->rulenum = atoi(*av);
2662 /* [set N] -- set number (0..RESVD_SET), optional */
2663 if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
2664 int set = strtoul(av[1], NULL, 10);
2665 if (set < 0 || set > RESVD_SET)
2666 errx(EX_DATAERR, "illegal set %s", av[1]);
2671 /* [prob D] -- match probability, optional */
2672 if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
2673 match_prob = strtod(av[1], NULL);
2675 if (match_prob <= 0 || match_prob > 1)
2676 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
2680 /* action -- mandatory */
2681 NEED1("missing action");
2682 i = match_token(rule_actions, *av);
2684 action->len = 1; /* default */
2686 case TOK_CHECKSTATE:
2687 have_state = action;
2688 action->opcode = O_CHECK_STATE;
2692 action->opcode = O_ACCEPT;
2696 action->opcode = O_DENY;
2701 action->opcode = O_REJECT;
2702 action->arg1 = ICMP_UNREACH_HOST;
2706 action->opcode = O_REJECT;
2707 action->arg1 = ICMP_REJECT_RST;
2711 action->opcode = O_UNREACH6;
2712 action->arg1 = ICMP6_UNREACH_RST;
2716 action->opcode = O_REJECT;
2717 NEED1("missing reject code");
2718 fill_reject_code(&action->arg1, *av);
2723 action->opcode = O_UNREACH6;
2724 NEED1("missing unreach code");
2725 fill_unreach6_code(&action->arg1, *av);
2730 action->opcode = O_COUNT;
2734 action->opcode = O_NAT;
2735 action->len = F_INSN_SIZE(ipfw_insn_nat);
2736 if (_substrcmp(*av, "global") == 0) {
2744 action->opcode = O_QUEUE;
2747 action->opcode = O_PIPE;
2750 action->opcode = O_SKIPTO;
2753 action->opcode = O_NETGRAPH;
2756 action->opcode = O_NGTEE;
2759 action->opcode = O_DIVERT;
2762 action->opcode = O_TEE;
2765 errx(EX_USAGE, "missing argument for %s", *(av - 1));
2766 if (isdigit(**av)) {
2767 action->arg1 = strtoul(*av, NULL, 10);
2768 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
2769 errx(EX_DATAERR, "illegal argument for %s",
2771 } else if (_substrcmp(*av, "tablearg") == 0) {
2772 action->arg1 = IP_FW_TABLEARG;
2773 } else if (i == TOK_DIVERT || i == TOK_TEE) {
2776 s = getservbyname(av[0], "divert");
2778 action->arg1 = ntohs(s->s_port);
2780 errx(EX_DATAERR, "illegal divert/tee port");
2782 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
2787 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
2790 NEED1("missing forward address[:port]");
2792 action->opcode = O_FORWARD_IP;
2793 action->len = F_INSN_SIZE(ipfw_insn_sa);
2796 * In the kernel we assume AF_INET and use only
2797 * sin_port and sin_addr. Remember to set sin_len as
2798 * the routing code seems to use it too.
2800 p->sa.sin_family = AF_INET;
2801 p->sa.sin_len = sizeof(struct sockaddr_in);
2804 * locate the address-port separator (':' or ',')
2806 s = strchr(*av, ':');
2808 s = strchr(*av, ',');
2811 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
2814 "illegal forwarding port ``%s''", s);
2815 p->sa.sin_port = (u_short)i;
2817 if (_substrcmp(*av, "tablearg") == 0)
2818 p->sa.sin_addr.s_addr = INADDR_ANY;
2820 lookup_host(*av, &(p->sa.sin_addr));
2825 /* pretend it is a 'count' rule followed by the comment */
2826 action->opcode = O_COUNT;
2827 av--; /* go back... */
2833 size_t intsize = sizeof(int);
2835 action->opcode = O_SETFIB;
2836 NEED1("missing fib number");
2837 if (_substrcmp(*av, "tablearg") == 0) {
2838 action->arg1 = IP_FW_TABLEARG;
2840 action->arg1 = strtoul(*av, NULL, 10);
2841 if (sysctlbyname("net.fibs", &numfibs, &intsize,
2843 errx(EX_DATAERR, "fibs not suported.\n");
2844 if (action->arg1 >= numfibs) /* Temporary */
2845 errx(EX_DATAERR, "fib too large.\n");
2852 action->opcode = O_REASS;
2856 errx(EX_DATAERR, "invalid action %s\n", av[-1]);
2858 action = next_cmd(action);
2861 * [altq queuename] -- altq tag, optional
2862 * [log [logamount N]] -- log, optional
2864 * If they exist, it go first in the cmdbuf, but then it is
2865 * skipped in the copy section to the end of the buffer.
2867 while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
2872 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
2877 "log cannot be specified more than once");
2878 have_log = (ipfw_insn *)c;
2879 cmd->len = F_INSN_SIZE(ipfw_insn_log);
2880 cmd->opcode = O_LOG;
2881 if (av[0] && _substrcmp(*av, "logamount") == 0) {
2883 NEED1("logamount requires argument");
2887 "logamount must be positive");
2891 len = sizeof(c->max_log);
2892 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
2893 &c->max_log, &len, NULL, 0) == -1)
2894 errx(1, "sysctlbyname(\"%s\")",
2895 "net.inet.ip.fw.verbose_limit");
2903 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
2905 NEED1("missing altq queue name");
2908 "altq cannot be specified more than once");
2909 have_altq = (ipfw_insn *)a;
2910 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
2911 cmd->opcode = O_ALTQ;
2912 a->qid = altq_name_to_qid(*av);
2923 errx(EX_USAGE, "tag and untag cannot be "
2924 "specified more than once");
2925 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
2926 rule_action_params);
2928 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
2936 cmd = next_cmd(cmd);
2939 if (have_state) /* must be a check-state, we are done */
2942 #define OR_START(target) \
2943 if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
2945 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
2948 if ( (av[0])[1] == '\0') { \
2959 strcmp(*av, ")") == 0 || \
2960 strcmp(*av, "}") == 0)) { \
2965 errx(EX_USAGE, "missing \")\"\n"); \
2969 if (av[0] && _substrcmp(*av, "not") == 0) { \
2970 if (cmd->len & F_NOT) \
2971 errx(EX_USAGE, "double \"not\" not allowed\n"); \
2972 cmd->len |= F_NOT; \
2976 #define OR_BLOCK(target) \
2977 if (av[0] && _substrcmp(*av, "or") == 0) { \
2978 if (prev == NULL || open_par == 0) \
2979 errx(EX_DATAERR, "invalid OR block"); \
2980 prev->len |= F_OR; \
2990 * MAC addresses, optional.
2991 * If we have this, we skip the part "proto from src to dst"
2992 * and jump straight to the option parsing.
2995 NEED1("missing protocol");
2996 if (_substrcmp(*av, "MAC") == 0 ||
2997 _substrcmp(*av, "mac") == 0) {
2998 av++; /* the "MAC" keyword */
2999 add_mac(cmd, av); /* exits in case of errors */
3000 cmd = next_cmd(cmd);
3001 av += 2; /* dst-mac and src-mac */
3003 NEED1("missing mac type");
3004 if (add_mactype(cmd, av[0]))
3005 cmd = next_cmd(cmd);
3006 av++; /* any or mac-type */
3012 * protocol, mandatory
3014 OR_START(get_proto);
3016 NEED1("missing protocol");
3017 if (add_proto_compat(cmd, *av, &proto)) {
3019 if (F_LEN(cmd) != 0) {
3021 cmd = next_cmd(cmd);
3023 } else if (first_cmd != cmd) {
3024 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
3027 OR_BLOCK(get_proto);
3032 if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
3033 errx(EX_USAGE, "missing ``from''");
3037 * source IP, mandatory
3039 OR_START(source_ip);
3040 NOT_BLOCK; /* optional "not" */
3041 NEED1("missing source address");
3042 if (add_src(cmd, *av, proto)) {
3044 if (F_LEN(cmd) != 0) { /* ! any */
3046 cmd = next_cmd(cmd);
3049 errx(EX_USAGE, "bad source address %s", *av);
3050 OR_BLOCK(source_ip);
3053 * source ports, optional
3055 NOT_BLOCK; /* optional "not" */
3056 if ( av[0] != NULL ) {
3057 if (_substrcmp(*av, "any") == 0 ||
3058 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
3060 if (F_LEN(cmd) != 0)
3061 cmd = next_cmd(cmd);
3068 if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
3069 errx(EX_USAGE, "missing ``to''");
3073 * destination, mandatory
3076 NOT_BLOCK; /* optional "not" */
3077 NEED1("missing dst address");
3078 if (add_dst(cmd, *av, proto)) {
3080 if (F_LEN(cmd) != 0) { /* ! any */
3082 cmd = next_cmd(cmd);
3085 errx( EX_USAGE, "bad destination address %s", *av);
3089 * dest. ports, optional
3091 NOT_BLOCK; /* optional "not" */
3093 if (_substrcmp(*av, "any") == 0 ||
3094 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
3096 if (F_LEN(cmd) != 0)
3097 cmd = next_cmd(cmd);
3102 if (av[0] && first_cmd == cmd) {
3104 * nothing specified so far, store in the rule to ease
3110 while ( av[0] != NULL ) {
3112 ipfw_insn_u32 *cmd32; /* alias for cmd */
3115 cmd32 = (ipfw_insn_u32 *)cmd;
3117 if (*s == '!') { /* alternate syntax for NOT */
3118 if (cmd->len & F_NOT)
3119 errx(EX_USAGE, "double \"not\" not allowed\n");
3123 i = match_token(rule_options, s);
3127 if (cmd->len & F_NOT)
3128 errx(EX_USAGE, "double \"not\" not allowed\n");
3133 if (open_par == 0 || prev == NULL)
3134 errx(EX_USAGE, "invalid \"or\" block\n");
3138 case TOK_STARTBRACE:
3140 errx(EX_USAGE, "+nested \"(\" not allowed\n");
3146 errx(EX_USAGE, "+missing \")\"\n");
3152 fill_cmd(cmd, O_IN, 0, 0);
3156 cmd->len ^= F_NOT; /* toggle F_NOT */
3157 fill_cmd(cmd, O_IN, 0, 0);
3161 fill_cmd(cmd, O_DIVERTED, 0, 3);
3164 case TOK_DIVERTEDLOOPBACK:
3165 fill_cmd(cmd, O_DIVERTED, 0, 1);
3168 case TOK_DIVERTEDOUTPUT:
3169 fill_cmd(cmd, O_DIVERTED, 0, 2);
3173 fill_cmd(cmd, O_FRAG, 0, 0);
3177 fill_cmd(cmd, O_LAYER2, 0, 0);
3183 NEED1("recv, xmit, via require interface name"
3185 fill_iface((ipfw_insn_if *)cmd, av[0]);
3187 if (F_LEN(cmd) == 0) /* not a valid address */
3190 cmd->opcode = O_XMIT;
3191 else if (i == TOK_RECV)
3192 cmd->opcode = O_RECV;
3193 else if (i == TOK_VIA)
3194 cmd->opcode = O_VIA;
3198 NEED1("icmptypes requires list of types");
3199 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
3203 case TOK_ICMP6TYPES:
3204 NEED1("icmptypes requires list of types");
3205 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av);
3210 NEED1("ipttl requires TTL");
3211 if (strpbrk(*av, "-,")) {
3212 if (!add_ports(cmd, *av, 0, O_IPTTL))
3213 errx(EX_DATAERR, "invalid ipttl %s", *av);
3215 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
3220 NEED1("ipid requires id");
3221 if (strpbrk(*av, "-,")) {
3222 if (!add_ports(cmd, *av, 0, O_IPID))
3223 errx(EX_DATAERR, "invalid ipid %s", *av);
3225 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
3230 NEED1("iplen requires length");
3231 if (strpbrk(*av, "-,")) {
3232 if (!add_ports(cmd, *av, 0, O_IPLEN))
3233 errx(EX_DATAERR, "invalid ip len %s", *av);
3235 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
3240 NEED1("ipver requires version");
3241 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
3245 case TOK_IPPRECEDENCE:
3246 NEED1("ipprecedence requires value");
3247 fill_cmd(cmd, O_IPPRECEDENCE, 0,
3248 (strtoul(*av, NULL, 0) & 7) << 5);
3253 NEED1("missing argument for ipoptions");
3254 fill_flags(cmd, O_IPOPT, f_ipopts, *av);
3259 NEED1("missing argument for iptos");
3260 fill_flags(cmd, O_IPTOS, f_iptos, *av);
3265 NEED1("uid requires argument");
3271 cmd->opcode = O_UID;
3272 uid = strtoul(*av, &end, 0);
3273 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
3275 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
3276 cmd32->d[0] = pwd->pw_uid;
3277 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3283 NEED1("gid requires argument");
3289 cmd->opcode = O_GID;
3290 gid = strtoul(*av, &end, 0);
3291 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
3293 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
3294 cmd32->d[0] = grp->gr_gid;
3295 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3301 NEED1("jail requires argument");
3306 cmd->opcode = O_JAIL;
3307 jid = (int)strtol(*av, &end, 0);
3308 if (jid < 0 || *end != '\0')
3309 errx(EX_DATAERR, "jail requires prison ID");
3310 cmd32->d[0] = (uint32_t)jid;
3311 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3317 fill_cmd(cmd, O_ESTAB, 0, 0);
3321 fill_cmd(cmd, O_TCPFLAGS, 0,
3322 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
3325 case TOK_TCPDATALEN:
3326 NEED1("tcpdatalen requires length");
3327 if (strpbrk(*av, "-,")) {
3328 if (!add_ports(cmd, *av, 0, O_TCPDATALEN))
3329 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
3331 fill_cmd(cmd, O_TCPDATALEN, 0,
3332 strtoul(*av, NULL, 0));
3337 NEED1("missing argument for tcpoptions");
3338 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
3344 NEED1("tcpseq/tcpack requires argument");
3345 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3346 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
3347 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
3352 NEED1("tcpwin requires length");
3353 fill_cmd(cmd, O_TCPWIN, 0,
3354 htons(strtoul(*av, NULL, 0)));
3359 NEED1("missing argument for tcpflags");
3360 cmd->opcode = O_TCPFLAGS;
3361 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
3367 errx(EX_USAGE, "keep-state cannot be part "
3370 errx(EX_USAGE, "only one of keep-state "
3371 "and limit is allowed");
3373 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
3377 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
3382 "limit cannot be part of an or block");
3384 errx(EX_USAGE, "only one of keep-state and "
3385 "limit is allowed");
3388 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
3389 cmd->opcode = O_LIMIT;
3390 c->limit_mask = c->conn_limit = 0;
3392 while ( av[0] != NULL ) {
3393 if ((val = match_token(limit_masks, *av)) <= 0)
3395 c->limit_mask |= val;
3399 if (c->limit_mask == 0)
3400 errx(EX_USAGE, "limit: missing limit mask");
3402 GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
3403 TOK_LIMIT, rule_options);
3410 NEED1("missing protocol");
3411 if (add_proto(cmd, *av, &proto)) {
3414 errx(EX_DATAERR, "invalid protocol ``%s''",
3419 NEED1("missing source IP");
3420 if (add_srcip(cmd, *av)) {
3426 NEED1("missing destination IP");
3427 if (add_dstip(cmd, *av)) {
3433 NEED1("missing source IP6");
3434 if (add_srcip6(cmd, *av)) {
3440 NEED1("missing destination IP6");
3441 if (add_dstip6(cmd, *av)) {
3447 NEED1("missing source port");
3448 if (_substrcmp(*av, "any") == 0 ||
3449 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
3452 errx(EX_DATAERR, "invalid source port %s", *av);
3456 NEED1("missing destination port");
3457 if (_substrcmp(*av, "any") == 0 ||
3458 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
3461 errx(EX_DATAERR, "invalid destination port %s",
3466 if (add_mac(cmd, av))
3471 NEED1("missing mac type");
3472 if (!add_mactype(cmd, *av))
3473 errx(EX_DATAERR, "invalid mac type %s", *av);
3477 case TOK_VERREVPATH:
3478 fill_cmd(cmd, O_VERREVPATH, 0, 0);
3481 case TOK_VERSRCREACH:
3482 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
3486 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
3490 fill_cmd(cmd, O_IPSEC, 0, 0);
3494 fill_cmd(cmd, O_IP6, 0, 0);
3498 fill_cmd(cmd, O_IP4, 0, 0);
3502 fill_ext6hdr( cmd, *av );
3507 if (proto != IPPROTO_IPV6 )
3508 errx( EX_USAGE, "flow-id filter is active "
3509 "only for ipv6 protocol\n");
3510 fill_flow6( (ipfw_insn_u32 *) cmd, *av );
3515 fill_comment(cmd, av);
3520 if (av[0] && strpbrk(*av, "-,")) {
3521 if (!add_ports(cmd, *av, 0, O_TAGGED))
3522 errx(EX_DATAERR, "tagged: invalid tag"
3528 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
3529 TOK_TAGGED, rule_options);
3530 fill_cmd(cmd, O_TAGGED, 0, tag);
3536 NEED1("fib requires fib number");
3537 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
3542 ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
3546 if (!av[0] || !av[1])
3547 errx(EX_USAGE, "format: lookup argument tablenum");
3548 cmd->opcode = O_IP_DST_LOOKUP;
3549 cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
3550 i = match_token(rule_options, *av);
3551 for (j = 0; lookup_key[j] >= 0 ; j++) {
3552 if (i == lookup_key[j])
3555 if (lookup_key[j] <= 0)
3556 errx(EX_USAGE, "format: cannot lookup on %s", *av);
3557 c->d[1] = j; // i converted to option
3559 cmd->arg1 = strtoul(*av, &p, 0);
3561 errx(EX_USAGE, "format: lookup argument tablenum");
3567 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
3569 if (F_LEN(cmd) > 0) { /* prepare to advance */
3571 cmd = next_cmd(cmd);
3577 * Now copy stuff into the rule.
3578 * If we have a keep-state option, the first instruction
3579 * must be a PROBE_STATE (which is generated here).
3580 * If we have a LOG option, it was stored as the first command,
3581 * and now must be moved to the top of the action part.
3583 dst = (ipfw_insn *)rule->cmd;
3586 * First thing to write into the command stream is the match probability.
3588 if (match_prob != 1) { /* 1 means always match */
3589 dst->opcode = O_PROB;
3591 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
3596 * generate O_PROBE_STATE if necessary
3598 if (have_state && have_state->opcode != O_CHECK_STATE) {
3599 fill_cmd(dst, O_PROBE_STATE, 0, 0);
3600 dst = next_cmd(dst);
3603 /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
3604 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
3607 switch (src->opcode) {
3615 bcopy(src, dst, i * sizeof(uint32_t));
3621 * put back the have_state command as last opcode
3623 if (have_state && have_state->opcode != O_CHECK_STATE) {
3624 i = F_LEN(have_state);
3625 bcopy(have_state, dst, i * sizeof(uint32_t));
3629 * start action section
3631 rule->act_ofs = dst - rule->cmd;
3633 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
3635 i = F_LEN(have_log);
3636 bcopy(have_log, dst, i * sizeof(uint32_t));
3640 i = F_LEN(have_altq);
3641 bcopy(have_altq, dst, i * sizeof(uint32_t));
3645 i = F_LEN(have_tag);
3646 bcopy(have_tag, dst, i * sizeof(uint32_t));
3650 * copy all other actions
3652 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
3654 bcopy(src, dst, i * sizeof(uint32_t));
3658 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
3659 i = (char *)dst - (char *)rule;
3660 if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1)
3661 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
3663 show_ipfw(rule, 0, 0);
3667 * clear the counters or the log counters.
3670 ipfw_zero(int ac, char *av[], int optname /* 0 = IP_FW_ZERO, 1 = IP_FW_RESETLOG */)
3672 uint32_t arg, saved_arg;
3675 char const *name = optname ? "RESETLOG" : "ZERO";
3677 optname = optname ? IP_FW_RESETLOG : IP_FW_ZERO;
3682 /* clear all entries */
3683 if (do_cmd(optname, NULL, 0) < 0)
3684 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name);
3686 printf("%s.\n", optname == IP_FW_ZERO ?
3687 "Accounting cleared":"Logging counts reset");
3694 if (isdigit(**av)) {
3695 arg = strtonum(*av, 0, 0xffff, &errstr);
3698 "invalid rule number %s\n", *av);
3701 arg |= (1 << 24) | ((co.use_set - 1) << 16);
3704 if (do_cmd(optname, &arg, sizeof(arg))) {
3705 warn("rule %u: setsockopt(IP_FW_%s)",
3707 failed = EX_UNAVAILABLE;
3708 } else if (!co.do_quiet)
3709 printf("Entry %d %s.\n", saved_arg,
3710 optname == IP_FW_ZERO ?
3711 "cleared" : "logging count reset");
3713 errx(EX_USAGE, "invalid rule number ``%s''", *av);
3716 if (failed != EX_OK)
3721 ipfw_flush(int force)
3723 int cmd = co.do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
3725 if (!force && !co.do_quiet) { /* need to ask user */
3728 printf("Are you sure? [yn] ");
3731 c = toupper(getc(stdin));
3732 while (c != '\n' && getc(stdin) != '\n')
3734 return; /* and do not flush */
3735 } while (c != 'Y' && c != 'N');
3737 if (c == 'N') /* user said no */
3744 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
3746 uint32_t arg = ((co.use_set - 1) & 0xffff) | (1 << 24);
3747 if (do_cmd(IP_FW_DEL, &arg, sizeof(arg)) < 0)
3748 err(EX_UNAVAILABLE, "setsockopt(IP_FW_DEL)");
3749 } else if (do_cmd(cmd, NULL, 0) < 0)
3750 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
3751 co.do_pipe ? "DUMMYNET" : "FW");
3753 printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
3757 static void table_list(ipfw_table_entry ent, int need_header);
3760 * This one handles all table-related commands
3761 * ipfw table N add addr[/masklen] [value]
3762 * ipfw table N delete addr[/masklen]
3763 * ipfw table {N | all} flush
3764 * ipfw table {N | all} list
3767 ipfw_table_handler(int ac, char *av[])
3769 ipfw_table_entry ent;
3775 uint32_t tables_max;
3777 len = sizeof(tables_max);
3778 if (sysctlbyname("net.inet.ip.fw.tables_max", &tables_max, &len,
3780 #ifdef IPFW_TABLES_MAX
3781 warn("Warn: Failed to get the max tables number via sysctl. "
3782 "Using the compiled in defaults. \nThe reason was");
3783 tables_max = IPFW_TABLES_MAX;
3785 errx(1, "Failed sysctlbyname(\"net.inet.ip.fw.tables_max\")");
3790 if (ac && isdigit(**av)) {
3791 ent.tbl = atoi(*av);
3794 } else if (ac && _substrcmp(*av, "all") == 0) {
3799 errx(EX_USAGE, "table number or 'all' keyword required");
3800 if (ent.tbl >= tables_max)
3801 errx(EX_USAGE, "The table number exceeds the maximum allowed "
3802 "value (%d)", tables_max - 1);
3803 NEED1("table needs command");
3804 if (is_all && _substrcmp(*av, "list") != 0
3805 && _substrcmp(*av, "flush") != 0)
3806 errx(EX_USAGE, "table number required");
3808 if (_substrcmp(*av, "add") == 0 ||
3809 _substrcmp(*av, "delete") == 0) {
3810 do_add = **av == 'a';
3813 errx(EX_USAGE, "IP address required");
3814 p = strchr(*av, '/');
3817 ent.masklen = atoi(p);
3818 if (ent.masklen > 32)
3819 errx(EX_DATAERR, "bad width ``%s''", p);
3822 if (lookup_host(*av, (struct in_addr *)&ent.addr) != 0)
3823 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
3827 /* isdigit is a bit of a hack here.. */
3828 if (strchr(*av, (int)'.') == NULL && isdigit(**av)) {
3829 ent.value = strtoul(*av, NULL, 0);
3831 if (lookup_host(*av, (struct in_addr *)&tval) == 0) {
3832 /* The value must be stored in host order *
3833 * so that the values < 65k can be distinguished */
3834 ent.value = ntohl(tval);
3836 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
3841 if (do_cmd(do_add ? IP_FW_TABLE_ADD : IP_FW_TABLE_DEL,
3842 &ent, sizeof(ent)) < 0) {
3843 /* If running silent, don't bomb out on these errors. */
3844 if (!(co.do_quiet && (errno == (do_add ? EEXIST : ESRCH))))
3845 err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)",
3846 do_add ? "ADD" : "DEL");
3847 /* In silent mode, react to a failed add by deleting */
3849 do_cmd(IP_FW_TABLE_DEL, &ent, sizeof(ent));
3850 if (do_cmd(IP_FW_TABLE_ADD,
3851 &ent, sizeof(ent)) < 0)
3853 "setsockopt(IP_FW_TABLE_ADD)");
3856 } else if (_substrcmp(*av, "flush") == 0) {
3857 a = is_all ? tables_max : (uint32_t)(ent.tbl + 1);
3859 if (do_cmd(IP_FW_TABLE_FLUSH, &ent.tbl,
3860 sizeof(ent.tbl)) < 0)
3861 err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)");
3862 } while (++ent.tbl < a);
3863 } else if (_substrcmp(*av, "list") == 0) {
3864 a = is_all ? tables_max : (uint32_t)(ent.tbl + 1);
3866 table_list(ent, is_all);
3867 } while (++ent.tbl < a);
3869 errx(EX_USAGE, "invalid table command %s", *av);
3873 table_list(ipfw_table_entry ent, int need_header)
3881 if (do_cmd(IP_FW_TABLE_GETSIZE, &a, (uintptr_t)&l) < 0)
3882 err(EX_OSERR, "getsockopt(IP_FW_TABLE_GETSIZE)");
3884 /* If a is zero we have nothing to do, the table is empty. */
3888 l = sizeof(*tbl) + a * sizeof(ipfw_table_entry);
3889 tbl = safe_calloc(1, l);
3891 if (do_cmd(IP_FW_TABLE_LIST, tbl, (uintptr_t)&l) < 0)
3892 err(EX_OSERR, "getsockopt(IP_FW_TABLE_LIST)");
3893 if (tbl->cnt && need_header)
3894 printf("---table(%d)---\n", tbl->tbl);
3895 for (a = 0; a < tbl->cnt; a++) {
3897 tval = tbl->ent[a].value;
3898 if (co.do_value_as_ip) {
3900 strncpy(tbuf, inet_ntoa(*(struct in_addr *)
3901 &tbl->ent[a].addr), 127);
3902 /* inet_ntoa expects network order */
3904 printf("%s/%u %s\n", tbuf, tbl->ent[a].masklen,
3905 inet_ntoa(*(struct in_addr *)&tval));
3907 printf("%s/%u %u\n",
3908 inet_ntoa(*(struct in_addr *)&tbl->ent[a].addr),
3909 tbl->ent[a].masklen, tval);