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 {"tcpwin", O_TCPWIN},
516 {"tagged", O_TAGGED},
521 * Print the values in a list 16-bit items of the types above.
522 * XXX todo: add support for mask.
525 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode)
527 uint16_t *p = cmd->ports;
532 sep = match_value(_port_name, opcode);
538 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
540 print_port(proto, p[0]);
543 print_port(proto, p[1]);
550 * Like strtol, but also translates service names into port numbers
551 * for some protocols.
553 * proto == -1 disables the protocol check;
554 * proto == IPPROTO_ETHERTYPE looks up an internal table
555 * proto == <some value in /etc/protocols> matches the values there.
556 * Returns *end == s in case the parameter is not found.
559 strtoport(char *s, char **end, int base, int proto)
565 *end = s; /* default - not found */
567 return 0; /* not found */
570 return strtol(s, end, base);
573 * find separator. '\\' escapes the next char.
575 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
576 if (*s1 == '\\' && s1[1] != '\0')
579 buf = safe_calloc(s1 - s + 1, 1);
582 * copy into a buffer skipping backslashes
584 for (p = s, i = 0; p != s1 ; p++)
589 if (proto == IPPROTO_ETHERTYPE) {
590 i = match_token(ether_types, buf);
592 if (i != -1) { /* found */
597 struct protoent *pe = NULL;
601 pe = getprotobynumber(proto);
603 se = getservbyname(buf, pe ? pe->p_name : NULL);
607 return ntohs(se->s_port);
610 return 0; /* not found */
614 * Fill the body of the command with the list of port ranges.
617 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto)
619 uint16_t a, b, *p = cmd->ports;
624 a = strtoport(av, &s, 0, proto);
625 if (s == av) /* empty or invalid argument */
629 case '-': /* a range */
631 b = strtoport(av, &s, 0, proto);
632 /* Reject expressions like '1-abc' or '1-2-3'. */
633 if (s == av || (*s != ',' && *s != '\0'))
638 case ',': /* comma separated list */
643 warnx("port list: invalid separator <%c> in <%s>",
653 if (i + 1 > F_LEN_MASK)
654 errx(EX_DATAERR, "too many ports/ranges\n");
655 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
660 static struct _s_x icmpcodes[] = {
661 { "net", ICMP_UNREACH_NET },
662 { "host", ICMP_UNREACH_HOST },
663 { "protocol", ICMP_UNREACH_PROTOCOL },
664 { "port", ICMP_UNREACH_PORT },
665 { "needfrag", ICMP_UNREACH_NEEDFRAG },
666 { "srcfail", ICMP_UNREACH_SRCFAIL },
667 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
668 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
669 { "isolated", ICMP_UNREACH_ISOLATED },
670 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
671 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
672 { "tosnet", ICMP_UNREACH_TOSNET },
673 { "toshost", ICMP_UNREACH_TOSHOST },
674 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
675 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
676 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
681 fill_reject_code(u_short *codep, char *str)
686 val = strtoul(str, &s, 0);
687 if (s == str || *s != '\0' || val >= 0x100)
688 val = match_token(icmpcodes, str);
690 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
696 print_reject_code(uint16_t code)
698 char const *s = match_value(icmpcodes, code);
701 printf("unreach %s", s);
703 printf("unreach %u", code);
707 * Returns the number of bits set (from left) in a contiguous bitmask,
708 * or -1 if the mask is not contiguous.
709 * XXX this needs a proper fix.
710 * This effectively works on masks in big-endian (network) format.
711 * when compiled on little endian architectures.
713 * First bit is bit 7 of the first byte -- note, for MAC addresses,
714 * the first bit on the wire is bit 0 of the first byte.
715 * len is the max length in bits.
718 contigmask(uint8_t *p, int len)
722 for (i=0; i<len ; i++)
723 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
725 for (n=i+1; n < len; n++)
726 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
727 return -1; /* mask not contiguous */
732 * print flags set/clear in the two bitmasks passed as parameters.
733 * There is a specialized check for f_tcpflags.
736 print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list)
738 char const *comma = "";
740 uint8_t set = cmd->arg1 & 0xff;
741 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
743 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
748 printf(" %s ", name);
749 for (i=0; list[i].x != 0; i++) {
750 if (set & list[i].x) {
752 printf("%s%s", comma, list[i].s);
755 if (clear & list[i].x) {
757 printf("%s!%s", comma, list[i].s);
764 * Print the ip address contained in a command.
767 print_ip(ipfw_insn_ip *cmd, char const *s)
769 struct hostent *he = NULL;
770 uint32_t len = F_LEN((ipfw_insn *)cmd);
771 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
773 if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
775 const char *arg = "<invalid>";
777 if (d < sizeof(lookup_key)/sizeof(lookup_key[0]))
778 arg = match_value(rule_options, lookup_key[d]);
779 printf("%s lookup %s %d", cmd->o.len & F_NOT ? " not": "",
783 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
785 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
789 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
790 cmd->o.opcode == O_IP_DST_LOOKUP) {
791 printf("table(%u", ((ipfw_insn *)cmd)->arg1);
792 if (len == F_INSN_SIZE(ipfw_insn_u32))
797 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
798 uint32_t x, *map = (uint32_t *)&(cmd->mask);
804 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
805 printf("%s/%d", inet_ntoa(cmd->addr),
806 contigmask((uint8_t *)&x, 32));
807 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
808 x &= 0xff; /* base */
810 * Print bits and ranges.
811 * Locate first bit set (i), then locate first bit unset (j).
812 * If we have 3+ consecutive bits set, then print them as a
813 * range, otherwise only print the initial bit and rescan.
815 for (i=0; i < cmd->o.arg1; i++)
816 if (map[i/32] & (1<<(i & 31))) {
817 for (j=i+1; j < cmd->o.arg1; j++)
818 if (!(map[ j/32] & (1<<(j & 31))))
820 printf("%c%d", comma, i+x);
821 if (j>i+2) { /* range has at least 3 elements */
822 printf("-%d", j-1+x);
831 * len == 2 indicates a single IP, whereas lists of 1 or more
832 * addr/mask pairs have len = (2n+1). We convert len to n so we
833 * use that to count the number of entries.
835 for (len = len / 2; len > 0; len--, a += 2) {
836 int mb = /* mask length */
837 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
838 32 : contigmask((uint8_t *)&(a[1]), 32);
839 if (mb == 32 && co.do_resolv)
840 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
841 if (he != NULL) /* resolved to name */
842 printf("%s", he->h_name);
843 else if (mb == 0) /* any */
845 else { /* numeric IP followed by some kind of mask */
846 printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) );
848 printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) );
858 * prints a MAC address/mask pair
861 print_mac(uint8_t *addr, uint8_t *mask)
863 int l = contigmask(mask, 48);
868 printf(" %02x:%02x:%02x:%02x:%02x:%02x",
869 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
871 printf("&%02x:%02x:%02x:%02x:%02x:%02x",
872 mask[0], mask[1], mask[2],
873 mask[3], mask[4], mask[5]);
880 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
889 type = strtoul(av, &av, 0);
891 if (*av != ',' && *av != '\0')
892 errx(EX_DATAERR, "invalid ICMP type");
895 errx(EX_DATAERR, "ICMP type out of range");
897 cmd->d[0] |= 1 << type;
899 cmd->o.opcode = O_ICMPTYPE;
900 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
904 print_icmptypes(ipfw_insn_u32 *cmd)
909 printf(" icmptypes");
910 for (i = 0; i < 32; i++) {
911 if ( (cmd->d[0] & (1 << (i))) == 0)
913 printf("%c%d", sep, i);
919 * show_ipfw() prints the body of an ipfw rule.
920 * Because the standard rule has at least proto src_ip dst_ip, we use
921 * a helper function to produce these entries if not provided explicitly.
922 * The first argument is the list of fields we have, the second is
923 * the list of fields we want to be printed.
925 * Special cases if we have provided a MAC header:
926 * + if the rule does not contain IP addresses/ports, do not print them;
927 * + if the rule does not contain an IP proto, print "all" instead of "ip";
929 * Once we have 'have_options', IP header fields are printed as options.
931 #define HAVE_PROTO 0x0001
932 #define HAVE_SRCIP 0x0002
933 #define HAVE_DSTIP 0x0004
934 #define HAVE_PROTO4 0x0008
935 #define HAVE_PROTO6 0x0010
936 #define HAVE_IP 0x0100
937 #define HAVE_OPTIONS 0x8000
940 show_prerequisites(int *flags, int want, int cmd __unused)
944 if ( (*flags & HAVE_IP) == HAVE_IP)
945 *flags |= HAVE_OPTIONS;
947 if ( !(*flags & HAVE_OPTIONS)) {
948 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) {
949 if ( (*flags & HAVE_PROTO4))
951 else if ( (*flags & HAVE_PROTO6))
956 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
958 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
965 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth)
967 static int twidth = 0;
969 ipfw_insn *cmd, *tagptr = NULL;
970 const char *comment = NULL; /* ptr to comment if we have one */
971 int proto = 0; /* default */
972 int flags = 0; /* prerequisites */
973 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
974 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
975 int or_block = 0; /* we are in an or block */
976 uint32_t set_disable;
978 bcopy(&rule->next_rule, &set_disable, sizeof(set_disable));
980 if (set_disable & (1 << rule->set)) { /* disabled */
984 printf("# DISABLED ");
986 printf("%05u ", rule->rulenum);
988 if (pcwidth > 0 || bcwidth > 0) {
989 pr_u64(&rule->pcnt, pcwidth);
990 pr_u64(&rule->bcnt, bcwidth);
994 printf("%10u ", rule->timestamp);
995 else if (co.do_time == 1) {
997 time_t t = (time_t)0;
1000 strcpy(timestr, ctime(&t));
1001 *strchr(timestr, '\n') = '\0';
1002 twidth = strlen(timestr);
1004 if (rule->timestamp) {
1005 t = _long_to_time(rule->timestamp);
1007 strcpy(timestr, ctime(&t));
1008 *strchr(timestr, '\n') = '\0';
1009 printf("%s ", timestr);
1011 printf("%*s", twidth, " ");
1016 printf("set %d ", rule->set);
1019 * print the optional "match probability"
1021 if (rule->cmd_len > 0) {
1023 if (cmd->opcode == O_PROB) {
1024 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1025 double d = 1.0 * p->d[0];
1027 d = (d / 0x7fffffff);
1028 printf("prob %f ", d);
1033 * first print actions
1035 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1036 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1037 switch(cmd->opcode) {
1039 printf("check-state");
1040 /* avoid printing anything else */
1041 flags = HAVE_PROTO | HAVE_SRCIP |
1042 HAVE_DSTIP | HAVE_IP;
1058 if (cmd->arg1 == ICMP_REJECT_RST)
1060 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1063 print_reject_code(cmd->arg1);
1067 if (cmd->arg1 == ICMP6_UNREACH_RST)
1070 print_unreach6_code(cmd->arg1);
1074 PRINT_UINT_ARG("skipto ", cmd->arg1);
1078 PRINT_UINT_ARG("pipe ", cmd->arg1);
1082 PRINT_UINT_ARG("queue ", cmd->arg1);
1086 PRINT_UINT_ARG("divert ", cmd->arg1);
1090 PRINT_UINT_ARG("tee ", cmd->arg1);
1094 PRINT_UINT_ARG("netgraph ", cmd->arg1);
1098 PRINT_UINT_ARG("ngtee ", cmd->arg1);
1103 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1105 if (s->sa.sin_addr.s_addr == INADDR_ANY) {
1106 printf("fwd tablearg");
1108 printf("fwd %s", inet_ntoa(s->sa.sin_addr));
1111 printf(",%d", s->sa.sin_port);
1117 char buf[4 + INET6_ADDRSTRLEN + 1];
1118 ipfw_insn_sa6 *s = (ipfw_insn_sa6 *)cmd;
1120 printf("fwd %s", inet_ntop(AF_INET6, &s->sa.sin6_addr,
1122 if (s->sa.sin6_port)
1123 printf(",%d", s->sa.sin6_port);
1127 case O_LOG: /* O_LOG is printed last */
1128 logptr = (ipfw_insn_log *)cmd;
1131 case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1132 altqptr = (ipfw_insn_altq *)cmd;
1141 PRINT_UINT_ARG("nat ", cmd->arg1);
1143 printf("nat global");
1147 PRINT_UINT_ARG("setfib ", cmd->arg1);
1155 if (cmd->len & F_NOT)
1158 PRINT_UINT_ARG("call ", cmd->arg1);
1162 printf("** unrecognized action %d len %d ",
1163 cmd->opcode, cmd->len);
1167 if (logptr->max_log > 0)
1168 printf(" log logamount %d", logptr->max_log);
1174 print_altq_cmd(altqptr);
1178 if (tagptr->len & F_NOT)
1179 PRINT_UINT_ARG(" untag ", tagptr->arg1);
1181 PRINT_UINT_ARG(" tag ", tagptr->arg1);
1185 * then print the body.
1187 for (l = rule->act_ofs, cmd = rule->cmd ;
1188 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1189 if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1191 if (cmd->opcode == O_IP4) {
1192 flags |= HAVE_PROTO4;
1194 } else if (cmd->opcode == O_IP6) {
1195 flags |= HAVE_PROTO6;
1199 if (rule->_pad & 1) { /* empty rules before options */
1200 if (!co.do_compact) {
1201 show_prerequisites(&flags, HAVE_PROTO, 0);
1202 printf(" from any to any");
1204 flags |= HAVE_IP | HAVE_OPTIONS | HAVE_PROTO |
1205 HAVE_SRCIP | HAVE_DSTIP;
1208 if (co.comment_only)
1211 for (l = rule->act_ofs, cmd = rule->cmd ;
1212 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1214 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1216 if (co.comment_only) {
1217 if (cmd->opcode != O_NOP)
1219 printf(" // %s\n", (char *)(cmd + 1));
1223 show_prerequisites(&flags, 0, cmd->opcode);
1225 switch(cmd->opcode) {
1227 break; /* done already */
1230 break; /* no need to print anything here */
1233 case O_IP_SRC_LOOKUP:
1237 show_prerequisites(&flags, HAVE_PROTO, 0);
1238 if (!(flags & HAVE_SRCIP))
1240 if ((cmd->len & F_OR) && !or_block)
1242 print_ip((ipfw_insn_ip *)cmd,
1243 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1244 flags |= HAVE_SRCIP;
1248 case O_IP_DST_LOOKUP:
1252 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1253 if (!(flags & HAVE_DSTIP))
1255 if ((cmd->len & F_OR) && !or_block)
1257 print_ip((ipfw_insn_ip *)cmd,
1258 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1259 flags |= HAVE_DSTIP;
1263 case O_IP6_SRC_MASK:
1265 show_prerequisites(&flags, HAVE_PROTO, 0);
1266 if (!(flags & HAVE_SRCIP))
1268 if ((cmd->len & F_OR) && !or_block)
1270 print_ip6((ipfw_insn_ip6 *)cmd,
1271 (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1272 flags |= HAVE_SRCIP | HAVE_PROTO;
1276 case O_IP6_DST_MASK:
1278 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1279 if (!(flags & HAVE_DSTIP))
1281 if ((cmd->len & F_OR) && !or_block)
1283 print_ip6((ipfw_insn_ip6 *)cmd,
1284 (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1285 flags |= HAVE_DSTIP;
1289 print_flow6id( (ipfw_insn_u32 *) cmd );
1290 flags |= HAVE_OPTIONS;
1294 show_prerequisites(&flags,
1295 HAVE_PROTO | HAVE_SRCIP |
1296 HAVE_DSTIP | HAVE_IP, 0);
1298 if (flags & HAVE_DSTIP)
1300 show_prerequisites(&flags,
1301 HAVE_PROTO | HAVE_SRCIP, 0);
1302 if ((cmd->len & F_OR) && !or_block)
1304 if (cmd->len & F_NOT)
1306 print_newports((ipfw_insn_u16 *)cmd, proto,
1307 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1311 struct protoent *pe = NULL;
1313 if ((cmd->len & F_OR) && !or_block)
1315 if (cmd->len & F_NOT)
1318 pe = getprotobynumber(cmd->arg1);
1319 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1320 !(flags & HAVE_PROTO))
1321 show_prerequisites(&flags,
1322 HAVE_PROTO | HAVE_IP | HAVE_SRCIP |
1323 HAVE_DSTIP | HAVE_OPTIONS, 0);
1324 if (flags & HAVE_OPTIONS)
1327 printf(" %s", pe->p_name);
1329 printf(" %u", cmd->arg1);
1331 flags |= HAVE_PROTO;
1334 default: /*options ... */
1335 if (!(cmd->len & (F_OR|F_NOT)))
1336 if (((cmd->opcode == O_IP6) &&
1337 (flags & HAVE_PROTO6)) ||
1338 ((cmd->opcode == O_IP4) &&
1339 (flags & HAVE_PROTO4)))
1341 show_prerequisites(&flags, HAVE_PROTO | HAVE_SRCIP |
1342 HAVE_DSTIP | HAVE_IP | HAVE_OPTIONS, 0);
1343 if ((cmd->len & F_OR) && !or_block)
1345 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1347 switch(cmd->opcode) {
1349 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1352 print_mac(m->addr, m->mask);
1353 print_mac(m->addr + 6, m->mask + 6);
1358 print_newports((ipfw_insn_u16 *)cmd,
1359 IPPROTO_ETHERTYPE, cmd->opcode);
1368 printf(" fib %u", cmd->arg1 );
1375 printf(cmd->len & F_NOT ? " out" : " in");
1379 switch (cmd->arg1) {
1381 printf(" diverted");
1384 printf(" diverted-loopback");
1387 printf(" diverted-output");
1390 printf(" diverted-?<%u>", cmd->arg1);
1403 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1405 if (cmd->opcode == O_XMIT)
1407 else if (cmd->opcode == O_RECV)
1409 else /* if (cmd->opcode == O_VIA) */
1411 if (cmdif->name[0] == '\0')
1413 inet_ntoa(cmdif->p.ip));
1415 printf(" %s %s", s, cmdif->name);
1420 if (F_LEN(cmd) == 1)
1421 printf(" ipid %u", cmd->arg1 );
1423 print_newports((ipfw_insn_u16 *)cmd, 0,
1428 if (F_LEN(cmd) == 1)
1429 printf(" ipttl %u", cmd->arg1 );
1431 print_newports((ipfw_insn_u16 *)cmd, 0,
1436 printf(" ipver %u", cmd->arg1 );
1439 case O_IPPRECEDENCE:
1440 printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1444 if (F_LEN(cmd) == 1)
1445 printf(" iplen %u", cmd->arg1 );
1447 print_newports((ipfw_insn_u16 *)cmd, 0,
1452 print_flags("ipoptions", cmd, f_ipopts);
1456 print_flags("iptos", cmd, f_iptos);
1460 print_icmptypes((ipfw_insn_u32 *)cmd);
1464 printf(" established");
1468 if (F_LEN(cmd) == 1)
1469 printf(" tcpdatalen %u", cmd->arg1 );
1471 print_newports((ipfw_insn_u16 *)cmd, 0,
1476 print_flags("tcpflags", cmd, f_tcpflags);
1480 print_flags("tcpoptions", cmd, f_tcpopts);
1484 if (F_LEN(cmd) == 1)
1485 printf(" tcpwin %u", cmd->arg1);
1487 print_newports((ipfw_insn_u16 *)cmd, 0,
1492 printf(" tcpack %d", ntohl(cmd32->d[0]));
1496 printf(" tcpseq %d", ntohl(cmd32->d[0]));
1501 struct passwd *pwd = getpwuid(cmd32->d[0]);
1504 printf(" uid %s", pwd->pw_name);
1506 printf(" uid %u", cmd32->d[0]);
1512 struct group *grp = getgrgid(cmd32->d[0]);
1515 printf(" gid %s", grp->gr_name);
1517 printf(" gid %u", cmd32->d[0]);
1522 printf(" jail %d", cmd32->d[0]);
1526 printf(" verrevpath");
1530 printf(" versrcreach");
1534 printf(" antispoof");
1542 comment = (char *)(cmd + 1);
1546 printf(" keep-state");
1550 struct _s_x *p = limit_masks;
1551 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1552 uint8_t x = c->limit_mask;
1553 char const *comma = " ";
1556 for (; p->x != 0 ; p++)
1557 if ((x & p->x) == p->x) {
1559 printf("%s%s", comma, p->s);
1562 PRINT_UINT_ARG(" ", c->conn_limit);
1575 print_icmp6types((ipfw_insn_u32 *)cmd);
1579 print_ext6hdr( (ipfw_insn *) cmd );
1583 if (F_LEN(cmd) == 1)
1584 PRINT_UINT_ARG(" tagged ", cmd->arg1);
1586 print_newports((ipfw_insn_u16 *)cmd, 0,
1591 printf(" [opcode %d len %d]",
1592 cmd->opcode, cmd->len);
1595 if (cmd->len & F_OR) {
1598 } else if (or_block) {
1603 show_prerequisites(&flags, HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP
1606 printf(" // %s", comment);
1611 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth)
1613 struct protoent *pe;
1616 char buf[INET6_ADDRSTRLEN];
1618 if (!co.do_expired) {
1619 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1622 bcopy(&d->rule, &rulenum, sizeof(rulenum));
1623 printf("%05d", rulenum);
1624 if (pcwidth > 0 || bcwidth > 0) {
1626 pr_u64(&d->pcnt, pcwidth);
1627 pr_u64(&d->bcnt, bcwidth);
1628 printf("(%ds)", d->expire);
1630 switch (d->dyn_type) {
1631 case O_LIMIT_PARENT:
1632 printf(" PARENT %d", d->count);
1637 case O_KEEP_STATE: /* bidir, no mask */
1642 if ((pe = getprotobynumber(d->id.proto)) != NULL)
1643 printf(" %s", pe->p_name);
1645 printf(" proto %u", d->id.proto);
1647 if (d->id.addr_type == 4) {
1648 a.s_addr = htonl(d->id.src_ip);
1649 printf(" %s %d", inet_ntoa(a), d->id.src_port);
1651 a.s_addr = htonl(d->id.dst_ip);
1652 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
1653 } else if (d->id.addr_type == 6) {
1654 printf(" %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
1655 sizeof(buf)), d->id.src_port);
1656 printf(" <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6, buf,
1657 sizeof(buf)), d->id.dst_port);
1659 printf(" UNKNOWN <-> UNKNOWN\n");
1665 * This one handles all set-related commands
1666 * ipfw set { show | enable | disable }
1668 * ipfw set move X to Y
1669 * ipfw set move rule X to Y
1672 ipfw_sets_handler(char *av[])
1674 uint32_t set_disable, masks[2];
1677 uint8_t cmd, new_set;
1682 errx(EX_USAGE, "set needs command");
1683 if (_substrcmp(*av, "show") == 0) {
1688 nalloc = nbytes = sizeof(struct ip_fw);
1689 while (nbytes >= nalloc) {
1692 nalloc = nalloc * 2 + 200;
1694 data = safe_calloc(1, nbytes);
1695 if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0)
1696 err(EX_OSERR, "getsockopt(IP_FW_GET)");
1699 bcopy(&((struct ip_fw *)data)->next_rule,
1700 &set_disable, sizeof(set_disable));
1702 for (i = 0, msg = "disable" ; i < RESVD_SET; i++)
1703 if ((set_disable & (1<<i))) {
1704 printf("%s %d", msg, i);
1707 msg = (set_disable) ? " enable" : "enable";
1708 for (i = 0; i < RESVD_SET; i++)
1709 if (!(set_disable & (1<<i))) {
1710 printf("%s %d", msg, i);
1714 } else if (_substrcmp(*av, "swap") == 0) {
1716 if ( av[0] == NULL || av[1] == NULL )
1717 errx(EX_USAGE, "set swap needs 2 set numbers\n");
1718 rulenum = atoi(av[0]);
1719 new_set = atoi(av[1]);
1720 if (!isdigit(*(av[0])) || rulenum > RESVD_SET)
1721 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
1722 if (!isdigit(*(av[1])) || new_set > RESVD_SET)
1723 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
1724 masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
1725 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
1726 } else if (_substrcmp(*av, "move") == 0) {
1728 if (av[0] && _substrcmp(*av, "rule") == 0) {
1733 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
1734 av[3] != NULL || _substrcmp(av[1], "to") != 0)
1735 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
1736 rulenum = atoi(av[0]);
1737 new_set = atoi(av[2]);
1738 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) ||
1739 (cmd == 2 && rulenum == IPFW_DEFAULT_RULE) )
1740 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
1741 if (!isdigit(*(av[2])) || new_set > RESVD_SET)
1742 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
1743 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
1744 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
1745 } else if (_substrcmp(*av, "disable") == 0 ||
1746 _substrcmp(*av, "enable") == 0 ) {
1747 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
1750 masks[0] = masks[1] = 0;
1753 if (isdigit(**av)) {
1755 if (i < 0 || i > RESVD_SET)
1757 "invalid set number %d\n", i);
1758 masks[which] |= (1<<i);
1759 } else if (_substrcmp(*av, "disable") == 0)
1761 else if (_substrcmp(*av, "enable") == 0)
1765 "invalid set command %s\n", *av);
1768 if ( (masks[0] & masks[1]) != 0 )
1770 "cannot enable and disable the same set\n");
1772 i = do_cmd(IP_FW_DEL, masks, sizeof(masks));
1774 warn("set enable/disable: setsockopt(IP_FW_DEL)");
1776 errx(EX_USAGE, "invalid set command %s\n", *av);
1780 ipfw_sysctl_handler(char *av[], int which)
1784 if (av[0] == NULL) {
1785 warnx("missing keyword to enable/disable\n");
1786 } else if (_substrcmp(*av, "firewall") == 0) {
1787 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
1788 &which, sizeof(which));
1789 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
1790 &which, sizeof(which));
1791 } else if (_substrcmp(*av, "one_pass") == 0) {
1792 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
1793 &which, sizeof(which));
1794 } else if (_substrcmp(*av, "debug") == 0) {
1795 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
1796 &which, sizeof(which));
1797 } else if (_substrcmp(*av, "verbose") == 0) {
1798 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
1799 &which, sizeof(which));
1800 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
1801 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
1802 &which, sizeof(which));
1804 } else if (_substrcmp(*av, "altq") == 0) {
1805 altq_set_enabled(which);
1808 warnx("unrecognize enable/disable keyword: %s\n", *av);
1813 ipfw_list(int ac, char *av[], int show_counters)
1816 ipfw_dyn_rule *dynrules, *d;
1818 #define NEXT(r) ((struct ip_fw *)((char *)r + RULESIZE(r)))
1821 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
1822 int exitval = EX_OK;
1830 const int ocmd = co.do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
1831 int nalloc = 1024; /* start somewhere... */
1836 fprintf(stderr, "Testing only, list disabled\n");
1840 dummynet_list(ac, av, show_counters);
1847 /* get rules or pipes from kernel, resizing array as necessary */
1850 while (nbytes >= nalloc) {
1851 nalloc = nalloc * 2 + 200;
1853 data = safe_realloc(data, nbytes);
1854 if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0)
1855 err(EX_OSERR, "getsockopt(IP_%s_GET)",
1856 co.do_pipe ? "DUMMYNET" : "FW");
1860 * Count static rules. They have variable size so we
1861 * need to scan the list to count them.
1863 for (nstat = 1, r = data, lim = (char *)data + nbytes;
1864 r->rulenum < IPFW_DEFAULT_RULE && (char *)r < lim;
1865 ++nstat, r = NEXT(r) )
1869 * Count dynamic rules. This is easier as they have
1873 dynrules = (ipfw_dyn_rule *)r ;
1874 n = (char *)r - (char *)data;
1875 ndyn = (nbytes - n) / sizeof *dynrules;
1877 /* if showing stats, figure out column widths ahead of time */
1878 bcwidth = pcwidth = 0;
1879 if (show_counters) {
1880 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
1881 /* skip rules from another set */
1882 if (co.use_set && r->set != co.use_set - 1)
1885 /* packet counter */
1886 width = pr_u64(&r->pcnt, 0);
1887 if (width > pcwidth)
1891 width = pr_u64(&r->bcnt, 0);
1892 if (width > bcwidth)
1896 if (co.do_dynamic && ndyn) {
1897 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1899 /* skip rules from another set */
1900 bcopy((char *)&d->rule + sizeof(uint16_t),
1901 &set, sizeof(uint8_t));
1902 if (set != co.use_set - 1)
1905 width = pr_u64(&d->pcnt, 0);
1906 if (width > pcwidth)
1909 width = pr_u64(&d->bcnt, 0);
1910 if (width > bcwidth)
1914 /* if no rule numbers were specified, list all rules */
1916 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
1917 if (co.use_set && r->set != co.use_set - 1)
1919 show_ipfw(r, pcwidth, bcwidth);
1922 if (co.do_dynamic && ndyn) {
1923 printf("## Dynamic rules (%d):\n", ndyn);
1924 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1926 bcopy((char *)&d->rule + sizeof(uint16_t),
1927 &set, sizeof(uint8_t));
1928 if (set != co.use_set - 1)
1931 show_dyn_ipfw(d, pcwidth, bcwidth);
1937 /* display specific rules requested on command line */
1939 for (lac = ac, lav = av; lac != 0; lac--) {
1940 /* convert command line rule # */
1941 last = rnum = strtoul(*lav++, &endptr, 10);
1943 last = strtoul(endptr+1, &endptr, 10);
1946 warnx("invalid rule number: %s", *(lav - 1));
1949 for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) {
1950 if (r->rulenum > last)
1952 if (co.use_set && r->set != co.use_set - 1)
1954 if (r->rulenum >= rnum && r->rulenum <= last) {
1955 show_ipfw(r, pcwidth, bcwidth);
1960 /* give precedence to other error(s) */
1961 if (exitval == EX_OK)
1962 exitval = EX_UNAVAILABLE;
1963 warnx("rule %lu does not exist", rnum);
1967 if (co.do_dynamic && ndyn) {
1968 printf("## Dynamic rules:\n");
1969 for (lac = ac, lav = av; lac != 0; lac--) {
1970 last = rnum = strtoul(*lav++, &endptr, 10);
1972 last = strtoul(endptr+1, &endptr, 10);
1974 /* already warned */
1976 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1979 bcopy(&d->rule, &rulenum, sizeof(rulenum));
1983 bcopy((char *)&d->rule + sizeof(uint16_t),
1984 &set, sizeof(uint8_t));
1985 if (set != co.use_set - 1)
1988 if (r->rulenum >= rnum && r->rulenum <= last)
1989 show_dyn_ipfw(d, pcwidth, bcwidth);
1999 if (exitval != EX_OK)
2005 lookup_host (char *host, struct in_addr *ipaddr)
2009 if (!inet_aton(host, ipaddr)) {
2010 if ((he = gethostbyname(host)) == NULL)
2012 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2018 * fills the addr and mask fields in the instruction as appropriate from av.
2019 * Update length as appropriate.
2020 * The following formats are allowed:
2021 * me returns O_IP_*_ME
2022 * 1.2.3.4 single IP address
2023 * 1.2.3.4:5.6.7.8 address:mask
2024 * 1.2.3.4/24 address/mask
2025 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
2026 * We can have multiple comma-separated address/mask entries.
2029 fill_ip(ipfw_insn_ip *cmd, char *av)
2032 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2034 cmd->o.len &= ~F_LEN_MASK; /* zero len */
2036 if (_substrcmp(av, "any") == 0)
2039 if (_substrcmp(av, "me") == 0) {
2040 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2044 if (strncmp(av, "table(", 6) == 0) {
2045 char *p = strchr(av + 6, ',');
2049 cmd->o.opcode = O_IP_DST_LOOKUP;
2050 cmd->o.arg1 = strtoul(av + 6, NULL, 0);
2052 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2053 d[0] = strtoul(p, NULL, 0);
2055 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2061 * After the address we can have '/' or ':' indicating a mask,
2062 * ',' indicating another address follows, '{' indicating a
2063 * set of addresses of unspecified size.
2065 char *t = NULL, *p = strpbrk(av, "/:,{");
2072 if ((t = strpbrk(p, ",{")) != NULL) {
2079 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2080 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2083 if (!inet_aton(p, (struct in_addr *)&d[1]))
2084 errx(EX_DATAERR, "bad netmask ``%s''", p);
2089 d[1] = htonl(0); /* mask */
2090 else if (masklen > 32)
2091 errx(EX_DATAERR, "bad width ``%s''", p);
2093 d[1] = htonl(~0 << (32 - masklen));
2095 case '{': /* no mask, assume /24 and put back the '{' */
2096 d[1] = htonl(~0 << (32 - 24));
2100 case ',': /* single address plus continuation */
2103 case 0: /* initialization value */
2105 d[1] = htonl(~0); /* force /32 */
2108 d[0] &= d[1]; /* mask base address with mask */
2111 /* find next separator */
2113 p = strpbrk(p, ",{");
2114 if (p && *p == '{') {
2116 * We have a set of addresses. They are stored as follows:
2117 * arg1 is the set size (powers of 2, 2..256)
2118 * addr is the base address IN HOST FORMAT
2119 * mask.. is an array of arg1 bits (rounded up to
2120 * the next multiple of 32) with bits set
2121 * for each host in the map.
2123 uint32_t *map = (uint32_t *)&cmd->mask;
2125 int i = contigmask((uint8_t *)&(d[1]), 32);
2128 errx(EX_DATAERR, "address set cannot be in a list");
2129 if (i < 24 || i > 31)
2130 errx(EX_DATAERR, "invalid set with mask %d\n", i);
2131 cmd->o.arg1 = 1<<(32-i); /* map length */
2132 d[0] = ntohl(d[0]); /* base addr in host format */
2133 cmd->o.opcode = O_IP_DST_SET; /* default */
2134 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2135 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2136 map[i] = 0; /* clear map */
2140 high = low + cmd->o.arg1 - 1;
2142 * Here, i stores the previous value when we specify a range
2143 * of addresses within a mask, e.g. 45-63. i = -1 means we
2144 * have no previous value.
2146 i = -1; /* previous value in a range */
2147 while (isdigit(*av)) {
2149 int a = strtol(av, &s, 0);
2151 if (s == av) { /* no parameter */
2153 errx(EX_DATAERR, "set not closed\n");
2155 errx(EX_DATAERR, "incomplete range %d-", i);
2158 if (a < low || a > high)
2159 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
2162 if (i == -1) /* no previous in range */
2164 else { /* check that range is valid */
2166 errx(EX_DATAERR, "invalid range %d-%d",
2169 errx(EX_DATAERR, "double '-' in range");
2172 map[i/32] |= 1<<(i & 31);
2183 if (av) /* then *av must be a ',' */
2186 /* Check this entry */
2187 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2189 * 'any' turns the entire list into a NOP.
2190 * 'not any' never matches, so it is removed from the
2191 * list unless it is the only item, in which case we
2194 if (cmd->o.len & F_NOT) { /* "not any" never matches */
2195 if (av == NULL && len == 0) /* only this entry */
2196 errx(EX_DATAERR, "not any never matches");
2198 /* else do nothing and skip this entry */
2201 /* A single IP can be stored in an optimized format */
2202 if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
2203 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2206 len += 2; /* two words... */
2209 if (len + 1 > F_LEN_MASK)
2210 errx(EX_DATAERR, "address list too long");
2211 cmd->o.len |= len+1;
2215 /* n2mask sets n bits of the mask */
2217 n2mask(struct in6_addr *mask, int n)
2219 static int minimask[9] =
2220 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
2223 memset(mask, 0, sizeof(struct in6_addr));
2224 p = (u_char *) mask;
2225 for (; n > 0; p++, n -= 8) {
2235 * helper function to process a set of flags and set bits in the
2236 * appropriate masks.
2239 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
2240 struct _s_x *flags, char *p)
2242 uint8_t set=0, clear=0;
2245 char *q; /* points to the separator */
2247 uint8_t *which; /* mask we are working on */
2257 val = match_token(flags, p);
2259 errx(EX_DATAERR, "invalid flag %s", p);
2260 *which |= (uint8_t)val;
2263 cmd->opcode = opcode;
2264 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
2265 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
2270 ipfw_delete(char *av[])
2274 int exitval = EX_OK;
2278 NEED1("missing rule specification");
2279 if ( *av && _substrcmp(*av, "set") == 0) {
2280 /* Do not allow using the following syntax:
2281 * ipfw set N delete set M
2284 errx(EX_DATAERR, "invalid syntax");
2285 do_set = 1; /* delete set */
2290 while (*av && isdigit(**av)) {
2291 i = atoi(*av); av++;
2293 exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
2295 exitval = EX_UNAVAILABLE;
2296 warn("rule %u not available", i);
2298 } else if (co.do_pipe) {
2299 exitval = ipfw_delete_pipe(co.do_pipe, i);
2302 rulenum = (i & 0xffff) | (5 << 24) |
2303 ((co.use_set - 1) << 16);
2305 rulenum = (i & 0xffff) | (do_set << 24);
2306 i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum);
2308 exitval = EX_UNAVAILABLE;
2309 warn("rule %u: setsockopt(IP_FW_DEL)",
2314 if (exitval != EX_OK)
2320 * fill the interface structure. We do not check the name as we can
2321 * create interfaces dynamically, so checking them at insert time
2322 * makes relatively little sense.
2323 * Interface names containing '*', '?', or '[' are assumed to be shell
2324 * patterns which match interfaces.
2327 fill_iface(ipfw_insn_if *cmd, char *arg)
2329 cmd->name[0] = '\0';
2330 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
2332 /* Parse the interface or address */
2333 if (strcmp(arg, "any") == 0)
2334 cmd->o.len = 0; /* effectively ignore this command */
2335 else if (!isdigit(*arg)) {
2336 strlcpy(cmd->name, arg, sizeof(cmd->name));
2337 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
2338 } else if (!inet_aton(arg, &cmd->p.ip))
2339 errx(EX_DATAERR, "bad ip address ``%s''", arg);
2343 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
2347 char *ap, *ptr, *optr;
2348 struct ether_addr *mac;
2349 const char *macset = "0123456789abcdefABCDEF:";
2351 if (strcmp(p, "any") == 0) {
2352 for (i = 0; i < ETHER_ADDR_LEN; i++)
2353 addr[i] = mask[i] = 0;
2357 optr = ptr = strdup(p);
2358 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
2360 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
2361 errx(EX_DATAERR, "Incorrect MAC address");
2362 bcopy(mac, addr, ETHER_ADDR_LEN);
2364 errx(EX_DATAERR, "Incorrect MAC address");
2366 if (ptr != NULL) { /* we have mask? */
2367 if (p[ptr - optr - 1] == '/') { /* mask len */
2368 long ml = strtol(ptr, &ap, 10);
2369 if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
2370 errx(EX_DATAERR, "Incorrect mask length");
2371 for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
2372 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
2375 if (strspn(ptr, macset) != l ||
2376 (mac = ether_aton(ptr)) == NULL)
2377 errx(EX_DATAERR, "Incorrect mask");
2378 bcopy(mac, mask, ETHER_ADDR_LEN);
2380 } else { /* default mask: ff:ff:ff:ff:ff:ff */
2381 for (i = 0; i < ETHER_ADDR_LEN; i++)
2384 for (i = 0; i < ETHER_ADDR_LEN; i++)
2391 * helper function, updates the pointer to cmd with the length
2392 * of the current command, and also cleans up the first word of
2393 * the new command in case it has been clobbered before.
2396 next_cmd(ipfw_insn *cmd)
2399 bzero(cmd, sizeof(*cmd));
2404 * Takes arguments and copies them into a comment
2407 fill_comment(ipfw_insn *cmd, char **av)
2410 char *p = (char *)(cmd + 1);
2412 cmd->opcode = O_NOP;
2413 cmd->len = (cmd->len & (F_NOT | F_OR));
2415 /* Compute length of comment string. */
2416 for (i = 0, l = 0; av[i] != NULL; i++)
2417 l += strlen(av[i]) + 1;
2422 "comment too long (max 80 chars)");
2424 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
2425 for (i = 0; av[i] != NULL; i++) {
2434 * A function to fill simple commands of size 1.
2435 * Existing flags are preserved.
2438 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
2440 cmd->opcode = opcode;
2441 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
2446 * Fetch and add the MAC address and type, with masks. This generates one or
2447 * two microinstructions, and returns the pointer to the last one.
2450 add_mac(ipfw_insn *cmd, char *av[])
2454 if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
2455 errx(EX_DATAERR, "MAC dst src");
2457 cmd->opcode = O_MACADDR2;
2458 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
2460 mac = (ipfw_insn_mac *)cmd;
2461 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
2462 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
2463 &(mac->mask[ETHER_ADDR_LEN])); /* src */
2468 add_mactype(ipfw_insn *cmd, char *av)
2471 errx(EX_DATAERR, "missing MAC type");
2472 if (strcmp(av, "any") != 0) { /* we have a non-null type */
2473 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE);
2474 cmd->opcode = O_MAC_TYPE;
2481 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
2483 struct protoent *pe;
2487 proto = strtol(av, &ep, 10);
2488 if (*ep != '\0' || proto <= 0) {
2489 if ((pe = getprotobyname(av)) == NULL)
2491 proto = pe->p_proto;
2494 fill_cmd(cmd, O_PROTO, 0, proto);
2500 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
2502 u_char proto = IPPROTO_IP;
2504 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2505 ; /* do not set O_IP4 nor O_IP6 */
2506 else if (strcmp(av, "ip4") == 0)
2507 /* explicit "just IPv4" rule */
2508 fill_cmd(cmd, O_IP4, 0, 0);
2509 else if (strcmp(av, "ip6") == 0) {
2510 /* explicit "just IPv6" rule */
2511 proto = IPPROTO_IPV6;
2512 fill_cmd(cmd, O_IP6, 0, 0);
2514 return add_proto0(cmd, av, protop);
2521 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
2523 u_char proto = IPPROTO_IP;
2525 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2526 ; /* do not set O_IP4 nor O_IP6 */
2527 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
2528 /* explicit "just IPv4" rule */
2529 fill_cmd(cmd, O_IP4, 0, 0);
2530 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
2531 /* explicit "just IPv6" rule */
2532 proto = IPPROTO_IPV6;
2533 fill_cmd(cmd, O_IP6, 0, 0);
2535 return add_proto0(cmd, av, protop);
2542 add_srcip(ipfw_insn *cmd, char *av)
2544 fill_ip((ipfw_insn_ip *)cmd, av);
2545 if (cmd->opcode == O_IP_DST_SET) /* set */
2546 cmd->opcode = O_IP_SRC_SET;
2547 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
2548 cmd->opcode = O_IP_SRC_LOOKUP;
2549 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2550 cmd->opcode = O_IP_SRC_ME;
2551 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2552 cmd->opcode = O_IP_SRC;
2553 else /* addr/mask */
2554 cmd->opcode = O_IP_SRC_MASK;
2559 add_dstip(ipfw_insn *cmd, char *av)
2561 fill_ip((ipfw_insn_ip *)cmd, av);
2562 if (cmd->opcode == O_IP_DST_SET) /* set */
2564 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
2566 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2567 cmd->opcode = O_IP_DST_ME;
2568 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2569 cmd->opcode = O_IP_DST;
2570 else /* addr/mask */
2571 cmd->opcode = O_IP_DST_MASK;
2576 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode)
2578 /* XXX "any" is trapped before. Perhaps "to" */
2579 if (_substrcmp(av, "any") == 0) {
2581 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) {
2582 /* XXX todo: check that we have a protocol with ports */
2583 cmd->opcode = opcode;
2590 add_src(ipfw_insn *cmd, char *av, u_char proto)
2594 ipfw_insn *ret = NULL;
2596 if ((host = strdup(av)) == NULL)
2598 if ((ch = strrchr(host, '/')) != NULL)
2601 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
2602 inet_pton(AF_INET6, host, &a) == 1)
2603 ret = add_srcip6(cmd, av);
2604 /* XXX: should check for IPv4, not !IPv6 */
2605 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2606 inet_pton(AF_INET6, host, &a) != 1))
2607 ret = add_srcip(cmd, av);
2608 if (ret == NULL && strcmp(av, "any") != 0)
2616 add_dst(ipfw_insn *cmd, char *av, u_char proto)
2620 ipfw_insn *ret = NULL;
2622 if ((host = strdup(av)) == NULL)
2624 if ((ch = strrchr(host, '/')) != NULL)
2627 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
2628 inet_pton(AF_INET6, host, &a) == 1)
2629 ret = add_dstip6(cmd, av);
2630 /* XXX: should check for IPv4, not !IPv6 */
2631 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2632 inet_pton(AF_INET6, host, &a) != 1))
2633 ret = add_dstip(cmd, av);
2634 if (ret == NULL && strcmp(av, "any") != 0)
2642 * Parse arguments and assemble the microinstructions which make up a rule.
2643 * Rules are added into the 'rulebuf' and then copied in the correct order
2644 * into the actual rule.
2646 * The syntax for a rule starts with the action, followed by
2647 * optional action parameters, and the various match patterns.
2648 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
2649 * (generated if the rule includes a keep-state option), then the
2650 * various match patterns, log/altq actions, and the actual action.
2654 ipfw_add(char *av[])
2657 * rules are added into the 'rulebuf' and then copied in
2658 * the correct order into the actual rule.
2659 * Some things that need to go out of order (prob, action etc.)
2662 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255];
2664 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
2665 ipfw_insn *first_cmd; /* first match pattern */
2670 * various flags used to record that we entered some fields.
2672 ipfw_insn *have_state = NULL; /* check-state or keep-state */
2673 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
2678 int open_par = 0; /* open parenthesis ( */
2680 /* proto is here because it is used to fetch ports */
2681 u_char proto = IPPROTO_IP; /* default protocol */
2683 double match_prob = 1; /* match probability, default is always match */
2685 bzero(actbuf, sizeof(actbuf)); /* actions go here */
2686 bzero(cmdbuf, sizeof(cmdbuf));
2687 bzero(rulebuf, sizeof(rulebuf));
2689 rule = (struct ip_fw *)rulebuf;
2690 cmd = (ipfw_insn *)cmdbuf;
2691 action = (ipfw_insn *)actbuf;
2695 /* [rule N] -- Rule number optional */
2696 if (av[0] && isdigit(**av)) {
2697 rule->rulenum = atoi(*av);
2701 /* [set N] -- set number (0..RESVD_SET), optional */
2702 if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
2703 int set = strtoul(av[1], NULL, 10);
2704 if (set < 0 || set > RESVD_SET)
2705 errx(EX_DATAERR, "illegal set %s", av[1]);
2710 /* [prob D] -- match probability, optional */
2711 if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
2712 match_prob = strtod(av[1], NULL);
2714 if (match_prob <= 0 || match_prob > 1)
2715 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
2719 /* action -- mandatory */
2720 NEED1("missing action");
2721 i = match_token(rule_actions, *av);
2723 action->len = 1; /* default */
2725 case TOK_CHECKSTATE:
2726 have_state = action;
2727 action->opcode = O_CHECK_STATE;
2731 action->opcode = O_ACCEPT;
2735 action->opcode = O_DENY;
2740 action->opcode = O_REJECT;
2741 action->arg1 = ICMP_UNREACH_HOST;
2745 action->opcode = O_REJECT;
2746 action->arg1 = ICMP_REJECT_RST;
2750 action->opcode = O_UNREACH6;
2751 action->arg1 = ICMP6_UNREACH_RST;
2755 action->opcode = O_REJECT;
2756 NEED1("missing reject code");
2757 fill_reject_code(&action->arg1, *av);
2762 action->opcode = O_UNREACH6;
2763 NEED1("missing unreach code");
2764 fill_unreach6_code(&action->arg1, *av);
2769 action->opcode = O_COUNT;
2773 action->opcode = O_NAT;
2774 action->len = F_INSN_SIZE(ipfw_insn_nat);
2775 if (_substrcmp(*av, "global") == 0) {
2783 action->opcode = O_QUEUE;
2786 action->opcode = O_PIPE;
2789 action->opcode = O_SKIPTO;
2792 action->opcode = O_NETGRAPH;
2795 action->opcode = O_NGTEE;
2798 action->opcode = O_DIVERT;
2801 action->opcode = O_TEE;
2804 action->opcode = O_CALLRETURN;
2807 errx(EX_USAGE, "missing argument for %s", *(av - 1));
2808 if (isdigit(**av)) {
2809 action->arg1 = strtoul(*av, NULL, 10);
2810 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
2811 errx(EX_DATAERR, "illegal argument for %s",
2813 } else if (_substrcmp(*av, "tablearg") == 0) {
2814 action->arg1 = IP_FW_TABLEARG;
2815 } else if (i == TOK_DIVERT || i == TOK_TEE) {
2818 s = getservbyname(av[0], "divert");
2820 action->arg1 = ntohs(s->s_port);
2822 errx(EX_DATAERR, "illegal divert/tee port");
2824 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
2830 * Locate the address-port separator (':' or ',').
2831 * Could be one of the following:
2835 * IPv6 w:x:y::z,port
2836 * The ':' can only be used with hostname and IPv4 address.
2837 * XXX-BZ Should we also support [w:x:y::z]:port?
2839 struct sockaddr_storage result;
2840 struct addrinfo *res;
2843 u_short port_number;
2845 NEED1("missing forward address[:port]");
2848 * locate the address-port separator (':' or ',')
2850 s = strchr(*av, ',');
2852 /* Distinguish between IPv4:port and IPv6 cases. */
2853 s = strchr(*av, ':');
2854 if (s && strchr(s+1, ':'))
2855 s = NULL; /* no port */
2860 /* Terminate host portion and set s to start of port. */
2862 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
2865 "illegal forwarding port ``%s''", s);
2866 port_number = (u_short)i;
2869 if (_substrcmp(*av, "tablearg") == 0) {
2871 ((struct sockaddr_in*)&result)->sin_addr.s_addr =
2875 * Resolve the host name or address to a family and a
2876 * network representation of the addres.
2878 if (getaddrinfo(*av, NULL, NULL, &res))
2879 errx(EX_DATAERR, NULL);
2880 /* Just use the first host in the answer. */
2881 family = res->ai_family;
2882 memcpy(&result, res->ai_addr, res->ai_addrlen);
2886 if (family == PF_INET) {
2887 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
2889 action->opcode = O_FORWARD_IP;
2890 action->len = F_INSN_SIZE(ipfw_insn_sa);
2893 * In the kernel we assume AF_INET and use only
2894 * sin_port and sin_addr. Remember to set sin_len as
2895 * the routing code seems to use it too.
2897 p->sa.sin_len = sizeof(struct sockaddr_in);
2898 p->sa.sin_family = AF_INET;
2899 p->sa.sin_port = port_number;
2900 p->sa.sin_addr.s_addr =
2901 ((struct sockaddr_in *)&result)->sin_addr.s_addr;
2902 } else if (family == PF_INET6) {
2903 ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
2905 action->opcode = O_FORWARD_IP6;
2906 action->len = F_INSN_SIZE(ipfw_insn_sa6);
2908 p->sa.sin6_len = sizeof(struct sockaddr_in6);
2909 p->sa.sin6_family = AF_INET6;
2910 p->sa.sin6_port = port_number;
2911 p->sa.sin6_flowinfo = 0;
2912 p->sa.sin6_scope_id = 0;
2913 /* No table support for v6 yet. */
2914 bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
2915 &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
2917 errx(EX_DATAERR, "Invalid address family in forward action");
2923 /* pretend it is a 'count' rule followed by the comment */
2924 action->opcode = O_COUNT;
2925 av--; /* go back... */
2931 size_t intsize = sizeof(int);
2933 action->opcode = O_SETFIB;
2934 NEED1("missing fib number");
2935 if (_substrcmp(*av, "tablearg") == 0) {
2936 action->arg1 = IP_FW_TABLEARG;
2938 action->arg1 = strtoul(*av, NULL, 10);
2939 if (sysctlbyname("net.fibs", &numfibs, &intsize,
2941 errx(EX_DATAERR, "fibs not suported.\n");
2942 if (action->arg1 >= numfibs) /* Temporary */
2943 errx(EX_DATAERR, "fib too large.\n");
2950 action->opcode = O_REASS;
2954 fill_cmd(action, O_CALLRETURN, F_NOT, 0);
2958 errx(EX_DATAERR, "invalid action %s\n", av[-1]);
2960 action = next_cmd(action);
2963 * [altq queuename] -- altq tag, optional
2964 * [log [logamount N]] -- log, optional
2966 * If they exist, it go first in the cmdbuf, but then it is
2967 * skipped in the copy section to the end of the buffer.
2969 while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
2974 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
2979 "log cannot be specified more than once");
2980 have_log = (ipfw_insn *)c;
2981 cmd->len = F_INSN_SIZE(ipfw_insn_log);
2982 cmd->opcode = O_LOG;
2983 if (av[0] && _substrcmp(*av, "logamount") == 0) {
2985 NEED1("logamount requires argument");
2989 "logamount must be positive");
2993 len = sizeof(c->max_log);
2994 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
2995 &c->max_log, &len, NULL, 0) == -1)
2996 errx(1, "sysctlbyname(\"%s\")",
2997 "net.inet.ip.fw.verbose_limit");
3005 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
3007 NEED1("missing altq queue name");
3010 "altq cannot be specified more than once");
3011 have_altq = (ipfw_insn *)a;
3012 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
3013 cmd->opcode = O_ALTQ;
3014 a->qid = altq_name_to_qid(*av);
3025 errx(EX_USAGE, "tag and untag cannot be "
3026 "specified more than once");
3027 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
3028 rule_action_params);
3030 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
3038 cmd = next_cmd(cmd);
3041 if (have_state) /* must be a check-state, we are done */
3044 #define OR_START(target) \
3045 if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
3047 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
3050 if ( (av[0])[1] == '\0') { \
3061 strcmp(*av, ")") == 0 || \
3062 strcmp(*av, "}") == 0)) { \
3067 errx(EX_USAGE, "missing \")\"\n"); \
3071 if (av[0] && _substrcmp(*av, "not") == 0) { \
3072 if (cmd->len & F_NOT) \
3073 errx(EX_USAGE, "double \"not\" not allowed\n"); \
3074 cmd->len |= F_NOT; \
3078 #define OR_BLOCK(target) \
3079 if (av[0] && _substrcmp(*av, "or") == 0) { \
3080 if (prev == NULL || open_par == 0) \
3081 errx(EX_DATAERR, "invalid OR block"); \
3082 prev->len |= F_OR; \
3092 * MAC addresses, optional.
3093 * If we have this, we skip the part "proto from src to dst"
3094 * and jump straight to the option parsing.
3097 NEED1("missing protocol");
3098 if (_substrcmp(*av, "MAC") == 0 ||
3099 _substrcmp(*av, "mac") == 0) {
3100 av++; /* the "MAC" keyword */
3101 add_mac(cmd, av); /* exits in case of errors */
3102 cmd = next_cmd(cmd);
3103 av += 2; /* dst-mac and src-mac */
3105 NEED1("missing mac type");
3106 if (add_mactype(cmd, av[0]))
3107 cmd = next_cmd(cmd);
3108 av++; /* any or mac-type */
3114 * protocol, mandatory
3116 OR_START(get_proto);
3118 NEED1("missing protocol");
3119 if (add_proto_compat(cmd, *av, &proto)) {
3121 if (F_LEN(cmd) != 0) {
3123 cmd = next_cmd(cmd);
3125 } else if (first_cmd != cmd) {
3126 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
3129 OR_BLOCK(get_proto);
3134 if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
3135 errx(EX_USAGE, "missing ``from''");
3139 * source IP, mandatory
3141 OR_START(source_ip);
3142 NOT_BLOCK; /* optional "not" */
3143 NEED1("missing source address");
3144 if (add_src(cmd, *av, proto)) {
3146 if (F_LEN(cmd) != 0) { /* ! any */
3148 cmd = next_cmd(cmd);
3151 errx(EX_USAGE, "bad source address %s", *av);
3152 OR_BLOCK(source_ip);
3155 * source ports, optional
3157 NOT_BLOCK; /* optional "not" */
3158 if ( av[0] != NULL ) {
3159 if (_substrcmp(*av, "any") == 0 ||
3160 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
3162 if (F_LEN(cmd) != 0)
3163 cmd = next_cmd(cmd);
3170 if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
3171 errx(EX_USAGE, "missing ``to''");
3175 * destination, mandatory
3178 NOT_BLOCK; /* optional "not" */
3179 NEED1("missing dst address");
3180 if (add_dst(cmd, *av, proto)) {
3182 if (F_LEN(cmd) != 0) { /* ! any */
3184 cmd = next_cmd(cmd);
3187 errx( EX_USAGE, "bad destination address %s", *av);
3191 * dest. ports, optional
3193 NOT_BLOCK; /* optional "not" */
3195 if (_substrcmp(*av, "any") == 0 ||
3196 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
3198 if (F_LEN(cmd) != 0)
3199 cmd = next_cmd(cmd);
3204 if (av[0] && first_cmd == cmd) {
3206 * nothing specified so far, store in the rule to ease
3212 while ( av[0] != NULL ) {
3214 ipfw_insn_u32 *cmd32; /* alias for cmd */
3217 cmd32 = (ipfw_insn_u32 *)cmd;
3219 if (*s == '!') { /* alternate syntax for NOT */
3220 if (cmd->len & F_NOT)
3221 errx(EX_USAGE, "double \"not\" not allowed\n");
3225 i = match_token(rule_options, s);
3229 if (cmd->len & F_NOT)
3230 errx(EX_USAGE, "double \"not\" not allowed\n");
3235 if (open_par == 0 || prev == NULL)
3236 errx(EX_USAGE, "invalid \"or\" block\n");
3240 case TOK_STARTBRACE:
3242 errx(EX_USAGE, "+nested \"(\" not allowed\n");
3248 errx(EX_USAGE, "+missing \")\"\n");
3254 fill_cmd(cmd, O_IN, 0, 0);
3258 cmd->len ^= F_NOT; /* toggle F_NOT */
3259 fill_cmd(cmd, O_IN, 0, 0);
3263 fill_cmd(cmd, O_DIVERTED, 0, 3);
3266 case TOK_DIVERTEDLOOPBACK:
3267 fill_cmd(cmd, O_DIVERTED, 0, 1);
3270 case TOK_DIVERTEDOUTPUT:
3271 fill_cmd(cmd, O_DIVERTED, 0, 2);
3275 fill_cmd(cmd, O_FRAG, 0, 0);
3279 fill_cmd(cmd, O_LAYER2, 0, 0);
3285 NEED1("recv, xmit, via require interface name"
3287 fill_iface((ipfw_insn_if *)cmd, av[0]);
3289 if (F_LEN(cmd) == 0) /* not a valid address */
3292 cmd->opcode = O_XMIT;
3293 else if (i == TOK_RECV)
3294 cmd->opcode = O_RECV;
3295 else if (i == TOK_VIA)
3296 cmd->opcode = O_VIA;
3300 NEED1("icmptypes requires list of types");
3301 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
3305 case TOK_ICMP6TYPES:
3306 NEED1("icmptypes requires list of types");
3307 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av);
3312 NEED1("ipttl requires TTL");
3313 if (strpbrk(*av, "-,")) {
3314 if (!add_ports(cmd, *av, 0, O_IPTTL))
3315 errx(EX_DATAERR, "invalid ipttl %s", *av);
3317 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
3322 NEED1("ipid requires id");
3323 if (strpbrk(*av, "-,")) {
3324 if (!add_ports(cmd, *av, 0, O_IPID))
3325 errx(EX_DATAERR, "invalid ipid %s", *av);
3327 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
3332 NEED1("iplen requires length");
3333 if (strpbrk(*av, "-,")) {
3334 if (!add_ports(cmd, *av, 0, O_IPLEN))
3335 errx(EX_DATAERR, "invalid ip len %s", *av);
3337 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
3342 NEED1("ipver requires version");
3343 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
3347 case TOK_IPPRECEDENCE:
3348 NEED1("ipprecedence requires value");
3349 fill_cmd(cmd, O_IPPRECEDENCE, 0,
3350 (strtoul(*av, NULL, 0) & 7) << 5);
3355 NEED1("missing argument for ipoptions");
3356 fill_flags(cmd, O_IPOPT, f_ipopts, *av);
3361 NEED1("missing argument for iptos");
3362 fill_flags(cmd, O_IPTOS, f_iptos, *av);
3367 NEED1("uid requires argument");
3373 cmd->opcode = O_UID;
3374 uid = strtoul(*av, &end, 0);
3375 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
3377 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
3378 cmd32->d[0] = pwd->pw_uid;
3379 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3385 NEED1("gid requires argument");
3391 cmd->opcode = O_GID;
3392 gid = strtoul(*av, &end, 0);
3393 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
3395 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
3396 cmd32->d[0] = grp->gr_gid;
3397 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3403 NEED1("jail requires argument");
3408 cmd->opcode = O_JAIL;
3409 jid = (int)strtol(*av, &end, 0);
3410 if (jid < 0 || *end != '\0')
3411 errx(EX_DATAERR, "jail requires prison ID");
3412 cmd32->d[0] = (uint32_t)jid;
3413 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3419 fill_cmd(cmd, O_ESTAB, 0, 0);
3423 fill_cmd(cmd, O_TCPFLAGS, 0,
3424 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
3427 case TOK_TCPDATALEN:
3428 NEED1("tcpdatalen requires length");
3429 if (strpbrk(*av, "-,")) {
3430 if (!add_ports(cmd, *av, 0, O_TCPDATALEN))
3431 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
3433 fill_cmd(cmd, O_TCPDATALEN, 0,
3434 strtoul(*av, NULL, 0));
3439 NEED1("missing argument for tcpoptions");
3440 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
3446 NEED1("tcpseq/tcpack requires argument");
3447 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3448 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
3449 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
3454 NEED1("tcpwin requires length");
3455 if (strpbrk(*av, "-,")) {
3456 if (!add_ports(cmd, *av, 0, O_TCPWIN))
3457 errx(EX_DATAERR, "invalid tcpwin len %s", *av);
3459 fill_cmd(cmd, O_TCPWIN, 0,
3460 strtoul(*av, NULL, 0));
3465 NEED1("missing argument for tcpflags");
3466 cmd->opcode = O_TCPFLAGS;
3467 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
3473 errx(EX_USAGE, "keep-state cannot be part "
3476 errx(EX_USAGE, "only one of keep-state "
3477 "and limit is allowed");
3479 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
3483 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
3488 "limit cannot be part of an or block");
3490 errx(EX_USAGE, "only one of keep-state and "
3491 "limit is allowed");
3494 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
3495 cmd->opcode = O_LIMIT;
3496 c->limit_mask = c->conn_limit = 0;
3498 while ( av[0] != NULL ) {
3499 if ((val = match_token(limit_masks, *av)) <= 0)
3501 c->limit_mask |= val;
3505 if (c->limit_mask == 0)
3506 errx(EX_USAGE, "limit: missing limit mask");
3508 GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
3509 TOK_LIMIT, rule_options);
3516 NEED1("missing protocol");
3517 if (add_proto(cmd, *av, &proto)) {
3520 errx(EX_DATAERR, "invalid protocol ``%s''",
3525 NEED1("missing source IP");
3526 if (add_srcip(cmd, *av)) {
3532 NEED1("missing destination IP");
3533 if (add_dstip(cmd, *av)) {
3539 NEED1("missing source IP6");
3540 if (add_srcip6(cmd, *av)) {
3546 NEED1("missing destination IP6");
3547 if (add_dstip6(cmd, *av)) {
3553 NEED1("missing source port");
3554 if (_substrcmp(*av, "any") == 0 ||
3555 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
3558 errx(EX_DATAERR, "invalid source port %s", *av);
3562 NEED1("missing destination port");
3563 if (_substrcmp(*av, "any") == 0 ||
3564 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
3567 errx(EX_DATAERR, "invalid destination port %s",
3572 if (add_mac(cmd, av))
3577 NEED1("missing mac type");
3578 if (!add_mactype(cmd, *av))
3579 errx(EX_DATAERR, "invalid mac type %s", *av);
3583 case TOK_VERREVPATH:
3584 fill_cmd(cmd, O_VERREVPATH, 0, 0);
3587 case TOK_VERSRCREACH:
3588 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
3592 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
3596 fill_cmd(cmd, O_IPSEC, 0, 0);
3600 fill_cmd(cmd, O_IP6, 0, 0);
3604 fill_cmd(cmd, O_IP4, 0, 0);
3608 fill_ext6hdr( cmd, *av );
3613 if (proto != IPPROTO_IPV6 )
3614 errx( EX_USAGE, "flow-id filter is active "
3615 "only for ipv6 protocol\n");
3616 fill_flow6( (ipfw_insn_u32 *) cmd, *av );
3621 fill_comment(cmd, av);
3626 if (av[0] && strpbrk(*av, "-,")) {
3627 if (!add_ports(cmd, *av, 0, O_TAGGED))
3628 errx(EX_DATAERR, "tagged: invalid tag"
3634 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
3635 TOK_TAGGED, rule_options);
3636 fill_cmd(cmd, O_TAGGED, 0, tag);
3642 NEED1("fib requires fib number");
3643 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
3647 fill_cmd(cmd, O_SOCKARG, 0, 0);
3651 ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
3655 if (!av[0] || !av[1])
3656 errx(EX_USAGE, "format: lookup argument tablenum");
3657 cmd->opcode = O_IP_DST_LOOKUP;
3658 cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
3659 i = match_token(rule_options, *av);
3660 for (j = 0; lookup_key[j] >= 0 ; j++) {
3661 if (i == lookup_key[j])
3664 if (lookup_key[j] <= 0)
3665 errx(EX_USAGE, "format: cannot lookup on %s", *av);
3666 __PAST_END(c->d, 1) = j; // i converted to option
3668 cmd->arg1 = strtoul(*av, &p, 0);
3670 errx(EX_USAGE, "format: lookup argument tablenum");
3676 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
3678 if (F_LEN(cmd) > 0) { /* prepare to advance */
3680 cmd = next_cmd(cmd);
3686 * Now copy stuff into the rule.
3687 * If we have a keep-state option, the first instruction
3688 * must be a PROBE_STATE (which is generated here).
3689 * If we have a LOG option, it was stored as the first command,
3690 * and now must be moved to the top of the action part.
3692 dst = (ipfw_insn *)rule->cmd;
3695 * First thing to write into the command stream is the match probability.
3697 if (match_prob != 1) { /* 1 means always match */
3698 dst->opcode = O_PROB;
3700 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
3705 * generate O_PROBE_STATE if necessary
3707 if (have_state && have_state->opcode != O_CHECK_STATE) {
3708 fill_cmd(dst, O_PROBE_STATE, 0, 0);
3709 dst = next_cmd(dst);
3712 /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
3713 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
3716 switch (src->opcode) {
3724 bcopy(src, dst, i * sizeof(uint32_t));
3730 * put back the have_state command as last opcode
3732 if (have_state && have_state->opcode != O_CHECK_STATE) {
3733 i = F_LEN(have_state);
3734 bcopy(have_state, dst, i * sizeof(uint32_t));
3738 * start action section
3740 rule->act_ofs = dst - rule->cmd;
3742 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
3744 i = F_LEN(have_log);
3745 bcopy(have_log, dst, i * sizeof(uint32_t));
3749 i = F_LEN(have_altq);
3750 bcopy(have_altq, dst, i * sizeof(uint32_t));
3754 i = F_LEN(have_tag);
3755 bcopy(have_tag, dst, i * sizeof(uint32_t));
3759 * copy all other actions
3761 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
3763 bcopy(src, dst, i * sizeof(uint32_t));
3767 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
3768 i = (char *)dst - (char *)rule;
3769 if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1)
3770 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
3772 show_ipfw(rule, 0, 0);
3776 * clear the counters or the log counters.
3779 ipfw_zero(int ac, char *av[], int optname /* 0 = IP_FW_ZERO, 1 = IP_FW_RESETLOG */)
3781 uint32_t arg, saved_arg;
3784 char const *name = optname ? "RESETLOG" : "ZERO";
3786 optname = optname ? IP_FW_RESETLOG : IP_FW_ZERO;
3791 /* clear all entries */
3792 if (do_cmd(optname, NULL, 0) < 0)
3793 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name);
3795 printf("%s.\n", optname == IP_FW_ZERO ?
3796 "Accounting cleared":"Logging counts reset");
3803 if (isdigit(**av)) {
3804 arg = strtonum(*av, 0, 0xffff, &errstr);
3807 "invalid rule number %s\n", *av);
3810 arg |= (1 << 24) | ((co.use_set - 1) << 16);
3813 if (do_cmd(optname, &arg, sizeof(arg))) {
3814 warn("rule %u: setsockopt(IP_FW_%s)",
3816 failed = EX_UNAVAILABLE;
3817 } else if (!co.do_quiet)
3818 printf("Entry %d %s.\n", saved_arg,
3819 optname == IP_FW_ZERO ?
3820 "cleared" : "logging count reset");
3822 errx(EX_USAGE, "invalid rule number ``%s''", *av);
3825 if (failed != EX_OK)
3830 ipfw_flush(int force)
3832 int cmd = co.do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
3834 if (!force && !co.do_quiet) { /* need to ask user */
3837 printf("Are you sure? [yn] ");
3840 c = toupper(getc(stdin));
3841 while (c != '\n' && getc(stdin) != '\n')
3843 return; /* and do not flush */
3844 } while (c != 'Y' && c != 'N');
3846 if (c == 'N') /* user said no */
3853 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
3855 uint32_t arg = ((co.use_set - 1) & 0xffff) | (1 << 24);
3856 if (do_cmd(IP_FW_DEL, &arg, sizeof(arg)) < 0)
3857 err(EX_UNAVAILABLE, "setsockopt(IP_FW_DEL)");
3858 } else if (do_cmd(cmd, NULL, 0) < 0)
3859 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
3860 co.do_pipe ? "DUMMYNET" : "FW");
3862 printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
3866 static void table_list(ipfw_table_entry ent, int need_header);
3869 * This one handles all table-related commands
3870 * ipfw table N add addr[/masklen] [value]
3871 * ipfw table N delete addr[/masklen]
3872 * ipfw table {N | all} flush
3873 * ipfw table {N | all} list
3876 ipfw_table_handler(int ac, char *av[])
3878 ipfw_table_entry ent;
3884 uint32_t tables_max;
3886 len = sizeof(tables_max);
3887 if (sysctlbyname("net.inet.ip.fw.tables_max", &tables_max, &len,
3889 #ifdef IPFW_TABLES_MAX
3890 warn("Warn: Failed to get the max tables number via sysctl. "
3891 "Using the compiled in defaults. \nThe reason was");
3892 tables_max = IPFW_TABLES_MAX;
3894 errx(1, "Failed sysctlbyname(\"net.inet.ip.fw.tables_max\")");
3899 if (ac && isdigit(**av)) {
3900 ent.tbl = atoi(*av);
3903 } else if (ac && _substrcmp(*av, "all") == 0) {
3908 errx(EX_USAGE, "table number or 'all' keyword required");
3909 if (ent.tbl >= tables_max)
3910 errx(EX_USAGE, "The table number exceeds the maximum allowed "
3911 "value (%d)", tables_max - 1);
3912 NEED1("table needs command");
3913 if (is_all && _substrcmp(*av, "list") != 0
3914 && _substrcmp(*av, "flush") != 0)
3915 errx(EX_USAGE, "table number required");
3917 if (_substrcmp(*av, "add") == 0 ||
3918 _substrcmp(*av, "delete") == 0) {
3919 do_add = **av == 'a';
3922 errx(EX_USAGE, "IP address required");
3923 p = strchr(*av, '/');
3926 ent.masklen = atoi(p);
3927 if (ent.masklen > 32)
3928 errx(EX_DATAERR, "bad width ``%s''", p);
3931 if (lookup_host(*av, (struct in_addr *)&ent.addr) != 0)
3932 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
3936 /* isdigit is a bit of a hack here.. */
3937 if (strchr(*av, (int)'.') == NULL && isdigit(**av)) {
3938 ent.value = strtoul(*av, NULL, 0);
3940 if (lookup_host(*av, (struct in_addr *)&tval) == 0) {
3941 /* The value must be stored in host order *
3942 * so that the values < 65k can be distinguished */
3943 ent.value = ntohl(tval);
3945 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
3950 if (do_cmd(do_add ? IP_FW_TABLE_ADD : IP_FW_TABLE_DEL,
3951 &ent, sizeof(ent)) < 0) {
3952 /* If running silent, don't bomb out on these errors. */
3953 if (!(co.do_quiet && (errno == (do_add ? EEXIST : ESRCH))))
3954 err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)",
3955 do_add ? "ADD" : "DEL");
3956 /* In silent mode, react to a failed add by deleting */
3958 do_cmd(IP_FW_TABLE_DEL, &ent, sizeof(ent));
3959 if (do_cmd(IP_FW_TABLE_ADD,
3960 &ent, sizeof(ent)) < 0)
3962 "setsockopt(IP_FW_TABLE_ADD)");
3965 } else if (_substrcmp(*av, "flush") == 0) {
3966 a = is_all ? tables_max : (uint32_t)(ent.tbl + 1);
3968 if (do_cmd(IP_FW_TABLE_FLUSH, &ent.tbl,
3969 sizeof(ent.tbl)) < 0)
3970 err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)");
3971 } while (++ent.tbl < a);
3972 } else if (_substrcmp(*av, "list") == 0) {
3973 a = is_all ? tables_max : (uint32_t)(ent.tbl + 1);
3975 table_list(ent, is_all);
3976 } while (++ent.tbl < a);
3978 errx(EX_USAGE, "invalid table command %s", *av);
3982 table_list(ipfw_table_entry ent, int need_header)
3990 if (do_cmd(IP_FW_TABLE_GETSIZE, &a, (uintptr_t)&l) < 0)
3991 err(EX_OSERR, "getsockopt(IP_FW_TABLE_GETSIZE)");
3993 /* If a is zero we have nothing to do, the table is empty. */
3997 l = sizeof(*tbl) + a * sizeof(ipfw_table_entry);
3998 tbl = safe_calloc(1, l);
4000 if (do_cmd(IP_FW_TABLE_LIST, tbl, (uintptr_t)&l) < 0)
4001 err(EX_OSERR, "getsockopt(IP_FW_TABLE_LIST)");
4002 if (tbl->cnt && need_header)
4003 printf("---table(%d)---\n", tbl->tbl);
4004 for (a = 0; a < tbl->cnt; a++) {
4006 tval = tbl->ent[a].value;
4007 if (co.do_value_as_ip) {
4009 strncpy(tbuf, inet_ntoa(*(struct in_addr *)
4010 &tbl->ent[a].addr), 127);
4011 /* inet_ntoa expects network order */
4013 printf("%s/%u %s\n", tbuf, tbl->ent[a].masklen,
4014 inet_ntoa(*(struct in_addr *)&tval));
4016 printf("%s/%u %u\n",
4017 inet_ntoa(*(struct in_addr *)&tbl->ent[a].addr),
4018 tbl->ent[a].masklen, tval);