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 */
45 #include <stddef.h> /* offsetof */
47 #include <net/ethernet.h>
48 #include <net/if.h> /* only IFNAMSIZ */
49 #include <netinet/in.h>
50 #include <netinet/in_systm.h> /* only n_short, n_long */
51 #include <netinet/ip.h>
52 #include <netinet/ip_icmp.h>
53 #include <netinet/ip_fw.h>
54 #include <netinet/tcp.h>
55 #include <arpa/inet.h>
57 struct cmdline_opts co; /* global options */
59 int resvd_set_number = RESVD_SET;
64 #define s6_addr32 __u6_addr.__u6_addr32
67 #define CHECK_LENGTH(v, len) do { \
69 errx(EX_DATAERR, "Rule too long"); \
72 * Check if we have enough space in cmd buffer. Note that since
73 * first 8? u32 words are reserved by reserved header, full cmd
74 * buffer can't be used, so we need to protect from buffer overrun
75 * only. At the beginnig, cblen is less than actual buffer size by
76 * size of ipfw_insn_u32 instruction + 1 u32 work. This eliminates need
77 * for checking small instructions fitting in given range.
78 * We also (ab)use the fact that ipfw_insn is always the first field
79 * for any custom instruction.
81 #define CHECK_CMDLEN CHECK_LENGTH(cblen, F_LEN((ipfw_insn *)cmd))
83 #define GET_UINT_ARG(arg, min, max, tok, s_x) do { \
85 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
86 if (_substrcmp(*av, "tablearg") == 0) { \
87 arg = IP_FW_TABLEARG; \
95 _xval = strtol(*av, &end, 10); \
97 if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
98 errx(EX_DATAERR, "%s: invalid argument: %s", \
99 match_value(s_x, tok), *av); \
101 if (errno == ERANGE || _xval < min || _xval > max) \
102 errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
103 match_value(s_x, tok), min, max, *av); \
105 if (_xval == IP_FW_TABLEARG) \
106 errx(EX_DATAERR, "%s: illegal argument value: %s", \
107 match_value(s_x, tok), *av); \
113 PRINT_UINT_ARG(const char *str, uint32_t arg)
117 if (arg == IP_FW_TABLEARG)
123 static struct _s_x f_tcpflags[] = {
134 static struct _s_x f_tcpopts[] = {
135 { "mss", IP_FW_TCPOPT_MSS },
136 { "maxseg", IP_FW_TCPOPT_MSS },
137 { "window", IP_FW_TCPOPT_WINDOW },
138 { "sack", IP_FW_TCPOPT_SACK },
139 { "ts", IP_FW_TCPOPT_TS },
140 { "timestamp", IP_FW_TCPOPT_TS },
141 { "cc", IP_FW_TCPOPT_CC },
147 * IP options span the range 0 to 255 so we need to remap them
148 * (though in fact only the low 5 bits are significant).
150 static struct _s_x f_ipopts[] = {
151 { "ssrr", IP_FW_IPOPT_SSRR},
152 { "lsrr", IP_FW_IPOPT_LSRR},
153 { "rr", IP_FW_IPOPT_RR},
154 { "ts", IP_FW_IPOPT_TS},
159 static struct _s_x f_iptos[] = {
160 { "lowdelay", IPTOS_LOWDELAY},
161 { "throughput", IPTOS_THROUGHPUT},
162 { "reliability", IPTOS_RELIABILITY},
163 { "mincost", IPTOS_MINCOST},
164 { "congestion", IPTOS_ECN_CE},
165 { "ecntransport", IPTOS_ECN_ECT0},
166 { "ip tos option", 0},
170 static struct _s_x limit_masks[] = {
171 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
172 {"src-addr", DYN_SRC_ADDR},
173 {"src-port", DYN_SRC_PORT},
174 {"dst-addr", DYN_DST_ADDR},
175 {"dst-port", DYN_DST_PORT},
180 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
181 * This is only used in this code.
183 #define IPPROTO_ETHERTYPE 0x1000
184 static struct _s_x ether_types[] = {
186 * Note, we cannot use "-:&/" in the names because they are field
187 * separators in the type specifications. Also, we use s = NULL as
188 * end-delimiter, because a type of 0 can be legal.
201 { "pppoe_disc", 0x8863 },
202 { "pppoe_sess", 0x8864 },
203 { "ipx_8022", 0x00E0 },
204 { "ipx_8023", 0x0000 },
205 { "ipx_ii", 0x8137 },
206 { "ipx_snap", 0x8137 },
213 static struct _s_x rule_actions[] = {
214 { "accept", TOK_ACCEPT },
215 { "pass", TOK_ACCEPT },
216 { "allow", TOK_ACCEPT },
217 { "permit", TOK_ACCEPT },
218 { "count", TOK_COUNT },
219 { "pipe", TOK_PIPE },
220 { "queue", TOK_QUEUE },
221 { "divert", TOK_DIVERT },
223 { "netgraph", TOK_NETGRAPH },
224 { "ngtee", TOK_NGTEE },
225 { "fwd", TOK_FORWARD },
226 { "forward", TOK_FORWARD },
227 { "skipto", TOK_SKIPTO },
228 { "deny", TOK_DENY },
229 { "drop", TOK_DENY },
230 { "reject", TOK_REJECT },
231 { "reset6", TOK_RESET6 },
232 { "reset", TOK_RESET },
233 { "unreach6", TOK_UNREACH6 },
234 { "unreach", TOK_UNREACH },
235 { "check-state", TOK_CHECKSTATE },
236 { "//", TOK_COMMENT },
238 { "reass", TOK_REASS },
239 { "setfib", TOK_SETFIB },
240 { "call", TOK_CALL },
241 { "return", TOK_RETURN },
242 { NULL, 0 } /* terminator */
245 static struct _s_x rule_action_params[] = {
246 { "altq", TOK_ALTQ },
249 { "untag", TOK_UNTAG },
250 { NULL, 0 } /* terminator */
254 * The 'lookup' instruction accepts one of the following arguments.
255 * -1 is a terminator for the list.
256 * Arguments are passed as v[1] in O_DST_LOOKUP options.
258 static int lookup_key[] = {
259 TOK_DSTIP, TOK_SRCIP, TOK_DSTPORT, TOK_SRCPORT,
260 TOK_UID, TOK_JAIL, TOK_DSCP, -1 };
262 static struct _s_x rule_options[] = {
263 { "tagged", TOK_TAGGED },
266 { "jail", TOK_JAIL },
268 { "limit", TOK_LIMIT },
269 { "keep-state", TOK_KEEPSTATE },
270 { "bridged", TOK_LAYER2 },
271 { "layer2", TOK_LAYER2 },
273 { "diverted", TOK_DIVERTED },
274 { "diverted-loopback", TOK_DIVERTEDLOOPBACK },
275 { "diverted-output", TOK_DIVERTEDOUTPUT },
276 { "xmit", TOK_XMIT },
277 { "recv", TOK_RECV },
279 { "fragment", TOK_FRAG },
280 { "frag", TOK_FRAG },
282 { "ipoptions", TOK_IPOPTS },
283 { "ipopts", TOK_IPOPTS },
284 { "iplen", TOK_IPLEN },
285 { "ipid", TOK_IPID },
286 { "ipprecedence", TOK_IPPRECEDENCE },
287 { "dscp", TOK_DSCP },
288 { "iptos", TOK_IPTOS },
289 { "ipttl", TOK_IPTTL },
290 { "ipversion", TOK_IPVER },
291 { "ipver", TOK_IPVER },
292 { "estab", TOK_ESTAB },
293 { "established", TOK_ESTAB },
294 { "setup", TOK_SETUP },
295 { "sockarg", TOK_SOCKARG },
296 { "tcpdatalen", TOK_TCPDATALEN },
297 { "tcpflags", TOK_TCPFLAGS },
298 { "tcpflgs", TOK_TCPFLAGS },
299 { "tcpoptions", TOK_TCPOPTS },
300 { "tcpopts", TOK_TCPOPTS },
301 { "tcpseq", TOK_TCPSEQ },
302 { "tcpack", TOK_TCPACK },
303 { "tcpwin", TOK_TCPWIN },
304 { "icmptype", TOK_ICMPTYPES },
305 { "icmptypes", TOK_ICMPTYPES },
306 { "dst-ip", TOK_DSTIP },
307 { "src-ip", TOK_SRCIP },
308 { "dst-port", TOK_DSTPORT },
309 { "src-port", TOK_SRCPORT },
310 { "proto", TOK_PROTO },
313 { "mac-type", TOK_MACTYPE },
314 { "verrevpath", TOK_VERREVPATH },
315 { "versrcreach", TOK_VERSRCREACH },
316 { "antispoof", TOK_ANTISPOOF },
317 { "ipsec", TOK_IPSEC },
318 { "icmp6type", TOK_ICMP6TYPES },
319 { "icmp6types", TOK_ICMP6TYPES },
320 { "ext6hdr", TOK_EXT6HDR},
321 { "flow-id", TOK_FLOWID},
326 { "dst-ipv6", TOK_DSTIP6},
327 { "dst-ip6", TOK_DSTIP6},
328 { "src-ipv6", TOK_SRCIP6},
329 { "src-ip6", TOK_SRCIP6},
330 { "lookup", TOK_LOOKUP},
331 { "//", TOK_COMMENT },
333 { "not", TOK_NOT }, /* pseudo option */
334 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
335 { "or", TOK_OR }, /* pseudo option */
336 { "|", /* escape */ TOK_OR }, /* pseudo option */
337 { "{", TOK_STARTBRACE }, /* pseudo option */
338 { "(", TOK_STARTBRACE }, /* pseudo option */
339 { "}", TOK_ENDBRACE }, /* pseudo option */
340 { ")", TOK_ENDBRACE }, /* pseudo option */
341 { NULL, 0 } /* terminator */
345 * Helper routine to print a possibly unaligned uint64_t on
346 * various platform. If width > 0, print the value with
347 * the desired width, followed by a space;
348 * otherwise, return the required width.
351 pr_u64(uint64_t *pd, int width)
354 #define U64_FMT "I64"
356 #define U64_FMT "llu"
359 unsigned long long d;
361 bcopy (pd, &u, sizeof(u));
364 printf("%*" U64_FMT " ", width, d) :
365 snprintf(NULL, 0, "%" U64_FMT, d) ;
370 safe_calloc(size_t number, size_t size)
372 void *ret = calloc(number, size);
375 err(EX_OSERR, "calloc");
380 safe_realloc(void *ptr, size_t size)
382 void *ret = realloc(ptr, size);
385 err(EX_OSERR, "realloc");
390 * conditionally runs the command.
391 * Selected options or negative -> getsockopt
394 do_cmd(int optname, void *optval, uintptr_t optlen)
401 if (ipfw_socket == -1)
402 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
404 err(EX_UNAVAILABLE, "socket");
406 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
407 optname == IP_FW_ADD || optname == IP_FW3 ||
408 optname == IP_FW_NAT_GET_CONFIG ||
410 optname == IP_FW_NAT_GET_LOG) {
413 i = getsockopt(ipfw_socket, IPPROTO_IP, optname, optval,
414 (socklen_t *)optlen);
416 i = setsockopt(ipfw_socket, IPPROTO_IP, optname, optval, optlen);
422 * do_setcmd3 - pass ipfw control cmd to kernel
423 * @optname: option name
424 * @optval: pointer to option data
425 * @optlen: option length
427 * Function encapsulates option value in IP_FW3 socket option
428 * and calls setsockopt().
429 * Function returns 0 on success or -1 otherwise.
432 do_setcmd3(int optname, void *optval, socklen_t optlen)
435 ip_fw3_opheader *op3;
440 if (ipfw_socket == -1)
441 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
443 err(EX_UNAVAILABLE, "socket");
445 len = sizeof(ip_fw3_opheader) + optlen;
447 /* Zero reserved fields */
448 memset(op3, 0, sizeof(ip_fw3_opheader));
449 memcpy(op3 + 1, optval, optlen);
450 op3->opcode = optname;
452 return setsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, len);
456 * match_token takes a table and a string, returns the value associated
457 * with the string (-1 in case of failure).
460 match_token(struct _s_x *table, char *string)
463 uint i = strlen(string);
465 for (pt = table ; i && pt->s != NULL ; pt++)
466 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
472 * match_value takes a table and a value, returns the string associated
473 * with the value (NULL in case of failure).
476 match_value(struct _s_x *p, int value)
478 for (; p->s != NULL; p++)
485 * _substrcmp takes two strings and returns 1 if they do not match,
486 * and 0 if they match exactly or the first string is a sub-string
487 * of the second. A warning is printed to stderr in the case that the
488 * first string is a sub-string of the second.
490 * This function will be removed in the future through the usual
491 * deprecation process.
494 _substrcmp(const char *str1, const char* str2)
497 if (strncmp(str1, str2, strlen(str1)) != 0)
500 if (strlen(str1) != strlen(str2))
501 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
507 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
508 * and 0 if they match exactly or the second string is a sub-string
509 * of the first. A warning is printed to stderr in the case that the
510 * first string does not match the third.
512 * This function exists to warn about the bizarre construction
513 * strncmp(str, "by", 2) which is used to allow people to use a shortcut
514 * for "bytes". The problem is that in addition to accepting "by",
515 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
516 * other string beginning with "by".
518 * This function will be removed in the future through the usual
519 * deprecation process.
522 _substrcmp2(const char *str1, const char* str2, const char* str3)
525 if (strncmp(str1, str2, strlen(str2)) != 0)
528 if (strcmp(str1, str3) != 0)
529 warnx("DEPRECATED: '%s' matched '%s'",
535 * prints one port, symbolic or numeric
538 print_port(int proto, uint16_t port)
541 if (proto == IPPROTO_ETHERTYPE) {
544 if (co.do_resolv && (s = match_value(ether_types, port)) )
547 printf("0x%04x", port);
549 struct servent *se = NULL;
551 struct protoent *pe = getprotobynumber(proto);
553 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
556 printf("%s", se->s_name);
562 static struct _s_x _port_name[] = {
563 {"dst-port", O_IP_DSTPORT},
564 {"src-port", O_IP_SRCPORT},
568 {"mac-type", O_MAC_TYPE},
569 {"tcpdatalen", O_TCPDATALEN},
570 {"tcpwin", O_TCPWIN},
571 {"tagged", O_TAGGED},
576 * Print the values in a list 16-bit items of the types above.
577 * XXX todo: add support for mask.
580 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode)
582 uint16_t *p = cmd->ports;
587 sep = match_value(_port_name, opcode);
593 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
595 print_port(proto, p[0]);
598 print_port(proto, p[1]);
605 * Like strtol, but also translates service names into port numbers
606 * for some protocols.
608 * proto == -1 disables the protocol check;
609 * proto == IPPROTO_ETHERTYPE looks up an internal table
610 * proto == <some value in /etc/protocols> matches the values there.
611 * Returns *end == s in case the parameter is not found.
614 strtoport(char *s, char **end, int base, int proto)
620 *end = s; /* default - not found */
622 return 0; /* not found */
625 return strtol(s, end, base);
628 * find separator. '\\' escapes the next char.
630 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
631 if (*s1 == '\\' && s1[1] != '\0')
634 buf = safe_calloc(s1 - s + 1, 1);
637 * copy into a buffer skipping backslashes
639 for (p = s, i = 0; p != s1 ; p++)
644 if (proto == IPPROTO_ETHERTYPE) {
645 i = match_token(ether_types, buf);
647 if (i != -1) { /* found */
652 struct protoent *pe = NULL;
656 pe = getprotobynumber(proto);
658 se = getservbyname(buf, pe ? pe->p_name : NULL);
662 return ntohs(se->s_port);
665 return 0; /* not found */
669 * Fill the body of the command with the list of port ranges.
672 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
674 uint16_t a, b, *p = cmd->ports;
679 a = strtoport(av, &s, 0, proto);
680 if (s == av) /* empty or invalid argument */
683 CHECK_LENGTH(cblen, i + 2);
686 case '-': /* a range */
688 b = strtoport(av, &s, 0, proto);
689 /* Reject expressions like '1-abc' or '1-2-3'. */
690 if (s == av || (*s != ',' && *s != '\0'))
695 case ',': /* comma separated list */
700 warnx("port list: invalid separator <%c> in <%s>",
710 if (i + 1 > F_LEN_MASK)
711 errx(EX_DATAERR, "too many ports/ranges\n");
712 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
717 static struct _s_x icmpcodes[] = {
718 { "net", ICMP_UNREACH_NET },
719 { "host", ICMP_UNREACH_HOST },
720 { "protocol", ICMP_UNREACH_PROTOCOL },
721 { "port", ICMP_UNREACH_PORT },
722 { "needfrag", ICMP_UNREACH_NEEDFRAG },
723 { "srcfail", ICMP_UNREACH_SRCFAIL },
724 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
725 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
726 { "isolated", ICMP_UNREACH_ISOLATED },
727 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
728 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
729 { "tosnet", ICMP_UNREACH_TOSNET },
730 { "toshost", ICMP_UNREACH_TOSHOST },
731 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
732 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
733 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
738 fill_reject_code(u_short *codep, char *str)
743 val = strtoul(str, &s, 0);
744 if (s == str || *s != '\0' || val >= 0x100)
745 val = match_token(icmpcodes, str);
747 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
753 print_reject_code(uint16_t code)
755 char const *s = match_value(icmpcodes, code);
758 printf("unreach %s", s);
760 printf("unreach %u", code);
764 * Returns the number of bits set (from left) in a contiguous bitmask,
765 * or -1 if the mask is not contiguous.
766 * XXX this needs a proper fix.
767 * This effectively works on masks in big-endian (network) format.
768 * when compiled on little endian architectures.
770 * First bit is bit 7 of the first byte -- note, for MAC addresses,
771 * the first bit on the wire is bit 0 of the first byte.
772 * len is the max length in bits.
775 contigmask(uint8_t *p, int len)
779 for (i=0; i<len ; i++)
780 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
782 for (n=i+1; n < len; n++)
783 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
784 return -1; /* mask not contiguous */
789 * print flags set/clear in the two bitmasks passed as parameters.
790 * There is a specialized check for f_tcpflags.
793 print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list)
795 char const *comma = "";
797 uint8_t set = cmd->arg1 & 0xff;
798 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
800 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
805 printf(" %s ", name);
806 for (i=0; list[i].x != 0; i++) {
807 if (set & list[i].x) {
809 printf("%s%s", comma, list[i].s);
812 if (clear & list[i].x) {
814 printf("%s!%s", comma, list[i].s);
821 * Print the ip address contained in a command.
824 print_ip(ipfw_insn_ip *cmd, char const *s)
826 struct hostent *he = NULL;
827 uint32_t len = F_LEN((ipfw_insn *)cmd);
828 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
830 if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
832 const char *arg = "<invalid>";
834 if (d < sizeof(lookup_key)/sizeof(lookup_key[0]))
835 arg = match_value(rule_options, lookup_key[d]);
836 printf("%s lookup %s %d", cmd->o.len & F_NOT ? " not": "",
840 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
842 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
846 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
847 cmd->o.opcode == O_IP_DST_LOOKUP) {
848 printf("table(%u", ((ipfw_insn *)cmd)->arg1);
849 if (len == F_INSN_SIZE(ipfw_insn_u32))
854 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
855 uint32_t x, *map = (uint32_t *)&(cmd->mask);
861 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
862 printf("%s/%d", inet_ntoa(cmd->addr),
863 contigmask((uint8_t *)&x, 32));
864 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
865 x &= 0xff; /* base */
867 * Print bits and ranges.
868 * Locate first bit set (i), then locate first bit unset (j).
869 * If we have 3+ consecutive bits set, then print them as a
870 * range, otherwise only print the initial bit and rescan.
872 for (i=0; i < cmd->o.arg1; i++)
873 if (map[i/32] & (1<<(i & 31))) {
874 for (j=i+1; j < cmd->o.arg1; j++)
875 if (!(map[ j/32] & (1<<(j & 31))))
877 printf("%c%d", comma, i+x);
878 if (j>i+2) { /* range has at least 3 elements */
879 printf("-%d", j-1+x);
888 * len == 2 indicates a single IP, whereas lists of 1 or more
889 * addr/mask pairs have len = (2n+1). We convert len to n so we
890 * use that to count the number of entries.
892 for (len = len / 2; len > 0; len--, a += 2) {
893 int mb = /* mask length */
894 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
895 32 : contigmask((uint8_t *)&(a[1]), 32);
896 if (mb == 32 && co.do_resolv)
897 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
898 if (he != NULL) /* resolved to name */
899 printf("%s", he->h_name);
900 else if (mb == 0) /* any */
902 else { /* numeric IP followed by some kind of mask */
903 printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) );
905 printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) );
915 * prints a MAC address/mask pair
918 print_mac(uint8_t *addr, uint8_t *mask)
920 int l = contigmask(mask, 48);
925 printf(" %02x:%02x:%02x:%02x:%02x:%02x",
926 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
928 printf("&%02x:%02x:%02x:%02x:%02x:%02x",
929 mask[0], mask[1], mask[2],
930 mask[3], mask[4], mask[5]);
937 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
946 type = strtoul(av, &av, 0);
948 if (*av != ',' && *av != '\0')
949 errx(EX_DATAERR, "invalid ICMP type");
952 errx(EX_DATAERR, "ICMP type out of range");
954 cmd->d[0] |= 1 << type;
956 cmd->o.opcode = O_ICMPTYPE;
957 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
961 print_icmptypes(ipfw_insn_u32 *cmd)
966 printf(" icmptypes");
967 for (i = 0; i < 32; i++) {
968 if ( (cmd->d[0] & (1 << (i))) == 0)
970 printf("%c%d", sep, i);
976 * show_ipfw() prints the body of an ipfw rule.
977 * Because the standard rule has at least proto src_ip dst_ip, we use
978 * a helper function to produce these entries if not provided explicitly.
979 * The first argument is the list of fields we have, the second is
980 * the list of fields we want to be printed.
982 * Special cases if we have provided a MAC header:
983 * + if the rule does not contain IP addresses/ports, do not print them;
984 * + if the rule does not contain an IP proto, print "all" instead of "ip";
986 * Once we have 'have_options', IP header fields are printed as options.
988 #define HAVE_PROTO 0x0001
989 #define HAVE_SRCIP 0x0002
990 #define HAVE_DSTIP 0x0004
991 #define HAVE_PROTO4 0x0008
992 #define HAVE_PROTO6 0x0010
993 #define HAVE_IP 0x0100
994 #define HAVE_OPTIONS 0x8000
997 show_prerequisites(int *flags, int want, int cmd)
999 (void)cmd; /* UNUSED */
1000 if (co.comment_only)
1002 if ( (*flags & HAVE_IP) == HAVE_IP)
1003 *flags |= HAVE_OPTIONS;
1005 if ( !(*flags & HAVE_OPTIONS)) {
1006 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) {
1007 if ( (*flags & HAVE_PROTO4))
1009 else if ( (*flags & HAVE_PROTO6))
1014 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
1015 printf(" from any");
1016 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
1023 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth)
1025 static int twidth = 0;
1027 ipfw_insn *cmd, *tagptr = NULL;
1028 const char *comment = NULL; /* ptr to comment if we have one */
1029 int proto = 0; /* default */
1030 int flags = 0; /* prerequisites */
1031 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
1032 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
1033 int or_block = 0; /* we are in an or block */
1034 uint32_t set_disable;
1036 bcopy(&rule->next_rule, &set_disable, sizeof(set_disable));
1038 if (set_disable & (1 << rule->set)) { /* disabled */
1042 printf("# DISABLED ");
1044 printf("%05u ", rule->rulenum);
1046 if (pcwidth > 0 || bcwidth > 0) {
1047 pr_u64(&rule->pcnt, pcwidth);
1048 pr_u64(&rule->bcnt, bcwidth);
1051 if (co.do_time == 2)
1052 printf("%10u ", rule->timestamp);
1053 else if (co.do_time == 1) {
1055 time_t t = (time_t)0;
1058 strcpy(timestr, ctime(&t));
1059 *strchr(timestr, '\n') = '\0';
1060 twidth = strlen(timestr);
1062 if (rule->timestamp) {
1063 t = _long_to_time(rule->timestamp);
1065 strcpy(timestr, ctime(&t));
1066 *strchr(timestr, '\n') = '\0';
1067 printf("%s ", timestr);
1069 printf("%*s", twidth, " ");
1074 printf("set %d ", rule->set);
1077 * print the optional "match probability"
1079 if (rule->cmd_len > 0) {
1081 if (cmd->opcode == O_PROB) {
1082 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1083 double d = 1.0 * p->d[0];
1085 d = (d / 0x7fffffff);
1086 printf("prob %f ", d);
1091 * first print actions
1093 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1094 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1095 switch(cmd->opcode) {
1097 printf("check-state");
1098 /* avoid printing anything else */
1099 flags = HAVE_PROTO | HAVE_SRCIP |
1100 HAVE_DSTIP | HAVE_IP;
1116 if (cmd->arg1 == ICMP_REJECT_RST)
1118 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1121 print_reject_code(cmd->arg1);
1125 if (cmd->arg1 == ICMP6_UNREACH_RST)
1128 print_unreach6_code(cmd->arg1);
1132 PRINT_UINT_ARG("skipto ", cmd->arg1);
1136 PRINT_UINT_ARG("pipe ", cmd->arg1);
1140 PRINT_UINT_ARG("queue ", cmd->arg1);
1144 PRINT_UINT_ARG("divert ", cmd->arg1);
1148 PRINT_UINT_ARG("tee ", cmd->arg1);
1152 PRINT_UINT_ARG("netgraph ", cmd->arg1);
1156 PRINT_UINT_ARG("ngtee ", cmd->arg1);
1161 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1163 if (s->sa.sin_addr.s_addr == INADDR_ANY) {
1164 printf("fwd tablearg");
1166 printf("fwd %s", inet_ntoa(s->sa.sin_addr));
1169 printf(",%d", s->sa.sin_port);
1175 char buf[4 + INET6_ADDRSTRLEN + 1];
1176 ipfw_insn_sa6 *s = (ipfw_insn_sa6 *)cmd;
1178 printf("fwd %s", inet_ntop(AF_INET6, &s->sa.sin6_addr,
1180 if (s->sa.sin6_port)
1181 printf(",%d", s->sa.sin6_port);
1185 case O_LOG: /* O_LOG is printed last */
1186 logptr = (ipfw_insn_log *)cmd;
1189 case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1190 altqptr = (ipfw_insn_altq *)cmd;
1199 PRINT_UINT_ARG("nat ", cmd->arg1);
1201 printf("nat global");
1205 PRINT_UINT_ARG("setfib ", cmd->arg1);
1213 if (cmd->len & F_NOT)
1216 PRINT_UINT_ARG("call ", cmd->arg1);
1220 printf("** unrecognized action %d len %d ",
1221 cmd->opcode, cmd->len);
1225 if (logptr->max_log > 0)
1226 printf(" log logamount %d", logptr->max_log);
1232 print_altq_cmd(altqptr);
1236 if (tagptr->len & F_NOT)
1237 PRINT_UINT_ARG(" untag ", tagptr->arg1);
1239 PRINT_UINT_ARG(" tag ", tagptr->arg1);
1243 * then print the body.
1245 for (l = rule->act_ofs, cmd = rule->cmd ;
1246 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1247 if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1249 if (cmd->opcode == O_IP4) {
1250 flags |= HAVE_PROTO4;
1252 } else if (cmd->opcode == O_IP6) {
1253 flags |= HAVE_PROTO6;
1257 if (rule->_pad & 1) { /* empty rules before options */
1258 if (!co.do_compact) {
1259 show_prerequisites(&flags, HAVE_PROTO, 0);
1260 printf(" from any to any");
1262 flags |= HAVE_IP | HAVE_OPTIONS | HAVE_PROTO |
1263 HAVE_SRCIP | HAVE_DSTIP;
1266 if (co.comment_only)
1269 for (l = rule->act_ofs, cmd = rule->cmd ;
1270 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1272 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1274 if (co.comment_only) {
1275 if (cmd->opcode != O_NOP)
1277 printf(" // %s\n", (char *)(cmd + 1));
1281 show_prerequisites(&flags, 0, cmd->opcode);
1283 switch(cmd->opcode) {
1285 break; /* done already */
1288 break; /* no need to print anything here */
1291 case O_IP_SRC_LOOKUP:
1295 show_prerequisites(&flags, HAVE_PROTO, 0);
1296 if (!(flags & HAVE_SRCIP))
1298 if ((cmd->len & F_OR) && !or_block)
1300 print_ip((ipfw_insn_ip *)cmd,
1301 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1302 flags |= HAVE_SRCIP;
1306 case O_IP_DST_LOOKUP:
1310 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1311 if (!(flags & HAVE_DSTIP))
1313 if ((cmd->len & F_OR) && !or_block)
1315 print_ip((ipfw_insn_ip *)cmd,
1316 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1317 flags |= HAVE_DSTIP;
1321 case O_IP6_SRC_MASK:
1323 show_prerequisites(&flags, HAVE_PROTO, 0);
1324 if (!(flags & HAVE_SRCIP))
1326 if ((cmd->len & F_OR) && !or_block)
1328 print_ip6((ipfw_insn_ip6 *)cmd,
1329 (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1330 flags |= HAVE_SRCIP | HAVE_PROTO;
1334 case O_IP6_DST_MASK:
1336 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1337 if (!(flags & HAVE_DSTIP))
1339 if ((cmd->len & F_OR) && !or_block)
1341 print_ip6((ipfw_insn_ip6 *)cmd,
1342 (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1343 flags |= HAVE_DSTIP;
1347 print_flow6id( (ipfw_insn_u32 *) cmd );
1348 flags |= HAVE_OPTIONS;
1352 show_prerequisites(&flags,
1353 HAVE_PROTO | HAVE_SRCIP |
1354 HAVE_DSTIP | HAVE_IP, 0);
1356 if (flags & HAVE_DSTIP)
1358 show_prerequisites(&flags,
1359 HAVE_PROTO | HAVE_SRCIP, 0);
1360 if ((cmd->len & F_OR) && !or_block)
1362 if (cmd->len & F_NOT)
1364 print_newports((ipfw_insn_u16 *)cmd, proto,
1365 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1369 struct protoent *pe = NULL;
1371 if ((cmd->len & F_OR) && !or_block)
1373 if (cmd->len & F_NOT)
1376 pe = getprotobynumber(cmd->arg1);
1377 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1378 !(flags & HAVE_PROTO))
1379 show_prerequisites(&flags,
1380 HAVE_PROTO | HAVE_IP | HAVE_SRCIP |
1381 HAVE_DSTIP | HAVE_OPTIONS, 0);
1382 if (flags & HAVE_OPTIONS)
1385 printf(" %s", pe->p_name);
1387 printf(" %u", cmd->arg1);
1389 flags |= HAVE_PROTO;
1392 default: /*options ... */
1393 if (!(cmd->len & (F_OR|F_NOT)))
1394 if (((cmd->opcode == O_IP6) &&
1395 (flags & HAVE_PROTO6)) ||
1396 ((cmd->opcode == O_IP4) &&
1397 (flags & HAVE_PROTO4)))
1399 show_prerequisites(&flags, HAVE_PROTO | HAVE_SRCIP |
1400 HAVE_DSTIP | HAVE_IP | HAVE_OPTIONS, 0);
1401 if ((cmd->len & F_OR) && !or_block)
1403 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1405 switch(cmd->opcode) {
1407 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1410 print_mac(m->addr, m->mask);
1411 print_mac(m->addr + 6, m->mask + 6);
1416 print_newports((ipfw_insn_u16 *)cmd,
1417 IPPROTO_ETHERTYPE, cmd->opcode);
1426 printf(" fib %u", cmd->arg1 );
1433 printf(cmd->len & F_NOT ? " out" : " in");
1437 switch (cmd->arg1) {
1439 printf(" diverted");
1442 printf(" diverted-loopback");
1445 printf(" diverted-output");
1448 printf(" diverted-?<%u>", cmd->arg1);
1461 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1463 if (cmd->opcode == O_XMIT)
1465 else if (cmd->opcode == O_RECV)
1467 else /* if (cmd->opcode == O_VIA) */
1469 if (cmdif->name[0] == '\0')
1471 inet_ntoa(cmdif->p.ip));
1472 else if (cmdif->name[0] == '\1') /* interface table */
1473 printf(" %s table(%d)", s, cmdif->p.glob);
1475 printf(" %s %s", s, cmdif->name);
1480 if (F_LEN(cmd) == 1)
1481 printf(" ipid %u", cmd->arg1 );
1483 print_newports((ipfw_insn_u16 *)cmd, 0,
1488 if (F_LEN(cmd) == 1)
1489 printf(" ipttl %u", cmd->arg1 );
1491 print_newports((ipfw_insn_u16 *)cmd, 0,
1496 printf(" ipver %u", cmd->arg1 );
1499 case O_IPPRECEDENCE:
1500 printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1504 if (F_LEN(cmd) == 1)
1505 printf(" iplen %u", cmd->arg1 );
1507 print_newports((ipfw_insn_u16 *)cmd, 0,
1512 print_flags("ipoptions", cmd, f_ipopts);
1516 print_flags("iptos", cmd, f_iptos);
1520 print_icmptypes((ipfw_insn_u32 *)cmd);
1524 printf(" established");
1528 if (F_LEN(cmd) == 1)
1529 printf(" tcpdatalen %u", cmd->arg1 );
1531 print_newports((ipfw_insn_u16 *)cmd, 0,
1536 print_flags("tcpflags", cmd, f_tcpflags);
1540 print_flags("tcpoptions", cmd, f_tcpopts);
1544 if (F_LEN(cmd) == 1)
1545 printf(" tcpwin %u", cmd->arg1);
1547 print_newports((ipfw_insn_u16 *)cmd, 0,
1552 printf(" tcpack %d", ntohl(cmd32->d[0]));
1556 printf(" tcpseq %d", ntohl(cmd32->d[0]));
1561 struct passwd *pwd = getpwuid(cmd32->d[0]);
1564 printf(" uid %s", pwd->pw_name);
1566 printf(" uid %u", cmd32->d[0]);
1572 struct group *grp = getgrgid(cmd32->d[0]);
1575 printf(" gid %s", grp->gr_name);
1577 printf(" gid %u", cmd32->d[0]);
1582 printf(" jail %d", cmd32->d[0]);
1586 printf(" verrevpath");
1590 printf(" versrcreach");
1594 printf(" antispoof");
1602 comment = (char *)(cmd + 1);
1606 printf(" keep-state");
1610 struct _s_x *p = limit_masks;
1611 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1612 uint8_t x = c->limit_mask;
1613 char const *comma = " ";
1616 for (; p->x != 0 ; p++)
1617 if ((x & p->x) == p->x) {
1619 printf("%s%s", comma, p->s);
1622 PRINT_UINT_ARG(" ", c->conn_limit);
1635 print_icmp6types((ipfw_insn_u32 *)cmd);
1639 print_ext6hdr( (ipfw_insn *) cmd );
1643 if (F_LEN(cmd) == 1)
1644 PRINT_UINT_ARG(" tagged ", cmd->arg1);
1646 print_newports((ipfw_insn_u16 *)cmd, 0,
1651 printf(" [opcode %d len %d]",
1652 cmd->opcode, cmd->len);
1655 if (cmd->len & F_OR) {
1658 } else if (or_block) {
1663 show_prerequisites(&flags, HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP
1666 printf(" // %s", comment);
1671 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth)
1673 struct protoent *pe;
1676 char buf[INET6_ADDRSTRLEN];
1678 if (!co.do_expired) {
1679 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1682 bcopy(&d->rule, &rulenum, sizeof(rulenum));
1683 printf("%05d", rulenum);
1684 if (pcwidth > 0 || bcwidth > 0) {
1686 pr_u64(&d->pcnt, pcwidth);
1687 pr_u64(&d->bcnt, bcwidth);
1688 printf("(%ds)", d->expire);
1690 switch (d->dyn_type) {
1691 case O_LIMIT_PARENT:
1692 printf(" PARENT %d", d->count);
1697 case O_KEEP_STATE: /* bidir, no mask */
1702 if ((pe = getprotobynumber(d->id.proto)) != NULL)
1703 printf(" %s", pe->p_name);
1705 printf(" proto %u", d->id.proto);
1707 if (d->id.addr_type == 4) {
1708 a.s_addr = htonl(d->id.src_ip);
1709 printf(" %s %d", inet_ntoa(a), d->id.src_port);
1711 a.s_addr = htonl(d->id.dst_ip);
1712 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
1713 } else if (d->id.addr_type == 6) {
1714 printf(" %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
1715 sizeof(buf)), d->id.src_port);
1716 printf(" <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6, buf,
1717 sizeof(buf)), d->id.dst_port);
1719 printf(" UNKNOWN <-> UNKNOWN\n");
1725 * This one handles all set-related commands
1726 * ipfw set { show | enable | disable }
1728 * ipfw set move X to Y
1729 * ipfw set move rule X to Y
1732 ipfw_sets_handler(char *av[])
1734 uint32_t set_disable, masks[2];
1737 uint8_t cmd, new_set;
1742 errx(EX_USAGE, "set needs command");
1743 if (_substrcmp(*av, "show") == 0) {
1748 nalloc = nbytes = sizeof(struct ip_fw);
1749 while (nbytes >= nalloc) {
1752 nalloc = nalloc * 2 + 200;
1754 data = safe_calloc(1, nbytes);
1755 if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0)
1756 err(EX_OSERR, "getsockopt(IP_FW_GET)");
1759 bcopy(&((struct ip_fw *)data)->next_rule,
1760 &set_disable, sizeof(set_disable));
1762 for (i = 0, msg = "disable" ; i < RESVD_SET; i++)
1763 if ((set_disable & (1<<i))) {
1764 printf("%s %d", msg, i);
1767 msg = (set_disable) ? " enable" : "enable";
1768 for (i = 0; i < RESVD_SET; i++)
1769 if (!(set_disable & (1<<i))) {
1770 printf("%s %d", msg, i);
1774 } else if (_substrcmp(*av, "swap") == 0) {
1776 if ( av[0] == NULL || av[1] == NULL )
1777 errx(EX_USAGE, "set swap needs 2 set numbers\n");
1778 rulenum = atoi(av[0]);
1779 new_set = atoi(av[1]);
1780 if (!isdigit(*(av[0])) || rulenum > RESVD_SET)
1781 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
1782 if (!isdigit(*(av[1])) || new_set > RESVD_SET)
1783 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
1784 masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
1785 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
1786 } else if (_substrcmp(*av, "move") == 0) {
1788 if (av[0] && _substrcmp(*av, "rule") == 0) {
1793 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
1794 av[3] != NULL || _substrcmp(av[1], "to") != 0)
1795 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
1796 rulenum = atoi(av[0]);
1797 new_set = atoi(av[2]);
1798 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) ||
1799 (cmd == 2 && rulenum == IPFW_DEFAULT_RULE) )
1800 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
1801 if (!isdigit(*(av[2])) || new_set > RESVD_SET)
1802 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
1803 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
1804 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
1805 } else if (_substrcmp(*av, "disable") == 0 ||
1806 _substrcmp(*av, "enable") == 0 ) {
1807 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
1810 masks[0] = masks[1] = 0;
1813 if (isdigit(**av)) {
1815 if (i < 0 || i > RESVD_SET)
1817 "invalid set number %d\n", i);
1818 masks[which] |= (1<<i);
1819 } else if (_substrcmp(*av, "disable") == 0)
1821 else if (_substrcmp(*av, "enable") == 0)
1825 "invalid set command %s\n", *av);
1828 if ( (masks[0] & masks[1]) != 0 )
1830 "cannot enable and disable the same set\n");
1832 i = do_cmd(IP_FW_DEL, masks, sizeof(masks));
1834 warn("set enable/disable: setsockopt(IP_FW_DEL)");
1836 errx(EX_USAGE, "invalid set command %s\n", *av);
1840 ipfw_sysctl_handler(char *av[], int which)
1844 if (av[0] == NULL) {
1845 warnx("missing keyword to enable/disable\n");
1846 } else if (_substrcmp(*av, "firewall") == 0) {
1847 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
1848 &which, sizeof(which));
1849 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
1850 &which, sizeof(which));
1851 } else if (_substrcmp(*av, "one_pass") == 0) {
1852 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
1853 &which, sizeof(which));
1854 } else if (_substrcmp(*av, "debug") == 0) {
1855 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
1856 &which, sizeof(which));
1857 } else if (_substrcmp(*av, "verbose") == 0) {
1858 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
1859 &which, sizeof(which));
1860 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
1861 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
1862 &which, sizeof(which));
1864 } else if (_substrcmp(*av, "altq") == 0) {
1865 altq_set_enabled(which);
1868 warnx("unrecognize enable/disable keyword: %s\n", *av);
1873 ipfw_list(int ac, char *av[], int show_counters)
1876 ipfw_dyn_rule *dynrules, *d;
1878 #define NEXT(r) ((struct ip_fw *)((char *)r + RULESIZE(r)))
1881 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
1882 int exitval = EX_OK;
1890 const int ocmd = co.do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
1891 int nalloc = 1024; /* start somewhere... */
1896 fprintf(stderr, "Testing only, list disabled\n");
1900 dummynet_list(ac, av, show_counters);
1907 /* get rules or pipes from kernel, resizing array as necessary */
1910 while (nbytes >= nalloc) {
1911 nalloc = nalloc * 2 + 200;
1913 data = safe_realloc(data, nbytes);
1914 if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0)
1915 err(EX_OSERR, "getsockopt(IP_%s_GET)",
1916 co.do_pipe ? "DUMMYNET" : "FW");
1920 * Count static rules. They have variable size so we
1921 * need to scan the list to count them.
1923 for (nstat = 1, r = data, lim = (char *)data + nbytes;
1924 r->rulenum < IPFW_DEFAULT_RULE && (char *)r < lim;
1925 ++nstat, r = NEXT(r) )
1929 * Count dynamic rules. This is easier as they have
1933 dynrules = (ipfw_dyn_rule *)r ;
1934 n = (char *)r - (char *)data;
1935 ndyn = (nbytes - n) / sizeof *dynrules;
1937 /* if showing stats, figure out column widths ahead of time */
1938 bcwidth = pcwidth = 0;
1939 if (show_counters) {
1940 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
1941 /* skip rules from another set */
1942 if (co.use_set && r->set != co.use_set - 1)
1945 /* packet counter */
1946 width = pr_u64(&r->pcnt, 0);
1947 if (width > pcwidth)
1951 width = pr_u64(&r->bcnt, 0);
1952 if (width > bcwidth)
1956 if (co.do_dynamic && ndyn) {
1957 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1959 /* skip rules from another set */
1960 bcopy((char *)&d->rule + sizeof(uint16_t),
1961 &set, sizeof(uint8_t));
1962 if (set != co.use_set - 1)
1965 width = pr_u64(&d->pcnt, 0);
1966 if (width > pcwidth)
1969 width = pr_u64(&d->bcnt, 0);
1970 if (width > bcwidth)
1974 /* if no rule numbers were specified, list all rules */
1976 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
1977 if (co.use_set && r->set != co.use_set - 1)
1979 show_ipfw(r, pcwidth, bcwidth);
1982 if (co.do_dynamic && ndyn) {
1983 printf("## Dynamic rules (%d):\n", ndyn);
1984 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1986 bcopy((char *)&d->rule + sizeof(uint16_t),
1987 &set, sizeof(uint8_t));
1988 if (set != co.use_set - 1)
1991 show_dyn_ipfw(d, pcwidth, bcwidth);
1997 /* display specific rules requested on command line */
1999 for (lac = ac, lav = av; lac != 0; lac--) {
2000 /* convert command line rule # */
2001 last = rnum = strtoul(*lav++, &endptr, 10);
2003 last = strtoul(endptr+1, &endptr, 10);
2006 warnx("invalid rule number: %s", *(lav - 1));
2009 for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) {
2010 if (r->rulenum > last)
2012 if (co.use_set && r->set != co.use_set - 1)
2014 if (r->rulenum >= rnum && r->rulenum <= last) {
2015 show_ipfw(r, pcwidth, bcwidth);
2020 /* give precedence to other error(s) */
2021 if (exitval == EX_OK)
2022 exitval = EX_UNAVAILABLE;
2023 warnx("rule %lu does not exist", rnum);
2027 if (co.do_dynamic && ndyn) {
2028 printf("## Dynamic rules:\n");
2029 for (lac = ac, lav = av; lac != 0; lac--) {
2030 last = rnum = strtoul(*lav++, &endptr, 10);
2032 last = strtoul(endptr+1, &endptr, 10);
2034 /* already warned */
2036 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2039 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2043 bcopy((char *)&d->rule + sizeof(uint16_t),
2044 &set, sizeof(uint8_t));
2045 if (set != co.use_set - 1)
2048 if (r->rulenum >= rnum && r->rulenum <= last)
2049 show_dyn_ipfw(d, pcwidth, bcwidth);
2059 if (exitval != EX_OK)
2065 lookup_host (char *host, struct in_addr *ipaddr)
2069 if (!inet_aton(host, ipaddr)) {
2070 if ((he = gethostbyname(host)) == NULL)
2072 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2078 * fills the addr and mask fields in the instruction as appropriate from av.
2079 * Update length as appropriate.
2080 * The following formats are allowed:
2081 * me returns O_IP_*_ME
2082 * 1.2.3.4 single IP address
2083 * 1.2.3.4:5.6.7.8 address:mask
2084 * 1.2.3.4/24 address/mask
2085 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
2086 * We can have multiple comma-separated address/mask entries.
2089 fill_ip(ipfw_insn_ip *cmd, char *av, int cblen)
2092 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2094 cmd->o.len &= ~F_LEN_MASK; /* zero len */
2096 if (_substrcmp(av, "any") == 0)
2099 if (_substrcmp(av, "me") == 0) {
2100 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2104 if (strncmp(av, "table(", 6) == 0) {
2105 char *p = strchr(av + 6, ',');
2109 cmd->o.opcode = O_IP_DST_LOOKUP;
2110 cmd->o.arg1 = strtoul(av + 6, NULL, 0);
2112 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2113 d[0] = strtoul(p, NULL, 0);
2115 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2121 * After the address we can have '/' or ':' indicating a mask,
2122 * ',' indicating another address follows, '{' indicating a
2123 * set of addresses of unspecified size.
2125 char *t = NULL, *p = strpbrk(av, "/:,{");
2129 CHECK_LENGTH(cblen, F_INSN_SIZE(ipfw_insn) + 2 + len);
2134 if ((t = strpbrk(p, ",{")) != NULL) {
2141 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2142 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2145 if (!inet_aton(p, (struct in_addr *)&d[1]))
2146 errx(EX_DATAERR, "bad netmask ``%s''", p);
2151 d[1] = htonl(0); /* mask */
2152 else if (masklen > 32)
2153 errx(EX_DATAERR, "bad width ``%s''", p);
2155 d[1] = htonl(~0 << (32 - masklen));
2157 case '{': /* no mask, assume /24 and put back the '{' */
2158 d[1] = htonl(~0 << (32 - 24));
2162 case ',': /* single address plus continuation */
2165 case 0: /* initialization value */
2167 d[1] = htonl(~0); /* force /32 */
2170 d[0] &= d[1]; /* mask base address with mask */
2173 /* find next separator */
2175 p = strpbrk(p, ",{");
2176 if (p && *p == '{') {
2178 * We have a set of addresses. They are stored as follows:
2179 * arg1 is the set size (powers of 2, 2..256)
2180 * addr is the base address IN HOST FORMAT
2181 * mask.. is an array of arg1 bits (rounded up to
2182 * the next multiple of 32) with bits set
2183 * for each host in the map.
2185 uint32_t *map = (uint32_t *)&cmd->mask;
2187 int i = contigmask((uint8_t *)&(d[1]), 32);
2190 errx(EX_DATAERR, "address set cannot be in a list");
2191 if (i < 24 || i > 31)
2192 errx(EX_DATAERR, "invalid set with mask %d\n", i);
2193 cmd->o.arg1 = 1<<(32-i); /* map length */
2194 d[0] = ntohl(d[0]); /* base addr in host format */
2195 cmd->o.opcode = O_IP_DST_SET; /* default */
2196 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2197 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2198 map[i] = 0; /* clear map */
2202 high = low + cmd->o.arg1 - 1;
2204 * Here, i stores the previous value when we specify a range
2205 * of addresses within a mask, e.g. 45-63. i = -1 means we
2206 * have no previous value.
2208 i = -1; /* previous value in a range */
2209 while (isdigit(*av)) {
2211 int a = strtol(av, &s, 0);
2213 if (s == av) { /* no parameter */
2215 errx(EX_DATAERR, "set not closed\n");
2217 errx(EX_DATAERR, "incomplete range %d-", i);
2220 if (a < low || a > high)
2221 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
2224 if (i == -1) /* no previous in range */
2226 else { /* check that range is valid */
2228 errx(EX_DATAERR, "invalid range %d-%d",
2231 errx(EX_DATAERR, "double '-' in range");
2234 map[i/32] |= 1<<(i & 31);
2245 if (av) /* then *av must be a ',' */
2248 /* Check this entry */
2249 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2251 * 'any' turns the entire list into a NOP.
2252 * 'not any' never matches, so it is removed from the
2253 * list unless it is the only item, in which case we
2256 if (cmd->o.len & F_NOT) { /* "not any" never matches */
2257 if (av == NULL && len == 0) /* only this entry */
2258 errx(EX_DATAERR, "not any never matches");
2260 /* else do nothing and skip this entry */
2263 /* A single IP can be stored in an optimized format */
2264 if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
2265 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2268 len += 2; /* two words... */
2271 if (len + 1 > F_LEN_MASK)
2272 errx(EX_DATAERR, "address list too long");
2273 cmd->o.len |= len+1;
2277 /* n2mask sets n bits of the mask */
2279 n2mask(struct in6_addr *mask, int n)
2281 static int minimask[9] =
2282 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
2285 memset(mask, 0, sizeof(struct in6_addr));
2286 p = (u_char *) mask;
2287 for (; n > 0; p++, n -= 8) {
2297 * helper function to process a set of flags and set bits in the
2298 * appropriate masks.
2301 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
2302 struct _s_x *flags, char *p)
2304 uint8_t set=0, clear=0;
2307 char *q; /* points to the separator */
2309 uint8_t *which; /* mask we are working on */
2319 val = match_token(flags, p);
2321 errx(EX_DATAERR, "invalid flag %s", p);
2322 *which |= (uint8_t)val;
2325 cmd->opcode = opcode;
2326 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
2327 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
2332 ipfw_delete(char *av[])
2336 int exitval = EX_OK;
2340 NEED1("missing rule specification");
2341 if ( *av && _substrcmp(*av, "set") == 0) {
2342 /* Do not allow using the following syntax:
2343 * ipfw set N delete set M
2346 errx(EX_DATAERR, "invalid syntax");
2347 do_set = 1; /* delete set */
2352 while (*av && isdigit(**av)) {
2353 i = atoi(*av); av++;
2355 exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
2357 exitval = EX_UNAVAILABLE;
2358 warn("rule %u not available", i);
2360 } else if (co.do_pipe) {
2361 exitval = ipfw_delete_pipe(co.do_pipe, i);
2364 rulenum = (i & 0xffff) | (5 << 24) |
2365 ((co.use_set - 1) << 16);
2367 rulenum = (i & 0xffff) | (do_set << 24);
2368 i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum);
2370 exitval = EX_UNAVAILABLE;
2371 warn("rule %u: setsockopt(IP_FW_DEL)",
2376 if (exitval != EX_OK)
2382 * fill the interface structure. We do not check the name as we can
2383 * create interfaces dynamically, so checking them at insert time
2384 * makes relatively little sense.
2385 * Interface names containing '*', '?', or '[' are assumed to be shell
2386 * patterns which match interfaces.
2389 fill_iface(ipfw_insn_if *cmd, char *arg, int cblen)
2391 cmd->name[0] = '\0';
2392 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
2396 /* Parse the interface or address */
2397 if (strcmp(arg, "any") == 0)
2398 cmd->o.len = 0; /* effectively ignore this command */
2399 else if (strncmp(arg, "table(", 6) == 0) {
2400 char *p = strchr(arg + 6, ',');
2403 cmd->name[0] = '\1'; /* Special value indicating table */
2404 cmd->p.glob = strtoul(arg + 6, NULL, 0);
2405 } else if (!isdigit(*arg)) {
2406 strlcpy(cmd->name, arg, sizeof(cmd->name));
2407 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
2408 } else if (!inet_aton(arg, &cmd->p.ip))
2409 errx(EX_DATAERR, "bad ip address ``%s''", arg);
2413 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
2417 char *ap, *ptr, *optr;
2418 struct ether_addr *mac;
2419 const char *macset = "0123456789abcdefABCDEF:";
2421 if (strcmp(p, "any") == 0) {
2422 for (i = 0; i < ETHER_ADDR_LEN; i++)
2423 addr[i] = mask[i] = 0;
2427 optr = ptr = strdup(p);
2428 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
2430 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
2431 errx(EX_DATAERR, "Incorrect MAC address");
2432 bcopy(mac, addr, ETHER_ADDR_LEN);
2434 errx(EX_DATAERR, "Incorrect MAC address");
2436 if (ptr != NULL) { /* we have mask? */
2437 if (p[ptr - optr - 1] == '/') { /* mask len */
2438 long ml = strtol(ptr, &ap, 10);
2439 if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
2440 errx(EX_DATAERR, "Incorrect mask length");
2441 for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
2442 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
2445 if (strspn(ptr, macset) != l ||
2446 (mac = ether_aton(ptr)) == NULL)
2447 errx(EX_DATAERR, "Incorrect mask");
2448 bcopy(mac, mask, ETHER_ADDR_LEN);
2450 } else { /* default mask: ff:ff:ff:ff:ff:ff */
2451 for (i = 0; i < ETHER_ADDR_LEN; i++)
2454 for (i = 0; i < ETHER_ADDR_LEN; i++)
2461 * helper function, updates the pointer to cmd with the length
2462 * of the current command, and also cleans up the first word of
2463 * the new command in case it has been clobbered before.
2466 next_cmd(ipfw_insn *cmd, int *len)
2469 CHECK_LENGTH(*len, 0);
2471 bzero(cmd, sizeof(*cmd));
2476 * Takes arguments and copies them into a comment
2479 fill_comment(ipfw_insn *cmd, char **av, int cblen)
2482 char *p = (char *)(cmd + 1);
2484 cmd->opcode = O_NOP;
2485 cmd->len = (cmd->len & (F_NOT | F_OR));
2487 /* Compute length of comment string. */
2488 for (i = 0, l = 0; av[i] != NULL; i++)
2489 l += strlen(av[i]) + 1;
2494 "comment too long (max 80 chars)");
2496 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
2499 for (i = 0; av[i] != NULL; i++) {
2508 * A function to fill simple commands of size 1.
2509 * Existing flags are preserved.
2512 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
2514 cmd->opcode = opcode;
2515 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
2520 * Fetch and add the MAC address and type, with masks. This generates one or
2521 * two microinstructions, and returns the pointer to the last one.
2524 add_mac(ipfw_insn *cmd, char *av[], int cblen)
2528 if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
2529 errx(EX_DATAERR, "MAC dst src");
2531 cmd->opcode = O_MACADDR2;
2532 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
2535 mac = (ipfw_insn_mac *)cmd;
2536 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
2537 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
2538 &(mac->mask[ETHER_ADDR_LEN])); /* src */
2543 add_mactype(ipfw_insn *cmd, char *av, int cblen)
2546 errx(EX_DATAERR, "missing MAC type");
2547 if (strcmp(av, "any") != 0) { /* we have a non-null type */
2548 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
2550 cmd->opcode = O_MAC_TYPE;
2557 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
2559 struct protoent *pe;
2563 proto = strtol(av, &ep, 10);
2564 if (*ep != '\0' || proto <= 0) {
2565 if ((pe = getprotobyname(av)) == NULL)
2567 proto = pe->p_proto;
2570 fill_cmd(cmd, O_PROTO, 0, proto);
2576 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
2578 u_char proto = IPPROTO_IP;
2580 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2581 ; /* do not set O_IP4 nor O_IP6 */
2582 else if (strcmp(av, "ip4") == 0)
2583 /* explicit "just IPv4" rule */
2584 fill_cmd(cmd, O_IP4, 0, 0);
2585 else if (strcmp(av, "ip6") == 0) {
2586 /* explicit "just IPv6" rule */
2587 proto = IPPROTO_IPV6;
2588 fill_cmd(cmd, O_IP6, 0, 0);
2590 return add_proto0(cmd, av, protop);
2597 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
2599 u_char proto = IPPROTO_IP;
2601 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2602 ; /* do not set O_IP4 nor O_IP6 */
2603 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
2604 /* explicit "just IPv4" rule */
2605 fill_cmd(cmd, O_IP4, 0, 0);
2606 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
2607 /* explicit "just IPv6" rule */
2608 proto = IPPROTO_IPV6;
2609 fill_cmd(cmd, O_IP6, 0, 0);
2611 return add_proto0(cmd, av, protop);
2618 add_srcip(ipfw_insn *cmd, char *av, int cblen)
2620 fill_ip((ipfw_insn_ip *)cmd, av, cblen);
2621 if (cmd->opcode == O_IP_DST_SET) /* set */
2622 cmd->opcode = O_IP_SRC_SET;
2623 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
2624 cmd->opcode = O_IP_SRC_LOOKUP;
2625 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2626 cmd->opcode = O_IP_SRC_ME;
2627 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2628 cmd->opcode = O_IP_SRC;
2629 else /* addr/mask */
2630 cmd->opcode = O_IP_SRC_MASK;
2635 add_dstip(ipfw_insn *cmd, char *av, int cblen)
2637 fill_ip((ipfw_insn_ip *)cmd, av, cblen);
2638 if (cmd->opcode == O_IP_DST_SET) /* set */
2640 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
2642 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2643 cmd->opcode = O_IP_DST_ME;
2644 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2645 cmd->opcode = O_IP_DST;
2646 else /* addr/mask */
2647 cmd->opcode = O_IP_DST_MASK;
2652 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
2654 /* XXX "any" is trapped before. Perhaps "to" */
2655 if (_substrcmp(av, "any") == 0) {
2657 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
2658 /* XXX todo: check that we have a protocol with ports */
2659 cmd->opcode = opcode;
2666 add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen)
2670 ipfw_insn *ret = NULL;
2672 if ((host = strdup(av)) == NULL)
2674 if ((ch = strrchr(host, '/')) != NULL)
2677 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
2678 inet_pton(AF_INET6, host, &a) == 1)
2679 ret = add_srcip6(cmd, av, cblen);
2680 /* XXX: should check for IPv4, not !IPv6 */
2681 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2682 inet_pton(AF_INET6, host, &a) != 1))
2683 ret = add_srcip(cmd, av, cblen);
2684 if (ret == NULL && strcmp(av, "any") != 0)
2692 add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen)
2696 ipfw_insn *ret = NULL;
2698 if ((host = strdup(av)) == NULL)
2700 if ((ch = strrchr(host, '/')) != NULL)
2703 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
2704 inet_pton(AF_INET6, host, &a) == 1)
2705 ret = add_dstip6(cmd, av, cblen);
2706 /* XXX: should check for IPv4, not !IPv6 */
2707 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2708 inet_pton(AF_INET6, host, &a) != 1))
2709 ret = add_dstip(cmd, av, cblen);
2710 if (ret == NULL && strcmp(av, "any") != 0)
2718 * Parse arguments and assemble the microinstructions which make up a rule.
2719 * Rules are added into the 'rulebuf' and then copied in the correct order
2720 * into the actual rule.
2722 * The syntax for a rule starts with the action, followed by
2723 * optional action parameters, and the various match patterns.
2724 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
2725 * (generated if the rule includes a keep-state option), then the
2726 * various match patterns, log/altq actions, and the actual action.
2730 ipfw_add(char *av[])
2733 * rules are added into the 'rulebuf' and then copied in
2734 * the correct order into the actual rule.
2735 * Some things that need to go out of order (prob, action etc.)
2738 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255];
2739 int rblen, ablen, cblen;
2741 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
2742 ipfw_insn *first_cmd; /* first match pattern */
2747 * various flags used to record that we entered some fields.
2749 ipfw_insn *have_state = NULL; /* check-state or keep-state */
2750 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
2755 int open_par = 0; /* open parenthesis ( */
2757 /* proto is here because it is used to fetch ports */
2758 u_char proto = IPPROTO_IP; /* default protocol */
2760 double match_prob = 1; /* match probability, default is always match */
2762 bzero(actbuf, sizeof(actbuf)); /* actions go here */
2763 bzero(cmdbuf, sizeof(cmdbuf));
2764 bzero(rulebuf, sizeof(rulebuf));
2766 rule = (struct ip_fw *)rulebuf;
2767 cmd = (ipfw_insn *)cmdbuf;
2768 action = (ipfw_insn *)actbuf;
2770 rblen = sizeof(rulebuf) / sizeof(rulebuf[0]);
2771 rblen -= offsetof(struct ip_fw, cmd) / sizeof(rulebuf[0]);
2772 ablen = sizeof(actbuf) / sizeof(actbuf[0]);
2773 cblen = sizeof(cmdbuf) / sizeof(cmdbuf[0]);
2774 cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
2776 #define CHECK_RBUFLEN(len) { CHECK_LENGTH(rblen, len); rblen -= len; }
2777 #define CHECK_ACTLEN CHECK_LENGTH(ablen, action->len)
2781 /* [rule N] -- Rule number optional */
2782 if (av[0] && isdigit(**av)) {
2783 rule->rulenum = atoi(*av);
2787 /* [set N] -- set number (0..RESVD_SET), optional */
2788 if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
2789 int set = strtoul(av[1], NULL, 10);
2790 if (set < 0 || set > RESVD_SET)
2791 errx(EX_DATAERR, "illegal set %s", av[1]);
2796 /* [prob D] -- match probability, optional */
2797 if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
2798 match_prob = strtod(av[1], NULL);
2800 if (match_prob <= 0 || match_prob > 1)
2801 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
2805 /* action -- mandatory */
2806 NEED1("missing action");
2807 i = match_token(rule_actions, *av);
2809 action->len = 1; /* default */
2812 case TOK_CHECKSTATE:
2813 have_state = action;
2814 action->opcode = O_CHECK_STATE;
2818 action->opcode = O_ACCEPT;
2822 action->opcode = O_DENY;
2827 action->opcode = O_REJECT;
2828 action->arg1 = ICMP_UNREACH_HOST;
2832 action->opcode = O_REJECT;
2833 action->arg1 = ICMP_REJECT_RST;
2837 action->opcode = O_UNREACH6;
2838 action->arg1 = ICMP6_UNREACH_RST;
2842 action->opcode = O_REJECT;
2843 NEED1("missing reject code");
2844 fill_reject_code(&action->arg1, *av);
2849 action->opcode = O_UNREACH6;
2850 NEED1("missing unreach code");
2851 fill_unreach6_code(&action->arg1, *av);
2856 action->opcode = O_COUNT;
2860 action->opcode = O_NAT;
2861 action->len = F_INSN_SIZE(ipfw_insn_nat);
2863 if (_substrcmp(*av, "global") == 0) {
2871 action->opcode = O_QUEUE;
2874 action->opcode = O_PIPE;
2877 action->opcode = O_SKIPTO;
2880 action->opcode = O_NETGRAPH;
2883 action->opcode = O_NGTEE;
2886 action->opcode = O_DIVERT;
2889 action->opcode = O_TEE;
2892 action->opcode = O_CALLRETURN;
2895 errx(EX_USAGE, "missing argument for %s", *(av - 1));
2896 if (isdigit(**av)) {
2897 action->arg1 = strtoul(*av, NULL, 10);
2898 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
2899 errx(EX_DATAERR, "illegal argument for %s",
2901 } else if (_substrcmp(*av, "tablearg") == 0) {
2902 action->arg1 = IP_FW_TABLEARG;
2903 } else if (i == TOK_DIVERT || i == TOK_TEE) {
2906 s = getservbyname(av[0], "divert");
2908 action->arg1 = ntohs(s->s_port);
2910 errx(EX_DATAERR, "illegal divert/tee port");
2912 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
2918 * Locate the address-port separator (':' or ',').
2919 * Could be one of the following:
2923 * IPv6 w:x:y::z,port
2924 * The ':' can only be used with hostname and IPv4 address.
2925 * XXX-BZ Should we also support [w:x:y::z]:port?
2927 struct sockaddr_storage result;
2928 struct addrinfo *res;
2931 u_short port_number;
2933 NEED1("missing forward address[:port]");
2936 * locate the address-port separator (':' or ',')
2938 s = strchr(*av, ',');
2940 /* Distinguish between IPv4:port and IPv6 cases. */
2941 s = strchr(*av, ':');
2942 if (s && strchr(s+1, ':'))
2943 s = NULL; /* no port */
2948 /* Terminate host portion and set s to start of port. */
2950 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
2953 "illegal forwarding port ``%s''", s);
2954 port_number = (u_short)i;
2957 if (_substrcmp(*av, "tablearg") == 0) {
2959 ((struct sockaddr_in*)&result)->sin_addr.s_addr =
2963 * Resolve the host name or address to a family and a
2964 * network representation of the address.
2966 if (getaddrinfo(*av, NULL, NULL, &res))
2967 errx(EX_DATAERR, NULL);
2968 /* Just use the first host in the answer. */
2969 family = res->ai_family;
2970 memcpy(&result, res->ai_addr, res->ai_addrlen);
2974 if (family == PF_INET) {
2975 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
2977 action->opcode = O_FORWARD_IP;
2978 action->len = F_INSN_SIZE(ipfw_insn_sa);
2982 * In the kernel we assume AF_INET and use only
2983 * sin_port and sin_addr. Remember to set sin_len as
2984 * the routing code seems to use it too.
2986 p->sa.sin_len = sizeof(struct sockaddr_in);
2987 p->sa.sin_family = AF_INET;
2988 p->sa.sin_port = port_number;
2989 p->sa.sin_addr.s_addr =
2990 ((struct sockaddr_in *)&result)->sin_addr.s_addr;
2991 } else if (family == PF_INET6) {
2992 ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
2994 action->opcode = O_FORWARD_IP6;
2995 action->len = F_INSN_SIZE(ipfw_insn_sa6);
2998 p->sa.sin6_len = sizeof(struct sockaddr_in6);
2999 p->sa.sin6_family = AF_INET6;
3000 p->sa.sin6_port = port_number;
3001 p->sa.sin6_flowinfo = 0;
3002 p->sa.sin6_scope_id = 0;
3003 /* No table support for v6 yet. */
3004 bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
3005 &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
3007 errx(EX_DATAERR, "Invalid address family in forward action");
3013 /* pretend it is a 'count' rule followed by the comment */
3014 action->opcode = O_COUNT;
3015 av--; /* go back... */
3021 size_t intsize = sizeof(int);
3023 action->opcode = O_SETFIB;
3024 NEED1("missing fib number");
3025 if (_substrcmp(*av, "tablearg") == 0) {
3026 action->arg1 = IP_FW_TABLEARG;
3028 action->arg1 = strtoul(*av, NULL, 10);
3029 if (sysctlbyname("net.fibs", &numfibs, &intsize,
3031 errx(EX_DATAERR, "fibs not suported.\n");
3032 if (action->arg1 >= numfibs) /* Temporary */
3033 errx(EX_DATAERR, "fib too large.\n");
3040 action->opcode = O_REASS;
3044 fill_cmd(action, O_CALLRETURN, F_NOT, 0);
3048 errx(EX_DATAERR, "invalid action %s\n", av[-1]);
3050 action = next_cmd(action, &ablen);
3053 * [altq queuename] -- altq tag, optional
3054 * [log [logamount N]] -- log, optional
3056 * If they exist, it go first in the cmdbuf, but then it is
3057 * skipped in the copy section to the end of the buffer.
3059 while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
3064 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
3069 "log cannot be specified more than once");
3070 have_log = (ipfw_insn *)c;
3071 cmd->len = F_INSN_SIZE(ipfw_insn_log);
3073 cmd->opcode = O_LOG;
3074 if (av[0] && _substrcmp(*av, "logamount") == 0) {
3076 NEED1("logamount requires argument");
3080 "logamount must be positive");
3084 len = sizeof(c->max_log);
3085 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
3086 &c->max_log, &len, NULL, 0) == -1)
3087 errx(1, "sysctlbyname(\"%s\")",
3088 "net.inet.ip.fw.verbose_limit");
3096 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
3098 NEED1("missing altq queue name");
3101 "altq cannot be specified more than once");
3102 have_altq = (ipfw_insn *)a;
3103 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
3105 cmd->opcode = O_ALTQ;
3106 a->qid = altq_name_to_qid(*av);
3117 errx(EX_USAGE, "tag and untag cannot be "
3118 "specified more than once");
3119 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
3120 rule_action_params);
3122 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
3130 cmd = next_cmd(cmd, &cblen);
3133 if (have_state) /* must be a check-state, we are done */
3136 #define OR_START(target) \
3137 if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
3139 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
3142 if ( (av[0])[1] == '\0') { \
3153 strcmp(*av, ")") == 0 || \
3154 strcmp(*av, "}") == 0)) { \
3159 errx(EX_USAGE, "missing \")\"\n"); \
3163 if (av[0] && _substrcmp(*av, "not") == 0) { \
3164 if (cmd->len & F_NOT) \
3165 errx(EX_USAGE, "double \"not\" not allowed\n"); \
3166 cmd->len |= F_NOT; \
3170 #define OR_BLOCK(target) \
3171 if (av[0] && _substrcmp(*av, "or") == 0) { \
3172 if (prev == NULL || open_par == 0) \
3173 errx(EX_DATAERR, "invalid OR block"); \
3174 prev->len |= F_OR; \
3184 * MAC addresses, optional.
3185 * If we have this, we skip the part "proto from src to dst"
3186 * and jump straight to the option parsing.
3189 NEED1("missing protocol");
3190 if (_substrcmp(*av, "MAC") == 0 ||
3191 _substrcmp(*av, "mac") == 0) {
3192 av++; /* the "MAC" keyword */
3193 add_mac(cmd, av); /* exits in case of errors */
3194 cmd = next_cmd(cmd);
3195 av += 2; /* dst-mac and src-mac */
3197 NEED1("missing mac type");
3198 if (add_mactype(cmd, av[0]))
3199 cmd = next_cmd(cmd);
3200 av++; /* any or mac-type */
3206 * protocol, mandatory
3208 OR_START(get_proto);
3210 NEED1("missing protocol");
3211 if (add_proto_compat(cmd, *av, &proto)) {
3213 if (F_LEN(cmd) != 0) {
3215 cmd = next_cmd(cmd, &cblen);
3217 } else if (first_cmd != cmd) {
3218 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
3221 OR_BLOCK(get_proto);
3226 if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
3227 errx(EX_USAGE, "missing ``from''");
3231 * source IP, mandatory
3233 OR_START(source_ip);
3234 NOT_BLOCK; /* optional "not" */
3235 NEED1("missing source address");
3236 if (add_src(cmd, *av, proto, cblen)) {
3238 if (F_LEN(cmd) != 0) { /* ! any */
3240 cmd = next_cmd(cmd, &cblen);
3243 errx(EX_USAGE, "bad source address %s", *av);
3244 OR_BLOCK(source_ip);
3247 * source ports, optional
3249 NOT_BLOCK; /* optional "not" */
3250 if ( av[0] != NULL ) {
3251 if (_substrcmp(*av, "any") == 0 ||
3252 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
3254 if (F_LEN(cmd) != 0)
3255 cmd = next_cmd(cmd, &cblen);
3262 if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
3263 errx(EX_USAGE, "missing ``to''");
3267 * destination, mandatory
3270 NOT_BLOCK; /* optional "not" */
3271 NEED1("missing dst address");
3272 if (add_dst(cmd, *av, proto, cblen)) {
3274 if (F_LEN(cmd) != 0) { /* ! any */
3276 cmd = next_cmd(cmd, &cblen);
3279 errx( EX_USAGE, "bad destination address %s", *av);
3283 * dest. ports, optional
3285 NOT_BLOCK; /* optional "not" */
3287 if (_substrcmp(*av, "any") == 0 ||
3288 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
3290 if (F_LEN(cmd) != 0)
3291 cmd = next_cmd(cmd, &cblen);
3296 if (av[0] && first_cmd == cmd) {
3298 * nothing specified so far, store in the rule to ease
3304 while ( av[0] != NULL ) {
3306 ipfw_insn_u32 *cmd32; /* alias for cmd */
3309 cmd32 = (ipfw_insn_u32 *)cmd;
3311 if (*s == '!') { /* alternate syntax for NOT */
3312 if (cmd->len & F_NOT)
3313 errx(EX_USAGE, "double \"not\" not allowed\n");
3317 i = match_token(rule_options, s);
3321 if (cmd->len & F_NOT)
3322 errx(EX_USAGE, "double \"not\" not allowed\n");
3327 if (open_par == 0 || prev == NULL)
3328 errx(EX_USAGE, "invalid \"or\" block\n");
3332 case TOK_STARTBRACE:
3334 errx(EX_USAGE, "+nested \"(\" not allowed\n");
3340 errx(EX_USAGE, "+missing \")\"\n");
3346 fill_cmd(cmd, O_IN, 0, 0);
3350 cmd->len ^= F_NOT; /* toggle F_NOT */
3351 fill_cmd(cmd, O_IN, 0, 0);
3355 fill_cmd(cmd, O_DIVERTED, 0, 3);
3358 case TOK_DIVERTEDLOOPBACK:
3359 fill_cmd(cmd, O_DIVERTED, 0, 1);
3362 case TOK_DIVERTEDOUTPUT:
3363 fill_cmd(cmd, O_DIVERTED, 0, 2);
3367 fill_cmd(cmd, O_FRAG, 0, 0);
3371 fill_cmd(cmd, O_LAYER2, 0, 0);
3377 NEED1("recv, xmit, via require interface name"
3379 fill_iface((ipfw_insn_if *)cmd, av[0], cblen);
3381 if (F_LEN(cmd) == 0) /* not a valid address */
3384 cmd->opcode = O_XMIT;
3385 else if (i == TOK_RECV)
3386 cmd->opcode = O_RECV;
3387 else if (i == TOK_VIA)
3388 cmd->opcode = O_VIA;
3392 NEED1("icmptypes requires list of types");
3393 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
3397 case TOK_ICMP6TYPES:
3398 NEED1("icmptypes requires list of types");
3399 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
3404 NEED1("ipttl requires TTL");
3405 if (strpbrk(*av, "-,")) {
3406 if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
3407 errx(EX_DATAERR, "invalid ipttl %s", *av);
3409 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
3414 NEED1("ipid requires id");
3415 if (strpbrk(*av, "-,")) {
3416 if (!add_ports(cmd, *av, 0, O_IPID, cblen))
3417 errx(EX_DATAERR, "invalid ipid %s", *av);
3419 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
3424 NEED1("iplen requires length");
3425 if (strpbrk(*av, "-,")) {
3426 if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
3427 errx(EX_DATAERR, "invalid ip len %s", *av);
3429 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
3434 NEED1("ipver requires version");
3435 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
3439 case TOK_IPPRECEDENCE:
3440 NEED1("ipprecedence requires value");
3441 fill_cmd(cmd, O_IPPRECEDENCE, 0,
3442 (strtoul(*av, NULL, 0) & 7) << 5);
3447 NEED1("missing argument for ipoptions");
3448 fill_flags(cmd, O_IPOPT, f_ipopts, *av);
3453 NEED1("missing argument for iptos");
3454 fill_flags(cmd, O_IPTOS, f_iptos, *av);
3459 NEED1("uid requires argument");
3465 cmd->opcode = O_UID;
3466 uid = strtoul(*av, &end, 0);
3467 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
3469 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
3470 cmd32->d[0] = pwd->pw_uid;
3471 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3477 NEED1("gid requires argument");
3483 cmd->opcode = O_GID;
3484 gid = strtoul(*av, &end, 0);
3485 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
3487 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
3488 cmd32->d[0] = grp->gr_gid;
3489 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3495 NEED1("jail requires argument");
3500 cmd->opcode = O_JAIL;
3501 jid = (int)strtol(*av, &end, 0);
3502 if (jid < 0 || *end != '\0')
3503 errx(EX_DATAERR, "jail requires prison ID");
3504 cmd32->d[0] = (uint32_t)jid;
3505 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3511 fill_cmd(cmd, O_ESTAB, 0, 0);
3515 fill_cmd(cmd, O_TCPFLAGS, 0,
3516 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
3519 case TOK_TCPDATALEN:
3520 NEED1("tcpdatalen requires length");
3521 if (strpbrk(*av, "-,")) {
3522 if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
3523 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
3525 fill_cmd(cmd, O_TCPDATALEN, 0,
3526 strtoul(*av, NULL, 0));
3531 NEED1("missing argument for tcpoptions");
3532 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
3538 NEED1("tcpseq/tcpack requires argument");
3539 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3540 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
3541 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
3546 NEED1("tcpwin requires length");
3547 if (strpbrk(*av, "-,")) {
3548 if (!add_ports(cmd, *av, 0, O_TCPWIN, cblen))
3549 errx(EX_DATAERR, "invalid tcpwin len %s", *av);
3551 fill_cmd(cmd, O_TCPWIN, 0,
3552 strtoul(*av, NULL, 0));
3557 NEED1("missing argument for tcpflags");
3558 cmd->opcode = O_TCPFLAGS;
3559 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
3565 errx(EX_USAGE, "keep-state cannot be part "
3568 errx(EX_USAGE, "only one of keep-state "
3569 "and limit is allowed");
3571 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
3575 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
3580 "limit cannot be part of an or block");
3582 errx(EX_USAGE, "only one of keep-state and "
3583 "limit is allowed");
3586 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
3588 cmd->opcode = O_LIMIT;
3589 c->limit_mask = c->conn_limit = 0;
3591 while ( av[0] != NULL ) {
3592 if ((val = match_token(limit_masks, *av)) <= 0)
3594 c->limit_mask |= val;
3598 if (c->limit_mask == 0)
3599 errx(EX_USAGE, "limit: missing limit mask");
3601 GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
3602 TOK_LIMIT, rule_options);
3609 NEED1("missing protocol");
3610 if (add_proto(cmd, *av, &proto)) {
3613 errx(EX_DATAERR, "invalid protocol ``%s''",
3618 NEED1("missing source IP");
3619 if (add_srcip(cmd, *av, cblen)) {
3625 NEED1("missing destination IP");
3626 if (add_dstip(cmd, *av, cblen)) {
3632 NEED1("missing source IP6");
3633 if (add_srcip6(cmd, *av, cblen)) {
3639 NEED1("missing destination IP6");
3640 if (add_dstip6(cmd, *av, cblen)) {
3646 NEED1("missing source port");
3647 if (_substrcmp(*av, "any") == 0 ||
3648 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
3651 errx(EX_DATAERR, "invalid source port %s", *av);
3655 NEED1("missing destination port");
3656 if (_substrcmp(*av, "any") == 0 ||
3657 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
3660 errx(EX_DATAERR, "invalid destination port %s",
3665 if (add_mac(cmd, av, cblen))
3670 NEED1("missing mac type");
3671 if (!add_mactype(cmd, *av, cblen))
3672 errx(EX_DATAERR, "invalid mac type %s", *av);
3676 case TOK_VERREVPATH:
3677 fill_cmd(cmd, O_VERREVPATH, 0, 0);
3680 case TOK_VERSRCREACH:
3681 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
3685 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
3689 fill_cmd(cmd, O_IPSEC, 0, 0);
3693 fill_cmd(cmd, O_IP6, 0, 0);
3697 fill_cmd(cmd, O_IP4, 0, 0);
3701 fill_ext6hdr( cmd, *av );
3706 if (proto != IPPROTO_IPV6 )
3707 errx( EX_USAGE, "flow-id filter is active "
3708 "only for ipv6 protocol\n");
3709 fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
3714 fill_comment(cmd, av, cblen);
3719 if (av[0] && strpbrk(*av, "-,")) {
3720 if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
3721 errx(EX_DATAERR, "tagged: invalid tag"
3727 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
3728 TOK_TAGGED, rule_options);
3729 fill_cmd(cmd, O_TAGGED, 0, tag);
3735 NEED1("fib requires fib number");
3736 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
3740 fill_cmd(cmd, O_SOCKARG, 0, 0);
3744 ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
3748 if (!av[0] || !av[1])
3749 errx(EX_USAGE, "format: lookup argument tablenum");
3750 cmd->opcode = O_IP_DST_LOOKUP;
3751 cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
3752 i = match_token(rule_options, *av);
3753 for (j = 0; lookup_key[j] >= 0 ; j++) {
3754 if (i == lookup_key[j])
3757 if (lookup_key[j] <= 0)
3758 errx(EX_USAGE, "format: cannot lookup on %s", *av);
3759 __PAST_END(c->d, 1) = j; // i converted to option
3761 cmd->arg1 = strtoul(*av, &p, 0);
3763 errx(EX_USAGE, "format: lookup argument tablenum");
3769 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
3771 if (F_LEN(cmd) > 0) { /* prepare to advance */
3773 cmd = next_cmd(cmd, &cblen);
3779 * Now copy stuff into the rule.
3780 * If we have a keep-state option, the first instruction
3781 * must be a PROBE_STATE (which is generated here).
3782 * If we have a LOG option, it was stored as the first command,
3783 * and now must be moved to the top of the action part.
3785 dst = (ipfw_insn *)rule->cmd;
3788 * First thing to write into the command stream is the match probability.
3790 if (match_prob != 1) { /* 1 means always match */
3791 dst->opcode = O_PROB;
3793 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
3798 * generate O_PROBE_STATE if necessary
3800 if (have_state && have_state->opcode != O_CHECK_STATE) {
3801 fill_cmd(dst, O_PROBE_STATE, 0, 0);
3802 dst = next_cmd(dst, &rblen);
3805 /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
3806 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
3810 switch (src->opcode) {
3818 bcopy(src, dst, i * sizeof(uint32_t));
3824 * put back the have_state command as last opcode
3826 if (have_state && have_state->opcode != O_CHECK_STATE) {
3827 i = F_LEN(have_state);
3829 bcopy(have_state, dst, i * sizeof(uint32_t));
3833 * start action section
3835 rule->act_ofs = dst - rule->cmd;
3837 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
3839 i = F_LEN(have_log);
3841 bcopy(have_log, dst, i * sizeof(uint32_t));
3845 i = F_LEN(have_altq);
3847 bcopy(have_altq, dst, i * sizeof(uint32_t));
3851 i = F_LEN(have_tag);
3853 bcopy(have_tag, dst, i * sizeof(uint32_t));
3858 * copy all other actions
3860 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
3863 bcopy(src, dst, i * sizeof(uint32_t));
3867 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
3868 i = (char *)dst - (char *)rule;
3869 if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1)
3870 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
3872 show_ipfw(rule, 0, 0);
3876 * clear the counters or the log counters.
3879 ipfw_zero(int ac, char *av[], int optname /* 0 = IP_FW_ZERO, 1 = IP_FW_RESETLOG */)
3881 uint32_t arg, saved_arg;
3884 char const *name = optname ? "RESETLOG" : "ZERO";
3886 optname = optname ? IP_FW_RESETLOG : IP_FW_ZERO;
3891 /* clear all entries */
3892 if (do_cmd(optname, NULL, 0) < 0)
3893 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name);
3895 printf("%s.\n", optname == IP_FW_ZERO ?
3896 "Accounting cleared":"Logging counts reset");
3903 if (isdigit(**av)) {
3904 arg = strtonum(*av, 0, 0xffff, &errstr);
3907 "invalid rule number %s\n", *av);
3910 arg |= (1 << 24) | ((co.use_set - 1) << 16);
3913 if (do_cmd(optname, &arg, sizeof(arg))) {
3914 warn("rule %u: setsockopt(IP_FW_%s)",
3916 failed = EX_UNAVAILABLE;
3917 } else if (!co.do_quiet)
3918 printf("Entry %d %s.\n", saved_arg,
3919 optname == IP_FW_ZERO ?
3920 "cleared" : "logging count reset");
3922 errx(EX_USAGE, "invalid rule number ``%s''", *av);
3925 if (failed != EX_OK)
3930 ipfw_flush(int force)
3932 int cmd = co.do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
3934 if (!force && !co.do_quiet) { /* need to ask user */
3937 printf("Are you sure? [yn] ");
3940 c = toupper(getc(stdin));
3941 while (c != '\n' && getc(stdin) != '\n')
3943 return; /* and do not flush */
3944 } while (c != 'Y' && c != 'N');
3946 if (c == 'N') /* user said no */
3953 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
3955 uint32_t arg = ((co.use_set - 1) & 0xffff) | (1 << 24);
3956 if (do_cmd(IP_FW_DEL, &arg, sizeof(arg)) < 0)
3957 err(EX_UNAVAILABLE, "setsockopt(IP_FW_DEL)");
3958 } else if (do_cmd(cmd, NULL, 0) < 0)
3959 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
3960 co.do_pipe ? "DUMMYNET" : "FW");
3962 printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
3966 static void table_list(uint16_t num, int need_header);
3967 static void table_fill_xentry(char *arg, ipfw_table_xentry *xent);
3970 * This one handles all table-related commands
3971 * ipfw table N add addr[/masklen] [value]
3972 * ipfw table N delete addr[/masklen]
3973 * ipfw table {N | all} flush
3974 * ipfw table {N | all} list
3977 ipfw_table_handler(int ac, char *av[])
3979 ipfw_table_xentry xent;
3984 uint32_t tables_max;
3986 mask = 0; // XXX uninitialized ?
3987 len = sizeof(tables_max);
3988 if (sysctlbyname("net.inet.ip.fw.tables_max", &tables_max, &len,
3990 errx(1, "Can't determine maximum number of ipfw tables. "
3991 "Perhaps you forgot to load ipfw module?");
3993 memset(&xent, 0, sizeof(xent));
3996 if (ac && isdigit(**av)) {
3997 xent.tbl = atoi(*av);
4000 } else if (ac && _substrcmp(*av, "all") == 0) {
4005 errx(EX_USAGE, "table number or 'all' keyword required");
4006 if (xent.tbl >= tables_max)
4007 errx(EX_USAGE, "The table number exceeds the maximum allowed "
4008 "value (%d)", tables_max - 1);
4009 NEED1("table needs command");
4010 if (is_all && _substrcmp(*av, "list") != 0
4011 && _substrcmp(*av, "flush") != 0)
4012 errx(EX_USAGE, "table number required");
4014 if (_substrcmp(*av, "add") == 0 ||
4015 _substrcmp(*av, "delete") == 0) {
4016 do_add = **av == 'a';
4019 errx(EX_USAGE, "address required");
4021 table_fill_xentry(*av, &xent);
4026 /* isdigit is a bit of a hack here.. */
4027 if (strchr(*av, (int)'.') == NULL && isdigit(**av)) {
4028 xent.value = strtoul(*av, NULL, 0);
4030 if (lookup_host(*av, (struct in_addr *)&tval) == 0) {
4031 /* The value must be stored in host order *
4032 * so that the values < 65k can be distinguished */
4033 xent.value = ntohl(tval);
4035 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
4040 if (do_setcmd3(do_add ? IP_FW_TABLE_XADD : IP_FW_TABLE_XDEL,
4041 &xent, xent.len) < 0) {
4042 /* If running silent, don't bomb out on these errors. */
4043 if (!(co.do_quiet && (errno == (do_add ? EEXIST : ESRCH))))
4044 err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)",
4045 do_add ? "XADD" : "XDEL");
4046 /* In silent mode, react to a failed add by deleting */
4048 do_setcmd3(IP_FW_TABLE_XDEL, &xent, xent.len);
4049 if (do_setcmd3(IP_FW_TABLE_XADD, &xent, xent.len) < 0)
4051 "setsockopt(IP_FW_TABLE_XADD)");
4054 } else if (_substrcmp(*av, "flush") == 0) {
4055 a = is_all ? tables_max : (uint32_t)(xent.tbl + 1);
4057 if (do_cmd(IP_FW_TABLE_FLUSH, &xent.tbl,
4058 sizeof(xent.tbl)) < 0)
4059 err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)");
4060 } while (++xent.tbl < a);
4061 } else if (_substrcmp(*av, "list") == 0) {
4062 a = is_all ? tables_max : (uint32_t)(xent.tbl + 1);
4064 table_list(xent.tbl, is_all);
4065 } while (++xent.tbl < a);
4067 errx(EX_USAGE, "invalid table command %s", *av);
4071 table_fill_xentry(char *arg, ipfw_table_xentry *xent)
4073 int addrlen, mask, masklen, type;
4074 struct in6_addr *paddr;
4085 * Let's try to guess type by agrument.
4090 * 4) port, uid/gid or other u32 key (base 10 format)
4093 paddr = &xent->k.addr6;
4094 if (ishexnumber(*arg) != 0 || *arg == ':') {
4095 /* Remove / if exists */
4096 if ((p = strchr(arg, '/')) != NULL) {
4101 if (inet_pton(AF_INET, arg, paddr) == 1) {
4102 if (p != NULL && mask > 32)
4103 errx(EX_DATAERR, "bad IPv4 mask width: %s",
4106 type = IPFW_TABLE_CIDR;
4107 masklen = p ? mask : 32;
4108 addrlen = sizeof(struct in_addr);
4109 } else if (inet_pton(AF_INET6, arg, paddr) == 1) {
4110 if (IN6_IS_ADDR_V4COMPAT(paddr))
4112 "Use IPv4 instead of v4-compatible");
4113 if (p != NULL && mask > 128)
4114 errx(EX_DATAERR, "bad IPv6 mask width: %s",
4117 type = IPFW_TABLE_CIDR;
4118 masklen = p ? mask : 128;
4119 addrlen = sizeof(struct in6_addr);
4121 /* Port or any other key */
4122 key = strtol(arg, &p, 10);
4123 /* Skip non-base 10 entries like 'fa1' */
4125 pkey = (uint32_t *)paddr;
4127 type = IPFW_TABLE_CIDR;
4128 addrlen = sizeof(uint32_t);
4133 if (type == 0 && strchr(arg, '.') == NULL) {
4134 /* Assume interface name. Copy significant data only */
4135 mask = MIN(strlen(arg), IF_NAMESIZE - 1);
4136 memcpy(xent->k.iface, arg, mask);
4137 /* Set mask to exact match */
4138 masklen = 8 * IF_NAMESIZE;
4139 type = IPFW_TABLE_INTERFACE;
4140 addrlen = IF_NAMESIZE;
4144 if (lookup_host(arg, (struct in_addr *)paddr) != 0)
4145 errx(EX_NOHOST, "hostname ``%s'' unknown", arg);
4148 type = IPFW_TABLE_CIDR;
4149 addrlen = sizeof(struct in_addr);
4153 xent->masklen = masklen;
4154 xent->len = offsetof(ipfw_table_xentry, k) + addrlen;
4158 table_list(uint16_t num, int need_header)
4161 ipfw_table_xentry *xent;
4163 uint32_t *a, sz, tval;
4165 struct in6_addr *addr6;
4166 ip_fw3_opheader *op3;
4168 /* Prepend value with IP_FW3 header */
4169 l = sizeof(ip_fw3_opheader) + sizeof(uint32_t);
4171 /* Zero reserved fields */
4172 memset(op3, 0, sizeof(ip_fw3_opheader));
4173 a = (uint32_t *)(op3 + 1);
4175 op3->opcode = IP_FW_TABLE_XGETSIZE;
4176 if (do_cmd(IP_FW3, op3, (uintptr_t)&l) < 0)
4177 err(EX_OSERR, "getsockopt(IP_FW_TABLE_XGETSIZE)");
4179 /* If a is zero we have nothing to do, the table is empty. */
4184 tbl = safe_calloc(1, l);
4185 tbl->opheader.opcode = IP_FW_TABLE_XLIST;
4187 if (do_cmd(IP_FW3, tbl, (uintptr_t)&l) < 0)
4188 err(EX_OSERR, "getsockopt(IP_FW_TABLE_XLIST)");
4189 if (tbl->cnt && need_header)
4190 printf("---table(%d)---\n", tbl->tbl);
4191 sz = tbl->size - sizeof(ipfw_xtable);
4192 xent = &tbl->xent[0];
4194 switch (tbl->type) {
4195 case IPFW_TABLE_CIDR:
4196 /* IPv4 or IPv6 prefixes */
4198 addr6 = &xent->k.addr6;
4201 if (IN6_IS_ADDR_V4COMPAT(addr6)) {
4203 inet_ntop(AF_INET, &addr6->s6_addr32[3], tbuf, sizeof(tbuf));
4206 inet_ntop(AF_INET6, addr6, tbuf, sizeof(tbuf));
4209 if (co.do_value_as_ip) {
4211 printf("%s/%u %s\n", tbuf, xent->masklen,
4212 inet_ntoa(*(struct in_addr *)&tval));
4214 printf("%s/%u %u\n", tbuf, xent->masklen, tval);
4216 case IPFW_TABLE_INTERFACE:
4217 /* Interface names */
4219 if (co.do_value_as_ip) {
4221 printf("%s %s\n", xent->k.iface,
4222 inet_ntoa(*(struct in_addr *)&tval));
4224 printf("%s %u\n", xent->k.iface, tval);
4230 xent = (ipfw_table_xentry *)((char *)xent + xent->len);