2 * Copyright (c) 2002-2003 Luigi Rizzo
3 * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
4 * Copyright (c) 1994 Ugen J.S.Antsilevich
6 * Idea and grammar partially left from:
7 * Copyright (c) 1993 Daniel Boulet
9 * Redistribution and use in source forms, with and without modification,
10 * are permitted provided that this entire comment appears intact.
12 * Redistribution in binary form may occur without any restrictions.
13 * Obviously, it would be nice if you gave credit where credit is due
14 * but requiring it would be too onerous.
16 * This software is provided ``AS IS'' without any warranties of any kind.
18 * NEW command line interface for IP firewall facility
20 * $FreeBSD: head/sbin/ipfw/ipfw2.c 206843 2010-04-19 15:11:45Z luigi $
23 #include <sys/types.h>
24 #include <sys/socket.h>
25 #include <sys/sockio.h>
26 #include <sys/sysctl.h>
40 #include <time.h> /* ctime */
41 #include <timeconv.h> /* _long_to_time */
44 * FreeBSD uses __unused as a shorthand for __attribute__ ((__unused__))
45 * whereas Linux sometimes uses __unused as a variable name.
46 * undefine the macro around problematic places.
50 #define __unused __attribute__ ((__unused__))
52 #include <net/ethernet.h>
53 #include <net/if.h> /* only IFNAMSIZ */
54 #include <netinet/in.h>
55 #include <netinet/in_systm.h> /* only n_short, n_long */
56 #include <netinet/ip.h>
57 #include <netinet/ip_icmp.h>
58 #include <netinet/ip_fw.h>
59 #include <netinet/tcp.h>
60 #include <arpa/inet.h>
62 struct cmdline_opts co; /* global options */
64 int resvd_set_number = RESVD_SET;
66 #define GET_UINT_ARG(arg, min, max, tok, s_x) do { \
68 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
69 if (_substrcmp(*av, "tablearg") == 0) { \
70 arg = IP_FW_TABLEARG; \
78 _xval = strtol(*av, &end, 10); \
80 if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
81 errx(EX_DATAERR, "%s: invalid argument: %s", \
82 match_value(s_x, tok), *av); \
84 if (errno == ERANGE || _xval < min || _xval > max) \
85 errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
86 match_value(s_x, tok), min, max, *av); \
88 if (_xval == IP_FW_TABLEARG) \
89 errx(EX_DATAERR, "%s: illegal argument value: %s", \
90 match_value(s_x, tok), *av); \
96 PRINT_UINT_ARG(const char *str, uint32_t arg)
100 if (arg == IP_FW_TABLEARG)
106 static struct _s_x f_tcpflags[] = {
117 static struct _s_x f_tcpopts[] = {
118 { "mss", IP_FW_TCPOPT_MSS },
119 { "maxseg", IP_FW_TCPOPT_MSS },
120 { "window", IP_FW_TCPOPT_WINDOW },
121 { "sack", IP_FW_TCPOPT_SACK },
122 { "ts", IP_FW_TCPOPT_TS },
123 { "timestamp", IP_FW_TCPOPT_TS },
124 { "cc", IP_FW_TCPOPT_CC },
130 * IP options span the range 0 to 255 so we need to remap them
131 * (though in fact only the low 5 bits are significant).
133 static struct _s_x f_ipopts[] = {
134 { "ssrr", IP_FW_IPOPT_SSRR},
135 { "lsrr", IP_FW_IPOPT_LSRR},
136 { "rr", IP_FW_IPOPT_RR},
137 { "ts", IP_FW_IPOPT_TS},
142 static struct _s_x f_iptos[] = {
143 { "lowdelay", IPTOS_LOWDELAY},
144 { "throughput", IPTOS_THROUGHPUT},
145 { "reliability", IPTOS_RELIABILITY},
146 { "mincost", IPTOS_MINCOST},
147 { "congestion", IPTOS_ECN_CE},
148 { "ecntransport", IPTOS_ECN_ECT0},
149 { "ip tos option", 0},
153 static struct _s_x limit_masks[] = {
154 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
155 {"src-addr", DYN_SRC_ADDR},
156 {"src-port", DYN_SRC_PORT},
157 {"dst-addr", DYN_DST_ADDR},
158 {"dst-port", DYN_DST_PORT},
163 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
164 * This is only used in this code.
166 #define IPPROTO_ETHERTYPE 0x1000
167 static struct _s_x ether_types[] = {
169 * Note, we cannot use "-:&/" in the names because they are field
170 * separators in the type specifications. Also, we use s = NULL as
171 * end-delimiter, because a type of 0 can be legal.
184 { "pppoe_disc", 0x8863 },
185 { "pppoe_sess", 0x8864 },
186 { "ipx_8022", 0x00E0 },
187 { "ipx_8023", 0x0000 },
188 { "ipx_ii", 0x8137 },
189 { "ipx_snap", 0x8137 },
196 static struct _s_x rule_actions[] = {
197 { "accept", TOK_ACCEPT },
198 { "pass", TOK_ACCEPT },
199 { "allow", TOK_ACCEPT },
200 { "permit", TOK_ACCEPT },
201 { "count", TOK_COUNT },
202 { "pipe", TOK_PIPE },
203 { "queue", TOK_QUEUE },
204 { "divert", TOK_DIVERT },
206 { "netgraph", TOK_NETGRAPH },
207 { "ngtee", TOK_NGTEE },
208 { "fwd", TOK_FORWARD },
209 { "forward", TOK_FORWARD },
210 { "skipto", TOK_SKIPTO },
211 { "deny", TOK_DENY },
212 { "drop", TOK_DENY },
213 { "reject", TOK_REJECT },
214 { "reset6", TOK_RESET6 },
215 { "reset", TOK_RESET },
216 { "unreach6", TOK_UNREACH6 },
217 { "unreach", TOK_UNREACH },
218 { "check-state", TOK_CHECKSTATE },
219 { "//", TOK_COMMENT },
221 { "reass", TOK_REASS },
222 { "setfib", TOK_SETFIB },
223 { NULL, 0 } /* terminator */
226 static struct _s_x rule_action_params[] = {
227 { "altq", TOK_ALTQ },
230 { "untag", TOK_UNTAG },
231 { NULL, 0 } /* terminator */
235 * The 'lookup' instruction accepts one of the following arguments.
236 * -1 is a terminator for the list.
237 * Arguments are passed as v[1] in O_DST_LOOKUP options.
239 static int lookup_key[] = {
240 TOK_DSTIP, TOK_SRCIP, TOK_DSTPORT, TOK_SRCPORT,
241 TOK_UID, TOK_JAIL, TOK_DSCP, -1 };
243 static struct _s_x rule_options[] = {
244 { "tagged", TOK_TAGGED },
247 { "jail", TOK_JAIL },
249 { "limit", TOK_LIMIT },
250 { "keep-state", TOK_KEEPSTATE },
251 { "bridged", TOK_LAYER2 },
252 { "layer2", TOK_LAYER2 },
254 { "diverted", TOK_DIVERTED },
255 { "diverted-loopback", TOK_DIVERTEDLOOPBACK },
256 { "diverted-output", TOK_DIVERTEDOUTPUT },
257 { "xmit", TOK_XMIT },
258 { "recv", TOK_RECV },
260 { "fragment", TOK_FRAG },
261 { "frag", TOK_FRAG },
263 { "ipoptions", TOK_IPOPTS },
264 { "ipopts", TOK_IPOPTS },
265 { "iplen", TOK_IPLEN },
266 { "ipid", TOK_IPID },
267 { "ipprecedence", TOK_IPPRECEDENCE },
268 { "dscp", TOK_DSCP },
269 { "iptos", TOK_IPTOS },
270 { "ipttl", TOK_IPTTL },
271 { "ipversion", TOK_IPVER },
272 { "ipver", TOK_IPVER },
273 { "estab", TOK_ESTAB },
274 { "established", TOK_ESTAB },
275 { "setup", TOK_SETUP },
276 { "tcpdatalen", TOK_TCPDATALEN },
277 { "tcpflags", TOK_TCPFLAGS },
278 { "tcpflgs", TOK_TCPFLAGS },
279 { "tcpoptions", TOK_TCPOPTS },
280 { "tcpopts", TOK_TCPOPTS },
281 { "tcpseq", TOK_TCPSEQ },
282 { "tcpack", TOK_TCPACK },
283 { "tcpwin", TOK_TCPWIN },
284 { "icmptype", TOK_ICMPTYPES },
285 { "icmptypes", TOK_ICMPTYPES },
286 { "dst-ip", TOK_DSTIP },
287 { "src-ip", TOK_SRCIP },
288 { "dst-port", TOK_DSTPORT },
289 { "src-port", TOK_SRCPORT },
290 { "proto", TOK_PROTO },
293 { "mac-type", TOK_MACTYPE },
294 { "verrevpath", TOK_VERREVPATH },
295 { "versrcreach", TOK_VERSRCREACH },
296 { "antispoof", TOK_ANTISPOOF },
297 { "ipsec", TOK_IPSEC },
298 { "icmp6type", TOK_ICMP6TYPES },
299 { "icmp6types", TOK_ICMP6TYPES },
300 { "ext6hdr", TOK_EXT6HDR},
301 { "flow-id", TOK_FLOWID},
306 { "dst-ipv6", TOK_DSTIP6},
307 { "dst-ip6", TOK_DSTIP6},
308 { "src-ipv6", TOK_SRCIP6},
309 { "src-ip6", TOK_SRCIP6},
310 { "lookup", TOK_LOOKUP},
311 { "//", TOK_COMMENT },
313 { "not", TOK_NOT }, /* pseudo option */
314 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
315 { "or", TOK_OR }, /* pseudo option */
316 { "|", /* escape */ TOK_OR }, /* pseudo option */
317 { "{", TOK_STARTBRACE }, /* pseudo option */
318 { "(", TOK_STARTBRACE }, /* pseudo option */
319 { "}", TOK_ENDBRACE }, /* pseudo option */
320 { ")", TOK_ENDBRACE }, /* pseudo option */
321 { NULL, 0 } /* terminator */
325 * Helper routine to print a possibly unaligned uint64_t on
326 * various platform. If width > 0, print the value with
327 * the desired width, followed by a space;
328 * otherwise, return the required width.
331 pr_u64(uint64_t *pd, int width)
334 #define U64_FMT "I64"
336 #define U64_FMT "llu"
339 unsigned long long d;
341 bcopy (pd, &u, sizeof(u));
344 printf("%*" U64_FMT " ", width, d) :
345 snprintf(NULL, 0, "%" U64_FMT, d) ;
350 safe_calloc(size_t number, size_t size)
352 void *ret = calloc(number, size);
355 err(EX_OSERR, "calloc");
360 safe_realloc(void *ptr, size_t size)
362 void *ret = realloc(ptr, size);
365 err(EX_OSERR, "realloc");
370 * conditionally runs the command.
371 * Selected options or negative -> getsockopt
374 do_cmd(int optname, void *optval, uintptr_t optlen)
376 static int s = -1; /* the socket */
383 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
385 err(EX_UNAVAILABLE, "socket");
387 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
388 optname == IP_FW_ADD || optname == IP_FW_TABLE_LIST ||
389 optname == IP_FW_TABLE_GETSIZE ||
390 optname == IP_FW_NAT_GET_CONFIG ||
392 optname == IP_FW_NAT_GET_LOG) {
395 i = getsockopt(s, IPPROTO_IP, optname, optval,
396 (socklen_t *)optlen);
398 i = setsockopt(s, IPPROTO_IP, optname, optval, optlen);
404 * match_token takes a table and a string, returns the value associated
405 * with the string (-1 in case of failure).
408 match_token(struct _s_x *table, char *string)
411 uint i = strlen(string);
413 for (pt = table ; i && pt->s != NULL ; pt++)
414 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
420 * match_value takes a table and a value, returns the string associated
421 * with the value (NULL in case of failure).
424 match_value(struct _s_x *p, int value)
426 for (; p->s != NULL; p++)
433 * _substrcmp takes two strings and returns 1 if they do not match,
434 * and 0 if they match exactly or the first string is a sub-string
435 * of the second. A warning is printed to stderr in the case that the
436 * first string is a sub-string of the second.
438 * This function will be removed in the future through the usual
439 * deprecation process.
442 _substrcmp(const char *str1, const char* str2)
445 if (strncmp(str1, str2, strlen(str1)) != 0)
448 if (strlen(str1) != strlen(str2))
449 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
455 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
456 * and 0 if they match exactly or the second string is a sub-string
457 * of the first. A warning is printed to stderr in the case that the
458 * first string does not match the third.
460 * This function exists to warn about the bizzare construction
461 * strncmp(str, "by", 2) which is used to allow people to use a shotcut
462 * for "bytes". The problem is that in addition to accepting "by",
463 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
464 * other string beginning with "by".
466 * This function will be removed in the future through the usual
467 * deprecation process.
470 _substrcmp2(const char *str1, const char* str2, const char* str3)
473 if (strncmp(str1, str2, strlen(str2)) != 0)
476 if (strcmp(str1, str3) != 0)
477 warnx("DEPRECATED: '%s' matched '%s'",
483 * prints one port, symbolic or numeric
486 print_port(int proto, uint16_t port)
489 if (proto == IPPROTO_ETHERTYPE) {
492 if (co.do_resolv && (s = match_value(ether_types, port)) )
495 printf("0x%04x", port);
497 struct servent *se = NULL;
499 struct protoent *pe = getprotobynumber(proto);
501 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
504 printf("%s", se->s_name);
510 static struct _s_x _port_name[] = {
511 {"dst-port", O_IP_DSTPORT},
512 {"src-port", O_IP_SRCPORT},
516 {"mac-type", O_MAC_TYPE},
517 {"tcpdatalen", O_TCPDATALEN},
518 {"tagged", O_TAGGED},
523 * Print the values in a list 16-bit items of the types above.
524 * XXX todo: add support for mask.
527 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode)
529 uint16_t *p = cmd->ports;
534 sep = match_value(_port_name, opcode);
540 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
542 print_port(proto, p[0]);
545 print_port(proto, p[1]);
552 * Like strtol, but also translates service names into port numbers
553 * for some protocols.
555 * proto == -1 disables the protocol check;
556 * proto == IPPROTO_ETHERTYPE looks up an internal table
557 * proto == <some value in /etc/protocols> matches the values there.
558 * Returns *end == s in case the parameter is not found.
561 strtoport(char *s, char **end, int base, int proto)
567 *end = s; /* default - not found */
569 return 0; /* not found */
572 return strtol(s, end, base);
575 * find separator. '\\' escapes the next char.
577 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
578 if (*s1 == '\\' && s1[1] != '\0')
581 buf = safe_calloc(s1 - s + 1, 1);
584 * copy into a buffer skipping backslashes
586 for (p = s, i = 0; p != s1 ; p++)
591 if (proto == IPPROTO_ETHERTYPE) {
592 i = match_token(ether_types, buf);
594 if (i != -1) { /* found */
599 struct protoent *pe = NULL;
603 pe = getprotobynumber(proto);
605 se = getservbyname(buf, pe ? pe->p_name : NULL);
609 return ntohs(se->s_port);
612 return 0; /* not found */
616 * Fill the body of the command with the list of port ranges.
619 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto)
621 uint16_t a, b, *p = cmd->ports;
626 a = strtoport(av, &s, 0, proto);
627 if (s == av) /* empty or invalid argument */
631 case '-': /* a range */
633 b = strtoport(av, &s, 0, proto);
634 /* Reject expressions like '1-abc' or '1-2-3'. */
635 if (s == av || (*s != ',' && *s != '\0'))
640 case ',': /* comma separated list */
645 warnx("port list: invalid separator <%c> in <%s>",
655 if (i + 1 > F_LEN_MASK)
656 errx(EX_DATAERR, "too many ports/ranges\n");
657 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
662 static struct _s_x icmpcodes[] = {
663 { "net", ICMP_UNREACH_NET },
664 { "host", ICMP_UNREACH_HOST },
665 { "protocol", ICMP_UNREACH_PROTOCOL },
666 { "port", ICMP_UNREACH_PORT },
667 { "needfrag", ICMP_UNREACH_NEEDFRAG },
668 { "srcfail", ICMP_UNREACH_SRCFAIL },
669 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
670 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
671 { "isolated", ICMP_UNREACH_ISOLATED },
672 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
673 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
674 { "tosnet", ICMP_UNREACH_TOSNET },
675 { "toshost", ICMP_UNREACH_TOSHOST },
676 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
677 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
678 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
683 fill_reject_code(u_short *codep, char *str)
688 val = strtoul(str, &s, 0);
689 if (s == str || *s != '\0' || val >= 0x100)
690 val = match_token(icmpcodes, str);
692 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
698 print_reject_code(uint16_t code)
700 char const *s = match_value(icmpcodes, code);
703 printf("unreach %s", s);
705 printf("unreach %u", code);
709 * Returns the number of bits set (from left) in a contiguous bitmask,
710 * or -1 if the mask is not contiguous.
711 * XXX this needs a proper fix.
712 * This effectively works on masks in big-endian (network) format.
713 * when compiled on little endian architectures.
715 * First bit is bit 7 of the first byte -- note, for MAC addresses,
716 * the first bit on the wire is bit 0 of the first byte.
717 * len is the max length in bits.
720 contigmask(uint8_t *p, int len)
724 for (i=0; i<len ; i++)
725 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
727 for (n=i+1; n < len; n++)
728 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
729 return -1; /* mask not contiguous */
734 * print flags set/clear in the two bitmasks passed as parameters.
735 * There is a specialized check for f_tcpflags.
738 print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list)
740 char const *comma = "";
742 uint8_t set = cmd->arg1 & 0xff;
743 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
745 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
750 printf(" %s ", name);
751 for (i=0; list[i].x != 0; i++) {
752 if (set & list[i].x) {
754 printf("%s%s", comma, list[i].s);
757 if (clear & list[i].x) {
759 printf("%s!%s", comma, list[i].s);
766 * Print the ip address contained in a command.
769 print_ip(ipfw_insn_ip *cmd, char const *s)
771 struct hostent *he = NULL;
772 uint32_t len = F_LEN((ipfw_insn *)cmd);
773 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
775 if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
777 const char *arg = "<invalid>";
779 if (d < sizeof(lookup_key)/sizeof(lookup_key[0]))
780 arg = match_value(rule_options, lookup_key[d]);
781 printf("%s lookup %s %d", cmd->o.len & F_NOT ? " not": "",
785 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
787 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
791 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
792 cmd->o.opcode == O_IP_DST_LOOKUP) {
793 printf("table(%u", ((ipfw_insn *)cmd)->arg1);
794 if (len == F_INSN_SIZE(ipfw_insn_u32))
799 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
800 uint32_t x, *map = (uint32_t *)&(cmd->mask);
806 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
807 printf("%s/%d", inet_ntoa(cmd->addr),
808 contigmask((uint8_t *)&x, 32));
809 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
810 x &= 0xff; /* base */
812 * Print bits and ranges.
813 * Locate first bit set (i), then locate first bit unset (j).
814 * If we have 3+ consecutive bits set, then print them as a
815 * range, otherwise only print the initial bit and rescan.
817 for (i=0; i < cmd->o.arg1; i++)
818 if (map[i/32] & (1<<(i & 31))) {
819 for (j=i+1; j < cmd->o.arg1; j++)
820 if (!(map[ j/32] & (1<<(j & 31))))
822 printf("%c%d", comma, i+x);
823 if (j>i+2) { /* range has at least 3 elements */
824 printf("-%d", j-1+x);
833 * len == 2 indicates a single IP, whereas lists of 1 or more
834 * addr/mask pairs have len = (2n+1). We convert len to n so we
835 * use that to count the number of entries.
837 for (len = len / 2; len > 0; len--, a += 2) {
838 int mb = /* mask length */
839 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
840 32 : contigmask((uint8_t *)&(a[1]), 32);
841 if (mb == 32 && co.do_resolv)
842 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
843 if (he != NULL) /* resolved to name */
844 printf("%s", he->h_name);
845 else if (mb == 0) /* any */
847 else { /* numeric IP followed by some kind of mask */
848 printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) );
850 printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) );
860 * prints a MAC address/mask pair
863 print_mac(uint8_t *addr, uint8_t *mask)
865 int l = contigmask(mask, 48);
870 printf(" %02x:%02x:%02x:%02x:%02x:%02x",
871 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
873 printf("&%02x:%02x:%02x:%02x:%02x:%02x",
874 mask[0], mask[1], mask[2],
875 mask[3], mask[4], mask[5]);
882 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
891 type = strtoul(av, &av, 0);
893 if (*av != ',' && *av != '\0')
894 errx(EX_DATAERR, "invalid ICMP type");
897 errx(EX_DATAERR, "ICMP type out of range");
899 cmd->d[0] |= 1 << type;
901 cmd->o.opcode = O_ICMPTYPE;
902 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
906 print_icmptypes(ipfw_insn_u32 *cmd)
911 printf(" icmptypes");
912 for (i = 0; i < 32; i++) {
913 if ( (cmd->d[0] & (1 << (i))) == 0)
915 printf("%c%d", sep, i);
921 * show_ipfw() prints the body of an ipfw rule.
922 * Because the standard rule has at least proto src_ip dst_ip, we use
923 * a helper function to produce these entries if not provided explicitly.
924 * The first argument is the list of fields we have, the second is
925 * the list of fields we want to be printed.
927 * Special cases if we have provided a MAC header:
928 * + if the rule does not contain IP addresses/ports, do not print them;
929 * + if the rule does not contain an IP proto, print "all" instead of "ip";
931 * Once we have 'have_options', IP header fields are printed as options.
933 #define HAVE_PROTO 0x0001
934 #define HAVE_SRCIP 0x0002
935 #define HAVE_DSTIP 0x0004
936 #define HAVE_PROTO4 0x0008
937 #define HAVE_PROTO6 0x0010
938 #define HAVE_IP 0x0100
939 #define HAVE_OPTIONS 0x8000
942 show_prerequisites(int *flags, int want, int cmd __unused)
946 if ( (*flags & HAVE_IP) == HAVE_IP)
947 *flags |= HAVE_OPTIONS;
949 if ( !(*flags & HAVE_OPTIONS)) {
950 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) {
951 if ( (*flags & HAVE_PROTO4))
953 else if ( (*flags & HAVE_PROTO6))
958 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
960 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
967 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth)
969 static int twidth = 0;
971 ipfw_insn *cmd, *tagptr = NULL;
972 const char *comment = NULL; /* ptr to comment if we have one */
973 int proto = 0; /* default */
974 int flags = 0; /* prerequisites */
975 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
976 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
977 int or_block = 0; /* we are in an or block */
978 uint32_t set_disable;
980 bcopy(&rule->next_rule, &set_disable, sizeof(set_disable));
982 if (set_disable & (1 << rule->set)) { /* disabled */
986 printf("# DISABLED ");
988 printf("%05u ", rule->rulenum);
990 if (pcwidth > 0 || bcwidth > 0) {
991 pr_u64(&rule->pcnt, pcwidth);
992 pr_u64(&rule->bcnt, bcwidth);
996 printf("%10u ", rule->timestamp);
997 else if (co.do_time == 1) {
999 time_t t = (time_t)0;
1002 strcpy(timestr, ctime(&t));
1003 *strchr(timestr, '\n') = '\0';
1004 twidth = strlen(timestr);
1006 if (rule->timestamp) {
1007 t = _long_to_time(rule->timestamp);
1009 strcpy(timestr, ctime(&t));
1010 *strchr(timestr, '\n') = '\0';
1011 printf("%s ", timestr);
1013 printf("%*s", twidth, " ");
1018 printf("set %d ", rule->set);
1021 * print the optional "match probability"
1023 if (rule->cmd_len > 0) {
1025 if (cmd->opcode == O_PROB) {
1026 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1027 double d = 1.0 * p->d[0];
1029 d = (d / 0x7fffffff);
1030 printf("prob %f ", d);
1035 * first print actions
1037 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1038 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1039 switch(cmd->opcode) {
1041 printf("check-state");
1042 /* avoid printing anything else */
1043 flags = HAVE_PROTO | HAVE_SRCIP |
1044 HAVE_DSTIP | HAVE_IP;
1060 if (cmd->arg1 == ICMP_REJECT_RST)
1062 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1065 print_reject_code(cmd->arg1);
1069 if (cmd->arg1 == ICMP6_UNREACH_RST)
1072 print_unreach6_code(cmd->arg1);
1076 PRINT_UINT_ARG("skipto ", cmd->arg1);
1080 PRINT_UINT_ARG("pipe ", cmd->arg1);
1084 PRINT_UINT_ARG("queue ", cmd->arg1);
1088 PRINT_UINT_ARG("divert ", cmd->arg1);
1092 PRINT_UINT_ARG("tee ", cmd->arg1);
1096 PRINT_UINT_ARG("netgraph ", cmd->arg1);
1100 PRINT_UINT_ARG("ngtee ", cmd->arg1);
1105 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1107 if (s->sa.sin_addr.s_addr == INADDR_ANY) {
1108 printf("fwd tablearg");
1110 printf("fwd %s", inet_ntoa(s->sa.sin_addr));
1113 printf(",%d", s->sa.sin_port);
1117 case O_LOG: /* O_LOG is printed last */
1118 logptr = (ipfw_insn_log *)cmd;
1121 case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1122 altqptr = (ipfw_insn_altq *)cmd;
1130 PRINT_UINT_ARG("nat ", cmd->arg1);
1134 PRINT_UINT_ARG("setfib ", cmd->arg1);
1142 printf("** unrecognized action %d len %d ",
1143 cmd->opcode, cmd->len);
1147 if (logptr->max_log > 0)
1148 printf(" log logamount %d", logptr->max_log);
1154 print_altq_cmd(altqptr);
1158 if (tagptr->len & F_NOT)
1159 PRINT_UINT_ARG(" untag ", tagptr->arg1);
1161 PRINT_UINT_ARG(" tag ", tagptr->arg1);
1165 * then print the body.
1167 for (l = rule->act_ofs, cmd = rule->cmd ;
1168 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1169 if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1171 if (cmd->opcode == O_IP4) {
1172 flags |= HAVE_PROTO4;
1174 } else if (cmd->opcode == O_IP6) {
1175 flags |= HAVE_PROTO6;
1179 if (rule->_pad & 1) { /* empty rules before options */
1180 if (!co.do_compact) {
1181 show_prerequisites(&flags, HAVE_PROTO, 0);
1182 printf(" from any to any");
1184 flags |= HAVE_IP | HAVE_OPTIONS | HAVE_PROTO |
1185 HAVE_SRCIP | HAVE_DSTIP;
1188 if (co.comment_only)
1191 for (l = rule->act_ofs, cmd = rule->cmd ;
1192 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1194 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1196 if (co.comment_only) {
1197 if (cmd->opcode != O_NOP)
1199 printf(" // %s\n", (char *)(cmd + 1));
1203 show_prerequisites(&flags, 0, cmd->opcode);
1205 switch(cmd->opcode) {
1207 break; /* done already */
1210 break; /* no need to print anything here */
1213 case O_IP_SRC_LOOKUP:
1217 show_prerequisites(&flags, HAVE_PROTO, 0);
1218 if (!(flags & HAVE_SRCIP))
1220 if ((cmd->len & F_OR) && !or_block)
1222 print_ip((ipfw_insn_ip *)cmd,
1223 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1224 flags |= HAVE_SRCIP;
1228 case O_IP_DST_LOOKUP:
1232 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1233 if (!(flags & HAVE_DSTIP))
1235 if ((cmd->len & F_OR) && !or_block)
1237 print_ip((ipfw_insn_ip *)cmd,
1238 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1239 flags |= HAVE_DSTIP;
1243 case O_IP6_SRC_MASK:
1245 show_prerequisites(&flags, HAVE_PROTO, 0);
1246 if (!(flags & HAVE_SRCIP))
1248 if ((cmd->len & F_OR) && !or_block)
1250 print_ip6((ipfw_insn_ip6 *)cmd,
1251 (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1252 flags |= HAVE_SRCIP | HAVE_PROTO;
1256 case O_IP6_DST_MASK:
1258 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1259 if (!(flags & HAVE_DSTIP))
1261 if ((cmd->len & F_OR) && !or_block)
1263 print_ip6((ipfw_insn_ip6 *)cmd,
1264 (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1265 flags |= HAVE_DSTIP;
1269 print_flow6id( (ipfw_insn_u32 *) cmd );
1270 flags |= HAVE_OPTIONS;
1274 show_prerequisites(&flags,
1275 HAVE_PROTO | HAVE_SRCIP |
1276 HAVE_DSTIP | HAVE_IP, 0);
1278 show_prerequisites(&flags,
1279 HAVE_PROTO | HAVE_SRCIP, 0);
1280 if ((cmd->len & F_OR) && !or_block)
1282 if (cmd->len & F_NOT)
1284 print_newports((ipfw_insn_u16 *)cmd, proto,
1285 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1289 struct protoent *pe = NULL;
1291 if ((cmd->len & F_OR) && !or_block)
1293 if (cmd->len & F_NOT)
1296 pe = getprotobynumber(cmd->arg1);
1297 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1298 !(flags & HAVE_PROTO))
1299 show_prerequisites(&flags,
1300 HAVE_PROTO | HAVE_IP | HAVE_SRCIP |
1301 HAVE_DSTIP | HAVE_OPTIONS, 0);
1302 if (flags & HAVE_OPTIONS)
1305 printf(" %s", pe->p_name);
1307 printf(" %u", cmd->arg1);
1309 flags |= HAVE_PROTO;
1312 default: /*options ... */
1313 if (!(cmd->len & (F_OR|F_NOT)))
1314 if (((cmd->opcode == O_IP6) &&
1315 (flags & HAVE_PROTO6)) ||
1316 ((cmd->opcode == O_IP4) &&
1317 (flags & HAVE_PROTO4)))
1319 show_prerequisites(&flags, HAVE_PROTO | HAVE_SRCIP |
1320 HAVE_DSTIP | HAVE_IP | HAVE_OPTIONS, 0);
1321 if ((cmd->len & F_OR) && !or_block)
1323 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1325 switch(cmd->opcode) {
1327 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1330 print_mac(m->addr, m->mask);
1331 print_mac(m->addr + 6, m->mask + 6);
1336 print_newports((ipfw_insn_u16 *)cmd,
1337 IPPROTO_ETHERTYPE, cmd->opcode);
1346 printf(" fib %u", cmd->arg1 );
1350 printf(cmd->len & F_NOT ? " out" : " in");
1354 switch (cmd->arg1) {
1356 printf(" diverted");
1359 printf(" diverted-loopback");
1362 printf(" diverted-output");
1365 printf(" diverted-?<%u>", cmd->arg1);
1378 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1380 if (cmd->opcode == O_XMIT)
1382 else if (cmd->opcode == O_RECV)
1384 else /* if (cmd->opcode == O_VIA) */
1386 if (cmdif->name[0] == '\0')
1388 inet_ntoa(cmdif->p.ip));
1390 printf(" %s %s", s, cmdif->name);
1395 if (F_LEN(cmd) == 1)
1396 printf(" ipid %u", cmd->arg1 );
1398 print_newports((ipfw_insn_u16 *)cmd, 0,
1403 if (F_LEN(cmd) == 1)
1404 printf(" ipttl %u", cmd->arg1 );
1406 print_newports((ipfw_insn_u16 *)cmd, 0,
1411 printf(" ipver %u", cmd->arg1 );
1414 case O_IPPRECEDENCE:
1415 printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1419 if (F_LEN(cmd) == 1)
1420 printf(" iplen %u", cmd->arg1 );
1422 print_newports((ipfw_insn_u16 *)cmd, 0,
1427 print_flags("ipoptions", cmd, f_ipopts);
1431 print_flags("iptos", cmd, f_iptos);
1435 print_icmptypes((ipfw_insn_u32 *)cmd);
1439 printf(" established");
1443 if (F_LEN(cmd) == 1)
1444 printf(" tcpdatalen %u", cmd->arg1 );
1446 print_newports((ipfw_insn_u16 *)cmd, 0,
1451 print_flags("tcpflags", cmd, f_tcpflags);
1455 print_flags("tcpoptions", cmd, f_tcpopts);
1459 printf(" tcpwin %d", ntohs(cmd->arg1));
1463 printf(" tcpack %d", ntohl(cmd32->d[0]));
1467 printf(" tcpseq %d", ntohl(cmd32->d[0]));
1472 struct passwd *pwd = getpwuid(cmd32->d[0]);
1475 printf(" uid %s", pwd->pw_name);
1477 printf(" uid %u", cmd32->d[0]);
1483 struct group *grp = getgrgid(cmd32->d[0]);
1486 printf(" gid %s", grp->gr_name);
1488 printf(" gid %u", cmd32->d[0]);
1493 printf(" jail %d", cmd32->d[0]);
1497 printf(" verrevpath");
1501 printf(" versrcreach");
1505 printf(" antispoof");
1513 comment = (char *)(cmd + 1);
1517 printf(" keep-state");
1521 struct _s_x *p = limit_masks;
1522 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1523 uint8_t x = c->limit_mask;
1524 char const *comma = " ";
1527 for (; p->x != 0 ; p++)
1528 if ((x & p->x) == p->x) {
1530 printf("%s%s", comma, p->s);
1533 PRINT_UINT_ARG(" ", c->conn_limit);
1546 print_icmp6types((ipfw_insn_u32 *)cmd);
1550 print_ext6hdr( (ipfw_insn *) cmd );
1554 if (F_LEN(cmd) == 1)
1555 PRINT_UINT_ARG(" tagged ", cmd->arg1);
1557 print_newports((ipfw_insn_u16 *)cmd, 0,
1562 printf(" [opcode %d len %d]",
1563 cmd->opcode, cmd->len);
1566 if (cmd->len & F_OR) {
1569 } else if (or_block) {
1574 show_prerequisites(&flags, HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP
1577 printf(" // %s", comment);
1582 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth)
1584 struct protoent *pe;
1587 char buf[INET6_ADDRSTRLEN];
1589 if (!co.do_expired) {
1590 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1593 bcopy(&d->rule, &rulenum, sizeof(rulenum));
1594 printf("%05d", rulenum);
1595 if (pcwidth > 0 || bcwidth > 0) {
1597 pr_u64(&d->pcnt, pcwidth);
1598 pr_u64(&d->bcnt, bcwidth);
1599 printf("(%ds)", d->expire);
1601 switch (d->dyn_type) {
1602 case O_LIMIT_PARENT:
1603 printf(" PARENT %d", d->count);
1608 case O_KEEP_STATE: /* bidir, no mask */
1613 if ((pe = getprotobynumber(d->id.proto)) != NULL)
1614 printf(" %s", pe->p_name);
1616 printf(" proto %u", d->id.proto);
1618 if (d->id.addr_type == 4) {
1619 a.s_addr = htonl(d->id.src_ip);
1620 printf(" %s %d", inet_ntoa(a), d->id.src_port);
1622 a.s_addr = htonl(d->id.dst_ip);
1623 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
1624 } else if (d->id.addr_type == 6) {
1625 printf(" %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
1626 sizeof(buf)), d->id.src_port);
1627 printf(" <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6, buf,
1628 sizeof(buf)), d->id.dst_port);
1630 printf(" UNKNOWN <-> UNKNOWN\n");
1636 * This one handles all set-related commands
1637 * ipfw set { show | enable | disable }
1639 * ipfw set move X to Y
1640 * ipfw set move rule X to Y
1643 ipfw_sets_handler(char *av[])
1645 uint32_t set_disable, masks[2];
1648 uint8_t cmd, new_set;
1653 errx(EX_USAGE, "set needs command");
1654 if (_substrcmp(*av, "show") == 0) {
1659 nalloc = nbytes = sizeof(struct ip_fw);
1660 while (nbytes >= nalloc) {
1663 nalloc = nalloc * 2 + 200;
1665 data = safe_calloc(1, nbytes);
1666 if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0)
1667 err(EX_OSERR, "getsockopt(IP_FW_GET)");
1670 bcopy(&((struct ip_fw *)data)->next_rule,
1671 &set_disable, sizeof(set_disable));
1673 for (i = 0, msg = "disable" ; i < RESVD_SET; i++)
1674 if ((set_disable & (1<<i))) {
1675 printf("%s %d", msg, i);
1678 msg = (set_disable) ? " enable" : "enable";
1679 for (i = 0; i < RESVD_SET; i++)
1680 if (!(set_disable & (1<<i))) {
1681 printf("%s %d", msg, i);
1685 } else if (_substrcmp(*av, "swap") == 0) {
1687 if ( av[0] == NULL || av[1] == NULL )
1688 errx(EX_USAGE, "set swap needs 2 set numbers\n");
1689 rulenum = atoi(av[0]);
1690 new_set = atoi(av[1]);
1691 if (!isdigit(*(av[0])) || rulenum > RESVD_SET)
1692 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
1693 if (!isdigit(*(av[1])) || new_set > RESVD_SET)
1694 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
1695 masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
1696 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
1697 } else if (_substrcmp(*av, "move") == 0) {
1699 if (av[0] && _substrcmp(*av, "rule") == 0) {
1704 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
1705 av[3] != NULL || _substrcmp(av[1], "to") != 0)
1706 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
1707 rulenum = atoi(av[0]);
1708 new_set = atoi(av[2]);
1709 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) ||
1710 (cmd == 2 && rulenum == IPFW_DEFAULT_RULE) )
1711 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
1712 if (!isdigit(*(av[2])) || new_set > RESVD_SET)
1713 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
1714 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
1715 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
1716 } else if (_substrcmp(*av, "disable") == 0 ||
1717 _substrcmp(*av, "enable") == 0 ) {
1718 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
1721 masks[0] = masks[1] = 0;
1724 if (isdigit(**av)) {
1726 if (i < 0 || i > RESVD_SET)
1728 "invalid set number %d\n", i);
1729 masks[which] |= (1<<i);
1730 } else if (_substrcmp(*av, "disable") == 0)
1732 else if (_substrcmp(*av, "enable") == 0)
1736 "invalid set command %s\n", *av);
1739 if ( (masks[0] & masks[1]) != 0 )
1741 "cannot enable and disable the same set\n");
1743 i = do_cmd(IP_FW_DEL, masks, sizeof(masks));
1745 warn("set enable/disable: setsockopt(IP_FW_DEL)");
1747 errx(EX_USAGE, "invalid set command %s\n", *av);
1751 ipfw_sysctl_handler(char *av[], int which)
1755 if (av[0] == NULL) {
1756 warnx("missing keyword to enable/disable\n");
1757 } else if (_substrcmp(*av, "firewall") == 0) {
1758 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
1759 &which, sizeof(which));
1760 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
1761 &which, sizeof(which));
1762 } else if (_substrcmp(*av, "one_pass") == 0) {
1763 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
1764 &which, sizeof(which));
1765 } else if (_substrcmp(*av, "debug") == 0) {
1766 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
1767 &which, sizeof(which));
1768 } else if (_substrcmp(*av, "verbose") == 0) {
1769 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
1770 &which, sizeof(which));
1771 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
1772 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
1773 &which, sizeof(which));
1775 } else if (_substrcmp(*av, "altq") == 0) {
1776 altq_set_enabled(which);
1779 warnx("unrecognize enable/disable keyword: %s\n", *av);
1784 ipfw_list(int ac, char *av[], int show_counters)
1787 ipfw_dyn_rule *dynrules, *d;
1789 #define NEXT(r) ((struct ip_fw *)((char *)r + RULESIZE(r)))
1792 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
1793 int exitval = EX_OK;
1801 const int ocmd = co.do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
1802 int nalloc = 1024; /* start somewhere... */
1807 fprintf(stderr, "Testing only, list disabled\n");
1811 dummynet_list(ac, av, show_counters);
1818 /* get rules or pipes from kernel, resizing array as necessary */
1821 while (nbytes >= nalloc) {
1822 nalloc = nalloc * 2 + 200;
1824 data = safe_realloc(data, nbytes);
1825 if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0)
1826 err(EX_OSERR, "getsockopt(IP_%s_GET)",
1827 co.do_pipe ? "DUMMYNET" : "FW");
1831 * Count static rules. They have variable size so we
1832 * need to scan the list to count them.
1834 for (nstat = 1, r = data, lim = (char *)data + nbytes;
1835 r->rulenum < IPFW_DEFAULT_RULE && (char *)r < lim;
1836 ++nstat, r = NEXT(r) )
1840 * Count dynamic rules. This is easier as they have
1844 dynrules = (ipfw_dyn_rule *)r ;
1845 n = (char *)r - (char *)data;
1846 ndyn = (nbytes - n) / sizeof *dynrules;
1848 /* if showing stats, figure out column widths ahead of time */
1849 bcwidth = pcwidth = 0;
1850 if (show_counters) {
1851 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
1852 /* skip rules from another set */
1853 if (co.use_set && r->set != co.use_set - 1)
1856 /* packet counter */
1857 width = pr_u64(&r->pcnt, 0);
1858 if (width > pcwidth)
1862 width = pr_u64(&r->bcnt, 0);
1863 if (width > bcwidth)
1867 if (co.do_dynamic && ndyn) {
1868 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1870 /* skip rules from another set */
1871 bcopy((char *)&d->rule + sizeof(uint16_t),
1872 &set, sizeof(uint8_t));
1873 if (set != co.use_set - 1)
1876 width = pr_u64(&d->pcnt, 0);
1877 if (width > pcwidth)
1880 width = pr_u64(&d->bcnt, 0);
1881 if (width > bcwidth)
1885 /* if no rule numbers were specified, list all rules */
1887 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
1888 if (co.use_set && r->set != co.use_set - 1)
1890 show_ipfw(r, pcwidth, bcwidth);
1893 if (co.do_dynamic && ndyn) {
1894 printf("## Dynamic rules (%d):\n", ndyn);
1895 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1897 bcopy((char *)&d->rule + sizeof(uint16_t),
1898 &set, sizeof(uint8_t));
1899 if (set != co.use_set - 1)
1902 show_dyn_ipfw(d, pcwidth, bcwidth);
1908 /* display specific rules requested on command line */
1910 for (lac = ac, lav = av; lac != 0; lac--) {
1911 /* convert command line rule # */
1912 last = rnum = strtoul(*lav++, &endptr, 10);
1914 last = strtoul(endptr+1, &endptr, 10);
1917 warnx("invalid rule number: %s", *(lav - 1));
1920 for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) {
1921 if (r->rulenum > last)
1923 if (co.use_set && r->set != co.use_set - 1)
1925 if (r->rulenum >= rnum && r->rulenum <= last) {
1926 show_ipfw(r, pcwidth, bcwidth);
1931 /* give precedence to other error(s) */
1932 if (exitval == EX_OK)
1933 exitval = EX_UNAVAILABLE;
1934 warnx("rule %lu does not exist", rnum);
1938 if (co.do_dynamic && ndyn) {
1939 printf("## Dynamic rules:\n");
1940 for (lac = ac, lav = av; lac != 0; lac--) {
1941 last = rnum = strtoul(*lav++, &endptr, 10);
1943 last = strtoul(endptr+1, &endptr, 10);
1945 /* already warned */
1947 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1950 bcopy(&d->rule, &rulenum, sizeof(rulenum));
1954 bcopy((char *)&d->rule + sizeof(uint16_t),
1955 &set, sizeof(uint8_t));
1956 if (set != co.use_set - 1)
1959 if (r->rulenum >= rnum && r->rulenum <= last)
1960 show_dyn_ipfw(d, pcwidth, bcwidth);
1970 if (exitval != EX_OK)
1976 lookup_host (char *host, struct in_addr *ipaddr)
1980 if (!inet_aton(host, ipaddr)) {
1981 if ((he = gethostbyname(host)) == NULL)
1983 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
1989 * fills the addr and mask fields in the instruction as appropriate from av.
1990 * Update length as appropriate.
1991 * The following formats are allowed:
1992 * me returns O_IP_*_ME
1993 * 1.2.3.4 single IP address
1994 * 1.2.3.4:5.6.7.8 address:mask
1995 * 1.2.3.4/24 address/mask
1996 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
1997 * We can have multiple comma-separated address/mask entries.
2000 fill_ip(ipfw_insn_ip *cmd, char *av)
2003 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2005 cmd->o.len &= ~F_LEN_MASK; /* zero len */
2007 if (_substrcmp(av, "any") == 0)
2010 if (_substrcmp(av, "me") == 0) {
2011 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2015 if (strncmp(av, "table(", 6) == 0) {
2016 char *p = strchr(av + 6, ',');
2020 cmd->o.opcode = O_IP_DST_LOOKUP;
2021 cmd->o.arg1 = strtoul(av + 6, NULL, 0);
2023 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2024 d[0] = strtoul(p, NULL, 0);
2026 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2032 * After the address we can have '/' or ':' indicating a mask,
2033 * ',' indicating another address follows, '{' indicating a
2034 * set of addresses of unspecified size.
2036 char *t = NULL, *p = strpbrk(av, "/:,{");
2043 if ((t = strpbrk(p, ",{")) != NULL) {
2050 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2051 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2054 if (!inet_aton(p, (struct in_addr *)&d[1]))
2055 errx(EX_DATAERR, "bad netmask ``%s''", p);
2060 d[1] = htonl(0); /* mask */
2061 else if (masklen > 32)
2062 errx(EX_DATAERR, "bad width ``%s''", p);
2064 d[1] = htonl(~0 << (32 - masklen));
2066 case '{': /* no mask, assume /24 and put back the '{' */
2067 d[1] = htonl(~0 << (32 - 24));
2071 case ',': /* single address plus continuation */
2074 case 0: /* initialization value */
2076 d[1] = htonl(~0); /* force /32 */
2079 d[0] &= d[1]; /* mask base address with mask */
2082 /* find next separator */
2084 p = strpbrk(p, ",{");
2085 if (p && *p == '{') {
2087 * We have a set of addresses. They are stored as follows:
2088 * arg1 is the set size (powers of 2, 2..256)
2089 * addr is the base address IN HOST FORMAT
2090 * mask.. is an array of arg1 bits (rounded up to
2091 * the next multiple of 32) with bits set
2092 * for each host in the map.
2094 uint32_t *map = (uint32_t *)&cmd->mask;
2096 int i = contigmask((uint8_t *)&(d[1]), 32);
2099 errx(EX_DATAERR, "address set cannot be in a list");
2100 if (i < 24 || i > 31)
2101 errx(EX_DATAERR, "invalid set with mask %d\n", i);
2102 cmd->o.arg1 = 1<<(32-i); /* map length */
2103 d[0] = ntohl(d[0]); /* base addr in host format */
2104 cmd->o.opcode = O_IP_DST_SET; /* default */
2105 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2106 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2107 map[i] = 0; /* clear map */
2111 high = low + cmd->o.arg1 - 1;
2113 * Here, i stores the previous value when we specify a range
2114 * of addresses within a mask, e.g. 45-63. i = -1 means we
2115 * have no previous value.
2117 i = -1; /* previous value in a range */
2118 while (isdigit(*av)) {
2120 int a = strtol(av, &s, 0);
2122 if (s == av) { /* no parameter */
2124 errx(EX_DATAERR, "set not closed\n");
2126 errx(EX_DATAERR, "incomplete range %d-", i);
2129 if (a < low || a > high)
2130 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
2133 if (i == -1) /* no previous in range */
2135 else { /* check that range is valid */
2137 errx(EX_DATAERR, "invalid range %d-%d",
2140 errx(EX_DATAERR, "double '-' in range");
2143 map[i/32] |= 1<<(i & 31);
2154 if (av) /* then *av must be a ',' */
2157 /* Check this entry */
2158 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2160 * 'any' turns the entire list into a NOP.
2161 * 'not any' never matches, so it is removed from the
2162 * list unless it is the only item, in which case we
2165 if (cmd->o.len & F_NOT) { /* "not any" never matches */
2166 if (av == NULL && len == 0) /* only this entry */
2167 errx(EX_DATAERR, "not any never matches");
2169 /* else do nothing and skip this entry */
2172 /* A single IP can be stored in an optimized format */
2173 if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
2174 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2177 len += 2; /* two words... */
2180 if (len + 1 > F_LEN_MASK)
2181 errx(EX_DATAERR, "address list too long");
2182 cmd->o.len |= len+1;
2186 /* n2mask sets n bits of the mask */
2188 n2mask(struct in6_addr *mask, int n)
2190 static int minimask[9] =
2191 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
2194 memset(mask, 0, sizeof(struct in6_addr));
2195 p = (u_char *) mask;
2196 for (; n > 0; p++, n -= 8) {
2207 * helper function to process a set of flags and set bits in the
2208 * appropriate masks.
2211 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
2212 struct _s_x *flags, char *p)
2214 uint8_t set=0, clear=0;
2217 char *q; /* points to the separator */
2219 uint8_t *which; /* mask we are working on */
2229 val = match_token(flags, p);
2231 errx(EX_DATAERR, "invalid flag %s", p);
2232 *which |= (uint8_t)val;
2235 cmd->opcode = opcode;
2236 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
2237 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
2242 ipfw_delete(char *av[])
2246 int exitval = EX_OK;
2250 NEED1("missing rule specification");
2251 if ( *av && _substrcmp(*av, "set") == 0) {
2252 /* Do not allow using the following syntax:
2253 * ipfw set N delete set M
2256 errx(EX_DATAERR, "invalid syntax");
2257 do_set = 1; /* delete set */
2262 while (*av && isdigit(**av)) {
2263 i = atoi(*av); av++;
2265 exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
2267 exitval = EX_UNAVAILABLE;
2268 warn("rule %u not available", i);
2270 } else if (co.do_pipe) {
2271 exitval = ipfw_delete_pipe(co.do_pipe, i);
2274 rulenum = (i & 0xffff) | (5 << 24) |
2275 ((co.use_set - 1) << 16);
2277 rulenum = (i & 0xffff) | (do_set << 24);
2278 i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum);
2280 exitval = EX_UNAVAILABLE;
2281 warn("rule %u: setsockopt(IP_FW_DEL)",
2286 if (exitval != EX_OK)
2292 * fill the interface structure. We do not check the name as we can
2293 * create interfaces dynamically, so checking them at insert time
2294 * makes relatively little sense.
2295 * Interface names containing '*', '?', or '[' are assumed to be shell
2296 * patterns which match interfaces.
2299 fill_iface(ipfw_insn_if *cmd, char *arg)
2301 cmd->name[0] = '\0';
2302 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
2304 /* Parse the interface or address */
2305 if (strcmp(arg, "any") == 0)
2306 cmd->o.len = 0; /* effectively ignore this command */
2307 else if (!isdigit(*arg)) {
2308 strlcpy(cmd->name, arg, sizeof(cmd->name));
2309 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
2310 } else if (!inet_aton(arg, &cmd->p.ip))
2311 errx(EX_DATAERR, "bad ip address ``%s''", arg);
2315 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
2319 char *ap, *ptr, *optr;
2320 struct ether_addr *mac;
2321 const char *macset = "0123456789abcdefABCDEF:";
2323 if (strcmp(p, "any") == 0) {
2324 for (i = 0; i < ETHER_ADDR_LEN; i++)
2325 addr[i] = mask[i] = 0;
2329 optr = ptr = strdup(p);
2330 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
2332 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
2333 errx(EX_DATAERR, "Incorrect MAC address");
2334 bcopy(mac, addr, ETHER_ADDR_LEN);
2336 errx(EX_DATAERR, "Incorrect MAC address");
2338 if (ptr != NULL) { /* we have mask? */
2339 if (p[ptr - optr - 1] == '/') { /* mask len */
2340 long ml = strtol(ptr, &ap, 10);
2341 if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
2342 errx(EX_DATAERR, "Incorrect mask length");
2343 for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
2344 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
2347 if (strspn(ptr, macset) != l ||
2348 (mac = ether_aton(ptr)) == NULL)
2349 errx(EX_DATAERR, "Incorrect mask");
2350 bcopy(mac, mask, ETHER_ADDR_LEN);
2352 } else { /* default mask: ff:ff:ff:ff:ff:ff */
2353 for (i = 0; i < ETHER_ADDR_LEN; i++)
2356 for (i = 0; i < ETHER_ADDR_LEN; i++)
2363 * helper function, updates the pointer to cmd with the length
2364 * of the current command, and also cleans up the first word of
2365 * the new command in case it has been clobbered before.
2368 next_cmd(ipfw_insn *cmd)
2371 bzero(cmd, sizeof(*cmd));
2376 * Takes arguments and copies them into a comment
2379 fill_comment(ipfw_insn *cmd, char **av)
2382 char *p = (char *)(cmd + 1);
2384 cmd->opcode = O_NOP;
2385 cmd->len = (cmd->len & (F_NOT | F_OR));
2387 /* Compute length of comment string. */
2388 for (i = 0, l = 0; av[i] != NULL; i++)
2389 l += strlen(av[i]) + 1;
2394 "comment too long (max 80 chars)");
2396 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
2397 for (i = 0; av[i] != NULL; i++) {
2406 * A function to fill simple commands of size 1.
2407 * Existing flags are preserved.
2410 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
2412 cmd->opcode = opcode;
2413 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
2418 * Fetch and add the MAC address and type, with masks. This generates one or
2419 * two microinstructions, and returns the pointer to the last one.
2422 add_mac(ipfw_insn *cmd, char *av[])
2426 if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
2427 errx(EX_DATAERR, "MAC dst src");
2429 cmd->opcode = O_MACADDR2;
2430 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
2432 mac = (ipfw_insn_mac *)cmd;
2433 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
2434 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
2435 &(mac->mask[ETHER_ADDR_LEN])); /* src */
2440 add_mactype(ipfw_insn *cmd, char *av)
2443 errx(EX_DATAERR, "missing MAC type");
2444 if (strcmp(av, "any") != 0) { /* we have a non-null type */
2445 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE);
2446 cmd->opcode = O_MAC_TYPE;
2453 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
2455 struct protoent *pe;
2459 proto = strtol(av, &ep, 10);
2460 if (*ep != '\0' || proto <= 0) {
2461 if ((pe = getprotobyname(av)) == NULL)
2463 proto = pe->p_proto;
2466 fill_cmd(cmd, O_PROTO, 0, proto);
2472 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
2474 u_char proto = IPPROTO_IP;
2476 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2477 ; /* do not set O_IP4 nor O_IP6 */
2478 else if (strcmp(av, "ip4") == 0)
2479 /* explicit "just IPv4" rule */
2480 fill_cmd(cmd, O_IP4, 0, 0);
2481 else if (strcmp(av, "ip6") == 0) {
2482 /* explicit "just IPv6" rule */
2483 proto = IPPROTO_IPV6;
2484 fill_cmd(cmd, O_IP6, 0, 0);
2486 return add_proto0(cmd, av, protop);
2493 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
2495 u_char proto = IPPROTO_IP;
2497 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2498 ; /* do not set O_IP4 nor O_IP6 */
2499 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
2500 /* explicit "just IPv4" rule */
2501 fill_cmd(cmd, O_IP4, 0, 0);
2502 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
2503 /* explicit "just IPv6" rule */
2504 proto = IPPROTO_IPV6;
2505 fill_cmd(cmd, O_IP6, 0, 0);
2507 return add_proto0(cmd, av, protop);
2514 add_srcip(ipfw_insn *cmd, char *av)
2516 fill_ip((ipfw_insn_ip *)cmd, av);
2517 if (cmd->opcode == O_IP_DST_SET) /* set */
2518 cmd->opcode = O_IP_SRC_SET;
2519 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
2520 cmd->opcode = O_IP_SRC_LOOKUP;
2521 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2522 cmd->opcode = O_IP_SRC_ME;
2523 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2524 cmd->opcode = O_IP_SRC;
2525 else /* addr/mask */
2526 cmd->opcode = O_IP_SRC_MASK;
2531 add_dstip(ipfw_insn *cmd, char *av)
2533 fill_ip((ipfw_insn_ip *)cmd, av);
2534 if (cmd->opcode == O_IP_DST_SET) /* set */
2536 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
2538 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2539 cmd->opcode = O_IP_DST_ME;
2540 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2541 cmd->opcode = O_IP_DST;
2542 else /* addr/mask */
2543 cmd->opcode = O_IP_DST_MASK;
2548 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode)
2550 /* XXX "any" is trapped before. Perhaps "to" */
2551 if (_substrcmp(av, "any") == 0) {
2553 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) {
2554 /* XXX todo: check that we have a protocol with ports */
2555 cmd->opcode = opcode;
2562 add_src(ipfw_insn *cmd, char *av, u_char proto)
2566 ipfw_insn *ret = NULL;
2568 if ((host = strdup(av)) == NULL)
2570 if ((ch = strrchr(host, '/')) != NULL)
2573 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
2574 inet_pton(AF_INET6, host, &a) == 1)
2575 ret = add_srcip6(cmd, av);
2576 /* XXX: should check for IPv4, not !IPv6 */
2577 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2578 inet_pton(AF_INET6, host, &a) != 1))
2579 ret = add_srcip(cmd, av);
2580 if (ret == NULL && strcmp(av, "any") != 0)
2588 add_dst(ipfw_insn *cmd, char *av, u_char proto)
2592 ipfw_insn *ret = NULL;
2594 if ((host = strdup(av)) == NULL)
2596 if ((ch = strrchr(host, '/')) != NULL)
2599 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
2600 inet_pton(AF_INET6, host, &a) == 1)
2601 ret = add_dstip6(cmd, av);
2602 /* XXX: should check for IPv4, not !IPv6 */
2603 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2604 inet_pton(AF_INET6, host, &a) != 1))
2605 ret = add_dstip(cmd, av);
2606 if (ret == NULL && strcmp(av, "any") != 0)
2614 * Parse arguments and assemble the microinstructions which make up a rule.
2615 * Rules are added into the 'rulebuf' and then copied in the correct order
2616 * into the actual rule.
2618 * The syntax for a rule starts with the action, followed by
2619 * optional action parameters, and the various match patterns.
2620 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
2621 * (generated if the rule includes a keep-state option), then the
2622 * various match patterns, log/altq actions, and the actual action.
2626 ipfw_add(char *av[])
2629 * rules are added into the 'rulebuf' and then copied in
2630 * the correct order into the actual rule.
2631 * Some things that need to go out of order (prob, action etc.)
2634 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255];
2636 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
2637 ipfw_insn *first_cmd; /* first match pattern */
2642 * various flags used to record that we entered some fields.
2644 ipfw_insn *have_state = NULL; /* check-state or keep-state */
2645 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
2650 int open_par = 0; /* open parenthesis ( */
2652 /* proto is here because it is used to fetch ports */
2653 u_char proto = IPPROTO_IP; /* default protocol */
2655 double match_prob = 1; /* match probability, default is always match */
2657 bzero(actbuf, sizeof(actbuf)); /* actions go here */
2658 bzero(cmdbuf, sizeof(cmdbuf));
2659 bzero(rulebuf, sizeof(rulebuf));
2661 rule = (struct ip_fw *)rulebuf;
2662 cmd = (ipfw_insn *)cmdbuf;
2663 action = (ipfw_insn *)actbuf;
2667 /* [rule N] -- Rule number optional */
2668 if (av[0] && isdigit(**av)) {
2669 rule->rulenum = atoi(*av);
2673 /* [set N] -- set number (0..RESVD_SET), optional */
2674 if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
2675 int set = strtoul(av[1], NULL, 10);
2676 if (set < 0 || set > RESVD_SET)
2677 errx(EX_DATAERR, "illegal set %s", av[1]);
2682 /* [prob D] -- match probability, optional */
2683 if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
2684 match_prob = strtod(av[1], NULL);
2686 if (match_prob <= 0 || match_prob > 1)
2687 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
2691 /* action -- mandatory */
2692 NEED1("missing action");
2693 i = match_token(rule_actions, *av);
2695 action->len = 1; /* default */
2697 case TOK_CHECKSTATE:
2698 have_state = action;
2699 action->opcode = O_CHECK_STATE;
2703 action->opcode = O_ACCEPT;
2707 action->opcode = O_DENY;
2712 action->opcode = O_REJECT;
2713 action->arg1 = ICMP_UNREACH_HOST;
2717 action->opcode = O_REJECT;
2718 action->arg1 = ICMP_REJECT_RST;
2722 action->opcode = O_UNREACH6;
2723 action->arg1 = ICMP6_UNREACH_RST;
2727 action->opcode = O_REJECT;
2728 NEED1("missing reject code");
2729 fill_reject_code(&action->arg1, *av);
2734 action->opcode = O_UNREACH6;
2735 NEED1("missing unreach code");
2736 fill_unreach6_code(&action->arg1, *av);
2741 action->opcode = O_COUNT;
2745 action->opcode = O_NAT;
2746 action->len = F_INSN_SIZE(ipfw_insn_nat);
2750 action->opcode = O_QUEUE;
2753 action->opcode = O_PIPE;
2756 action->opcode = O_SKIPTO;
2759 action->opcode = O_NETGRAPH;
2762 action->opcode = O_NGTEE;
2765 action->opcode = O_DIVERT;
2768 action->opcode = O_TEE;
2771 errx(EX_USAGE, "missing argument for %s", *(av - 1));
2772 if (isdigit(**av)) {
2773 action->arg1 = strtoul(*av, NULL, 10);
2774 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
2775 errx(EX_DATAERR, "illegal argument for %s",
2777 } else if (_substrcmp(*av, "tablearg") == 0) {
2778 action->arg1 = IP_FW_TABLEARG;
2779 } else if (i == TOK_DIVERT || i == TOK_TEE) {
2782 s = getservbyname(av[0], "divert");
2784 action->arg1 = ntohs(s->s_port);
2786 errx(EX_DATAERR, "illegal divert/tee port");
2788 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
2793 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
2796 NEED1("missing forward address[:port]");
2798 action->opcode = O_FORWARD_IP;
2799 action->len = F_INSN_SIZE(ipfw_insn_sa);
2802 * In the kernel we assume AF_INET and use only
2803 * sin_port and sin_addr. Remember to set sin_len as
2804 * the routing code seems to use it too.
2806 p->sa.sin_family = AF_INET;
2807 p->sa.sin_len = sizeof(struct sockaddr_in);
2810 * locate the address-port separator (':' or ',')
2812 s = strchr(*av, ':');
2814 s = strchr(*av, ',');
2817 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
2820 "illegal forwarding port ``%s''", s);
2821 p->sa.sin_port = (u_short)i;
2823 if (_substrcmp(*av, "tablearg") == 0)
2824 p->sa.sin_addr.s_addr = INADDR_ANY;
2826 lookup_host(*av, &(p->sa.sin_addr));
2831 /* pretend it is a 'count' rule followed by the comment */
2832 action->opcode = O_COUNT;
2833 av--; /* go back... */
2839 size_t intsize = sizeof(int);
2841 action->opcode = O_SETFIB;
2842 NEED1("missing fib number");
2843 action->arg1 = strtoul(*av, NULL, 10);
2844 if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
2845 errx(EX_DATAERR, "fibs not suported.\n");
2846 if (action->arg1 >= numfibs) /* Temporary */
2847 errx(EX_DATAERR, "fib too large.\n");
2853 action->opcode = O_REASS;
2857 errx(EX_DATAERR, "invalid action %s\n", av[-1]);
2859 action = next_cmd(action);
2862 * [altq queuename] -- altq tag, optional
2863 * [log [logamount N]] -- log, optional
2865 * If they exist, it go first in the cmdbuf, but then it is
2866 * skipped in the copy section to the end of the buffer.
2868 while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
2873 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
2878 "log cannot be specified more than once");
2879 have_log = (ipfw_insn *)c;
2880 cmd->len = F_INSN_SIZE(ipfw_insn_log);
2881 cmd->opcode = O_LOG;
2882 if (av[0] && _substrcmp(*av, "logamount") == 0) {
2884 NEED1("logamount requires argument");
2888 "logamount must be positive");
2892 len = sizeof(c->max_log);
2893 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
2894 &c->max_log, &len, NULL, 0) == -1)
2895 errx(1, "sysctlbyname(\"%s\")",
2896 "net.inet.ip.fw.verbose_limit");
2904 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
2906 NEED1("missing altq queue name");
2909 "altq cannot be specified more than once");
2910 have_altq = (ipfw_insn *)a;
2911 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
2912 cmd->opcode = O_ALTQ;
2913 a->qid = altq_name_to_qid(*av);
2924 errx(EX_USAGE, "tag and untag cannot be "
2925 "specified more than once");
2926 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
2927 rule_action_params);
2929 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
2937 cmd = next_cmd(cmd);
2940 if (have_state) /* must be a check-state, we are done */
2943 #define OR_START(target) \
2944 if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
2946 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
2949 if ( (av[0])[1] == '\0') { \
2960 strcmp(*av, ")") == 0 || \
2961 strcmp(*av, "}") == 0)) { \
2966 errx(EX_USAGE, "missing \")\"\n"); \
2970 if (av[0] && _substrcmp(*av, "not") == 0) { \
2971 if (cmd->len & F_NOT) \
2972 errx(EX_USAGE, "double \"not\" not allowed\n"); \
2973 cmd->len |= F_NOT; \
2977 #define OR_BLOCK(target) \
2978 if (av[0] && _substrcmp(*av, "or") == 0) { \
2979 if (prev == NULL || open_par == 0) \
2980 errx(EX_DATAERR, "invalid OR block"); \
2981 prev->len |= F_OR; \
2991 * MAC addresses, optional.
2992 * If we have this, we skip the part "proto from src to dst"
2993 * and jump straight to the option parsing.
2996 NEED1("missing protocol");
2997 if (_substrcmp(*av, "MAC") == 0 ||
2998 _substrcmp(*av, "mac") == 0) {
2999 av++; /* the "MAC" keyword */
3000 add_mac(cmd, av); /* exits in case of errors */
3001 cmd = next_cmd(cmd);
3002 av += 2; /* dst-mac and src-mac */
3004 NEED1("missing mac type");
3005 if (add_mactype(cmd, av[0]))
3006 cmd = next_cmd(cmd);
3007 av++; /* any or mac-type */
3013 * protocol, mandatory
3015 OR_START(get_proto);
3017 NEED1("missing protocol");
3018 if (add_proto_compat(cmd, *av, &proto)) {
3020 if (F_LEN(cmd) != 0) {
3022 cmd = next_cmd(cmd);
3024 } else if (first_cmd != cmd) {
3025 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
3028 OR_BLOCK(get_proto);
3033 if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
3034 errx(EX_USAGE, "missing ``from''");
3038 * source IP, mandatory
3040 OR_START(source_ip);
3041 NOT_BLOCK; /* optional "not" */
3042 NEED1("missing source address");
3043 if (add_src(cmd, *av, proto)) {
3045 if (F_LEN(cmd) != 0) { /* ! any */
3047 cmd = next_cmd(cmd);
3050 errx(EX_USAGE, "bad source address %s", *av);
3051 OR_BLOCK(source_ip);
3054 * source ports, optional
3056 NOT_BLOCK; /* optional "not" */
3057 if ( av[0] != NULL ) {
3058 if (_substrcmp(*av, "any") == 0 ||
3059 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
3061 if (F_LEN(cmd) != 0)
3062 cmd = next_cmd(cmd);
3069 if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
3070 errx(EX_USAGE, "missing ``to''");
3074 * destination, mandatory
3077 NOT_BLOCK; /* optional "not" */
3078 NEED1("missing dst address");
3079 if (add_dst(cmd, *av, proto)) {
3081 if (F_LEN(cmd) != 0) { /* ! any */
3083 cmd = next_cmd(cmd);
3086 errx( EX_USAGE, "bad destination address %s", *av);
3090 * dest. ports, optional
3092 NOT_BLOCK; /* optional "not" */
3094 if (_substrcmp(*av, "any") == 0 ||
3095 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
3097 if (F_LEN(cmd) != 0)
3098 cmd = next_cmd(cmd);
3103 if (av[0] && first_cmd == cmd) {
3105 * nothing specified so far, store in the rule to ease
3111 while ( av[0] != NULL ) {
3113 ipfw_insn_u32 *cmd32; /* alias for cmd */
3116 cmd32 = (ipfw_insn_u32 *)cmd;
3118 if (*s == '!') { /* alternate syntax for NOT */
3119 if (cmd->len & F_NOT)
3120 errx(EX_USAGE, "double \"not\" not allowed\n");
3124 i = match_token(rule_options, s);
3128 if (cmd->len & F_NOT)
3129 errx(EX_USAGE, "double \"not\" not allowed\n");
3134 if (open_par == 0 || prev == NULL)
3135 errx(EX_USAGE, "invalid \"or\" block\n");
3139 case TOK_STARTBRACE:
3141 errx(EX_USAGE, "+nested \"(\" not allowed\n");
3147 errx(EX_USAGE, "+missing \")\"\n");
3153 fill_cmd(cmd, O_IN, 0, 0);
3157 cmd->len ^= F_NOT; /* toggle F_NOT */
3158 fill_cmd(cmd, O_IN, 0, 0);
3162 fill_cmd(cmd, O_DIVERTED, 0, 3);
3165 case TOK_DIVERTEDLOOPBACK:
3166 fill_cmd(cmd, O_DIVERTED, 0, 1);
3169 case TOK_DIVERTEDOUTPUT:
3170 fill_cmd(cmd, O_DIVERTED, 0, 2);
3174 fill_cmd(cmd, O_FRAG, 0, 0);
3178 fill_cmd(cmd, O_LAYER2, 0, 0);
3184 NEED1("recv, xmit, via require interface name"
3186 fill_iface((ipfw_insn_if *)cmd, av[0]);
3188 if (F_LEN(cmd) == 0) /* not a valid address */
3191 cmd->opcode = O_XMIT;
3192 else if (i == TOK_RECV)
3193 cmd->opcode = O_RECV;
3194 else if (i == TOK_VIA)
3195 cmd->opcode = O_VIA;
3199 NEED1("icmptypes requires list of types");
3200 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
3204 case TOK_ICMP6TYPES:
3205 NEED1("icmptypes requires list of types");
3206 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av);
3211 NEED1("ipttl requires TTL");
3212 if (strpbrk(*av, "-,")) {
3213 if (!add_ports(cmd, *av, 0, O_IPTTL))
3214 errx(EX_DATAERR, "invalid ipttl %s", *av);
3216 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
3221 NEED1("ipid requires id");
3222 if (strpbrk(*av, "-,")) {
3223 if (!add_ports(cmd, *av, 0, O_IPID))
3224 errx(EX_DATAERR, "invalid ipid %s", *av);
3226 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
3231 NEED1("iplen requires length");
3232 if (strpbrk(*av, "-,")) {
3233 if (!add_ports(cmd, *av, 0, O_IPLEN))
3234 errx(EX_DATAERR, "invalid ip len %s", *av);
3236 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
3241 NEED1("ipver requires version");
3242 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
3246 case TOK_IPPRECEDENCE:
3247 NEED1("ipprecedence requires value");
3248 fill_cmd(cmd, O_IPPRECEDENCE, 0,
3249 (strtoul(*av, NULL, 0) & 7) << 5);
3254 NEED1("missing argument for ipoptions");
3255 fill_flags(cmd, O_IPOPT, f_ipopts, *av);
3260 NEED1("missing argument for iptos");
3261 fill_flags(cmd, O_IPTOS, f_iptos, *av);
3266 NEED1("uid requires argument");
3272 cmd->opcode = O_UID;
3273 uid = strtoul(*av, &end, 0);
3274 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
3276 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
3277 cmd32->d[0] = pwd->pw_uid;
3278 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3284 NEED1("gid requires argument");
3290 cmd->opcode = O_GID;
3291 gid = strtoul(*av, &end, 0);
3292 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
3294 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
3295 cmd32->d[0] = grp->gr_gid;
3296 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3302 NEED1("jail requires argument");
3307 cmd->opcode = O_JAIL;
3308 jid = (int)strtol(*av, &end, 0);
3309 if (jid < 0 || *end != '\0')
3310 errx(EX_DATAERR, "jail requires prison ID");
3311 cmd32->d[0] = (uint32_t)jid;
3312 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3318 fill_cmd(cmd, O_ESTAB, 0, 0);
3322 fill_cmd(cmd, O_TCPFLAGS, 0,
3323 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
3326 case TOK_TCPDATALEN:
3327 NEED1("tcpdatalen requires length");
3328 if (strpbrk(*av, "-,")) {
3329 if (!add_ports(cmd, *av, 0, O_TCPDATALEN))
3330 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
3332 fill_cmd(cmd, O_TCPDATALEN, 0,
3333 strtoul(*av, NULL, 0));
3338 NEED1("missing argument for tcpoptions");
3339 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
3345 NEED1("tcpseq/tcpack requires argument");
3346 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3347 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
3348 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
3353 NEED1("tcpwin requires length");
3354 fill_cmd(cmd, O_TCPWIN, 0,
3355 htons(strtoul(*av, NULL, 0)));
3360 NEED1("missing argument for tcpflags");
3361 cmd->opcode = O_TCPFLAGS;
3362 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
3368 errx(EX_USAGE, "keep-state cannot be part "
3371 errx(EX_USAGE, "only one of keep-state "
3372 "and limit is allowed");
3374 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
3378 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
3383 "limit cannot be part of an or block");
3385 errx(EX_USAGE, "only one of keep-state and "
3386 "limit is allowed");
3389 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
3390 cmd->opcode = O_LIMIT;
3391 c->limit_mask = c->conn_limit = 0;
3393 while ( av[0] != NULL ) {
3394 if ((val = match_token(limit_masks, *av)) <= 0)
3396 c->limit_mask |= val;
3400 if (c->limit_mask == 0)
3401 errx(EX_USAGE, "limit: missing limit mask");
3403 GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
3404 TOK_LIMIT, rule_options);
3411 NEED1("missing protocol");
3412 if (add_proto(cmd, *av, &proto)) {
3415 errx(EX_DATAERR, "invalid protocol ``%s''",
3420 NEED1("missing source IP");
3421 if (add_srcip(cmd, *av)) {
3427 NEED1("missing destination IP");
3428 if (add_dstip(cmd, *av)) {
3434 NEED1("missing source IP6");
3435 if (add_srcip6(cmd, *av)) {
3441 NEED1("missing destination IP6");
3442 if (add_dstip6(cmd, *av)) {
3448 NEED1("missing source port");
3449 if (_substrcmp(*av, "any") == 0 ||
3450 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
3453 errx(EX_DATAERR, "invalid source port %s", *av);
3457 NEED1("missing destination port");
3458 if (_substrcmp(*av, "any") == 0 ||
3459 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
3462 errx(EX_DATAERR, "invalid destination port %s",
3467 if (add_mac(cmd, av))
3472 NEED1("missing mac type");
3473 if (!add_mactype(cmd, *av))
3474 errx(EX_DATAERR, "invalid mac type %s", *av);
3478 case TOK_VERREVPATH:
3479 fill_cmd(cmd, O_VERREVPATH, 0, 0);
3482 case TOK_VERSRCREACH:
3483 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
3487 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
3491 fill_cmd(cmd, O_IPSEC, 0, 0);
3495 fill_cmd(cmd, O_IP6, 0, 0);
3499 fill_cmd(cmd, O_IP4, 0, 0);
3503 fill_ext6hdr( cmd, *av );
3508 if (proto != IPPROTO_IPV6 )
3509 errx( EX_USAGE, "flow-id filter is active "
3510 "only for ipv6 protocol\n");
3511 fill_flow6( (ipfw_insn_u32 *) cmd, *av );
3516 fill_comment(cmd, av);
3521 if (av[0] && strpbrk(*av, "-,")) {
3522 if (!add_ports(cmd, *av, 0, O_TAGGED))
3523 errx(EX_DATAERR, "tagged: invalid tag"
3529 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
3530 TOK_TAGGED, rule_options);
3531 fill_cmd(cmd, O_TAGGED, 0, tag);
3537 NEED1("fib requires fib number");
3538 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
3543 ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
3547 if (!av[0] || !av[1])
3548 errx(EX_USAGE, "format: lookup argument tablenum");
3549 cmd->opcode = O_IP_DST_LOOKUP;
3550 cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
3551 i = match_token(rule_options, *av);
3552 for (j = 0; lookup_key[j] >= 0 ; j++) {
3553 if (i == lookup_key[j])
3556 if (lookup_key[j] <= 0)
3557 errx(EX_USAGE, "format: cannot lookup on %s", *av);
3558 c->d[1] = j; // i converted to option
3560 cmd->arg1 = strtoul(*av, &p, 0);
3562 errx(EX_USAGE, "format: lookup argument tablenum");
3568 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
3570 if (F_LEN(cmd) > 0) { /* prepare to advance */
3572 cmd = next_cmd(cmd);
3578 * Now copy stuff into the rule.
3579 * If we have a keep-state option, the first instruction
3580 * must be a PROBE_STATE (which is generated here).
3581 * If we have a LOG option, it was stored as the first command,
3582 * and now must be moved to the top of the action part.
3584 dst = (ipfw_insn *)rule->cmd;
3587 * First thing to write into the command stream is the match probability.
3589 if (match_prob != 1) { /* 1 means always match */
3590 dst->opcode = O_PROB;
3592 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
3597 * generate O_PROBE_STATE if necessary
3599 if (have_state && have_state->opcode != O_CHECK_STATE) {
3600 fill_cmd(dst, O_PROBE_STATE, 0, 0);
3601 dst = next_cmd(dst);
3604 /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
3605 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
3608 switch (src->opcode) {
3616 bcopy(src, dst, i * sizeof(uint32_t));
3622 * put back the have_state command as last opcode
3624 if (have_state && have_state->opcode != O_CHECK_STATE) {
3625 i = F_LEN(have_state);
3626 bcopy(have_state, dst, i * sizeof(uint32_t));
3630 * start action section
3632 rule->act_ofs = dst - rule->cmd;
3634 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
3636 i = F_LEN(have_log);
3637 bcopy(have_log, dst, i * sizeof(uint32_t));
3641 i = F_LEN(have_altq);
3642 bcopy(have_altq, dst, i * sizeof(uint32_t));
3646 i = F_LEN(have_tag);
3647 bcopy(have_tag, dst, i * sizeof(uint32_t));
3651 * copy all other actions
3653 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
3655 bcopy(src, dst, i * sizeof(uint32_t));
3659 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
3660 i = (char *)dst - (char *)rule;
3661 if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1)
3662 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
3664 show_ipfw(rule, 0, 0);
3668 * clear the counters or the log counters.
3671 ipfw_zero(int ac, char *av[], int optname /* 0 = IP_FW_ZERO, 1 = IP_FW_RESETLOG */)
3673 uint32_t arg, saved_arg;
3676 char const *name = optname ? "RESETLOG" : "ZERO";
3678 optname = optname ? IP_FW_RESETLOG : IP_FW_ZERO;
3683 /* clear all entries */
3684 if (do_cmd(optname, NULL, 0) < 0)
3685 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name);
3687 printf("%s.\n", optname == IP_FW_ZERO ?
3688 "Accounting cleared":"Logging counts reset");
3695 if (isdigit(**av)) {
3696 arg = strtonum(*av, 0, 0xffff, &errstr);
3699 "invalid rule number %s\n", *av);
3702 arg |= (1 << 24) | ((co.use_set - 1) << 16);
3705 if (do_cmd(optname, &arg, sizeof(arg))) {
3706 warn("rule %u: setsockopt(IP_FW_%s)",
3708 failed = EX_UNAVAILABLE;
3709 } else if (!co.do_quiet)
3710 printf("Entry %d %s.\n", saved_arg,
3711 optname == IP_FW_ZERO ?
3712 "cleared" : "logging count reset");
3714 errx(EX_USAGE, "invalid rule number ``%s''", *av);
3717 if (failed != EX_OK)
3722 ipfw_flush(int force)
3724 int cmd = co.do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
3726 if (!force && !co.do_quiet) { /* need to ask user */
3729 printf("Are you sure? [yn] ");
3732 c = toupper(getc(stdin));
3733 while (c != '\n' && getc(stdin) != '\n')
3735 return; /* and do not flush */
3736 } while (c != 'Y' && c != 'N');
3738 if (c == 'N') /* user said no */
3745 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
3747 uint32_t arg = ((co.use_set - 1) & 0xffff) | (1 << 24);
3748 if (do_cmd(IP_FW_DEL, &arg, sizeof(arg)) < 0)
3749 err(EX_UNAVAILABLE, "setsockopt(IP_FW_DEL)");
3750 } else if (do_cmd(cmd, NULL, 0) < 0)
3751 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
3752 co.do_pipe ? "DUMMYNET" : "FW");
3754 printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
3758 static void table_list(ipfw_table_entry ent, int need_header);
3761 * This one handles all table-related commands
3762 * ipfw table N add addr[/masklen] [value]
3763 * ipfw table N delete addr[/masklen]
3764 * ipfw table {N | all} flush
3765 * ipfw table {N | all} list
3768 ipfw_table_handler(int ac, char *av[])
3770 ipfw_table_entry ent;
3776 uint32_t tables_max;
3778 len = sizeof(tables_max);
3779 if (sysctlbyname("net.inet.ip.fw.tables_max", &tables_max, &len,
3781 #ifdef IPFW_TABLES_MAX
3782 warn("Warn: Failed to get the max tables number via sysctl. "
3783 "Using the compiled in defaults. \nThe reason was");
3784 tables_max = IPFW_TABLES_MAX;
3786 errx(1, "Failed sysctlbyname(\"net.inet.ip.fw.tables_max\")");
3791 if (ac && isdigit(**av)) {
3792 ent.tbl = atoi(*av);
3795 } else if (ac && _substrcmp(*av, "all") == 0) {
3800 errx(EX_USAGE, "table number or 'all' keyword required");
3801 if (ent.tbl >= tables_max)
3802 errx(EX_USAGE, "The table number exceeds the maximum allowed "
3803 "value (%d)", tables_max - 1);
3804 NEED1("table needs command");
3805 if (is_all && _substrcmp(*av, "list") != 0
3806 && _substrcmp(*av, "flush") != 0)
3807 errx(EX_USAGE, "table number required");
3809 if (_substrcmp(*av, "add") == 0 ||
3810 _substrcmp(*av, "delete") == 0) {
3811 do_add = **av == 'a';
3814 errx(EX_USAGE, "IP address required");
3815 p = strchr(*av, '/');
3818 ent.masklen = atoi(p);
3819 if (ent.masklen > 32)
3820 errx(EX_DATAERR, "bad width ``%s''", p);
3823 if (lookup_host(*av, (struct in_addr *)&ent.addr) != 0)
3824 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
3828 /* isdigit is a bit of a hack here.. */
3829 if (strchr(*av, (int)'.') == NULL && isdigit(**av)) {
3830 ent.value = strtoul(*av, NULL, 0);
3832 if (lookup_host(*av, (struct in_addr *)&tval) == 0) {
3833 /* The value must be stored in host order *
3834 * so that the values < 65k can be distinguished */
3835 ent.value = ntohl(tval);
3837 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
3842 if (do_cmd(do_add ? IP_FW_TABLE_ADD : IP_FW_TABLE_DEL,
3843 &ent, sizeof(ent)) < 0) {
3844 /* If running silent, don't bomb out on these errors. */
3845 if (!(co.do_quiet && (errno == (do_add ? EEXIST : ESRCH))))
3846 err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)",
3847 do_add ? "ADD" : "DEL");
3848 /* In silent mode, react to a failed add by deleting */
3850 do_cmd(IP_FW_TABLE_DEL, &ent, sizeof(ent));
3851 if (do_cmd(IP_FW_TABLE_ADD,
3852 &ent, sizeof(ent)) < 0)
3854 "setsockopt(IP_FW_TABLE_ADD)");
3857 } else if (_substrcmp(*av, "flush") == 0) {
3858 a = is_all ? tables_max : (uint32_t)(ent.tbl + 1);
3860 if (do_cmd(IP_FW_TABLE_FLUSH, &ent.tbl,
3861 sizeof(ent.tbl)) < 0)
3862 err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)");
3863 } while (++ent.tbl < a);
3864 } else if (_substrcmp(*av, "list") == 0) {
3865 a = is_all ? tables_max : (uint32_t)(ent.tbl + 1);
3867 table_list(ent, is_all);
3868 } while (++ent.tbl < a);
3870 errx(EX_USAGE, "invalid table command %s", *av);
3874 table_list(ipfw_table_entry ent, int need_header)
3882 if (do_cmd(IP_FW_TABLE_GETSIZE, &a, (uintptr_t)&l) < 0)
3883 err(EX_OSERR, "getsockopt(IP_FW_TABLE_GETSIZE)");
3885 /* If a is zero we have nothing to do, the table is empty. */
3889 l = sizeof(*tbl) + a * sizeof(ipfw_table_entry);
3890 tbl = safe_calloc(1, l);
3892 if (do_cmd(IP_FW_TABLE_LIST, tbl, (uintptr_t)&l) < 0)
3893 err(EX_OSERR, "getsockopt(IP_FW_TABLE_LIST)");
3894 if (tbl->cnt && need_header)
3895 printf("---table(%d)---\n", tbl->tbl);
3896 for (a = 0; a < tbl->cnt; a++) {
3898 tval = tbl->ent[a].value;
3899 if (co.do_value_as_ip) {
3901 strncpy(tbuf, inet_ntoa(*(struct in_addr *)
3902 &tbl->ent[a].addr), 127);
3903 /* inet_ntoa expects network order */
3905 printf("%s/%u %s\n", tbuf, tbl->ent[a].masklen,
3906 inet_ntoa(*(struct in_addr *)&tval));
3908 printf("%s/%u %u\n",
3909 inet_ntoa(*(struct in_addr *)&tbl->ent[a].addr),
3910 tbl->ent[a].masklen, tval);