2 * Copyright (c) 2002-2003 Luigi Rizzo
3 * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
4 * Copyright (c) 1994 Ugen J.S.Antsilevich
6 * Idea and grammar partially left from:
7 * Copyright (c) 1993 Daniel Boulet
9 * Redistribution and use in source forms, with and without modification,
10 * are permitted provided that this entire comment appears intact.
12 * Redistribution in binary form may occur without any restrictions.
13 * Obviously, it would be nice if you gave credit where credit is due
14 * but requiring it would be too onerous.
16 * This software is provided ``AS IS'' without any warranties of any kind.
18 * NEW command line interface for IP firewall facility
23 #include <sys/types.h>
24 #include <sys/param.h>
25 #include <sys/socket.h>
26 #include <sys/sockio.h>
27 #include <sys/sysctl.h>
41 #include <time.h> /* ctime */
42 #include <timeconv.h> /* _long_to_time */
46 #include <net/ethernet.h>
47 #include <net/if.h> /* only IFNAMSIZ */
48 #include <netinet/in.h>
49 #include <netinet/in_systm.h> /* only n_short, n_long */
50 #include <netinet/ip.h>
51 #include <netinet/ip_icmp.h>
52 #include <netinet/ip_fw.h>
53 #include <netinet/tcp.h>
54 #include <arpa/inet.h>
56 struct cmdline_opts co; /* global options */
58 int resvd_set_number = RESVD_SET;
60 #define GET_UINT_ARG(arg, min, max, tok, s_x) do { \
62 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
63 if (_substrcmp(*av, "tablearg") == 0) { \
64 arg = IP_FW_TABLEARG; \
72 _xval = strtol(*av, &end, 10); \
74 if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
75 errx(EX_DATAERR, "%s: invalid argument: %s", \
76 match_value(s_x, tok), *av); \
78 if (errno == ERANGE || _xval < min || _xval > max) \
79 errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
80 match_value(s_x, tok), min, max, *av); \
82 if (_xval == IP_FW_TABLEARG) \
83 errx(EX_DATAERR, "%s: illegal argument value: %s", \
84 match_value(s_x, tok), *av); \
90 PRINT_UINT_ARG(const char *str, uint32_t arg)
94 if (arg == IP_FW_TABLEARG)
100 static struct _s_x f_tcpflags[] = {
111 static struct _s_x f_tcpopts[] = {
112 { "mss", IP_FW_TCPOPT_MSS },
113 { "maxseg", IP_FW_TCPOPT_MSS },
114 { "window", IP_FW_TCPOPT_WINDOW },
115 { "sack", IP_FW_TCPOPT_SACK },
116 { "ts", IP_FW_TCPOPT_TS },
117 { "timestamp", IP_FW_TCPOPT_TS },
118 { "cc", IP_FW_TCPOPT_CC },
124 * IP options span the range 0 to 255 so we need to remap them
125 * (though in fact only the low 5 bits are significant).
127 static struct _s_x f_ipopts[] = {
128 { "ssrr", IP_FW_IPOPT_SSRR},
129 { "lsrr", IP_FW_IPOPT_LSRR},
130 { "rr", IP_FW_IPOPT_RR},
131 { "ts", IP_FW_IPOPT_TS},
136 static struct _s_x f_iptos[] = {
137 { "lowdelay", IPTOS_LOWDELAY},
138 { "throughput", IPTOS_THROUGHPUT},
139 { "reliability", IPTOS_RELIABILITY},
140 { "mincost", IPTOS_MINCOST},
141 { "congestion", IPTOS_ECN_CE},
142 { "ecntransport", IPTOS_ECN_ECT0},
143 { "ip tos option", 0},
147 static struct _s_x limit_masks[] = {
148 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
149 {"src-addr", DYN_SRC_ADDR},
150 {"src-port", DYN_SRC_PORT},
151 {"dst-addr", DYN_DST_ADDR},
152 {"dst-port", DYN_DST_PORT},
157 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
158 * This is only used in this code.
160 #define IPPROTO_ETHERTYPE 0x1000
161 static struct _s_x ether_types[] = {
163 * Note, we cannot use "-:&/" in the names because they are field
164 * separators in the type specifications. Also, we use s = NULL as
165 * end-delimiter, because a type of 0 can be legal.
178 { "pppoe_disc", 0x8863 },
179 { "pppoe_sess", 0x8864 },
180 { "ipx_8022", 0x00E0 },
181 { "ipx_8023", 0x0000 },
182 { "ipx_ii", 0x8137 },
183 { "ipx_snap", 0x8137 },
190 static struct _s_x rule_actions[] = {
191 { "accept", TOK_ACCEPT },
192 { "pass", TOK_ACCEPT },
193 { "allow", TOK_ACCEPT },
194 { "permit", TOK_ACCEPT },
195 { "count", TOK_COUNT },
196 { "pipe", TOK_PIPE },
197 { "queue", TOK_QUEUE },
198 { "divert", TOK_DIVERT },
200 { "netgraph", TOK_NETGRAPH },
201 { "ngtee", TOK_NGTEE },
202 { "fwd", TOK_FORWARD },
203 { "forward", TOK_FORWARD },
204 { "skipto", TOK_SKIPTO },
205 { "deny", TOK_DENY },
206 { "drop", TOK_DENY },
207 { "reject", TOK_REJECT },
208 { "reset6", TOK_RESET6 },
209 { "reset", TOK_RESET },
210 { "unreach6", TOK_UNREACH6 },
211 { "unreach", TOK_UNREACH },
212 { "check-state", TOK_CHECKSTATE },
213 { "//", TOK_COMMENT },
215 { "reass", TOK_REASS },
216 { "setfib", TOK_SETFIB },
217 { "call", TOK_CALL },
218 { "return", TOK_RETURN },
219 { NULL, 0 } /* terminator */
222 static struct _s_x rule_action_params[] = {
223 { "altq", TOK_ALTQ },
226 { "untag", TOK_UNTAG },
227 { NULL, 0 } /* terminator */
231 * The 'lookup' instruction accepts one of the following arguments.
232 * -1 is a terminator for the list.
233 * Arguments are passed as v[1] in O_DST_LOOKUP options.
235 static int lookup_key[] = {
236 TOK_DSTIP, TOK_SRCIP, TOK_DSTPORT, TOK_SRCPORT,
237 TOK_UID, TOK_JAIL, TOK_DSCP, -1 };
239 static struct _s_x rule_options[] = {
240 { "tagged", TOK_TAGGED },
243 { "jail", TOK_JAIL },
245 { "limit", TOK_LIMIT },
246 { "keep-state", TOK_KEEPSTATE },
247 { "bridged", TOK_LAYER2 },
248 { "layer2", TOK_LAYER2 },
250 { "diverted", TOK_DIVERTED },
251 { "diverted-loopback", TOK_DIVERTEDLOOPBACK },
252 { "diverted-output", TOK_DIVERTEDOUTPUT },
253 { "xmit", TOK_XMIT },
254 { "recv", TOK_RECV },
256 { "fragment", TOK_FRAG },
257 { "frag", TOK_FRAG },
259 { "ipoptions", TOK_IPOPTS },
260 { "ipopts", TOK_IPOPTS },
261 { "iplen", TOK_IPLEN },
262 { "ipid", TOK_IPID },
263 { "ipprecedence", TOK_IPPRECEDENCE },
264 { "dscp", TOK_DSCP },
265 { "iptos", TOK_IPTOS },
266 { "ipttl", TOK_IPTTL },
267 { "ipversion", TOK_IPVER },
268 { "ipver", TOK_IPVER },
269 { "estab", TOK_ESTAB },
270 { "established", TOK_ESTAB },
271 { "setup", TOK_SETUP },
272 { "sockarg", TOK_SOCKARG },
273 { "tcpdatalen", TOK_TCPDATALEN },
274 { "tcpflags", TOK_TCPFLAGS },
275 { "tcpflgs", TOK_TCPFLAGS },
276 { "tcpoptions", TOK_TCPOPTS },
277 { "tcpopts", TOK_TCPOPTS },
278 { "tcpseq", TOK_TCPSEQ },
279 { "tcpack", TOK_TCPACK },
280 { "tcpwin", TOK_TCPWIN },
281 { "icmptype", TOK_ICMPTYPES },
282 { "icmptypes", TOK_ICMPTYPES },
283 { "dst-ip", TOK_DSTIP },
284 { "src-ip", TOK_SRCIP },
285 { "dst-port", TOK_DSTPORT },
286 { "src-port", TOK_SRCPORT },
287 { "proto", TOK_PROTO },
290 { "mac-type", TOK_MACTYPE },
291 { "verrevpath", TOK_VERREVPATH },
292 { "versrcreach", TOK_VERSRCREACH },
293 { "antispoof", TOK_ANTISPOOF },
294 { "ipsec", TOK_IPSEC },
295 { "icmp6type", TOK_ICMP6TYPES },
296 { "icmp6types", TOK_ICMP6TYPES },
297 { "ext6hdr", TOK_EXT6HDR},
298 { "flow-id", TOK_FLOWID},
303 { "dst-ipv6", TOK_DSTIP6},
304 { "dst-ip6", TOK_DSTIP6},
305 { "src-ipv6", TOK_SRCIP6},
306 { "src-ip6", TOK_SRCIP6},
307 { "lookup", TOK_LOOKUP},
308 { "//", TOK_COMMENT },
310 { "not", TOK_NOT }, /* pseudo option */
311 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
312 { "or", TOK_OR }, /* pseudo option */
313 { "|", /* escape */ TOK_OR }, /* pseudo option */
314 { "{", TOK_STARTBRACE }, /* pseudo option */
315 { "(", TOK_STARTBRACE }, /* pseudo option */
316 { "}", TOK_ENDBRACE }, /* pseudo option */
317 { ")", TOK_ENDBRACE }, /* pseudo option */
318 { NULL, 0 } /* terminator */
322 * Helper routine to print a possibly unaligned uint64_t on
323 * various platform. If width > 0, print the value with
324 * the desired width, followed by a space;
325 * otherwise, return the required width.
328 pr_u64(uint64_t *pd, int width)
331 #define U64_FMT "I64"
333 #define U64_FMT "llu"
336 unsigned long long d;
338 bcopy (pd, &u, sizeof(u));
341 printf("%*" U64_FMT " ", width, d) :
342 snprintf(NULL, 0, "%" U64_FMT, d) ;
347 safe_calloc(size_t number, size_t size)
349 void *ret = calloc(number, size);
352 err(EX_OSERR, "calloc");
357 safe_realloc(void *ptr, size_t size)
359 void *ret = realloc(ptr, size);
362 err(EX_OSERR, "realloc");
367 * conditionally runs the command.
368 * Selected options or negative -> getsockopt
371 do_cmd(int optname, void *optval, uintptr_t optlen)
373 static int s = -1; /* the socket */
380 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
382 err(EX_UNAVAILABLE, "socket");
384 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
385 optname == IP_FW_ADD || optname == IP_FW_TABLE_LIST ||
386 optname == IP_FW_TABLE_GETSIZE ||
387 optname == IP_FW_NAT_GET_CONFIG ||
389 optname == IP_FW_NAT_GET_LOG) {
392 i = getsockopt(s, IPPROTO_IP, optname, optval,
393 (socklen_t *)optlen);
395 i = setsockopt(s, IPPROTO_IP, optname, optval, optlen);
401 * match_token takes a table and a string, returns the value associated
402 * with the string (-1 in case of failure).
405 match_token(struct _s_x *table, char *string)
408 uint i = strlen(string);
410 for (pt = table ; i && pt->s != NULL ; pt++)
411 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
417 * match_value takes a table and a value, returns the string associated
418 * with the value (NULL in case of failure).
421 match_value(struct _s_x *p, int value)
423 for (; p->s != NULL; p++)
430 * _substrcmp takes two strings and returns 1 if they do not match,
431 * and 0 if they match exactly or the first string is a sub-string
432 * of the second. A warning is printed to stderr in the case that the
433 * first string is a sub-string of the second.
435 * This function will be removed in the future through the usual
436 * deprecation process.
439 _substrcmp(const char *str1, const char* str2)
442 if (strncmp(str1, str2, strlen(str1)) != 0)
445 if (strlen(str1) != strlen(str2))
446 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
452 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
453 * and 0 if they match exactly or the second string is a sub-string
454 * of the first. A warning is printed to stderr in the case that the
455 * first string does not match the third.
457 * This function exists to warn about the bizzare construction
458 * strncmp(str, "by", 2) which is used to allow people to use a shotcut
459 * for "bytes". The problem is that in addition to accepting "by",
460 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
461 * other string beginning with "by".
463 * This function will be removed in the future through the usual
464 * deprecation process.
467 _substrcmp2(const char *str1, const char* str2, const char* str3)
470 if (strncmp(str1, str2, strlen(str2)) != 0)
473 if (strcmp(str1, str3) != 0)
474 warnx("DEPRECATED: '%s' matched '%s'",
480 * prints one port, symbolic or numeric
483 print_port(int proto, uint16_t port)
486 if (proto == IPPROTO_ETHERTYPE) {
489 if (co.do_resolv && (s = match_value(ether_types, port)) )
492 printf("0x%04x", port);
494 struct servent *se = NULL;
496 struct protoent *pe = getprotobynumber(proto);
498 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
501 printf("%s", se->s_name);
507 static struct _s_x _port_name[] = {
508 {"dst-port", O_IP_DSTPORT},
509 {"src-port", O_IP_SRCPORT},
513 {"mac-type", O_MAC_TYPE},
514 {"tcpdatalen", O_TCPDATALEN},
515 {"tagged", O_TAGGED},
520 * Print the values in a list 16-bit items of the types above.
521 * XXX todo: add support for mask.
524 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode)
526 uint16_t *p = cmd->ports;
531 sep = match_value(_port_name, opcode);
537 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
539 print_port(proto, p[0]);
542 print_port(proto, p[1]);
549 * Like strtol, but also translates service names into port numbers
550 * for some protocols.
552 * proto == -1 disables the protocol check;
553 * proto == IPPROTO_ETHERTYPE looks up an internal table
554 * proto == <some value in /etc/protocols> matches the values there.
555 * Returns *end == s in case the parameter is not found.
558 strtoport(char *s, char **end, int base, int proto)
564 *end = s; /* default - not found */
566 return 0; /* not found */
569 return strtol(s, end, base);
572 * find separator. '\\' escapes the next char.
574 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
575 if (*s1 == '\\' && s1[1] != '\0')
578 buf = safe_calloc(s1 - s + 1, 1);
581 * copy into a buffer skipping backslashes
583 for (p = s, i = 0; p != s1 ; p++)
588 if (proto == IPPROTO_ETHERTYPE) {
589 i = match_token(ether_types, buf);
591 if (i != -1) { /* found */
596 struct protoent *pe = NULL;
600 pe = getprotobynumber(proto);
602 se = getservbyname(buf, pe ? pe->p_name : NULL);
606 return ntohs(se->s_port);
609 return 0; /* not found */
613 * Fill the body of the command with the list of port ranges.
616 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto)
618 uint16_t a, b, *p = cmd->ports;
623 a = strtoport(av, &s, 0, proto);
624 if (s == av) /* empty or invalid argument */
628 case '-': /* a range */
630 b = strtoport(av, &s, 0, proto);
631 /* Reject expressions like '1-abc' or '1-2-3'. */
632 if (s == av || (*s != ',' && *s != '\0'))
637 case ',': /* comma separated list */
642 warnx("port list: invalid separator <%c> in <%s>",
652 if (i + 1 > F_LEN_MASK)
653 errx(EX_DATAERR, "too many ports/ranges\n");
654 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
659 static struct _s_x icmpcodes[] = {
660 { "net", ICMP_UNREACH_NET },
661 { "host", ICMP_UNREACH_HOST },
662 { "protocol", ICMP_UNREACH_PROTOCOL },
663 { "port", ICMP_UNREACH_PORT },
664 { "needfrag", ICMP_UNREACH_NEEDFRAG },
665 { "srcfail", ICMP_UNREACH_SRCFAIL },
666 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
667 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
668 { "isolated", ICMP_UNREACH_ISOLATED },
669 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
670 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
671 { "tosnet", ICMP_UNREACH_TOSNET },
672 { "toshost", ICMP_UNREACH_TOSHOST },
673 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
674 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
675 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
680 fill_reject_code(u_short *codep, char *str)
685 val = strtoul(str, &s, 0);
686 if (s == str || *s != '\0' || val >= 0x100)
687 val = match_token(icmpcodes, str);
689 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
695 print_reject_code(uint16_t code)
697 char const *s = match_value(icmpcodes, code);
700 printf("unreach %s", s);
702 printf("unreach %u", code);
706 * Returns the number of bits set (from left) in a contiguous bitmask,
707 * or -1 if the mask is not contiguous.
708 * XXX this needs a proper fix.
709 * This effectively works on masks in big-endian (network) format.
710 * when compiled on little endian architectures.
712 * First bit is bit 7 of the first byte -- note, for MAC addresses,
713 * the first bit on the wire is bit 0 of the first byte.
714 * len is the max length in bits.
717 contigmask(uint8_t *p, int len)
721 for (i=0; i<len ; i++)
722 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
724 for (n=i+1; n < len; n++)
725 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
726 return -1; /* mask not contiguous */
731 * print flags set/clear in the two bitmasks passed as parameters.
732 * There is a specialized check for f_tcpflags.
735 print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list)
737 char const *comma = "";
739 uint8_t set = cmd->arg1 & 0xff;
740 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
742 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
747 printf(" %s ", name);
748 for (i=0; list[i].x != 0; i++) {
749 if (set & list[i].x) {
751 printf("%s%s", comma, list[i].s);
754 if (clear & list[i].x) {
756 printf("%s!%s", comma, list[i].s);
763 * Print the ip address contained in a command.
766 print_ip(ipfw_insn_ip *cmd, char const *s)
768 struct hostent *he = NULL;
769 uint32_t len = F_LEN((ipfw_insn *)cmd);
770 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
772 if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
774 const char *arg = "<invalid>";
776 if (d < sizeof(lookup_key)/sizeof(lookup_key[0]))
777 arg = match_value(rule_options, lookup_key[d]);
778 printf("%s lookup %s %d", cmd->o.len & F_NOT ? " not": "",
782 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
784 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
788 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
789 cmd->o.opcode == O_IP_DST_LOOKUP) {
790 printf("table(%u", ((ipfw_insn *)cmd)->arg1);
791 if (len == F_INSN_SIZE(ipfw_insn_u32))
796 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
797 uint32_t x, *map = (uint32_t *)&(cmd->mask);
803 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
804 printf("%s/%d", inet_ntoa(cmd->addr),
805 contigmask((uint8_t *)&x, 32));
806 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
807 x &= 0xff; /* base */
809 * Print bits and ranges.
810 * Locate first bit set (i), then locate first bit unset (j).
811 * If we have 3+ consecutive bits set, then print them as a
812 * range, otherwise only print the initial bit and rescan.
814 for (i=0; i < cmd->o.arg1; i++)
815 if (map[i/32] & (1<<(i & 31))) {
816 for (j=i+1; j < cmd->o.arg1; j++)
817 if (!(map[ j/32] & (1<<(j & 31))))
819 printf("%c%d", comma, i+x);
820 if (j>i+2) { /* range has at least 3 elements */
821 printf("-%d", j-1+x);
830 * len == 2 indicates a single IP, whereas lists of 1 or more
831 * addr/mask pairs have len = (2n+1). We convert len to n so we
832 * use that to count the number of entries.
834 for (len = len / 2; len > 0; len--, a += 2) {
835 int mb = /* mask length */
836 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
837 32 : contigmask((uint8_t *)&(a[1]), 32);
838 if (mb == 32 && co.do_resolv)
839 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
840 if (he != NULL) /* resolved to name */
841 printf("%s", he->h_name);
842 else if (mb == 0) /* any */
844 else { /* numeric IP followed by some kind of mask */
845 printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) );
847 printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) );
857 * prints a MAC address/mask pair
860 print_mac(uint8_t *addr, uint8_t *mask)
862 int l = contigmask(mask, 48);
867 printf(" %02x:%02x:%02x:%02x:%02x:%02x",
868 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
870 printf("&%02x:%02x:%02x:%02x:%02x:%02x",
871 mask[0], mask[1], mask[2],
872 mask[3], mask[4], mask[5]);
879 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
888 type = strtoul(av, &av, 0);
890 if (*av != ',' && *av != '\0')
891 errx(EX_DATAERR, "invalid ICMP type");
894 errx(EX_DATAERR, "ICMP type out of range");
896 cmd->d[0] |= 1 << type;
898 cmd->o.opcode = O_ICMPTYPE;
899 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
903 print_icmptypes(ipfw_insn_u32 *cmd)
908 printf(" icmptypes");
909 for (i = 0; i < 32; i++) {
910 if ( (cmd->d[0] & (1 << (i))) == 0)
912 printf("%c%d", sep, i);
918 * show_ipfw() prints the body of an ipfw rule.
919 * Because the standard rule has at least proto src_ip dst_ip, we use
920 * a helper function to produce these entries if not provided explicitly.
921 * The first argument is the list of fields we have, the second is
922 * the list of fields we want to be printed.
924 * Special cases if we have provided a MAC header:
925 * + if the rule does not contain IP addresses/ports, do not print them;
926 * + if the rule does not contain an IP proto, print "all" instead of "ip";
928 * Once we have 'have_options', IP header fields are printed as options.
930 #define HAVE_PROTO 0x0001
931 #define HAVE_SRCIP 0x0002
932 #define HAVE_DSTIP 0x0004
933 #define HAVE_PROTO4 0x0008
934 #define HAVE_PROTO6 0x0010
935 #define HAVE_IP 0x0100
936 #define HAVE_OPTIONS 0x8000
939 show_prerequisites(int *flags, int want, int cmd __unused)
943 if ( (*flags & HAVE_IP) == HAVE_IP)
944 *flags |= HAVE_OPTIONS;
946 if ( !(*flags & HAVE_OPTIONS)) {
947 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) {
948 if ( (*flags & HAVE_PROTO4))
950 else if ( (*flags & HAVE_PROTO6))
955 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
957 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
964 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth)
966 static int twidth = 0;
968 ipfw_insn *cmd, *tagptr = NULL;
969 const char *comment = NULL; /* ptr to comment if we have one */
970 int proto = 0; /* default */
971 int flags = 0; /* prerequisites */
972 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
973 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
974 int or_block = 0; /* we are in an or block */
975 uint32_t set_disable;
977 bcopy(&rule->next_rule, &set_disable, sizeof(set_disable));
979 if (set_disable & (1 << rule->set)) { /* disabled */
983 printf("# DISABLED ");
985 printf("%05u ", rule->rulenum);
987 if (pcwidth > 0 || bcwidth > 0) {
988 pr_u64(&rule->pcnt, pcwidth);
989 pr_u64(&rule->bcnt, bcwidth);
993 printf("%10u ", rule->timestamp);
994 else if (co.do_time == 1) {
996 time_t t = (time_t)0;
999 strcpy(timestr, ctime(&t));
1000 *strchr(timestr, '\n') = '\0';
1001 twidth = strlen(timestr);
1003 if (rule->timestamp) {
1004 t = _long_to_time(rule->timestamp);
1006 strcpy(timestr, ctime(&t));
1007 *strchr(timestr, '\n') = '\0';
1008 printf("%s ", timestr);
1010 printf("%*s", twidth, " ");
1015 printf("set %d ", rule->set);
1018 * print the optional "match probability"
1020 if (rule->cmd_len > 0) {
1022 if (cmd->opcode == O_PROB) {
1023 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1024 double d = 1.0 * p->d[0];
1026 d = (d / 0x7fffffff);
1027 printf("prob %f ", d);
1032 * first print actions
1034 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1035 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1036 switch(cmd->opcode) {
1038 printf("check-state");
1039 /* avoid printing anything else */
1040 flags = HAVE_PROTO | HAVE_SRCIP |
1041 HAVE_DSTIP | HAVE_IP;
1057 if (cmd->arg1 == ICMP_REJECT_RST)
1059 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1062 print_reject_code(cmd->arg1);
1066 if (cmd->arg1 == ICMP6_UNREACH_RST)
1069 print_unreach6_code(cmd->arg1);
1073 PRINT_UINT_ARG("skipto ", cmd->arg1);
1077 PRINT_UINT_ARG("pipe ", cmd->arg1);
1081 PRINT_UINT_ARG("queue ", cmd->arg1);
1085 PRINT_UINT_ARG("divert ", cmd->arg1);
1089 PRINT_UINT_ARG("tee ", cmd->arg1);
1093 PRINT_UINT_ARG("netgraph ", cmd->arg1);
1097 PRINT_UINT_ARG("ngtee ", cmd->arg1);
1102 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1104 if (s->sa.sin_addr.s_addr == INADDR_ANY) {
1105 printf("fwd tablearg");
1107 printf("fwd %s", inet_ntoa(s->sa.sin_addr));
1110 printf(",%d", s->sa.sin_port);
1114 case O_LOG: /* O_LOG is printed last */
1115 logptr = (ipfw_insn_log *)cmd;
1118 case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1119 altqptr = (ipfw_insn_altq *)cmd;
1128 PRINT_UINT_ARG("nat ", cmd->arg1);
1130 printf("nat global");
1134 PRINT_UINT_ARG("setfib ", cmd->arg1);
1142 if (cmd->len & F_NOT)
1145 PRINT_UINT_ARG("call ", cmd->arg1);
1149 printf("** unrecognized action %d len %d ",
1150 cmd->opcode, cmd->len);
1154 if (logptr->max_log > 0)
1155 printf(" log logamount %d", logptr->max_log);
1161 print_altq_cmd(altqptr);
1165 if (tagptr->len & F_NOT)
1166 PRINT_UINT_ARG(" untag ", tagptr->arg1);
1168 PRINT_UINT_ARG(" tag ", tagptr->arg1);
1172 * then print the body.
1174 for (l = rule->act_ofs, cmd = rule->cmd ;
1175 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1176 if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1178 if (cmd->opcode == O_IP4) {
1179 flags |= HAVE_PROTO4;
1181 } else if (cmd->opcode == O_IP6) {
1182 flags |= HAVE_PROTO6;
1186 if (rule->_pad & 1) { /* empty rules before options */
1187 if (!co.do_compact) {
1188 show_prerequisites(&flags, HAVE_PROTO, 0);
1189 printf(" from any to any");
1191 flags |= HAVE_IP | HAVE_OPTIONS | HAVE_PROTO |
1192 HAVE_SRCIP | HAVE_DSTIP;
1195 if (co.comment_only)
1198 for (l = rule->act_ofs, cmd = rule->cmd ;
1199 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1201 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1203 if (co.comment_only) {
1204 if (cmd->opcode != O_NOP)
1206 printf(" // %s\n", (char *)(cmd + 1));
1210 show_prerequisites(&flags, 0, cmd->opcode);
1212 switch(cmd->opcode) {
1214 break; /* done already */
1217 break; /* no need to print anything here */
1220 case O_IP_SRC_LOOKUP:
1224 show_prerequisites(&flags, HAVE_PROTO, 0);
1225 if (!(flags & HAVE_SRCIP))
1227 if ((cmd->len & F_OR) && !or_block)
1229 print_ip((ipfw_insn_ip *)cmd,
1230 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1231 flags |= HAVE_SRCIP;
1235 case O_IP_DST_LOOKUP:
1239 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1240 if (!(flags & HAVE_DSTIP))
1242 if ((cmd->len & F_OR) && !or_block)
1244 print_ip((ipfw_insn_ip *)cmd,
1245 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1246 flags |= HAVE_DSTIP;
1250 case O_IP6_SRC_MASK:
1252 show_prerequisites(&flags, HAVE_PROTO, 0);
1253 if (!(flags & HAVE_SRCIP))
1255 if ((cmd->len & F_OR) && !or_block)
1257 print_ip6((ipfw_insn_ip6 *)cmd,
1258 (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1259 flags |= HAVE_SRCIP | HAVE_PROTO;
1263 case O_IP6_DST_MASK:
1265 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1266 if (!(flags & HAVE_DSTIP))
1268 if ((cmd->len & F_OR) && !or_block)
1270 print_ip6((ipfw_insn_ip6 *)cmd,
1271 (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1272 flags |= HAVE_DSTIP;
1276 print_flow6id( (ipfw_insn_u32 *) cmd );
1277 flags |= HAVE_OPTIONS;
1281 show_prerequisites(&flags,
1282 HAVE_PROTO | HAVE_SRCIP |
1283 HAVE_DSTIP | HAVE_IP, 0);
1285 if (flags & HAVE_DSTIP)
1287 show_prerequisites(&flags,
1288 HAVE_PROTO | HAVE_SRCIP, 0);
1289 if ((cmd->len & F_OR) && !or_block)
1291 if (cmd->len & F_NOT)
1293 print_newports((ipfw_insn_u16 *)cmd, proto,
1294 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1298 struct protoent *pe = NULL;
1300 if ((cmd->len & F_OR) && !or_block)
1302 if (cmd->len & F_NOT)
1305 pe = getprotobynumber(cmd->arg1);
1306 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1307 !(flags & HAVE_PROTO))
1308 show_prerequisites(&flags,
1309 HAVE_PROTO | HAVE_IP | HAVE_SRCIP |
1310 HAVE_DSTIP | HAVE_OPTIONS, 0);
1311 if (flags & HAVE_OPTIONS)
1314 printf(" %s", pe->p_name);
1316 printf(" %u", cmd->arg1);
1318 flags |= HAVE_PROTO;
1321 default: /*options ... */
1322 if (!(cmd->len & (F_OR|F_NOT)))
1323 if (((cmd->opcode == O_IP6) &&
1324 (flags & HAVE_PROTO6)) ||
1325 ((cmd->opcode == O_IP4) &&
1326 (flags & HAVE_PROTO4)))
1328 show_prerequisites(&flags, HAVE_PROTO | HAVE_SRCIP |
1329 HAVE_DSTIP | HAVE_IP | HAVE_OPTIONS, 0);
1330 if ((cmd->len & F_OR) && !or_block)
1332 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1334 switch(cmd->opcode) {
1336 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1339 print_mac(m->addr, m->mask);
1340 print_mac(m->addr + 6, m->mask + 6);
1345 print_newports((ipfw_insn_u16 *)cmd,
1346 IPPROTO_ETHERTYPE, cmd->opcode);
1355 printf(" fib %u", cmd->arg1 );
1362 printf(cmd->len & F_NOT ? " out" : " in");
1366 switch (cmd->arg1) {
1368 printf(" diverted");
1371 printf(" diverted-loopback");
1374 printf(" diverted-output");
1377 printf(" diverted-?<%u>", cmd->arg1);
1390 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1392 if (cmd->opcode == O_XMIT)
1394 else if (cmd->opcode == O_RECV)
1396 else /* if (cmd->opcode == O_VIA) */
1398 if (cmdif->name[0] == '\0')
1400 inet_ntoa(cmdif->p.ip));
1402 printf(" %s %s", s, cmdif->name);
1407 if (F_LEN(cmd) == 1)
1408 printf(" ipid %u", cmd->arg1 );
1410 print_newports((ipfw_insn_u16 *)cmd, 0,
1415 if (F_LEN(cmd) == 1)
1416 printf(" ipttl %u", cmd->arg1 );
1418 print_newports((ipfw_insn_u16 *)cmd, 0,
1423 printf(" ipver %u", cmd->arg1 );
1426 case O_IPPRECEDENCE:
1427 printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1431 if (F_LEN(cmd) == 1)
1432 printf(" iplen %u", cmd->arg1 );
1434 print_newports((ipfw_insn_u16 *)cmd, 0,
1439 print_flags("ipoptions", cmd, f_ipopts);
1443 print_flags("iptos", cmd, f_iptos);
1447 print_icmptypes((ipfw_insn_u32 *)cmd);
1451 printf(" established");
1455 if (F_LEN(cmd) == 1)
1456 printf(" tcpdatalen %u", cmd->arg1 );
1458 print_newports((ipfw_insn_u16 *)cmd, 0,
1463 print_flags("tcpflags", cmd, f_tcpflags);
1467 print_flags("tcpoptions", cmd, f_tcpopts);
1471 printf(" tcpwin %d", ntohs(cmd->arg1));
1475 printf(" tcpack %d", ntohl(cmd32->d[0]));
1479 printf(" tcpseq %d", ntohl(cmd32->d[0]));
1484 struct passwd *pwd = getpwuid(cmd32->d[0]);
1487 printf(" uid %s", pwd->pw_name);
1489 printf(" uid %u", cmd32->d[0]);
1495 struct group *grp = getgrgid(cmd32->d[0]);
1498 printf(" gid %s", grp->gr_name);
1500 printf(" gid %u", cmd32->d[0]);
1505 printf(" jail %d", cmd32->d[0]);
1509 printf(" verrevpath");
1513 printf(" versrcreach");
1517 printf(" antispoof");
1525 comment = (char *)(cmd + 1);
1529 printf(" keep-state");
1533 struct _s_x *p = limit_masks;
1534 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1535 uint8_t x = c->limit_mask;
1536 char const *comma = " ";
1539 for (; p->x != 0 ; p++)
1540 if ((x & p->x) == p->x) {
1542 printf("%s%s", comma, p->s);
1545 PRINT_UINT_ARG(" ", c->conn_limit);
1558 print_icmp6types((ipfw_insn_u32 *)cmd);
1562 print_ext6hdr( (ipfw_insn *) cmd );
1566 if (F_LEN(cmd) == 1)
1567 PRINT_UINT_ARG(" tagged ", cmd->arg1);
1569 print_newports((ipfw_insn_u16 *)cmd, 0,
1574 printf(" [opcode %d len %d]",
1575 cmd->opcode, cmd->len);
1578 if (cmd->len & F_OR) {
1581 } else if (or_block) {
1586 show_prerequisites(&flags, HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP
1589 printf(" // %s", comment);
1594 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth)
1596 struct protoent *pe;
1599 char buf[INET6_ADDRSTRLEN];
1601 if (!co.do_expired) {
1602 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1605 bcopy(&d->rule, &rulenum, sizeof(rulenum));
1606 printf("%05d", rulenum);
1607 if (pcwidth > 0 || bcwidth > 0) {
1609 pr_u64(&d->pcnt, pcwidth);
1610 pr_u64(&d->bcnt, bcwidth);
1611 printf("(%ds)", d->expire);
1613 switch (d->dyn_type) {
1614 case O_LIMIT_PARENT:
1615 printf(" PARENT %d", d->count);
1620 case O_KEEP_STATE: /* bidir, no mask */
1625 if ((pe = getprotobynumber(d->id.proto)) != NULL)
1626 printf(" %s", pe->p_name);
1628 printf(" proto %u", d->id.proto);
1630 if (d->id.addr_type == 4) {
1631 a.s_addr = htonl(d->id.src_ip);
1632 printf(" %s %d", inet_ntoa(a), d->id.src_port);
1634 a.s_addr = htonl(d->id.dst_ip);
1635 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
1636 } else if (d->id.addr_type == 6) {
1637 printf(" %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
1638 sizeof(buf)), d->id.src_port);
1639 printf(" <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6, buf,
1640 sizeof(buf)), d->id.dst_port);
1642 printf(" UNKNOWN <-> UNKNOWN\n");
1648 * This one handles all set-related commands
1649 * ipfw set { show | enable | disable }
1651 * ipfw set move X to Y
1652 * ipfw set move rule X to Y
1655 ipfw_sets_handler(char *av[])
1657 uint32_t set_disable, masks[2];
1660 uint8_t cmd, new_set;
1665 errx(EX_USAGE, "set needs command");
1666 if (_substrcmp(*av, "show") == 0) {
1671 nalloc = nbytes = sizeof(struct ip_fw);
1672 while (nbytes >= nalloc) {
1675 nalloc = nalloc * 2 + 200;
1677 data = safe_calloc(1, nbytes);
1678 if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0)
1679 err(EX_OSERR, "getsockopt(IP_FW_GET)");
1682 bcopy(&((struct ip_fw *)data)->next_rule,
1683 &set_disable, sizeof(set_disable));
1685 for (i = 0, msg = "disable" ; i < RESVD_SET; i++)
1686 if ((set_disable & (1<<i))) {
1687 printf("%s %d", msg, i);
1690 msg = (set_disable) ? " enable" : "enable";
1691 for (i = 0; i < RESVD_SET; i++)
1692 if (!(set_disable & (1<<i))) {
1693 printf("%s %d", msg, i);
1697 } else if (_substrcmp(*av, "swap") == 0) {
1699 if ( av[0] == NULL || av[1] == NULL )
1700 errx(EX_USAGE, "set swap needs 2 set numbers\n");
1701 rulenum = atoi(av[0]);
1702 new_set = atoi(av[1]);
1703 if (!isdigit(*(av[0])) || rulenum > RESVD_SET)
1704 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
1705 if (!isdigit(*(av[1])) || new_set > RESVD_SET)
1706 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
1707 masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
1708 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
1709 } else if (_substrcmp(*av, "move") == 0) {
1711 if (av[0] && _substrcmp(*av, "rule") == 0) {
1716 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
1717 av[3] != NULL || _substrcmp(av[1], "to") != 0)
1718 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
1719 rulenum = atoi(av[0]);
1720 new_set = atoi(av[2]);
1721 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) ||
1722 (cmd == 2 && rulenum == IPFW_DEFAULT_RULE) )
1723 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
1724 if (!isdigit(*(av[2])) || new_set > RESVD_SET)
1725 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
1726 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
1727 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
1728 } else if (_substrcmp(*av, "disable") == 0 ||
1729 _substrcmp(*av, "enable") == 0 ) {
1730 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
1733 masks[0] = masks[1] = 0;
1736 if (isdigit(**av)) {
1738 if (i < 0 || i > RESVD_SET)
1740 "invalid set number %d\n", i);
1741 masks[which] |= (1<<i);
1742 } else if (_substrcmp(*av, "disable") == 0)
1744 else if (_substrcmp(*av, "enable") == 0)
1748 "invalid set command %s\n", *av);
1751 if ( (masks[0] & masks[1]) != 0 )
1753 "cannot enable and disable the same set\n");
1755 i = do_cmd(IP_FW_DEL, masks, sizeof(masks));
1757 warn("set enable/disable: setsockopt(IP_FW_DEL)");
1759 errx(EX_USAGE, "invalid set command %s\n", *av);
1763 ipfw_sysctl_handler(char *av[], int which)
1767 if (av[0] == NULL) {
1768 warnx("missing keyword to enable/disable\n");
1769 } else if (_substrcmp(*av, "firewall") == 0) {
1770 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
1771 &which, sizeof(which));
1772 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
1773 &which, sizeof(which));
1774 } else if (_substrcmp(*av, "one_pass") == 0) {
1775 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
1776 &which, sizeof(which));
1777 } else if (_substrcmp(*av, "debug") == 0) {
1778 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
1779 &which, sizeof(which));
1780 } else if (_substrcmp(*av, "verbose") == 0) {
1781 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
1782 &which, sizeof(which));
1783 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
1784 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
1785 &which, sizeof(which));
1787 } else if (_substrcmp(*av, "altq") == 0) {
1788 altq_set_enabled(which);
1791 warnx("unrecognize enable/disable keyword: %s\n", *av);
1796 ipfw_list(int ac, char *av[], int show_counters)
1799 ipfw_dyn_rule *dynrules, *d;
1801 #define NEXT(r) ((struct ip_fw *)((char *)r + RULESIZE(r)))
1804 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
1805 int exitval = EX_OK;
1813 const int ocmd = co.do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
1814 int nalloc = 1024; /* start somewhere... */
1819 fprintf(stderr, "Testing only, list disabled\n");
1823 dummynet_list(ac, av, show_counters);
1830 /* get rules or pipes from kernel, resizing array as necessary */
1833 while (nbytes >= nalloc) {
1834 nalloc = nalloc * 2 + 200;
1836 data = safe_realloc(data, nbytes);
1837 if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0)
1838 err(EX_OSERR, "getsockopt(IP_%s_GET)",
1839 co.do_pipe ? "DUMMYNET" : "FW");
1843 * Count static rules. They have variable size so we
1844 * need to scan the list to count them.
1846 for (nstat = 1, r = data, lim = (char *)data + nbytes;
1847 r->rulenum < IPFW_DEFAULT_RULE && (char *)r < lim;
1848 ++nstat, r = NEXT(r) )
1852 * Count dynamic rules. This is easier as they have
1856 dynrules = (ipfw_dyn_rule *)r ;
1857 n = (char *)r - (char *)data;
1858 ndyn = (nbytes - n) / sizeof *dynrules;
1860 /* if showing stats, figure out column widths ahead of time */
1861 bcwidth = pcwidth = 0;
1862 if (show_counters) {
1863 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
1864 /* skip rules from another set */
1865 if (co.use_set && r->set != co.use_set - 1)
1868 /* packet counter */
1869 width = pr_u64(&r->pcnt, 0);
1870 if (width > pcwidth)
1874 width = pr_u64(&r->bcnt, 0);
1875 if (width > bcwidth)
1879 if (co.do_dynamic && ndyn) {
1880 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1882 /* skip rules from another set */
1883 bcopy((char *)&d->rule + sizeof(uint16_t),
1884 &set, sizeof(uint8_t));
1885 if (set != co.use_set - 1)
1888 width = pr_u64(&d->pcnt, 0);
1889 if (width > pcwidth)
1892 width = pr_u64(&d->bcnt, 0);
1893 if (width > bcwidth)
1897 /* if no rule numbers were specified, list all rules */
1899 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
1900 if (co.use_set && r->set != co.use_set - 1)
1902 show_ipfw(r, pcwidth, bcwidth);
1905 if (co.do_dynamic && ndyn) {
1906 printf("## Dynamic rules (%d):\n", ndyn);
1907 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1909 bcopy((char *)&d->rule + sizeof(uint16_t),
1910 &set, sizeof(uint8_t));
1911 if (set != co.use_set - 1)
1914 show_dyn_ipfw(d, pcwidth, bcwidth);
1920 /* display specific rules requested on command line */
1922 for (lac = ac, lav = av; lac != 0; lac--) {
1923 /* convert command line rule # */
1924 last = rnum = strtoul(*lav++, &endptr, 10);
1926 last = strtoul(endptr+1, &endptr, 10);
1929 warnx("invalid rule number: %s", *(lav - 1));
1932 for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) {
1933 if (r->rulenum > last)
1935 if (co.use_set && r->set != co.use_set - 1)
1937 if (r->rulenum >= rnum && r->rulenum <= last) {
1938 show_ipfw(r, pcwidth, bcwidth);
1943 /* give precedence to other error(s) */
1944 if (exitval == EX_OK)
1945 exitval = EX_UNAVAILABLE;
1946 warnx("rule %lu does not exist", rnum);
1950 if (co.do_dynamic && ndyn) {
1951 printf("## Dynamic rules:\n");
1952 for (lac = ac, lav = av; lac != 0; lac--) {
1953 last = rnum = strtoul(*lav++, &endptr, 10);
1955 last = strtoul(endptr+1, &endptr, 10);
1957 /* already warned */
1959 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1962 bcopy(&d->rule, &rulenum, sizeof(rulenum));
1966 bcopy((char *)&d->rule + sizeof(uint16_t),
1967 &set, sizeof(uint8_t));
1968 if (set != co.use_set - 1)
1971 if (r->rulenum >= rnum && r->rulenum <= last)
1972 show_dyn_ipfw(d, pcwidth, bcwidth);
1982 if (exitval != EX_OK)
1988 lookup_host (char *host, struct in_addr *ipaddr)
1992 if (!inet_aton(host, ipaddr)) {
1993 if ((he = gethostbyname(host)) == NULL)
1995 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2001 * fills the addr and mask fields in the instruction as appropriate from av.
2002 * Update length as appropriate.
2003 * The following formats are allowed:
2004 * me returns O_IP_*_ME
2005 * 1.2.3.4 single IP address
2006 * 1.2.3.4:5.6.7.8 address:mask
2007 * 1.2.3.4/24 address/mask
2008 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
2009 * We can have multiple comma-separated address/mask entries.
2012 fill_ip(ipfw_insn_ip *cmd, char *av)
2015 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2017 cmd->o.len &= ~F_LEN_MASK; /* zero len */
2019 if (_substrcmp(av, "any") == 0)
2022 if (_substrcmp(av, "me") == 0) {
2023 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2027 if (strncmp(av, "table(", 6) == 0) {
2028 char *p = strchr(av + 6, ',');
2032 cmd->o.opcode = O_IP_DST_LOOKUP;
2033 cmd->o.arg1 = strtoul(av + 6, NULL, 0);
2035 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2036 d[0] = strtoul(p, NULL, 0);
2038 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2044 * After the address we can have '/' or ':' indicating a mask,
2045 * ',' indicating another address follows, '{' indicating a
2046 * set of addresses of unspecified size.
2048 char *t = NULL, *p = strpbrk(av, "/:,{");
2055 if ((t = strpbrk(p, ",{")) != NULL) {
2062 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2063 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2066 if (!inet_aton(p, (struct in_addr *)&d[1]))
2067 errx(EX_DATAERR, "bad netmask ``%s''", p);
2072 d[1] = htonl(0); /* mask */
2073 else if (masklen > 32)
2074 errx(EX_DATAERR, "bad width ``%s''", p);
2076 d[1] = htonl(~0 << (32 - masklen));
2078 case '{': /* no mask, assume /24 and put back the '{' */
2079 d[1] = htonl(~0 << (32 - 24));
2083 case ',': /* single address plus continuation */
2086 case 0: /* initialization value */
2088 d[1] = htonl(~0); /* force /32 */
2091 d[0] &= d[1]; /* mask base address with mask */
2094 /* find next separator */
2096 p = strpbrk(p, ",{");
2097 if (p && *p == '{') {
2099 * We have a set of addresses. They are stored as follows:
2100 * arg1 is the set size (powers of 2, 2..256)
2101 * addr is the base address IN HOST FORMAT
2102 * mask.. is an array of arg1 bits (rounded up to
2103 * the next multiple of 32) with bits set
2104 * for each host in the map.
2106 uint32_t *map = (uint32_t *)&cmd->mask;
2108 int i = contigmask((uint8_t *)&(d[1]), 32);
2111 errx(EX_DATAERR, "address set cannot be in a list");
2112 if (i < 24 || i > 31)
2113 errx(EX_DATAERR, "invalid set with mask %d\n", i);
2114 cmd->o.arg1 = 1<<(32-i); /* map length */
2115 d[0] = ntohl(d[0]); /* base addr in host format */
2116 cmd->o.opcode = O_IP_DST_SET; /* default */
2117 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2118 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2119 map[i] = 0; /* clear map */
2123 high = low + cmd->o.arg1 - 1;
2125 * Here, i stores the previous value when we specify a range
2126 * of addresses within a mask, e.g. 45-63. i = -1 means we
2127 * have no previous value.
2129 i = -1; /* previous value in a range */
2130 while (isdigit(*av)) {
2132 int a = strtol(av, &s, 0);
2134 if (s == av) { /* no parameter */
2136 errx(EX_DATAERR, "set not closed\n");
2138 errx(EX_DATAERR, "incomplete range %d-", i);
2141 if (a < low || a > high)
2142 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
2145 if (i == -1) /* no previous in range */
2147 else { /* check that range is valid */
2149 errx(EX_DATAERR, "invalid range %d-%d",
2152 errx(EX_DATAERR, "double '-' in range");
2155 map[i/32] |= 1<<(i & 31);
2166 if (av) /* then *av must be a ',' */
2169 /* Check this entry */
2170 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2172 * 'any' turns the entire list into a NOP.
2173 * 'not any' never matches, so it is removed from the
2174 * list unless it is the only item, in which case we
2177 if (cmd->o.len & F_NOT) { /* "not any" never matches */
2178 if (av == NULL && len == 0) /* only this entry */
2179 errx(EX_DATAERR, "not any never matches");
2181 /* else do nothing and skip this entry */
2184 /* A single IP can be stored in an optimized format */
2185 if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
2186 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2189 len += 2; /* two words... */
2192 if (len + 1 > F_LEN_MASK)
2193 errx(EX_DATAERR, "address list too long");
2194 cmd->o.len |= len+1;
2198 /* n2mask sets n bits of the mask */
2200 n2mask(struct in6_addr *mask, int n)
2202 static int minimask[9] =
2203 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
2206 memset(mask, 0, sizeof(struct in6_addr));
2207 p = (u_char *) mask;
2208 for (; n > 0; p++, n -= 8) {
2218 * helper function to process a set of flags and set bits in the
2219 * appropriate masks.
2222 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
2223 struct _s_x *flags, char *p)
2225 uint8_t set=0, clear=0;
2228 char *q; /* points to the separator */
2230 uint8_t *which; /* mask we are working on */
2240 val = match_token(flags, p);
2242 errx(EX_DATAERR, "invalid flag %s", p);
2243 *which |= (uint8_t)val;
2246 cmd->opcode = opcode;
2247 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
2248 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
2253 ipfw_delete(char *av[])
2257 int exitval = EX_OK;
2261 NEED1("missing rule specification");
2262 if ( *av && _substrcmp(*av, "set") == 0) {
2263 /* Do not allow using the following syntax:
2264 * ipfw set N delete set M
2267 errx(EX_DATAERR, "invalid syntax");
2268 do_set = 1; /* delete set */
2273 while (*av && isdigit(**av)) {
2274 i = atoi(*av); av++;
2276 exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
2278 exitval = EX_UNAVAILABLE;
2279 warn("rule %u not available", i);
2281 } else if (co.do_pipe) {
2282 exitval = ipfw_delete_pipe(co.do_pipe, i);
2285 rulenum = (i & 0xffff) | (5 << 24) |
2286 ((co.use_set - 1) << 16);
2288 rulenum = (i & 0xffff) | (do_set << 24);
2289 i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum);
2291 exitval = EX_UNAVAILABLE;
2292 warn("rule %u: setsockopt(IP_FW_DEL)",
2297 if (exitval != EX_OK)
2303 * fill the interface structure. We do not check the name as we can
2304 * create interfaces dynamically, so checking them at insert time
2305 * makes relatively little sense.
2306 * Interface names containing '*', '?', or '[' are assumed to be shell
2307 * patterns which match interfaces.
2310 fill_iface(ipfw_insn_if *cmd, char *arg)
2312 cmd->name[0] = '\0';
2313 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
2315 /* Parse the interface or address */
2316 if (strcmp(arg, "any") == 0)
2317 cmd->o.len = 0; /* effectively ignore this command */
2318 else if (!isdigit(*arg)) {
2319 strlcpy(cmd->name, arg, sizeof(cmd->name));
2320 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
2321 } else if (!inet_aton(arg, &cmd->p.ip))
2322 errx(EX_DATAERR, "bad ip address ``%s''", arg);
2326 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
2330 char *ap, *ptr, *optr;
2331 struct ether_addr *mac;
2332 const char *macset = "0123456789abcdefABCDEF:";
2334 if (strcmp(p, "any") == 0) {
2335 for (i = 0; i < ETHER_ADDR_LEN; i++)
2336 addr[i] = mask[i] = 0;
2340 optr = ptr = strdup(p);
2341 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
2343 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
2344 errx(EX_DATAERR, "Incorrect MAC address");
2345 bcopy(mac, addr, ETHER_ADDR_LEN);
2347 errx(EX_DATAERR, "Incorrect MAC address");
2349 if (ptr != NULL) { /* we have mask? */
2350 if (p[ptr - optr - 1] == '/') { /* mask len */
2351 long ml = strtol(ptr, &ap, 10);
2352 if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
2353 errx(EX_DATAERR, "Incorrect mask length");
2354 for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
2355 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
2358 if (strspn(ptr, macset) != l ||
2359 (mac = ether_aton(ptr)) == NULL)
2360 errx(EX_DATAERR, "Incorrect mask");
2361 bcopy(mac, mask, ETHER_ADDR_LEN);
2363 } else { /* default mask: ff:ff:ff:ff:ff:ff */
2364 for (i = 0; i < ETHER_ADDR_LEN; i++)
2367 for (i = 0; i < ETHER_ADDR_LEN; i++)
2374 * helper function, updates the pointer to cmd with the length
2375 * of the current command, and also cleans up the first word of
2376 * the new command in case it has been clobbered before.
2379 next_cmd(ipfw_insn *cmd)
2382 bzero(cmd, sizeof(*cmd));
2387 * Takes arguments and copies them into a comment
2390 fill_comment(ipfw_insn *cmd, char **av)
2393 char *p = (char *)(cmd + 1);
2395 cmd->opcode = O_NOP;
2396 cmd->len = (cmd->len & (F_NOT | F_OR));
2398 /* Compute length of comment string. */
2399 for (i = 0, l = 0; av[i] != NULL; i++)
2400 l += strlen(av[i]) + 1;
2405 "comment too long (max 80 chars)");
2407 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
2408 for (i = 0; av[i] != NULL; i++) {
2417 * A function to fill simple commands of size 1.
2418 * Existing flags are preserved.
2421 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
2423 cmd->opcode = opcode;
2424 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
2429 * Fetch and add the MAC address and type, with masks. This generates one or
2430 * two microinstructions, and returns the pointer to the last one.
2433 add_mac(ipfw_insn *cmd, char *av[])
2437 if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
2438 errx(EX_DATAERR, "MAC dst src");
2440 cmd->opcode = O_MACADDR2;
2441 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
2443 mac = (ipfw_insn_mac *)cmd;
2444 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
2445 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
2446 &(mac->mask[ETHER_ADDR_LEN])); /* src */
2451 add_mactype(ipfw_insn *cmd, char *av)
2454 errx(EX_DATAERR, "missing MAC type");
2455 if (strcmp(av, "any") != 0) { /* we have a non-null type */
2456 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE);
2457 cmd->opcode = O_MAC_TYPE;
2464 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
2466 struct protoent *pe;
2470 proto = strtol(av, &ep, 10);
2471 if (*ep != '\0' || proto <= 0) {
2472 if ((pe = getprotobyname(av)) == NULL)
2474 proto = pe->p_proto;
2477 fill_cmd(cmd, O_PROTO, 0, proto);
2483 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
2485 u_char proto = IPPROTO_IP;
2487 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2488 ; /* do not set O_IP4 nor O_IP6 */
2489 else if (strcmp(av, "ip4") == 0)
2490 /* explicit "just IPv4" rule */
2491 fill_cmd(cmd, O_IP4, 0, 0);
2492 else if (strcmp(av, "ip6") == 0) {
2493 /* explicit "just IPv6" rule */
2494 proto = IPPROTO_IPV6;
2495 fill_cmd(cmd, O_IP6, 0, 0);
2497 return add_proto0(cmd, av, protop);
2504 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
2506 u_char proto = IPPROTO_IP;
2508 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2509 ; /* do not set O_IP4 nor O_IP6 */
2510 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
2511 /* explicit "just IPv4" rule */
2512 fill_cmd(cmd, O_IP4, 0, 0);
2513 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
2514 /* explicit "just IPv6" rule */
2515 proto = IPPROTO_IPV6;
2516 fill_cmd(cmd, O_IP6, 0, 0);
2518 return add_proto0(cmd, av, protop);
2525 add_srcip(ipfw_insn *cmd, char *av)
2527 fill_ip((ipfw_insn_ip *)cmd, av);
2528 if (cmd->opcode == O_IP_DST_SET) /* set */
2529 cmd->opcode = O_IP_SRC_SET;
2530 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
2531 cmd->opcode = O_IP_SRC_LOOKUP;
2532 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2533 cmd->opcode = O_IP_SRC_ME;
2534 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2535 cmd->opcode = O_IP_SRC;
2536 else /* addr/mask */
2537 cmd->opcode = O_IP_SRC_MASK;
2542 add_dstip(ipfw_insn *cmd, char *av)
2544 fill_ip((ipfw_insn_ip *)cmd, av);
2545 if (cmd->opcode == O_IP_DST_SET) /* set */
2547 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
2549 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2550 cmd->opcode = O_IP_DST_ME;
2551 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2552 cmd->opcode = O_IP_DST;
2553 else /* addr/mask */
2554 cmd->opcode = O_IP_DST_MASK;
2559 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode)
2561 /* XXX "any" is trapped before. Perhaps "to" */
2562 if (_substrcmp(av, "any") == 0) {
2564 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) {
2565 /* XXX todo: check that we have a protocol with ports */
2566 cmd->opcode = opcode;
2573 add_src(ipfw_insn *cmd, char *av, u_char proto)
2577 ipfw_insn *ret = NULL;
2579 if ((host = strdup(av)) == NULL)
2581 if ((ch = strrchr(host, '/')) != NULL)
2584 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
2585 inet_pton(AF_INET6, host, &a) == 1)
2586 ret = add_srcip6(cmd, av);
2587 /* XXX: should check for IPv4, not !IPv6 */
2588 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2589 inet_pton(AF_INET6, host, &a) != 1))
2590 ret = add_srcip(cmd, av);
2591 if (ret == NULL && strcmp(av, "any") != 0)
2599 add_dst(ipfw_insn *cmd, char *av, u_char proto)
2603 ipfw_insn *ret = NULL;
2605 if ((host = strdup(av)) == NULL)
2607 if ((ch = strrchr(host, '/')) != NULL)
2610 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
2611 inet_pton(AF_INET6, host, &a) == 1)
2612 ret = add_dstip6(cmd, av);
2613 /* XXX: should check for IPv4, not !IPv6 */
2614 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2615 inet_pton(AF_INET6, host, &a) != 1))
2616 ret = add_dstip(cmd, av);
2617 if (ret == NULL && strcmp(av, "any") != 0)
2625 * Parse arguments and assemble the microinstructions which make up a rule.
2626 * Rules are added into the 'rulebuf' and then copied in the correct order
2627 * into the actual rule.
2629 * The syntax for a rule starts with the action, followed by
2630 * optional action parameters, and the various match patterns.
2631 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
2632 * (generated if the rule includes a keep-state option), then the
2633 * various match patterns, log/altq actions, and the actual action.
2637 ipfw_add(char *av[])
2640 * rules are added into the 'rulebuf' and then copied in
2641 * the correct order into the actual rule.
2642 * Some things that need to go out of order (prob, action etc.)
2645 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255];
2647 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
2648 ipfw_insn *first_cmd; /* first match pattern */
2653 * various flags used to record that we entered some fields.
2655 ipfw_insn *have_state = NULL; /* check-state or keep-state */
2656 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
2661 int open_par = 0; /* open parenthesis ( */
2663 /* proto is here because it is used to fetch ports */
2664 u_char proto = IPPROTO_IP; /* default protocol */
2666 double match_prob = 1; /* match probability, default is always match */
2668 bzero(actbuf, sizeof(actbuf)); /* actions go here */
2669 bzero(cmdbuf, sizeof(cmdbuf));
2670 bzero(rulebuf, sizeof(rulebuf));
2672 rule = (struct ip_fw *)rulebuf;
2673 cmd = (ipfw_insn *)cmdbuf;
2674 action = (ipfw_insn *)actbuf;
2678 /* [rule N] -- Rule number optional */
2679 if (av[0] && isdigit(**av)) {
2680 rule->rulenum = atoi(*av);
2684 /* [set N] -- set number (0..RESVD_SET), optional */
2685 if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
2686 int set = strtoul(av[1], NULL, 10);
2687 if (set < 0 || set > RESVD_SET)
2688 errx(EX_DATAERR, "illegal set %s", av[1]);
2693 /* [prob D] -- match probability, optional */
2694 if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
2695 match_prob = strtod(av[1], NULL);
2697 if (match_prob <= 0 || match_prob > 1)
2698 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
2702 /* action -- mandatory */
2703 NEED1("missing action");
2704 i = match_token(rule_actions, *av);
2706 action->len = 1; /* default */
2708 case TOK_CHECKSTATE:
2709 have_state = action;
2710 action->opcode = O_CHECK_STATE;
2714 action->opcode = O_ACCEPT;
2718 action->opcode = O_DENY;
2723 action->opcode = O_REJECT;
2724 action->arg1 = ICMP_UNREACH_HOST;
2728 action->opcode = O_REJECT;
2729 action->arg1 = ICMP_REJECT_RST;
2733 action->opcode = O_UNREACH6;
2734 action->arg1 = ICMP6_UNREACH_RST;
2738 action->opcode = O_REJECT;
2739 NEED1("missing reject code");
2740 fill_reject_code(&action->arg1, *av);
2745 action->opcode = O_UNREACH6;
2746 NEED1("missing unreach code");
2747 fill_unreach6_code(&action->arg1, *av);
2752 action->opcode = O_COUNT;
2756 action->opcode = O_NAT;
2757 action->len = F_INSN_SIZE(ipfw_insn_nat);
2758 if (_substrcmp(*av, "global") == 0) {
2766 action->opcode = O_QUEUE;
2769 action->opcode = O_PIPE;
2772 action->opcode = O_SKIPTO;
2775 action->opcode = O_NETGRAPH;
2778 action->opcode = O_NGTEE;
2781 action->opcode = O_DIVERT;
2784 action->opcode = O_TEE;
2787 action->opcode = O_CALLRETURN;
2790 errx(EX_USAGE, "missing argument for %s", *(av - 1));
2791 if (isdigit(**av)) {
2792 action->arg1 = strtoul(*av, NULL, 10);
2793 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
2794 errx(EX_DATAERR, "illegal argument for %s",
2796 } else if (_substrcmp(*av, "tablearg") == 0) {
2797 action->arg1 = IP_FW_TABLEARG;
2798 } else if (i == TOK_DIVERT || i == TOK_TEE) {
2801 s = getservbyname(av[0], "divert");
2803 action->arg1 = ntohs(s->s_port);
2805 errx(EX_DATAERR, "illegal divert/tee port");
2807 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
2812 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
2815 NEED1("missing forward address[:port]");
2817 action->opcode = O_FORWARD_IP;
2818 action->len = F_INSN_SIZE(ipfw_insn_sa);
2821 * In the kernel we assume AF_INET and use only
2822 * sin_port and sin_addr. Remember to set sin_len as
2823 * the routing code seems to use it too.
2825 p->sa.sin_family = AF_INET;
2826 p->sa.sin_len = sizeof(struct sockaddr_in);
2829 * locate the address-port separator (':' or ',')
2831 s = strchr(*av, ':');
2833 s = strchr(*av, ',');
2836 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
2839 "illegal forwarding port ``%s''", s);
2840 p->sa.sin_port = (u_short)i;
2842 if (_substrcmp(*av, "tablearg") == 0)
2843 p->sa.sin_addr.s_addr = INADDR_ANY;
2845 lookup_host(*av, &(p->sa.sin_addr));
2850 /* pretend it is a 'count' rule followed by the comment */
2851 action->opcode = O_COUNT;
2852 av--; /* go back... */
2858 size_t intsize = sizeof(int);
2860 action->opcode = O_SETFIB;
2861 NEED1("missing fib number");
2862 if (_substrcmp(*av, "tablearg") == 0) {
2863 action->arg1 = IP_FW_TABLEARG;
2865 action->arg1 = strtoul(*av, NULL, 10);
2866 if (sysctlbyname("net.fibs", &numfibs, &intsize,
2868 errx(EX_DATAERR, "fibs not suported.\n");
2869 if (action->arg1 >= numfibs) /* Temporary */
2870 errx(EX_DATAERR, "fib too large.\n");
2877 action->opcode = O_REASS;
2881 fill_cmd(action, O_CALLRETURN, F_NOT, 0);
2885 errx(EX_DATAERR, "invalid action %s\n", av[-1]);
2887 action = next_cmd(action);
2890 * [altq queuename] -- altq tag, optional
2891 * [log [logamount N]] -- log, optional
2893 * If they exist, it go first in the cmdbuf, but then it is
2894 * skipped in the copy section to the end of the buffer.
2896 while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
2901 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
2906 "log cannot be specified more than once");
2907 have_log = (ipfw_insn *)c;
2908 cmd->len = F_INSN_SIZE(ipfw_insn_log);
2909 cmd->opcode = O_LOG;
2910 if (av[0] && _substrcmp(*av, "logamount") == 0) {
2912 NEED1("logamount requires argument");
2916 "logamount must be positive");
2920 len = sizeof(c->max_log);
2921 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
2922 &c->max_log, &len, NULL, 0) == -1)
2923 errx(1, "sysctlbyname(\"%s\")",
2924 "net.inet.ip.fw.verbose_limit");
2932 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
2934 NEED1("missing altq queue name");
2937 "altq cannot be specified more than once");
2938 have_altq = (ipfw_insn *)a;
2939 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
2940 cmd->opcode = O_ALTQ;
2941 a->qid = altq_name_to_qid(*av);
2952 errx(EX_USAGE, "tag and untag cannot be "
2953 "specified more than once");
2954 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
2955 rule_action_params);
2957 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
2965 cmd = next_cmd(cmd);
2968 if (have_state) /* must be a check-state, we are done */
2971 #define OR_START(target) \
2972 if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
2974 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
2977 if ( (av[0])[1] == '\0') { \
2988 strcmp(*av, ")") == 0 || \
2989 strcmp(*av, "}") == 0)) { \
2994 errx(EX_USAGE, "missing \")\"\n"); \
2998 if (av[0] && _substrcmp(*av, "not") == 0) { \
2999 if (cmd->len & F_NOT) \
3000 errx(EX_USAGE, "double \"not\" not allowed\n"); \
3001 cmd->len |= F_NOT; \
3005 #define OR_BLOCK(target) \
3006 if (av[0] && _substrcmp(*av, "or") == 0) { \
3007 if (prev == NULL || open_par == 0) \
3008 errx(EX_DATAERR, "invalid OR block"); \
3009 prev->len |= F_OR; \
3019 * MAC addresses, optional.
3020 * If we have this, we skip the part "proto from src to dst"
3021 * and jump straight to the option parsing.
3024 NEED1("missing protocol");
3025 if (_substrcmp(*av, "MAC") == 0 ||
3026 _substrcmp(*av, "mac") == 0) {
3027 av++; /* the "MAC" keyword */
3028 add_mac(cmd, av); /* exits in case of errors */
3029 cmd = next_cmd(cmd);
3030 av += 2; /* dst-mac and src-mac */
3032 NEED1("missing mac type");
3033 if (add_mactype(cmd, av[0]))
3034 cmd = next_cmd(cmd);
3035 av++; /* any or mac-type */
3041 * protocol, mandatory
3043 OR_START(get_proto);
3045 NEED1("missing protocol");
3046 if (add_proto_compat(cmd, *av, &proto)) {
3048 if (F_LEN(cmd) != 0) {
3050 cmd = next_cmd(cmd);
3052 } else if (first_cmd != cmd) {
3053 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
3056 OR_BLOCK(get_proto);
3061 if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
3062 errx(EX_USAGE, "missing ``from''");
3066 * source IP, mandatory
3068 OR_START(source_ip);
3069 NOT_BLOCK; /* optional "not" */
3070 NEED1("missing source address");
3071 if (add_src(cmd, *av, proto)) {
3073 if (F_LEN(cmd) != 0) { /* ! any */
3075 cmd = next_cmd(cmd);
3078 errx(EX_USAGE, "bad source address %s", *av);
3079 OR_BLOCK(source_ip);
3082 * source ports, optional
3084 NOT_BLOCK; /* optional "not" */
3085 if ( av[0] != NULL ) {
3086 if (_substrcmp(*av, "any") == 0 ||
3087 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
3089 if (F_LEN(cmd) != 0)
3090 cmd = next_cmd(cmd);
3097 if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
3098 errx(EX_USAGE, "missing ``to''");
3102 * destination, mandatory
3105 NOT_BLOCK; /* optional "not" */
3106 NEED1("missing dst address");
3107 if (add_dst(cmd, *av, proto)) {
3109 if (F_LEN(cmd) != 0) { /* ! any */
3111 cmd = next_cmd(cmd);
3114 errx( EX_USAGE, "bad destination address %s", *av);
3118 * dest. ports, optional
3120 NOT_BLOCK; /* optional "not" */
3122 if (_substrcmp(*av, "any") == 0 ||
3123 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
3125 if (F_LEN(cmd) != 0)
3126 cmd = next_cmd(cmd);
3131 if (av[0] && first_cmd == cmd) {
3133 * nothing specified so far, store in the rule to ease
3139 while ( av[0] != NULL ) {
3141 ipfw_insn_u32 *cmd32; /* alias for cmd */
3144 cmd32 = (ipfw_insn_u32 *)cmd;
3146 if (*s == '!') { /* alternate syntax for NOT */
3147 if (cmd->len & F_NOT)
3148 errx(EX_USAGE, "double \"not\" not allowed\n");
3152 i = match_token(rule_options, s);
3156 if (cmd->len & F_NOT)
3157 errx(EX_USAGE, "double \"not\" not allowed\n");
3162 if (open_par == 0 || prev == NULL)
3163 errx(EX_USAGE, "invalid \"or\" block\n");
3167 case TOK_STARTBRACE:
3169 errx(EX_USAGE, "+nested \"(\" not allowed\n");
3175 errx(EX_USAGE, "+missing \")\"\n");
3181 fill_cmd(cmd, O_IN, 0, 0);
3185 cmd->len ^= F_NOT; /* toggle F_NOT */
3186 fill_cmd(cmd, O_IN, 0, 0);
3190 fill_cmd(cmd, O_DIVERTED, 0, 3);
3193 case TOK_DIVERTEDLOOPBACK:
3194 fill_cmd(cmd, O_DIVERTED, 0, 1);
3197 case TOK_DIVERTEDOUTPUT:
3198 fill_cmd(cmd, O_DIVERTED, 0, 2);
3202 fill_cmd(cmd, O_FRAG, 0, 0);
3206 fill_cmd(cmd, O_LAYER2, 0, 0);
3212 NEED1("recv, xmit, via require interface name"
3214 fill_iface((ipfw_insn_if *)cmd, av[0]);
3216 if (F_LEN(cmd) == 0) /* not a valid address */
3219 cmd->opcode = O_XMIT;
3220 else if (i == TOK_RECV)
3221 cmd->opcode = O_RECV;
3222 else if (i == TOK_VIA)
3223 cmd->opcode = O_VIA;
3227 NEED1("icmptypes requires list of types");
3228 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
3232 case TOK_ICMP6TYPES:
3233 NEED1("icmptypes requires list of types");
3234 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av);
3239 NEED1("ipttl requires TTL");
3240 if (strpbrk(*av, "-,")) {
3241 if (!add_ports(cmd, *av, 0, O_IPTTL))
3242 errx(EX_DATAERR, "invalid ipttl %s", *av);
3244 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
3249 NEED1("ipid requires id");
3250 if (strpbrk(*av, "-,")) {
3251 if (!add_ports(cmd, *av, 0, O_IPID))
3252 errx(EX_DATAERR, "invalid ipid %s", *av);
3254 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
3259 NEED1("iplen requires length");
3260 if (strpbrk(*av, "-,")) {
3261 if (!add_ports(cmd, *av, 0, O_IPLEN))
3262 errx(EX_DATAERR, "invalid ip len %s", *av);
3264 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
3269 NEED1("ipver requires version");
3270 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
3274 case TOK_IPPRECEDENCE:
3275 NEED1("ipprecedence requires value");
3276 fill_cmd(cmd, O_IPPRECEDENCE, 0,
3277 (strtoul(*av, NULL, 0) & 7) << 5);
3282 NEED1("missing argument for ipoptions");
3283 fill_flags(cmd, O_IPOPT, f_ipopts, *av);
3288 NEED1("missing argument for iptos");
3289 fill_flags(cmd, O_IPTOS, f_iptos, *av);
3294 NEED1("uid requires argument");
3300 cmd->opcode = O_UID;
3301 uid = strtoul(*av, &end, 0);
3302 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
3304 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
3305 cmd32->d[0] = pwd->pw_uid;
3306 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3312 NEED1("gid requires argument");
3318 cmd->opcode = O_GID;
3319 gid = strtoul(*av, &end, 0);
3320 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
3322 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
3323 cmd32->d[0] = grp->gr_gid;
3324 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3330 NEED1("jail requires argument");
3335 cmd->opcode = O_JAIL;
3336 jid = (int)strtol(*av, &end, 0);
3337 if (jid < 0 || *end != '\0')
3338 errx(EX_DATAERR, "jail requires prison ID");
3339 cmd32->d[0] = (uint32_t)jid;
3340 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3346 fill_cmd(cmd, O_ESTAB, 0, 0);
3350 fill_cmd(cmd, O_TCPFLAGS, 0,
3351 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
3354 case TOK_TCPDATALEN:
3355 NEED1("tcpdatalen requires length");
3356 if (strpbrk(*av, "-,")) {
3357 if (!add_ports(cmd, *av, 0, O_TCPDATALEN))
3358 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
3360 fill_cmd(cmd, O_TCPDATALEN, 0,
3361 strtoul(*av, NULL, 0));
3366 NEED1("missing argument for tcpoptions");
3367 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
3373 NEED1("tcpseq/tcpack requires argument");
3374 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3375 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
3376 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
3381 NEED1("tcpwin requires length");
3382 fill_cmd(cmd, O_TCPWIN, 0,
3383 htons(strtoul(*av, NULL, 0)));
3388 NEED1("missing argument for tcpflags");
3389 cmd->opcode = O_TCPFLAGS;
3390 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
3396 errx(EX_USAGE, "keep-state cannot be part "
3399 errx(EX_USAGE, "only one of keep-state "
3400 "and limit is allowed");
3402 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
3406 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
3411 "limit cannot be part of an or block");
3413 errx(EX_USAGE, "only one of keep-state and "
3414 "limit is allowed");
3417 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
3418 cmd->opcode = O_LIMIT;
3419 c->limit_mask = c->conn_limit = 0;
3421 while ( av[0] != NULL ) {
3422 if ((val = match_token(limit_masks, *av)) <= 0)
3424 c->limit_mask |= val;
3428 if (c->limit_mask == 0)
3429 errx(EX_USAGE, "limit: missing limit mask");
3431 GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
3432 TOK_LIMIT, rule_options);
3439 NEED1("missing protocol");
3440 if (add_proto(cmd, *av, &proto)) {
3443 errx(EX_DATAERR, "invalid protocol ``%s''",
3448 NEED1("missing source IP");
3449 if (add_srcip(cmd, *av)) {
3455 NEED1("missing destination IP");
3456 if (add_dstip(cmd, *av)) {
3462 NEED1("missing source IP6");
3463 if (add_srcip6(cmd, *av)) {
3469 NEED1("missing destination IP6");
3470 if (add_dstip6(cmd, *av)) {
3476 NEED1("missing source port");
3477 if (_substrcmp(*av, "any") == 0 ||
3478 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
3481 errx(EX_DATAERR, "invalid source port %s", *av);
3485 NEED1("missing destination port");
3486 if (_substrcmp(*av, "any") == 0 ||
3487 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
3490 errx(EX_DATAERR, "invalid destination port %s",
3495 if (add_mac(cmd, av))
3500 NEED1("missing mac type");
3501 if (!add_mactype(cmd, *av))
3502 errx(EX_DATAERR, "invalid mac type %s", *av);
3506 case TOK_VERREVPATH:
3507 fill_cmd(cmd, O_VERREVPATH, 0, 0);
3510 case TOK_VERSRCREACH:
3511 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
3515 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
3519 fill_cmd(cmd, O_IPSEC, 0, 0);
3523 fill_cmd(cmd, O_IP6, 0, 0);
3527 fill_cmd(cmd, O_IP4, 0, 0);
3531 fill_ext6hdr( cmd, *av );
3536 if (proto != IPPROTO_IPV6 )
3537 errx( EX_USAGE, "flow-id filter is active "
3538 "only for ipv6 protocol\n");
3539 fill_flow6( (ipfw_insn_u32 *) cmd, *av );
3544 fill_comment(cmd, av);
3549 if (av[0] && strpbrk(*av, "-,")) {
3550 if (!add_ports(cmd, *av, 0, O_TAGGED))
3551 errx(EX_DATAERR, "tagged: invalid tag"
3557 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
3558 TOK_TAGGED, rule_options);
3559 fill_cmd(cmd, O_TAGGED, 0, tag);
3565 NEED1("fib requires fib number");
3566 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
3570 fill_cmd(cmd, O_SOCKARG, 0, 0);
3574 ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
3578 if (!av[0] || !av[1])
3579 errx(EX_USAGE, "format: lookup argument tablenum");
3580 cmd->opcode = O_IP_DST_LOOKUP;
3581 cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
3582 i = match_token(rule_options, *av);
3583 for (j = 0; lookup_key[j] >= 0 ; j++) {
3584 if (i == lookup_key[j])
3587 if (lookup_key[j] <= 0)
3588 errx(EX_USAGE, "format: cannot lookup on %s", *av);
3589 __PAST_END(c->d, 1) = j; // i converted to option
3591 cmd->arg1 = strtoul(*av, &p, 0);
3593 errx(EX_USAGE, "format: lookup argument tablenum");
3599 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
3601 if (F_LEN(cmd) > 0) { /* prepare to advance */
3603 cmd = next_cmd(cmd);
3609 * Now copy stuff into the rule.
3610 * If we have a keep-state option, the first instruction
3611 * must be a PROBE_STATE (which is generated here).
3612 * If we have a LOG option, it was stored as the first command,
3613 * and now must be moved to the top of the action part.
3615 dst = (ipfw_insn *)rule->cmd;
3618 * First thing to write into the command stream is the match probability.
3620 if (match_prob != 1) { /* 1 means always match */
3621 dst->opcode = O_PROB;
3623 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
3628 * generate O_PROBE_STATE if necessary
3630 if (have_state && have_state->opcode != O_CHECK_STATE) {
3631 fill_cmd(dst, O_PROBE_STATE, 0, 0);
3632 dst = next_cmd(dst);
3635 /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
3636 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
3639 switch (src->opcode) {
3647 bcopy(src, dst, i * sizeof(uint32_t));
3653 * put back the have_state command as last opcode
3655 if (have_state && have_state->opcode != O_CHECK_STATE) {
3656 i = F_LEN(have_state);
3657 bcopy(have_state, dst, i * sizeof(uint32_t));
3661 * start action section
3663 rule->act_ofs = dst - rule->cmd;
3665 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
3667 i = F_LEN(have_log);
3668 bcopy(have_log, dst, i * sizeof(uint32_t));
3672 i = F_LEN(have_altq);
3673 bcopy(have_altq, dst, i * sizeof(uint32_t));
3677 i = F_LEN(have_tag);
3678 bcopy(have_tag, dst, i * sizeof(uint32_t));
3682 * copy all other actions
3684 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
3686 bcopy(src, dst, i * sizeof(uint32_t));
3690 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
3691 i = (char *)dst - (char *)rule;
3692 if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1)
3693 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
3695 show_ipfw(rule, 0, 0);
3699 * clear the counters or the log counters.
3702 ipfw_zero(int ac, char *av[], int optname /* 0 = IP_FW_ZERO, 1 = IP_FW_RESETLOG */)
3704 uint32_t arg, saved_arg;
3707 char const *name = optname ? "RESETLOG" : "ZERO";
3709 optname = optname ? IP_FW_RESETLOG : IP_FW_ZERO;
3714 /* clear all entries */
3715 if (do_cmd(optname, NULL, 0) < 0)
3716 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name);
3718 printf("%s.\n", optname == IP_FW_ZERO ?
3719 "Accounting cleared":"Logging counts reset");
3726 if (isdigit(**av)) {
3727 arg = strtonum(*av, 0, 0xffff, &errstr);
3730 "invalid rule number %s\n", *av);
3733 arg |= (1 << 24) | ((co.use_set - 1) << 16);
3736 if (do_cmd(optname, &arg, sizeof(arg))) {
3737 warn("rule %u: setsockopt(IP_FW_%s)",
3739 failed = EX_UNAVAILABLE;
3740 } else if (!co.do_quiet)
3741 printf("Entry %d %s.\n", saved_arg,
3742 optname == IP_FW_ZERO ?
3743 "cleared" : "logging count reset");
3745 errx(EX_USAGE, "invalid rule number ``%s''", *av);
3748 if (failed != EX_OK)
3753 ipfw_flush(int force)
3755 int cmd = co.do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
3757 if (!force && !co.do_quiet) { /* need to ask user */
3760 printf("Are you sure? [yn] ");
3763 c = toupper(getc(stdin));
3764 while (c != '\n' && getc(stdin) != '\n')
3766 return; /* and do not flush */
3767 } while (c != 'Y' && c != 'N');
3769 if (c == 'N') /* user said no */
3776 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
3778 uint32_t arg = ((co.use_set - 1) & 0xffff) | (1 << 24);
3779 if (do_cmd(IP_FW_DEL, &arg, sizeof(arg)) < 0)
3780 err(EX_UNAVAILABLE, "setsockopt(IP_FW_DEL)");
3781 } else if (do_cmd(cmd, NULL, 0) < 0)
3782 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
3783 co.do_pipe ? "DUMMYNET" : "FW");
3785 printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
3789 static void table_list(ipfw_table_entry ent, int need_header);
3792 * This one handles all table-related commands
3793 * ipfw table N add addr[/masklen] [value]
3794 * ipfw table N delete addr[/masklen]
3795 * ipfw table {N | all} flush
3796 * ipfw table {N | all} list
3799 ipfw_table_handler(int ac, char *av[])
3801 ipfw_table_entry ent;
3807 uint32_t tables_max;
3809 len = sizeof(tables_max);
3810 if (sysctlbyname("net.inet.ip.fw.tables_max", &tables_max, &len,
3812 #ifdef IPFW_TABLES_MAX
3813 warn("Warn: Failed to get the max tables number via sysctl. "
3814 "Using the compiled in defaults. \nThe reason was");
3815 tables_max = IPFW_TABLES_MAX;
3817 errx(1, "Failed sysctlbyname(\"net.inet.ip.fw.tables_max\")");
3822 if (ac && isdigit(**av)) {
3823 ent.tbl = atoi(*av);
3826 } else if (ac && _substrcmp(*av, "all") == 0) {
3831 errx(EX_USAGE, "table number or 'all' keyword required");
3832 if (ent.tbl >= tables_max)
3833 errx(EX_USAGE, "The table number exceeds the maximum allowed "
3834 "value (%d)", tables_max - 1);
3835 NEED1("table needs command");
3836 if (is_all && _substrcmp(*av, "list") != 0
3837 && _substrcmp(*av, "flush") != 0)
3838 errx(EX_USAGE, "table number required");
3840 if (_substrcmp(*av, "add") == 0 ||
3841 _substrcmp(*av, "delete") == 0) {
3842 do_add = **av == 'a';
3845 errx(EX_USAGE, "IP address required");
3846 p = strchr(*av, '/');
3849 ent.masklen = atoi(p);
3850 if (ent.masklen > 32)
3851 errx(EX_DATAERR, "bad width ``%s''", p);
3854 if (lookup_host(*av, (struct in_addr *)&ent.addr) != 0)
3855 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
3859 /* isdigit is a bit of a hack here.. */
3860 if (strchr(*av, (int)'.') == NULL && isdigit(**av)) {
3861 ent.value = strtoul(*av, NULL, 0);
3863 if (lookup_host(*av, (struct in_addr *)&tval) == 0) {
3864 /* The value must be stored in host order *
3865 * so that the values < 65k can be distinguished */
3866 ent.value = ntohl(tval);
3868 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
3873 if (do_cmd(do_add ? IP_FW_TABLE_ADD : IP_FW_TABLE_DEL,
3874 &ent, sizeof(ent)) < 0) {
3875 /* If running silent, don't bomb out on these errors. */
3876 if (!(co.do_quiet && (errno == (do_add ? EEXIST : ESRCH))))
3877 err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)",
3878 do_add ? "ADD" : "DEL");
3879 /* In silent mode, react to a failed add by deleting */
3881 do_cmd(IP_FW_TABLE_DEL, &ent, sizeof(ent));
3882 if (do_cmd(IP_FW_TABLE_ADD,
3883 &ent, sizeof(ent)) < 0)
3885 "setsockopt(IP_FW_TABLE_ADD)");
3888 } else if (_substrcmp(*av, "flush") == 0) {
3889 a = is_all ? tables_max : (uint32_t)(ent.tbl + 1);
3891 if (do_cmd(IP_FW_TABLE_FLUSH, &ent.tbl,
3892 sizeof(ent.tbl)) < 0)
3893 err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)");
3894 } while (++ent.tbl < a);
3895 } else if (_substrcmp(*av, "list") == 0) {
3896 a = is_all ? tables_max : (uint32_t)(ent.tbl + 1);
3898 table_list(ent, is_all);
3899 } while (++ent.tbl < a);
3901 errx(EX_USAGE, "invalid table command %s", *av);
3905 table_list(ipfw_table_entry ent, int need_header)
3913 if (do_cmd(IP_FW_TABLE_GETSIZE, &a, (uintptr_t)&l) < 0)
3914 err(EX_OSERR, "getsockopt(IP_FW_TABLE_GETSIZE)");
3916 /* If a is zero we have nothing to do, the table is empty. */
3920 l = sizeof(*tbl) + a * sizeof(ipfw_table_entry);
3921 tbl = safe_calloc(1, l);
3923 if (do_cmd(IP_FW_TABLE_LIST, tbl, (uintptr_t)&l) < 0)
3924 err(EX_OSERR, "getsockopt(IP_FW_TABLE_LIST)");
3925 if (tbl->cnt && need_header)
3926 printf("---table(%d)---\n", tbl->tbl);
3927 for (a = 0; a < tbl->cnt; a++) {
3929 tval = tbl->ent[a].value;
3930 if (co.do_value_as_ip) {
3932 strncpy(tbuf, inet_ntoa(*(struct in_addr *)
3933 &tbl->ent[a].addr), 127);
3934 /* inet_ntoa expects network order */
3936 printf("%s/%u %s\n", tbuf, tbl->ent[a].masklen,
3937 inet_ntoa(*(struct in_addr *)&tval));
3939 printf("%s/%u %u\n",
3940 inet_ntoa(*(struct in_addr *)&tbl->ent[a].addr),
3941 tbl->ent[a].masklen, tval);