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);
1116 char buf[4 + INET6_ADDRSTRLEN + 1];
1117 ipfw_insn_sa6 *s = (ipfw_insn_sa6 *)cmd;
1119 printf("fwd %s", inet_ntop(AF_INET6, &s->sa.sin6_addr,
1121 if (s->sa.sin6_port)
1122 printf(",%d", s->sa.sin6_port);
1126 case O_LOG: /* O_LOG is printed last */
1127 logptr = (ipfw_insn_log *)cmd;
1130 case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1131 altqptr = (ipfw_insn_altq *)cmd;
1140 PRINT_UINT_ARG("nat ", cmd->arg1);
1142 printf("nat global");
1146 PRINT_UINT_ARG("setfib ", cmd->arg1);
1154 if (cmd->len & F_NOT)
1157 PRINT_UINT_ARG("call ", cmd->arg1);
1161 printf("** unrecognized action %d len %d ",
1162 cmd->opcode, cmd->len);
1166 if (logptr->max_log > 0)
1167 printf(" log logamount %d", logptr->max_log);
1173 print_altq_cmd(altqptr);
1177 if (tagptr->len & F_NOT)
1178 PRINT_UINT_ARG(" untag ", tagptr->arg1);
1180 PRINT_UINT_ARG(" tag ", tagptr->arg1);
1184 * then print the body.
1186 for (l = rule->act_ofs, cmd = rule->cmd ;
1187 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1188 if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1190 if (cmd->opcode == O_IP4) {
1191 flags |= HAVE_PROTO4;
1193 } else if (cmd->opcode == O_IP6) {
1194 flags |= HAVE_PROTO6;
1198 if (rule->_pad & 1) { /* empty rules before options */
1199 if (!co.do_compact) {
1200 show_prerequisites(&flags, HAVE_PROTO, 0);
1201 printf(" from any to any");
1203 flags |= HAVE_IP | HAVE_OPTIONS | HAVE_PROTO |
1204 HAVE_SRCIP | HAVE_DSTIP;
1207 if (co.comment_only)
1210 for (l = rule->act_ofs, cmd = rule->cmd ;
1211 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1213 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1215 if (co.comment_only) {
1216 if (cmd->opcode != O_NOP)
1218 printf(" // %s\n", (char *)(cmd + 1));
1222 show_prerequisites(&flags, 0, cmd->opcode);
1224 switch(cmd->opcode) {
1226 break; /* done already */
1229 break; /* no need to print anything here */
1232 case O_IP_SRC_LOOKUP:
1236 show_prerequisites(&flags, HAVE_PROTO, 0);
1237 if (!(flags & HAVE_SRCIP))
1239 if ((cmd->len & F_OR) && !or_block)
1241 print_ip((ipfw_insn_ip *)cmd,
1242 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1243 flags |= HAVE_SRCIP;
1247 case O_IP_DST_LOOKUP:
1251 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1252 if (!(flags & HAVE_DSTIP))
1254 if ((cmd->len & F_OR) && !or_block)
1256 print_ip((ipfw_insn_ip *)cmd,
1257 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1258 flags |= HAVE_DSTIP;
1262 case O_IP6_SRC_MASK:
1264 show_prerequisites(&flags, HAVE_PROTO, 0);
1265 if (!(flags & HAVE_SRCIP))
1267 if ((cmd->len & F_OR) && !or_block)
1269 print_ip6((ipfw_insn_ip6 *)cmd,
1270 (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1271 flags |= HAVE_SRCIP | HAVE_PROTO;
1275 case O_IP6_DST_MASK:
1277 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1278 if (!(flags & HAVE_DSTIP))
1280 if ((cmd->len & F_OR) && !or_block)
1282 print_ip6((ipfw_insn_ip6 *)cmd,
1283 (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1284 flags |= HAVE_DSTIP;
1288 print_flow6id( (ipfw_insn_u32 *) cmd );
1289 flags |= HAVE_OPTIONS;
1293 show_prerequisites(&flags,
1294 HAVE_PROTO | HAVE_SRCIP |
1295 HAVE_DSTIP | HAVE_IP, 0);
1297 if (flags & HAVE_DSTIP)
1299 show_prerequisites(&flags,
1300 HAVE_PROTO | HAVE_SRCIP, 0);
1301 if ((cmd->len & F_OR) && !or_block)
1303 if (cmd->len & F_NOT)
1305 print_newports((ipfw_insn_u16 *)cmd, proto,
1306 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1310 struct protoent *pe = NULL;
1312 if ((cmd->len & F_OR) && !or_block)
1314 if (cmd->len & F_NOT)
1317 pe = getprotobynumber(cmd->arg1);
1318 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1319 !(flags & HAVE_PROTO))
1320 show_prerequisites(&flags,
1321 HAVE_PROTO | HAVE_IP | HAVE_SRCIP |
1322 HAVE_DSTIP | HAVE_OPTIONS, 0);
1323 if (flags & HAVE_OPTIONS)
1326 printf(" %s", pe->p_name);
1328 printf(" %u", cmd->arg1);
1330 flags |= HAVE_PROTO;
1333 default: /*options ... */
1334 if (!(cmd->len & (F_OR|F_NOT)))
1335 if (((cmd->opcode == O_IP6) &&
1336 (flags & HAVE_PROTO6)) ||
1337 ((cmd->opcode == O_IP4) &&
1338 (flags & HAVE_PROTO4)))
1340 show_prerequisites(&flags, HAVE_PROTO | HAVE_SRCIP |
1341 HAVE_DSTIP | HAVE_IP | HAVE_OPTIONS, 0);
1342 if ((cmd->len & F_OR) && !or_block)
1344 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1346 switch(cmd->opcode) {
1348 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1351 print_mac(m->addr, m->mask);
1352 print_mac(m->addr + 6, m->mask + 6);
1357 print_newports((ipfw_insn_u16 *)cmd,
1358 IPPROTO_ETHERTYPE, cmd->opcode);
1367 printf(" fib %u", cmd->arg1 );
1374 printf(cmd->len & F_NOT ? " out" : " in");
1378 switch (cmd->arg1) {
1380 printf(" diverted");
1383 printf(" diverted-loopback");
1386 printf(" diverted-output");
1389 printf(" diverted-?<%u>", cmd->arg1);
1402 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1404 if (cmd->opcode == O_XMIT)
1406 else if (cmd->opcode == O_RECV)
1408 else /* if (cmd->opcode == O_VIA) */
1410 if (cmdif->name[0] == '\0')
1412 inet_ntoa(cmdif->p.ip));
1414 printf(" %s %s", s, cmdif->name);
1419 if (F_LEN(cmd) == 1)
1420 printf(" ipid %u", cmd->arg1 );
1422 print_newports((ipfw_insn_u16 *)cmd, 0,
1427 if (F_LEN(cmd) == 1)
1428 printf(" ipttl %u", cmd->arg1 );
1430 print_newports((ipfw_insn_u16 *)cmd, 0,
1435 printf(" ipver %u", cmd->arg1 );
1438 case O_IPPRECEDENCE:
1439 printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1443 if (F_LEN(cmd) == 1)
1444 printf(" iplen %u", cmd->arg1 );
1446 print_newports((ipfw_insn_u16 *)cmd, 0,
1451 print_flags("ipoptions", cmd, f_ipopts);
1455 print_flags("iptos", cmd, f_iptos);
1459 print_icmptypes((ipfw_insn_u32 *)cmd);
1463 printf(" established");
1467 if (F_LEN(cmd) == 1)
1468 printf(" tcpdatalen %u", cmd->arg1 );
1470 print_newports((ipfw_insn_u16 *)cmd, 0,
1475 print_flags("tcpflags", cmd, f_tcpflags);
1479 print_flags("tcpoptions", cmd, f_tcpopts);
1483 printf(" tcpwin %d", ntohs(cmd->arg1));
1487 printf(" tcpack %d", ntohl(cmd32->d[0]));
1491 printf(" tcpseq %d", ntohl(cmd32->d[0]));
1496 struct passwd *pwd = getpwuid(cmd32->d[0]);
1499 printf(" uid %s", pwd->pw_name);
1501 printf(" uid %u", cmd32->d[0]);
1507 struct group *grp = getgrgid(cmd32->d[0]);
1510 printf(" gid %s", grp->gr_name);
1512 printf(" gid %u", cmd32->d[0]);
1517 printf(" jail %d", cmd32->d[0]);
1521 printf(" verrevpath");
1525 printf(" versrcreach");
1529 printf(" antispoof");
1537 comment = (char *)(cmd + 1);
1541 printf(" keep-state");
1545 struct _s_x *p = limit_masks;
1546 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1547 uint8_t x = c->limit_mask;
1548 char const *comma = " ";
1551 for (; p->x != 0 ; p++)
1552 if ((x & p->x) == p->x) {
1554 printf("%s%s", comma, p->s);
1557 PRINT_UINT_ARG(" ", c->conn_limit);
1570 print_icmp6types((ipfw_insn_u32 *)cmd);
1574 print_ext6hdr( (ipfw_insn *) cmd );
1578 if (F_LEN(cmd) == 1)
1579 PRINT_UINT_ARG(" tagged ", cmd->arg1);
1581 print_newports((ipfw_insn_u16 *)cmd, 0,
1586 printf(" [opcode %d len %d]",
1587 cmd->opcode, cmd->len);
1590 if (cmd->len & F_OR) {
1593 } else if (or_block) {
1598 show_prerequisites(&flags, HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP
1601 printf(" // %s", comment);
1606 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth)
1608 struct protoent *pe;
1611 char buf[INET6_ADDRSTRLEN];
1613 if (!co.do_expired) {
1614 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1617 bcopy(&d->rule, &rulenum, sizeof(rulenum));
1618 printf("%05d", rulenum);
1619 if (pcwidth > 0 || bcwidth > 0) {
1621 pr_u64(&d->pcnt, pcwidth);
1622 pr_u64(&d->bcnt, bcwidth);
1623 printf("(%ds)", d->expire);
1625 switch (d->dyn_type) {
1626 case O_LIMIT_PARENT:
1627 printf(" PARENT %d", d->count);
1632 case O_KEEP_STATE: /* bidir, no mask */
1637 if ((pe = getprotobynumber(d->id.proto)) != NULL)
1638 printf(" %s", pe->p_name);
1640 printf(" proto %u", d->id.proto);
1642 if (d->id.addr_type == 4) {
1643 a.s_addr = htonl(d->id.src_ip);
1644 printf(" %s %d", inet_ntoa(a), d->id.src_port);
1646 a.s_addr = htonl(d->id.dst_ip);
1647 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
1648 } else if (d->id.addr_type == 6) {
1649 printf(" %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
1650 sizeof(buf)), d->id.src_port);
1651 printf(" <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6, buf,
1652 sizeof(buf)), d->id.dst_port);
1654 printf(" UNKNOWN <-> UNKNOWN\n");
1660 * This one handles all set-related commands
1661 * ipfw set { show | enable | disable }
1663 * ipfw set move X to Y
1664 * ipfw set move rule X to Y
1667 ipfw_sets_handler(char *av[])
1669 uint32_t set_disable, masks[2];
1672 uint8_t cmd, new_set;
1677 errx(EX_USAGE, "set needs command");
1678 if (_substrcmp(*av, "show") == 0) {
1683 nalloc = nbytes = sizeof(struct ip_fw);
1684 while (nbytes >= nalloc) {
1687 nalloc = nalloc * 2 + 200;
1689 data = safe_calloc(1, nbytes);
1690 if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0)
1691 err(EX_OSERR, "getsockopt(IP_FW_GET)");
1694 bcopy(&((struct ip_fw *)data)->next_rule,
1695 &set_disable, sizeof(set_disable));
1697 for (i = 0, msg = "disable" ; i < RESVD_SET; i++)
1698 if ((set_disable & (1<<i))) {
1699 printf("%s %d", msg, i);
1702 msg = (set_disable) ? " enable" : "enable";
1703 for (i = 0; i < RESVD_SET; i++)
1704 if (!(set_disable & (1<<i))) {
1705 printf("%s %d", msg, i);
1709 } else if (_substrcmp(*av, "swap") == 0) {
1711 if ( av[0] == NULL || av[1] == NULL )
1712 errx(EX_USAGE, "set swap needs 2 set numbers\n");
1713 rulenum = atoi(av[0]);
1714 new_set = atoi(av[1]);
1715 if (!isdigit(*(av[0])) || rulenum > RESVD_SET)
1716 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
1717 if (!isdigit(*(av[1])) || new_set > RESVD_SET)
1718 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
1719 masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
1720 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
1721 } else if (_substrcmp(*av, "move") == 0) {
1723 if (av[0] && _substrcmp(*av, "rule") == 0) {
1728 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
1729 av[3] != NULL || _substrcmp(av[1], "to") != 0)
1730 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
1731 rulenum = atoi(av[0]);
1732 new_set = atoi(av[2]);
1733 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) ||
1734 (cmd == 2 && rulenum == IPFW_DEFAULT_RULE) )
1735 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
1736 if (!isdigit(*(av[2])) || new_set > RESVD_SET)
1737 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
1738 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
1739 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
1740 } else if (_substrcmp(*av, "disable") == 0 ||
1741 _substrcmp(*av, "enable") == 0 ) {
1742 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
1745 masks[0] = masks[1] = 0;
1748 if (isdigit(**av)) {
1750 if (i < 0 || i > RESVD_SET)
1752 "invalid set number %d\n", i);
1753 masks[which] |= (1<<i);
1754 } else if (_substrcmp(*av, "disable") == 0)
1756 else if (_substrcmp(*av, "enable") == 0)
1760 "invalid set command %s\n", *av);
1763 if ( (masks[0] & masks[1]) != 0 )
1765 "cannot enable and disable the same set\n");
1767 i = do_cmd(IP_FW_DEL, masks, sizeof(masks));
1769 warn("set enable/disable: setsockopt(IP_FW_DEL)");
1771 errx(EX_USAGE, "invalid set command %s\n", *av);
1775 ipfw_sysctl_handler(char *av[], int which)
1779 if (av[0] == NULL) {
1780 warnx("missing keyword to enable/disable\n");
1781 } else if (_substrcmp(*av, "firewall") == 0) {
1782 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
1783 &which, sizeof(which));
1784 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
1785 &which, sizeof(which));
1786 } else if (_substrcmp(*av, "one_pass") == 0) {
1787 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
1788 &which, sizeof(which));
1789 } else if (_substrcmp(*av, "debug") == 0) {
1790 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
1791 &which, sizeof(which));
1792 } else if (_substrcmp(*av, "verbose") == 0) {
1793 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
1794 &which, sizeof(which));
1795 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
1796 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
1797 &which, sizeof(which));
1799 } else if (_substrcmp(*av, "altq") == 0) {
1800 altq_set_enabled(which);
1803 warnx("unrecognize enable/disable keyword: %s\n", *av);
1808 ipfw_list(int ac, char *av[], int show_counters)
1811 ipfw_dyn_rule *dynrules, *d;
1813 #define NEXT(r) ((struct ip_fw *)((char *)r + RULESIZE(r)))
1816 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
1817 int exitval = EX_OK;
1825 const int ocmd = co.do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
1826 int nalloc = 1024; /* start somewhere... */
1831 fprintf(stderr, "Testing only, list disabled\n");
1835 dummynet_list(ac, av, show_counters);
1842 /* get rules or pipes from kernel, resizing array as necessary */
1845 while (nbytes >= nalloc) {
1846 nalloc = nalloc * 2 + 200;
1848 data = safe_realloc(data, nbytes);
1849 if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0)
1850 err(EX_OSERR, "getsockopt(IP_%s_GET)",
1851 co.do_pipe ? "DUMMYNET" : "FW");
1855 * Count static rules. They have variable size so we
1856 * need to scan the list to count them.
1858 for (nstat = 1, r = data, lim = (char *)data + nbytes;
1859 r->rulenum < IPFW_DEFAULT_RULE && (char *)r < lim;
1860 ++nstat, r = NEXT(r) )
1864 * Count dynamic rules. This is easier as they have
1868 dynrules = (ipfw_dyn_rule *)r ;
1869 n = (char *)r - (char *)data;
1870 ndyn = (nbytes - n) / sizeof *dynrules;
1872 /* if showing stats, figure out column widths ahead of time */
1873 bcwidth = pcwidth = 0;
1874 if (show_counters) {
1875 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
1876 /* skip rules from another set */
1877 if (co.use_set && r->set != co.use_set - 1)
1880 /* packet counter */
1881 width = pr_u64(&r->pcnt, 0);
1882 if (width > pcwidth)
1886 width = pr_u64(&r->bcnt, 0);
1887 if (width > bcwidth)
1891 if (co.do_dynamic && ndyn) {
1892 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1894 /* skip rules from another set */
1895 bcopy((char *)&d->rule + sizeof(uint16_t),
1896 &set, sizeof(uint8_t));
1897 if (set != co.use_set - 1)
1900 width = pr_u64(&d->pcnt, 0);
1901 if (width > pcwidth)
1904 width = pr_u64(&d->bcnt, 0);
1905 if (width > bcwidth)
1909 /* if no rule numbers were specified, list all rules */
1911 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
1912 if (co.use_set && r->set != co.use_set - 1)
1914 show_ipfw(r, pcwidth, bcwidth);
1917 if (co.do_dynamic && ndyn) {
1918 printf("## Dynamic rules (%d):\n", ndyn);
1919 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1921 bcopy((char *)&d->rule + sizeof(uint16_t),
1922 &set, sizeof(uint8_t));
1923 if (set != co.use_set - 1)
1926 show_dyn_ipfw(d, pcwidth, bcwidth);
1932 /* display specific rules requested on command line */
1934 for (lac = ac, lav = av; lac != 0; lac--) {
1935 /* convert command line rule # */
1936 last = rnum = strtoul(*lav++, &endptr, 10);
1938 last = strtoul(endptr+1, &endptr, 10);
1941 warnx("invalid rule number: %s", *(lav - 1));
1944 for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) {
1945 if (r->rulenum > last)
1947 if (co.use_set && r->set != co.use_set - 1)
1949 if (r->rulenum >= rnum && r->rulenum <= last) {
1950 show_ipfw(r, pcwidth, bcwidth);
1955 /* give precedence to other error(s) */
1956 if (exitval == EX_OK)
1957 exitval = EX_UNAVAILABLE;
1958 warnx("rule %lu does not exist", rnum);
1962 if (co.do_dynamic && ndyn) {
1963 printf("## Dynamic rules:\n");
1964 for (lac = ac, lav = av; lac != 0; lac--) {
1965 last = rnum = strtoul(*lav++, &endptr, 10);
1967 last = strtoul(endptr+1, &endptr, 10);
1969 /* already warned */
1971 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1974 bcopy(&d->rule, &rulenum, sizeof(rulenum));
1978 bcopy((char *)&d->rule + sizeof(uint16_t),
1979 &set, sizeof(uint8_t));
1980 if (set != co.use_set - 1)
1983 if (r->rulenum >= rnum && r->rulenum <= last)
1984 show_dyn_ipfw(d, pcwidth, bcwidth);
1994 if (exitval != EX_OK)
2000 lookup_host (char *host, struct in_addr *ipaddr)
2004 if (!inet_aton(host, ipaddr)) {
2005 if ((he = gethostbyname(host)) == NULL)
2007 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2013 * fills the addr and mask fields in the instruction as appropriate from av.
2014 * Update length as appropriate.
2015 * The following formats are allowed:
2016 * me returns O_IP_*_ME
2017 * 1.2.3.4 single IP address
2018 * 1.2.3.4:5.6.7.8 address:mask
2019 * 1.2.3.4/24 address/mask
2020 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
2021 * We can have multiple comma-separated address/mask entries.
2024 fill_ip(ipfw_insn_ip *cmd, char *av)
2027 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2029 cmd->o.len &= ~F_LEN_MASK; /* zero len */
2031 if (_substrcmp(av, "any") == 0)
2034 if (_substrcmp(av, "me") == 0) {
2035 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2039 if (strncmp(av, "table(", 6) == 0) {
2040 char *p = strchr(av + 6, ',');
2044 cmd->o.opcode = O_IP_DST_LOOKUP;
2045 cmd->o.arg1 = strtoul(av + 6, NULL, 0);
2047 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2048 d[0] = strtoul(p, NULL, 0);
2050 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2056 * After the address we can have '/' or ':' indicating a mask,
2057 * ',' indicating another address follows, '{' indicating a
2058 * set of addresses of unspecified size.
2060 char *t = NULL, *p = strpbrk(av, "/:,{");
2067 if ((t = strpbrk(p, ",{")) != NULL) {
2074 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2075 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2078 if (!inet_aton(p, (struct in_addr *)&d[1]))
2079 errx(EX_DATAERR, "bad netmask ``%s''", p);
2084 d[1] = htonl(0); /* mask */
2085 else if (masklen > 32)
2086 errx(EX_DATAERR, "bad width ``%s''", p);
2088 d[1] = htonl(~0 << (32 - masklen));
2090 case '{': /* no mask, assume /24 and put back the '{' */
2091 d[1] = htonl(~0 << (32 - 24));
2095 case ',': /* single address plus continuation */
2098 case 0: /* initialization value */
2100 d[1] = htonl(~0); /* force /32 */
2103 d[0] &= d[1]; /* mask base address with mask */
2106 /* find next separator */
2108 p = strpbrk(p, ",{");
2109 if (p && *p == '{') {
2111 * We have a set of addresses. They are stored as follows:
2112 * arg1 is the set size (powers of 2, 2..256)
2113 * addr is the base address IN HOST FORMAT
2114 * mask.. is an array of arg1 bits (rounded up to
2115 * the next multiple of 32) with bits set
2116 * for each host in the map.
2118 uint32_t *map = (uint32_t *)&cmd->mask;
2120 int i = contigmask((uint8_t *)&(d[1]), 32);
2123 errx(EX_DATAERR, "address set cannot be in a list");
2124 if (i < 24 || i > 31)
2125 errx(EX_DATAERR, "invalid set with mask %d\n", i);
2126 cmd->o.arg1 = 1<<(32-i); /* map length */
2127 d[0] = ntohl(d[0]); /* base addr in host format */
2128 cmd->o.opcode = O_IP_DST_SET; /* default */
2129 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2130 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2131 map[i] = 0; /* clear map */
2135 high = low + cmd->o.arg1 - 1;
2137 * Here, i stores the previous value when we specify a range
2138 * of addresses within a mask, e.g. 45-63. i = -1 means we
2139 * have no previous value.
2141 i = -1; /* previous value in a range */
2142 while (isdigit(*av)) {
2144 int a = strtol(av, &s, 0);
2146 if (s == av) { /* no parameter */
2148 errx(EX_DATAERR, "set not closed\n");
2150 errx(EX_DATAERR, "incomplete range %d-", i);
2153 if (a < low || a > high)
2154 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
2157 if (i == -1) /* no previous in range */
2159 else { /* check that range is valid */
2161 errx(EX_DATAERR, "invalid range %d-%d",
2164 errx(EX_DATAERR, "double '-' in range");
2167 map[i/32] |= 1<<(i & 31);
2178 if (av) /* then *av must be a ',' */
2181 /* Check this entry */
2182 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2184 * 'any' turns the entire list into a NOP.
2185 * 'not any' never matches, so it is removed from the
2186 * list unless it is the only item, in which case we
2189 if (cmd->o.len & F_NOT) { /* "not any" never matches */
2190 if (av == NULL && len == 0) /* only this entry */
2191 errx(EX_DATAERR, "not any never matches");
2193 /* else do nothing and skip this entry */
2196 /* A single IP can be stored in an optimized format */
2197 if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
2198 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2201 len += 2; /* two words... */
2204 if (len + 1 > F_LEN_MASK)
2205 errx(EX_DATAERR, "address list too long");
2206 cmd->o.len |= len+1;
2210 /* n2mask sets n bits of the mask */
2212 n2mask(struct in6_addr *mask, int n)
2214 static int minimask[9] =
2215 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
2218 memset(mask, 0, sizeof(struct in6_addr));
2219 p = (u_char *) mask;
2220 for (; n > 0; p++, n -= 8) {
2230 * helper function to process a set of flags and set bits in the
2231 * appropriate masks.
2234 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
2235 struct _s_x *flags, char *p)
2237 uint8_t set=0, clear=0;
2240 char *q; /* points to the separator */
2242 uint8_t *which; /* mask we are working on */
2252 val = match_token(flags, p);
2254 errx(EX_DATAERR, "invalid flag %s", p);
2255 *which |= (uint8_t)val;
2258 cmd->opcode = opcode;
2259 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
2260 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
2265 ipfw_delete(char *av[])
2269 int exitval = EX_OK;
2273 NEED1("missing rule specification");
2274 if ( *av && _substrcmp(*av, "set") == 0) {
2275 /* Do not allow using the following syntax:
2276 * ipfw set N delete set M
2279 errx(EX_DATAERR, "invalid syntax");
2280 do_set = 1; /* delete set */
2285 while (*av && isdigit(**av)) {
2286 i = atoi(*av); av++;
2288 exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
2290 exitval = EX_UNAVAILABLE;
2291 warn("rule %u not available", i);
2293 } else if (co.do_pipe) {
2294 exitval = ipfw_delete_pipe(co.do_pipe, i);
2297 rulenum = (i & 0xffff) | (5 << 24) |
2298 ((co.use_set - 1) << 16);
2300 rulenum = (i & 0xffff) | (do_set << 24);
2301 i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum);
2303 exitval = EX_UNAVAILABLE;
2304 warn("rule %u: setsockopt(IP_FW_DEL)",
2309 if (exitval != EX_OK)
2315 * fill the interface structure. We do not check the name as we can
2316 * create interfaces dynamically, so checking them at insert time
2317 * makes relatively little sense.
2318 * Interface names containing '*', '?', or '[' are assumed to be shell
2319 * patterns which match interfaces.
2322 fill_iface(ipfw_insn_if *cmd, char *arg)
2324 cmd->name[0] = '\0';
2325 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
2327 /* Parse the interface or address */
2328 if (strcmp(arg, "any") == 0)
2329 cmd->o.len = 0; /* effectively ignore this command */
2330 else if (!isdigit(*arg)) {
2331 strlcpy(cmd->name, arg, sizeof(cmd->name));
2332 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
2333 } else if (!inet_aton(arg, &cmd->p.ip))
2334 errx(EX_DATAERR, "bad ip address ``%s''", arg);
2338 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
2342 char *ap, *ptr, *optr;
2343 struct ether_addr *mac;
2344 const char *macset = "0123456789abcdefABCDEF:";
2346 if (strcmp(p, "any") == 0) {
2347 for (i = 0; i < ETHER_ADDR_LEN; i++)
2348 addr[i] = mask[i] = 0;
2352 optr = ptr = strdup(p);
2353 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
2355 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
2356 errx(EX_DATAERR, "Incorrect MAC address");
2357 bcopy(mac, addr, ETHER_ADDR_LEN);
2359 errx(EX_DATAERR, "Incorrect MAC address");
2361 if (ptr != NULL) { /* we have mask? */
2362 if (p[ptr - optr - 1] == '/') { /* mask len */
2363 long ml = strtol(ptr, &ap, 10);
2364 if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
2365 errx(EX_DATAERR, "Incorrect mask length");
2366 for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
2367 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
2370 if (strspn(ptr, macset) != l ||
2371 (mac = ether_aton(ptr)) == NULL)
2372 errx(EX_DATAERR, "Incorrect mask");
2373 bcopy(mac, mask, ETHER_ADDR_LEN);
2375 } else { /* default mask: ff:ff:ff:ff:ff:ff */
2376 for (i = 0; i < ETHER_ADDR_LEN; i++)
2379 for (i = 0; i < ETHER_ADDR_LEN; i++)
2386 * helper function, updates the pointer to cmd with the length
2387 * of the current command, and also cleans up the first word of
2388 * the new command in case it has been clobbered before.
2391 next_cmd(ipfw_insn *cmd)
2394 bzero(cmd, sizeof(*cmd));
2399 * Takes arguments and copies them into a comment
2402 fill_comment(ipfw_insn *cmd, char **av)
2405 char *p = (char *)(cmd + 1);
2407 cmd->opcode = O_NOP;
2408 cmd->len = (cmd->len & (F_NOT | F_OR));
2410 /* Compute length of comment string. */
2411 for (i = 0, l = 0; av[i] != NULL; i++)
2412 l += strlen(av[i]) + 1;
2417 "comment too long (max 80 chars)");
2419 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
2420 for (i = 0; av[i] != NULL; i++) {
2429 * A function to fill simple commands of size 1.
2430 * Existing flags are preserved.
2433 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
2435 cmd->opcode = opcode;
2436 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
2441 * Fetch and add the MAC address and type, with masks. This generates one or
2442 * two microinstructions, and returns the pointer to the last one.
2445 add_mac(ipfw_insn *cmd, char *av[])
2449 if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
2450 errx(EX_DATAERR, "MAC dst src");
2452 cmd->opcode = O_MACADDR2;
2453 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
2455 mac = (ipfw_insn_mac *)cmd;
2456 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
2457 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
2458 &(mac->mask[ETHER_ADDR_LEN])); /* src */
2463 add_mactype(ipfw_insn *cmd, char *av)
2466 errx(EX_DATAERR, "missing MAC type");
2467 if (strcmp(av, "any") != 0) { /* we have a non-null type */
2468 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE);
2469 cmd->opcode = O_MAC_TYPE;
2476 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
2478 struct protoent *pe;
2482 proto = strtol(av, &ep, 10);
2483 if (*ep != '\0' || proto <= 0) {
2484 if ((pe = getprotobyname(av)) == NULL)
2486 proto = pe->p_proto;
2489 fill_cmd(cmd, O_PROTO, 0, proto);
2495 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
2497 u_char proto = IPPROTO_IP;
2499 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2500 ; /* do not set O_IP4 nor O_IP6 */
2501 else if (strcmp(av, "ip4") == 0)
2502 /* explicit "just IPv4" rule */
2503 fill_cmd(cmd, O_IP4, 0, 0);
2504 else if (strcmp(av, "ip6") == 0) {
2505 /* explicit "just IPv6" rule */
2506 proto = IPPROTO_IPV6;
2507 fill_cmd(cmd, O_IP6, 0, 0);
2509 return add_proto0(cmd, av, protop);
2516 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
2518 u_char proto = IPPROTO_IP;
2520 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2521 ; /* do not set O_IP4 nor O_IP6 */
2522 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
2523 /* explicit "just IPv4" rule */
2524 fill_cmd(cmd, O_IP4, 0, 0);
2525 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
2526 /* explicit "just IPv6" rule */
2527 proto = IPPROTO_IPV6;
2528 fill_cmd(cmd, O_IP6, 0, 0);
2530 return add_proto0(cmd, av, protop);
2537 add_srcip(ipfw_insn *cmd, char *av)
2539 fill_ip((ipfw_insn_ip *)cmd, av);
2540 if (cmd->opcode == O_IP_DST_SET) /* set */
2541 cmd->opcode = O_IP_SRC_SET;
2542 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
2543 cmd->opcode = O_IP_SRC_LOOKUP;
2544 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2545 cmd->opcode = O_IP_SRC_ME;
2546 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2547 cmd->opcode = O_IP_SRC;
2548 else /* addr/mask */
2549 cmd->opcode = O_IP_SRC_MASK;
2554 add_dstip(ipfw_insn *cmd, char *av)
2556 fill_ip((ipfw_insn_ip *)cmd, av);
2557 if (cmd->opcode == O_IP_DST_SET) /* set */
2559 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
2561 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2562 cmd->opcode = O_IP_DST_ME;
2563 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2564 cmd->opcode = O_IP_DST;
2565 else /* addr/mask */
2566 cmd->opcode = O_IP_DST_MASK;
2571 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode)
2573 /* XXX "any" is trapped before. Perhaps "to" */
2574 if (_substrcmp(av, "any") == 0) {
2576 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) {
2577 /* XXX todo: check that we have a protocol with ports */
2578 cmd->opcode = opcode;
2585 add_src(ipfw_insn *cmd, char *av, u_char proto)
2589 ipfw_insn *ret = NULL;
2591 if ((host = strdup(av)) == NULL)
2593 if ((ch = strrchr(host, '/')) != NULL)
2596 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
2597 inet_pton(AF_INET6, host, &a) == 1)
2598 ret = add_srcip6(cmd, av);
2599 /* XXX: should check for IPv4, not !IPv6 */
2600 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2601 inet_pton(AF_INET6, host, &a) != 1))
2602 ret = add_srcip(cmd, av);
2603 if (ret == NULL && strcmp(av, "any") != 0)
2611 add_dst(ipfw_insn *cmd, char *av, u_char proto)
2615 ipfw_insn *ret = NULL;
2617 if ((host = strdup(av)) == NULL)
2619 if ((ch = strrchr(host, '/')) != NULL)
2622 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
2623 inet_pton(AF_INET6, host, &a) == 1)
2624 ret = add_dstip6(cmd, av);
2625 /* XXX: should check for IPv4, not !IPv6 */
2626 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2627 inet_pton(AF_INET6, host, &a) != 1))
2628 ret = add_dstip(cmd, av);
2629 if (ret == NULL && strcmp(av, "any") != 0)
2637 * Parse arguments and assemble the microinstructions which make up a rule.
2638 * Rules are added into the 'rulebuf' and then copied in the correct order
2639 * into the actual rule.
2641 * The syntax for a rule starts with the action, followed by
2642 * optional action parameters, and the various match patterns.
2643 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
2644 * (generated if the rule includes a keep-state option), then the
2645 * various match patterns, log/altq actions, and the actual action.
2649 ipfw_add(char *av[])
2652 * rules are added into the 'rulebuf' and then copied in
2653 * the correct order into the actual rule.
2654 * Some things that need to go out of order (prob, action etc.)
2657 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255];
2659 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
2660 ipfw_insn *first_cmd; /* first match pattern */
2665 * various flags used to record that we entered some fields.
2667 ipfw_insn *have_state = NULL; /* check-state or keep-state */
2668 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
2673 int open_par = 0; /* open parenthesis ( */
2675 /* proto is here because it is used to fetch ports */
2676 u_char proto = IPPROTO_IP; /* default protocol */
2678 double match_prob = 1; /* match probability, default is always match */
2680 bzero(actbuf, sizeof(actbuf)); /* actions go here */
2681 bzero(cmdbuf, sizeof(cmdbuf));
2682 bzero(rulebuf, sizeof(rulebuf));
2684 rule = (struct ip_fw *)rulebuf;
2685 cmd = (ipfw_insn *)cmdbuf;
2686 action = (ipfw_insn *)actbuf;
2690 /* [rule N] -- Rule number optional */
2691 if (av[0] && isdigit(**av)) {
2692 rule->rulenum = atoi(*av);
2696 /* [set N] -- set number (0..RESVD_SET), optional */
2697 if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
2698 int set = strtoul(av[1], NULL, 10);
2699 if (set < 0 || set > RESVD_SET)
2700 errx(EX_DATAERR, "illegal set %s", av[1]);
2705 /* [prob D] -- match probability, optional */
2706 if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
2707 match_prob = strtod(av[1], NULL);
2709 if (match_prob <= 0 || match_prob > 1)
2710 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
2714 /* action -- mandatory */
2715 NEED1("missing action");
2716 i = match_token(rule_actions, *av);
2718 action->len = 1; /* default */
2720 case TOK_CHECKSTATE:
2721 have_state = action;
2722 action->opcode = O_CHECK_STATE;
2726 action->opcode = O_ACCEPT;
2730 action->opcode = O_DENY;
2735 action->opcode = O_REJECT;
2736 action->arg1 = ICMP_UNREACH_HOST;
2740 action->opcode = O_REJECT;
2741 action->arg1 = ICMP_REJECT_RST;
2745 action->opcode = O_UNREACH6;
2746 action->arg1 = ICMP6_UNREACH_RST;
2750 action->opcode = O_REJECT;
2751 NEED1("missing reject code");
2752 fill_reject_code(&action->arg1, *av);
2757 action->opcode = O_UNREACH6;
2758 NEED1("missing unreach code");
2759 fill_unreach6_code(&action->arg1, *av);
2764 action->opcode = O_COUNT;
2768 action->opcode = O_NAT;
2769 action->len = F_INSN_SIZE(ipfw_insn_nat);
2770 if (_substrcmp(*av, "global") == 0) {
2778 action->opcode = O_QUEUE;
2781 action->opcode = O_PIPE;
2784 action->opcode = O_SKIPTO;
2787 action->opcode = O_NETGRAPH;
2790 action->opcode = O_NGTEE;
2793 action->opcode = O_DIVERT;
2796 action->opcode = O_TEE;
2799 action->opcode = O_CALLRETURN;
2802 errx(EX_USAGE, "missing argument for %s", *(av - 1));
2803 if (isdigit(**av)) {
2804 action->arg1 = strtoul(*av, NULL, 10);
2805 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
2806 errx(EX_DATAERR, "illegal argument for %s",
2808 } else if (_substrcmp(*av, "tablearg") == 0) {
2809 action->arg1 = IP_FW_TABLEARG;
2810 } else if (i == TOK_DIVERT || i == TOK_TEE) {
2813 s = getservbyname(av[0], "divert");
2815 action->arg1 = ntohs(s->s_port);
2817 errx(EX_DATAERR, "illegal divert/tee port");
2819 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
2825 * Locate the address-port separator (':' or ',').
2826 * Could be one of the following:
2830 * IPv6 w:x:y::z,port
2831 * The ':' can only be used with hostname and IPv4 address.
2832 * XXX-BZ Should we also support [w:x:y::z]:port?
2834 struct sockaddr_storage result;
2835 struct addrinfo *res;
2838 u_short port_number;
2840 NEED1("missing forward address[:port]");
2843 * locate the address-port separator (':' or ',')
2845 s = strchr(*av, ',');
2847 /* Distinguish between IPv4:port and IPv6 cases. */
2848 s = strchr(*av, ':');
2849 if (s && strchr(s+1, ':'))
2850 s = NULL; /* no port */
2855 /* Terminate host portion and set s to start of port. */
2857 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
2860 "illegal forwarding port ``%s''", s);
2861 port_number = (u_short)i;
2864 if (_substrcmp(*av, "tablearg") == 0) {
2866 ((struct sockaddr_in*)&result)->sin_addr.s_addr =
2870 * Resolve the host name or address to a family and a
2871 * network representation of the addres.
2873 if (getaddrinfo(*av, NULL, NULL, &res))
2874 errx(EX_DATAERR, NULL);
2875 /* Just use the first host in the answer. */
2876 family = res->ai_family;
2877 memcpy(&result, res->ai_addr, res->ai_addrlen);
2881 if (family == PF_INET) {
2882 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
2884 action->opcode = O_FORWARD_IP;
2885 action->len = F_INSN_SIZE(ipfw_insn_sa);
2888 * In the kernel we assume AF_INET and use only
2889 * sin_port and sin_addr. Remember to set sin_len as
2890 * the routing code seems to use it too.
2892 p->sa.sin_len = sizeof(struct sockaddr_in);
2893 p->sa.sin_family = AF_INET;
2894 p->sa.sin_port = port_number;
2895 p->sa.sin_addr.s_addr =
2896 ((struct sockaddr_in *)&result)->sin_addr.s_addr;
2897 } else if (family == PF_INET6) {
2898 ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
2900 action->opcode = O_FORWARD_IP6;
2901 action->len = F_INSN_SIZE(ipfw_insn_sa6);
2903 p->sa.sin6_len = sizeof(struct sockaddr_in6);
2904 p->sa.sin6_family = AF_INET6;
2905 p->sa.sin6_port = port_number;
2906 p->sa.sin6_flowinfo = 0;
2907 p->sa.sin6_scope_id = 0;
2908 /* No table support for v6 yet. */
2909 bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
2910 &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
2912 errx(EX_DATAERR, "Invalid address family in forward action");
2918 /* pretend it is a 'count' rule followed by the comment */
2919 action->opcode = O_COUNT;
2920 av--; /* go back... */
2926 size_t intsize = sizeof(int);
2928 action->opcode = O_SETFIB;
2929 NEED1("missing fib number");
2930 if (_substrcmp(*av, "tablearg") == 0) {
2931 action->arg1 = IP_FW_TABLEARG;
2933 action->arg1 = strtoul(*av, NULL, 10);
2934 if (sysctlbyname("net.fibs", &numfibs, &intsize,
2936 errx(EX_DATAERR, "fibs not suported.\n");
2937 if (action->arg1 >= numfibs) /* Temporary */
2938 errx(EX_DATAERR, "fib too large.\n");
2945 action->opcode = O_REASS;
2949 fill_cmd(action, O_CALLRETURN, F_NOT, 0);
2953 errx(EX_DATAERR, "invalid action %s\n", av[-1]);
2955 action = next_cmd(action);
2958 * [altq queuename] -- altq tag, optional
2959 * [log [logamount N]] -- log, optional
2961 * If they exist, it go first in the cmdbuf, but then it is
2962 * skipped in the copy section to the end of the buffer.
2964 while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
2969 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
2974 "log cannot be specified more than once");
2975 have_log = (ipfw_insn *)c;
2976 cmd->len = F_INSN_SIZE(ipfw_insn_log);
2977 cmd->opcode = O_LOG;
2978 if (av[0] && _substrcmp(*av, "logamount") == 0) {
2980 NEED1("logamount requires argument");
2984 "logamount must be positive");
2988 len = sizeof(c->max_log);
2989 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
2990 &c->max_log, &len, NULL, 0) == -1)
2991 errx(1, "sysctlbyname(\"%s\")",
2992 "net.inet.ip.fw.verbose_limit");
3000 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
3002 NEED1("missing altq queue name");
3005 "altq cannot be specified more than once");
3006 have_altq = (ipfw_insn *)a;
3007 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
3008 cmd->opcode = O_ALTQ;
3009 a->qid = altq_name_to_qid(*av);
3020 errx(EX_USAGE, "tag and untag cannot be "
3021 "specified more than once");
3022 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
3023 rule_action_params);
3025 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
3033 cmd = next_cmd(cmd);
3036 if (have_state) /* must be a check-state, we are done */
3039 #define OR_START(target) \
3040 if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
3042 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
3045 if ( (av[0])[1] == '\0') { \
3056 strcmp(*av, ")") == 0 || \
3057 strcmp(*av, "}") == 0)) { \
3062 errx(EX_USAGE, "missing \")\"\n"); \
3066 if (av[0] && _substrcmp(*av, "not") == 0) { \
3067 if (cmd->len & F_NOT) \
3068 errx(EX_USAGE, "double \"not\" not allowed\n"); \
3069 cmd->len |= F_NOT; \
3073 #define OR_BLOCK(target) \
3074 if (av[0] && _substrcmp(*av, "or") == 0) { \
3075 if (prev == NULL || open_par == 0) \
3076 errx(EX_DATAERR, "invalid OR block"); \
3077 prev->len |= F_OR; \
3087 * MAC addresses, optional.
3088 * If we have this, we skip the part "proto from src to dst"
3089 * and jump straight to the option parsing.
3092 NEED1("missing protocol");
3093 if (_substrcmp(*av, "MAC") == 0 ||
3094 _substrcmp(*av, "mac") == 0) {
3095 av++; /* the "MAC" keyword */
3096 add_mac(cmd, av); /* exits in case of errors */
3097 cmd = next_cmd(cmd);
3098 av += 2; /* dst-mac and src-mac */
3100 NEED1("missing mac type");
3101 if (add_mactype(cmd, av[0]))
3102 cmd = next_cmd(cmd);
3103 av++; /* any or mac-type */
3109 * protocol, mandatory
3111 OR_START(get_proto);
3113 NEED1("missing protocol");
3114 if (add_proto_compat(cmd, *av, &proto)) {
3116 if (F_LEN(cmd) != 0) {
3118 cmd = next_cmd(cmd);
3120 } else if (first_cmd != cmd) {
3121 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
3124 OR_BLOCK(get_proto);
3129 if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
3130 errx(EX_USAGE, "missing ``from''");
3134 * source IP, mandatory
3136 OR_START(source_ip);
3137 NOT_BLOCK; /* optional "not" */
3138 NEED1("missing source address");
3139 if (add_src(cmd, *av, proto)) {
3141 if (F_LEN(cmd) != 0) { /* ! any */
3143 cmd = next_cmd(cmd);
3146 errx(EX_USAGE, "bad source address %s", *av);
3147 OR_BLOCK(source_ip);
3150 * source ports, optional
3152 NOT_BLOCK; /* optional "not" */
3153 if ( av[0] != NULL ) {
3154 if (_substrcmp(*av, "any") == 0 ||
3155 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
3157 if (F_LEN(cmd) != 0)
3158 cmd = next_cmd(cmd);
3165 if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
3166 errx(EX_USAGE, "missing ``to''");
3170 * destination, mandatory
3173 NOT_BLOCK; /* optional "not" */
3174 NEED1("missing dst address");
3175 if (add_dst(cmd, *av, proto)) {
3177 if (F_LEN(cmd) != 0) { /* ! any */
3179 cmd = next_cmd(cmd);
3182 errx( EX_USAGE, "bad destination address %s", *av);
3186 * dest. ports, optional
3188 NOT_BLOCK; /* optional "not" */
3190 if (_substrcmp(*av, "any") == 0 ||
3191 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
3193 if (F_LEN(cmd) != 0)
3194 cmd = next_cmd(cmd);
3199 if (av[0] && first_cmd == cmd) {
3201 * nothing specified so far, store in the rule to ease
3207 while ( av[0] != NULL ) {
3209 ipfw_insn_u32 *cmd32; /* alias for cmd */
3212 cmd32 = (ipfw_insn_u32 *)cmd;
3214 if (*s == '!') { /* alternate syntax for NOT */
3215 if (cmd->len & F_NOT)
3216 errx(EX_USAGE, "double \"not\" not allowed\n");
3220 i = match_token(rule_options, s);
3224 if (cmd->len & F_NOT)
3225 errx(EX_USAGE, "double \"not\" not allowed\n");
3230 if (open_par == 0 || prev == NULL)
3231 errx(EX_USAGE, "invalid \"or\" block\n");
3235 case TOK_STARTBRACE:
3237 errx(EX_USAGE, "+nested \"(\" not allowed\n");
3243 errx(EX_USAGE, "+missing \")\"\n");
3249 fill_cmd(cmd, O_IN, 0, 0);
3253 cmd->len ^= F_NOT; /* toggle F_NOT */
3254 fill_cmd(cmd, O_IN, 0, 0);
3258 fill_cmd(cmd, O_DIVERTED, 0, 3);
3261 case TOK_DIVERTEDLOOPBACK:
3262 fill_cmd(cmd, O_DIVERTED, 0, 1);
3265 case TOK_DIVERTEDOUTPUT:
3266 fill_cmd(cmd, O_DIVERTED, 0, 2);
3270 fill_cmd(cmd, O_FRAG, 0, 0);
3274 fill_cmd(cmd, O_LAYER2, 0, 0);
3280 NEED1("recv, xmit, via require interface name"
3282 fill_iface((ipfw_insn_if *)cmd, av[0]);
3284 if (F_LEN(cmd) == 0) /* not a valid address */
3287 cmd->opcode = O_XMIT;
3288 else if (i == TOK_RECV)
3289 cmd->opcode = O_RECV;
3290 else if (i == TOK_VIA)
3291 cmd->opcode = O_VIA;
3295 NEED1("icmptypes requires list of types");
3296 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
3300 case TOK_ICMP6TYPES:
3301 NEED1("icmptypes requires list of types");
3302 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av);
3307 NEED1("ipttl requires TTL");
3308 if (strpbrk(*av, "-,")) {
3309 if (!add_ports(cmd, *av, 0, O_IPTTL))
3310 errx(EX_DATAERR, "invalid ipttl %s", *av);
3312 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
3317 NEED1("ipid requires id");
3318 if (strpbrk(*av, "-,")) {
3319 if (!add_ports(cmd, *av, 0, O_IPID))
3320 errx(EX_DATAERR, "invalid ipid %s", *av);
3322 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
3327 NEED1("iplen requires length");
3328 if (strpbrk(*av, "-,")) {
3329 if (!add_ports(cmd, *av, 0, O_IPLEN))
3330 errx(EX_DATAERR, "invalid ip len %s", *av);
3332 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
3337 NEED1("ipver requires version");
3338 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
3342 case TOK_IPPRECEDENCE:
3343 NEED1("ipprecedence requires value");
3344 fill_cmd(cmd, O_IPPRECEDENCE, 0,
3345 (strtoul(*av, NULL, 0) & 7) << 5);
3350 NEED1("missing argument for ipoptions");
3351 fill_flags(cmd, O_IPOPT, f_ipopts, *av);
3356 NEED1("missing argument for iptos");
3357 fill_flags(cmd, O_IPTOS, f_iptos, *av);
3362 NEED1("uid requires argument");
3368 cmd->opcode = O_UID;
3369 uid = strtoul(*av, &end, 0);
3370 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
3372 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
3373 cmd32->d[0] = pwd->pw_uid;
3374 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3380 NEED1("gid requires argument");
3386 cmd->opcode = O_GID;
3387 gid = strtoul(*av, &end, 0);
3388 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
3390 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
3391 cmd32->d[0] = grp->gr_gid;
3392 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3398 NEED1("jail requires argument");
3403 cmd->opcode = O_JAIL;
3404 jid = (int)strtol(*av, &end, 0);
3405 if (jid < 0 || *end != '\0')
3406 errx(EX_DATAERR, "jail requires prison ID");
3407 cmd32->d[0] = (uint32_t)jid;
3408 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3414 fill_cmd(cmd, O_ESTAB, 0, 0);
3418 fill_cmd(cmd, O_TCPFLAGS, 0,
3419 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
3422 case TOK_TCPDATALEN:
3423 NEED1("tcpdatalen requires length");
3424 if (strpbrk(*av, "-,")) {
3425 if (!add_ports(cmd, *av, 0, O_TCPDATALEN))
3426 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
3428 fill_cmd(cmd, O_TCPDATALEN, 0,
3429 strtoul(*av, NULL, 0));
3434 NEED1("missing argument for tcpoptions");
3435 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
3441 NEED1("tcpseq/tcpack requires argument");
3442 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3443 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
3444 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
3449 NEED1("tcpwin requires length");
3450 fill_cmd(cmd, O_TCPWIN, 0,
3451 htons(strtoul(*av, NULL, 0)));
3456 NEED1("missing argument for tcpflags");
3457 cmd->opcode = O_TCPFLAGS;
3458 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
3464 errx(EX_USAGE, "keep-state cannot be part "
3467 errx(EX_USAGE, "only one of keep-state "
3468 "and limit is allowed");
3470 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
3474 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
3479 "limit cannot be part of an or block");
3481 errx(EX_USAGE, "only one of keep-state and "
3482 "limit is allowed");
3485 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
3486 cmd->opcode = O_LIMIT;
3487 c->limit_mask = c->conn_limit = 0;
3489 while ( av[0] != NULL ) {
3490 if ((val = match_token(limit_masks, *av)) <= 0)
3492 c->limit_mask |= val;
3496 if (c->limit_mask == 0)
3497 errx(EX_USAGE, "limit: missing limit mask");
3499 GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
3500 TOK_LIMIT, rule_options);
3507 NEED1("missing protocol");
3508 if (add_proto(cmd, *av, &proto)) {
3511 errx(EX_DATAERR, "invalid protocol ``%s''",
3516 NEED1("missing source IP");
3517 if (add_srcip(cmd, *av)) {
3523 NEED1("missing destination IP");
3524 if (add_dstip(cmd, *av)) {
3530 NEED1("missing source IP6");
3531 if (add_srcip6(cmd, *av)) {
3537 NEED1("missing destination IP6");
3538 if (add_dstip6(cmd, *av)) {
3544 NEED1("missing source port");
3545 if (_substrcmp(*av, "any") == 0 ||
3546 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
3549 errx(EX_DATAERR, "invalid source port %s", *av);
3553 NEED1("missing destination port");
3554 if (_substrcmp(*av, "any") == 0 ||
3555 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
3558 errx(EX_DATAERR, "invalid destination port %s",
3563 if (add_mac(cmd, av))
3568 NEED1("missing mac type");
3569 if (!add_mactype(cmd, *av))
3570 errx(EX_DATAERR, "invalid mac type %s", *av);
3574 case TOK_VERREVPATH:
3575 fill_cmd(cmd, O_VERREVPATH, 0, 0);
3578 case TOK_VERSRCREACH:
3579 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
3583 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
3587 fill_cmd(cmd, O_IPSEC, 0, 0);
3591 fill_cmd(cmd, O_IP6, 0, 0);
3595 fill_cmd(cmd, O_IP4, 0, 0);
3599 fill_ext6hdr( cmd, *av );
3604 if (proto != IPPROTO_IPV6 )
3605 errx( EX_USAGE, "flow-id filter is active "
3606 "only for ipv6 protocol\n");
3607 fill_flow6( (ipfw_insn_u32 *) cmd, *av );
3612 fill_comment(cmd, av);
3617 if (av[0] && strpbrk(*av, "-,")) {
3618 if (!add_ports(cmd, *av, 0, O_TAGGED))
3619 errx(EX_DATAERR, "tagged: invalid tag"
3625 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
3626 TOK_TAGGED, rule_options);
3627 fill_cmd(cmd, O_TAGGED, 0, tag);
3633 NEED1("fib requires fib number");
3634 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
3638 fill_cmd(cmd, O_SOCKARG, 0, 0);
3642 ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
3646 if (!av[0] || !av[1])
3647 errx(EX_USAGE, "format: lookup argument tablenum");
3648 cmd->opcode = O_IP_DST_LOOKUP;
3649 cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
3650 i = match_token(rule_options, *av);
3651 for (j = 0; lookup_key[j] >= 0 ; j++) {
3652 if (i == lookup_key[j])
3655 if (lookup_key[j] <= 0)
3656 errx(EX_USAGE, "format: cannot lookup on %s", *av);
3657 __PAST_END(c->d, 1) = j; // i converted to option
3659 cmd->arg1 = strtoul(*av, &p, 0);
3661 errx(EX_USAGE, "format: lookup argument tablenum");
3667 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
3669 if (F_LEN(cmd) > 0) { /* prepare to advance */
3671 cmd = next_cmd(cmd);
3677 * Now copy stuff into the rule.
3678 * If we have a keep-state option, the first instruction
3679 * must be a PROBE_STATE (which is generated here).
3680 * If we have a LOG option, it was stored as the first command,
3681 * and now must be moved to the top of the action part.
3683 dst = (ipfw_insn *)rule->cmd;
3686 * First thing to write into the command stream is the match probability.
3688 if (match_prob != 1) { /* 1 means always match */
3689 dst->opcode = O_PROB;
3691 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
3696 * generate O_PROBE_STATE if necessary
3698 if (have_state && have_state->opcode != O_CHECK_STATE) {
3699 fill_cmd(dst, O_PROBE_STATE, 0, 0);
3700 dst = next_cmd(dst);
3703 /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
3704 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
3707 switch (src->opcode) {
3715 bcopy(src, dst, i * sizeof(uint32_t));
3721 * put back the have_state command as last opcode
3723 if (have_state && have_state->opcode != O_CHECK_STATE) {
3724 i = F_LEN(have_state);
3725 bcopy(have_state, dst, i * sizeof(uint32_t));
3729 * start action section
3731 rule->act_ofs = dst - rule->cmd;
3733 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
3735 i = F_LEN(have_log);
3736 bcopy(have_log, dst, i * sizeof(uint32_t));
3740 i = F_LEN(have_altq);
3741 bcopy(have_altq, dst, i * sizeof(uint32_t));
3745 i = F_LEN(have_tag);
3746 bcopy(have_tag, dst, i * sizeof(uint32_t));
3750 * copy all other actions
3752 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
3754 bcopy(src, dst, i * sizeof(uint32_t));
3758 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
3759 i = (char *)dst - (char *)rule;
3760 if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1)
3761 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
3763 show_ipfw(rule, 0, 0);
3767 * clear the counters or the log counters.
3770 ipfw_zero(int ac, char *av[], int optname /* 0 = IP_FW_ZERO, 1 = IP_FW_RESETLOG */)
3772 uint32_t arg, saved_arg;
3775 char const *name = optname ? "RESETLOG" : "ZERO";
3777 optname = optname ? IP_FW_RESETLOG : IP_FW_ZERO;
3782 /* clear all entries */
3783 if (do_cmd(optname, NULL, 0) < 0)
3784 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name);
3786 printf("%s.\n", optname == IP_FW_ZERO ?
3787 "Accounting cleared":"Logging counts reset");
3794 if (isdigit(**av)) {
3795 arg = strtonum(*av, 0, 0xffff, &errstr);
3798 "invalid rule number %s\n", *av);
3801 arg |= (1 << 24) | ((co.use_set - 1) << 16);
3804 if (do_cmd(optname, &arg, sizeof(arg))) {
3805 warn("rule %u: setsockopt(IP_FW_%s)",
3807 failed = EX_UNAVAILABLE;
3808 } else if (!co.do_quiet)
3809 printf("Entry %d %s.\n", saved_arg,
3810 optname == IP_FW_ZERO ?
3811 "cleared" : "logging count reset");
3813 errx(EX_USAGE, "invalid rule number ``%s''", *av);
3816 if (failed != EX_OK)
3821 ipfw_flush(int force)
3823 int cmd = co.do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
3825 if (!force && !co.do_quiet) { /* need to ask user */
3828 printf("Are you sure? [yn] ");
3831 c = toupper(getc(stdin));
3832 while (c != '\n' && getc(stdin) != '\n')
3834 return; /* and do not flush */
3835 } while (c != 'Y' && c != 'N');
3837 if (c == 'N') /* user said no */
3844 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
3846 uint32_t arg = ((co.use_set - 1) & 0xffff) | (1 << 24);
3847 if (do_cmd(IP_FW_DEL, &arg, sizeof(arg)) < 0)
3848 err(EX_UNAVAILABLE, "setsockopt(IP_FW_DEL)");
3849 } else if (do_cmd(cmd, NULL, 0) < 0)
3850 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
3851 co.do_pipe ? "DUMMYNET" : "FW");
3853 printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
3857 static void table_list(ipfw_table_entry ent, int need_header);
3860 * This one handles all table-related commands
3861 * ipfw table N add addr[/masklen] [value]
3862 * ipfw table N delete addr[/masklen]
3863 * ipfw table {N | all} flush
3864 * ipfw table {N | all} list
3867 ipfw_table_handler(int ac, char *av[])
3869 ipfw_table_entry ent;
3875 uint32_t tables_max;
3877 len = sizeof(tables_max);
3878 if (sysctlbyname("net.inet.ip.fw.tables_max", &tables_max, &len,
3880 #ifdef IPFW_TABLES_MAX
3881 warn("Warn: Failed to get the max tables number via sysctl. "
3882 "Using the compiled in defaults. \nThe reason was");
3883 tables_max = IPFW_TABLES_MAX;
3885 errx(1, "Failed sysctlbyname(\"net.inet.ip.fw.tables_max\")");
3890 if (ac && isdigit(**av)) {
3891 ent.tbl = atoi(*av);
3894 } else if (ac && _substrcmp(*av, "all") == 0) {
3899 errx(EX_USAGE, "table number or 'all' keyword required");
3900 if (ent.tbl >= tables_max)
3901 errx(EX_USAGE, "The table number exceeds the maximum allowed "
3902 "value (%d)", tables_max - 1);
3903 NEED1("table needs command");
3904 if (is_all && _substrcmp(*av, "list") != 0
3905 && _substrcmp(*av, "flush") != 0)
3906 errx(EX_USAGE, "table number required");
3908 if (_substrcmp(*av, "add") == 0 ||
3909 _substrcmp(*av, "delete") == 0) {
3910 do_add = **av == 'a';
3913 errx(EX_USAGE, "IP address required");
3914 p = strchr(*av, '/');
3917 ent.masklen = atoi(p);
3918 if (ent.masklen > 32)
3919 errx(EX_DATAERR, "bad width ``%s''", p);
3922 if (lookup_host(*av, (struct in_addr *)&ent.addr) != 0)
3923 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
3927 /* isdigit is a bit of a hack here.. */
3928 if (strchr(*av, (int)'.') == NULL && isdigit(**av)) {
3929 ent.value = strtoul(*av, NULL, 0);
3931 if (lookup_host(*av, (struct in_addr *)&tval) == 0) {
3932 /* The value must be stored in host order *
3933 * so that the values < 65k can be distinguished */
3934 ent.value = ntohl(tval);
3936 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
3941 if (do_cmd(do_add ? IP_FW_TABLE_ADD : IP_FW_TABLE_DEL,
3942 &ent, sizeof(ent)) < 0) {
3943 /* If running silent, don't bomb out on these errors. */
3944 if (!(co.do_quiet && (errno == (do_add ? EEXIST : ESRCH))))
3945 err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)",
3946 do_add ? "ADD" : "DEL");
3947 /* In silent mode, react to a failed add by deleting */
3949 do_cmd(IP_FW_TABLE_DEL, &ent, sizeof(ent));
3950 if (do_cmd(IP_FW_TABLE_ADD,
3951 &ent, sizeof(ent)) < 0)
3953 "setsockopt(IP_FW_TABLE_ADD)");
3956 } else if (_substrcmp(*av, "flush") == 0) {
3957 a = is_all ? tables_max : (uint32_t)(ent.tbl + 1);
3959 if (do_cmd(IP_FW_TABLE_FLUSH, &ent.tbl,
3960 sizeof(ent.tbl)) < 0)
3961 err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)");
3962 } while (++ent.tbl < a);
3963 } else if (_substrcmp(*av, "list") == 0) {
3964 a = is_all ? tables_max : (uint32_t)(ent.tbl + 1);
3966 table_list(ent, is_all);
3967 } while (++ent.tbl < a);
3969 errx(EX_USAGE, "invalid table command %s", *av);
3973 table_list(ipfw_table_entry ent, int need_header)
3981 if (do_cmd(IP_FW_TABLE_GETSIZE, &a, (uintptr_t)&l) < 0)
3982 err(EX_OSERR, "getsockopt(IP_FW_TABLE_GETSIZE)");
3984 /* If a is zero we have nothing to do, the table is empty. */
3988 l = sizeof(*tbl) + a * sizeof(ipfw_table_entry);
3989 tbl = safe_calloc(1, l);
3991 if (do_cmd(IP_FW_TABLE_LIST, tbl, (uintptr_t)&l) < 0)
3992 err(EX_OSERR, "getsockopt(IP_FW_TABLE_LIST)");
3993 if (tbl->cnt && need_header)
3994 printf("---table(%d)---\n", tbl->tbl);
3995 for (a = 0; a < tbl->cnt; a++) {
3997 tval = tbl->ent[a].value;
3998 if (co.do_value_as_ip) {
4000 strncpy(tbuf, inet_ntoa(*(struct in_addr *)
4001 &tbl->ent[a].addr), 127);
4002 /* inet_ntoa expects network order */
4004 printf("%s/%u %s\n", tbuf, tbl->ent[a].masklen,
4005 inet_ntoa(*(struct in_addr *)&tval));
4007 printf("%s/%u %u\n",
4008 inet_ntoa(*(struct in_addr *)&tbl->ent[a].addr),
4009 tbl->ent[a].masklen, tval);