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 f_ipdscp[] = {
171 { "af11", IPTOS_DSCP_AF11 >> 2 }, /* 001010 */
172 { "af12", IPTOS_DSCP_AF12 >> 2 }, /* 001100 */
173 { "af13", IPTOS_DSCP_AF13 >> 2 }, /* 001110 */
174 { "af21", IPTOS_DSCP_AF21 >> 2 }, /* 010010 */
175 { "af22", IPTOS_DSCP_AF22 >> 2 }, /* 010100 */
176 { "af23", IPTOS_DSCP_AF23 >> 2 }, /* 010110 */
177 { "af31", IPTOS_DSCP_AF31 >> 2 }, /* 011010 */
178 { "af32", IPTOS_DSCP_AF32 >> 2 }, /* 011100 */
179 { "af33", IPTOS_DSCP_AF33 >> 2 }, /* 011110 */
180 { "af41", IPTOS_DSCP_AF41 >> 2 }, /* 100010 */
181 { "af42", IPTOS_DSCP_AF42 >> 2 }, /* 100100 */
182 { "af43", IPTOS_DSCP_AF43 >> 2 }, /* 100110 */
183 { "be", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
184 { "ef", IPTOS_DSCP_EF >> 2 }, /* 101110 */
185 { "cs0", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
186 { "cs1", IPTOS_DSCP_CS1 >> 2 }, /* 001000 */
187 { "cs2", IPTOS_DSCP_CS2 >> 2 }, /* 010000 */
188 { "cs3", IPTOS_DSCP_CS3 >> 2 }, /* 011000 */
189 { "cs4", IPTOS_DSCP_CS4 >> 2 }, /* 100000 */
190 { "cs5", IPTOS_DSCP_CS5 >> 2 }, /* 101000 */
191 { "cs6", IPTOS_DSCP_CS6 >> 2 }, /* 110000 */
192 { "cs7", IPTOS_DSCP_CS7 >> 2 }, /* 100000 */
196 static struct _s_x limit_masks[] = {
197 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
198 {"src-addr", DYN_SRC_ADDR},
199 {"src-port", DYN_SRC_PORT},
200 {"dst-addr", DYN_DST_ADDR},
201 {"dst-port", DYN_DST_PORT},
206 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
207 * This is only used in this code.
209 #define IPPROTO_ETHERTYPE 0x1000
210 static struct _s_x ether_types[] = {
212 * Note, we cannot use "-:&/" in the names because they are field
213 * separators in the type specifications. Also, we use s = NULL as
214 * end-delimiter, because a type of 0 can be legal.
227 { "pppoe_disc", 0x8863 },
228 { "pppoe_sess", 0x8864 },
229 { "ipx_8022", 0x00E0 },
230 { "ipx_8023", 0x0000 },
231 { "ipx_ii", 0x8137 },
232 { "ipx_snap", 0x8137 },
239 static struct _s_x rule_actions[] = {
240 { "accept", TOK_ACCEPT },
241 { "pass", TOK_ACCEPT },
242 { "allow", TOK_ACCEPT },
243 { "permit", TOK_ACCEPT },
244 { "count", TOK_COUNT },
245 { "pipe", TOK_PIPE },
246 { "queue", TOK_QUEUE },
247 { "divert", TOK_DIVERT },
249 { "netgraph", TOK_NETGRAPH },
250 { "ngtee", TOK_NGTEE },
251 { "fwd", TOK_FORWARD },
252 { "forward", TOK_FORWARD },
253 { "skipto", TOK_SKIPTO },
254 { "deny", TOK_DENY },
255 { "drop", TOK_DENY },
256 { "reject", TOK_REJECT },
257 { "reset6", TOK_RESET6 },
258 { "reset", TOK_RESET },
259 { "unreach6", TOK_UNREACH6 },
260 { "unreach", TOK_UNREACH },
261 { "check-state", TOK_CHECKSTATE },
262 { "//", TOK_COMMENT },
264 { "reass", TOK_REASS },
265 { "setfib", TOK_SETFIB },
266 { "setdscp", TOK_SETDSCP },
267 { "call", TOK_CALL },
268 { "return", TOK_RETURN },
269 { NULL, 0 } /* terminator */
272 static struct _s_x rule_action_params[] = {
273 { "altq", TOK_ALTQ },
276 { "untag", TOK_UNTAG },
277 { NULL, 0 } /* terminator */
281 * The 'lookup' instruction accepts one of the following arguments.
282 * -1 is a terminator for the list.
283 * Arguments are passed as v[1] in O_DST_LOOKUP options.
285 static int lookup_key[] = {
286 TOK_DSTIP, TOK_SRCIP, TOK_DSTPORT, TOK_SRCPORT,
287 TOK_UID, TOK_JAIL, TOK_DSCP, -1 };
289 static struct _s_x rule_options[] = {
290 { "tagged", TOK_TAGGED },
293 { "jail", TOK_JAIL },
295 { "limit", TOK_LIMIT },
296 { "keep-state", TOK_KEEPSTATE },
297 { "bridged", TOK_LAYER2 },
298 { "layer2", TOK_LAYER2 },
300 { "diverted", TOK_DIVERTED },
301 { "diverted-loopback", TOK_DIVERTEDLOOPBACK },
302 { "diverted-output", TOK_DIVERTEDOUTPUT },
303 { "xmit", TOK_XMIT },
304 { "recv", TOK_RECV },
306 { "fragment", TOK_FRAG },
307 { "frag", TOK_FRAG },
309 { "ipoptions", TOK_IPOPTS },
310 { "ipopts", TOK_IPOPTS },
311 { "iplen", TOK_IPLEN },
312 { "ipid", TOK_IPID },
313 { "ipprecedence", TOK_IPPRECEDENCE },
314 { "dscp", TOK_DSCP },
315 { "iptos", TOK_IPTOS },
316 { "ipttl", TOK_IPTTL },
317 { "ipversion", TOK_IPVER },
318 { "ipver", TOK_IPVER },
319 { "estab", TOK_ESTAB },
320 { "established", TOK_ESTAB },
321 { "setup", TOK_SETUP },
322 { "sockarg", TOK_SOCKARG },
323 { "tcpdatalen", TOK_TCPDATALEN },
324 { "tcpflags", TOK_TCPFLAGS },
325 { "tcpflgs", TOK_TCPFLAGS },
326 { "tcpoptions", TOK_TCPOPTS },
327 { "tcpopts", TOK_TCPOPTS },
328 { "tcpseq", TOK_TCPSEQ },
329 { "tcpack", TOK_TCPACK },
330 { "tcpwin", TOK_TCPWIN },
331 { "icmptype", TOK_ICMPTYPES },
332 { "icmptypes", TOK_ICMPTYPES },
333 { "dst-ip", TOK_DSTIP },
334 { "src-ip", TOK_SRCIP },
335 { "dst-port", TOK_DSTPORT },
336 { "src-port", TOK_SRCPORT },
337 { "proto", TOK_PROTO },
340 { "mac-type", TOK_MACTYPE },
341 { "verrevpath", TOK_VERREVPATH },
342 { "versrcreach", TOK_VERSRCREACH },
343 { "antispoof", TOK_ANTISPOOF },
344 { "ipsec", TOK_IPSEC },
345 { "icmp6type", TOK_ICMP6TYPES },
346 { "icmp6types", TOK_ICMP6TYPES },
347 { "ext6hdr", TOK_EXT6HDR},
348 { "flow-id", TOK_FLOWID},
353 { "dst-ipv6", TOK_DSTIP6},
354 { "dst-ip6", TOK_DSTIP6},
355 { "src-ipv6", TOK_SRCIP6},
356 { "src-ip6", TOK_SRCIP6},
357 { "lookup", TOK_LOOKUP},
358 { "//", TOK_COMMENT },
360 { "not", TOK_NOT }, /* pseudo option */
361 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
362 { "or", TOK_OR }, /* pseudo option */
363 { "|", /* escape */ TOK_OR }, /* pseudo option */
364 { "{", TOK_STARTBRACE }, /* pseudo option */
365 { "(", TOK_STARTBRACE }, /* pseudo option */
366 { "}", TOK_ENDBRACE }, /* pseudo option */
367 { ")", TOK_ENDBRACE }, /* pseudo option */
368 { NULL, 0 } /* terminator */
372 * Helper routine to print a possibly unaligned uint64_t on
373 * various platform. If width > 0, print the value with
374 * the desired width, followed by a space;
375 * otherwise, return the required width.
378 pr_u64(uint64_t *pd, int width)
381 #define U64_FMT "I64"
383 #define U64_FMT "llu"
386 unsigned long long d;
388 bcopy (pd, &u, sizeof(u));
391 printf("%*" U64_FMT " ", width, d) :
392 snprintf(NULL, 0, "%" U64_FMT, d) ;
397 safe_calloc(size_t number, size_t size)
399 void *ret = calloc(number, size);
402 err(EX_OSERR, "calloc");
407 safe_realloc(void *ptr, size_t size)
409 void *ret = realloc(ptr, size);
412 err(EX_OSERR, "realloc");
417 * conditionally runs the command.
418 * Selected options or negative -> getsockopt
421 do_cmd(int optname, void *optval, uintptr_t optlen)
428 if (ipfw_socket == -1)
429 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
431 err(EX_UNAVAILABLE, "socket");
433 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
434 optname == IP_FW_ADD || optname == IP_FW3 ||
435 optname == IP_FW_NAT_GET_CONFIG ||
437 optname == IP_FW_NAT_GET_LOG) {
440 i = getsockopt(ipfw_socket, IPPROTO_IP, optname, optval,
441 (socklen_t *)optlen);
443 i = setsockopt(ipfw_socket, IPPROTO_IP, optname, optval, optlen);
449 * do_setcmd3 - pass ipfw control cmd to kernel
450 * @optname: option name
451 * @optval: pointer to option data
452 * @optlen: option length
454 * Function encapsulates option value in IP_FW3 socket option
455 * and calls setsockopt().
456 * Function returns 0 on success or -1 otherwise.
459 do_setcmd3(int optname, void *optval, socklen_t optlen)
462 ip_fw3_opheader *op3;
467 if (ipfw_socket == -1)
468 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
470 err(EX_UNAVAILABLE, "socket");
472 len = sizeof(ip_fw3_opheader) + optlen;
474 /* Zero reserved fields */
475 memset(op3, 0, sizeof(ip_fw3_opheader));
476 memcpy(op3 + 1, optval, optlen);
477 op3->opcode = optname;
479 return setsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, len);
483 * match_token takes a table and a string, returns the value associated
484 * with the string (-1 in case of failure).
487 match_token(struct _s_x *table, char *string)
490 uint i = strlen(string);
492 for (pt = table ; i && pt->s != NULL ; pt++)
493 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
499 * match_value takes a table and a value, returns the string associated
500 * with the value (NULL in case of failure).
503 match_value(struct _s_x *p, int value)
505 for (; p->s != NULL; p++)
512 * _substrcmp takes two strings and returns 1 if they do not match,
513 * and 0 if they match exactly or the first string is a sub-string
514 * of the second. A warning is printed to stderr in the case that the
515 * first string is a sub-string of the second.
517 * This function will be removed in the future through the usual
518 * deprecation process.
521 _substrcmp(const char *str1, const char* str2)
524 if (strncmp(str1, str2, strlen(str1)) != 0)
527 if (strlen(str1) != strlen(str2))
528 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
534 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
535 * and 0 if they match exactly or the second string is a sub-string
536 * of the first. A warning is printed to stderr in the case that the
537 * first string does not match the third.
539 * This function exists to warn about the bizzare construction
540 * strncmp(str, "by", 2) which is used to allow people to use a shotcut
541 * for "bytes". The problem is that in addition to accepting "by",
542 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
543 * other string beginning with "by".
545 * This function will be removed in the future through the usual
546 * deprecation process.
549 _substrcmp2(const char *str1, const char* str2, const char* str3)
552 if (strncmp(str1, str2, strlen(str2)) != 0)
555 if (strcmp(str1, str3) != 0)
556 warnx("DEPRECATED: '%s' matched '%s'",
562 * prints one port, symbolic or numeric
565 print_port(int proto, uint16_t port)
568 if (proto == IPPROTO_ETHERTYPE) {
571 if (co.do_resolv && (s = match_value(ether_types, port)) )
574 printf("0x%04x", port);
576 struct servent *se = NULL;
578 struct protoent *pe = getprotobynumber(proto);
580 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
583 printf("%s", se->s_name);
589 static struct _s_x _port_name[] = {
590 {"dst-port", O_IP_DSTPORT},
591 {"src-port", O_IP_SRCPORT},
595 {"mac-type", O_MAC_TYPE},
596 {"tcpdatalen", O_TCPDATALEN},
597 {"tcpwin", O_TCPWIN},
598 {"tagged", O_TAGGED},
603 * Print the values in a list 16-bit items of the types above.
604 * XXX todo: add support for mask.
607 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode)
609 uint16_t *p = cmd->ports;
614 sep = match_value(_port_name, opcode);
620 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
622 print_port(proto, p[0]);
625 print_port(proto, p[1]);
632 * Like strtol, but also translates service names into port numbers
633 * for some protocols.
635 * proto == -1 disables the protocol check;
636 * proto == IPPROTO_ETHERTYPE looks up an internal table
637 * proto == <some value in /etc/protocols> matches the values there.
638 * Returns *end == s in case the parameter is not found.
641 strtoport(char *s, char **end, int base, int proto)
647 *end = s; /* default - not found */
649 return 0; /* not found */
652 return strtol(s, end, base);
655 * find separator. '\\' escapes the next char.
657 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
658 if (*s1 == '\\' && s1[1] != '\0')
661 buf = safe_calloc(s1 - s + 1, 1);
664 * copy into a buffer skipping backslashes
666 for (p = s, i = 0; p != s1 ; p++)
671 if (proto == IPPROTO_ETHERTYPE) {
672 i = match_token(ether_types, buf);
674 if (i != -1) { /* found */
679 struct protoent *pe = NULL;
683 pe = getprotobynumber(proto);
685 se = getservbyname(buf, pe ? pe->p_name : NULL);
689 return ntohs(se->s_port);
692 return 0; /* not found */
696 * Fill the body of the command with the list of port ranges.
699 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
701 uint16_t a, b, *p = cmd->ports;
706 a = strtoport(av, &s, 0, proto);
707 if (s == av) /* empty or invalid argument */
710 CHECK_LENGTH(cblen, i + 2);
713 case '-': /* a range */
715 b = strtoport(av, &s, 0, proto);
716 /* Reject expressions like '1-abc' or '1-2-3'. */
717 if (s == av || (*s != ',' && *s != '\0'))
722 case ',': /* comma separated list */
727 warnx("port list: invalid separator <%c> in <%s>",
737 if (i + 1 > F_LEN_MASK)
738 errx(EX_DATAERR, "too many ports/ranges\n");
739 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
745 * Fill the body of the command with the list of DiffServ codepoints.
748 fill_dscp(ipfw_insn *cmd, char *av, int cblen)
750 uint32_t *low, *high;
754 cmd->opcode = O_DSCP;
755 cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
759 low = (uint32_t *)(cmd + 1);
772 if ((code = match_token(f_ipdscp, s)) == -1)
773 errx(EX_DATAERR, "Unknown DSCP code");
775 code = strtoul(s, NULL, 10);
776 if (code < 0 || code > 63)
777 errx(EX_DATAERR, "Invalid DSCP value");
781 *high |= 1 << (code - 32);
789 static struct _s_x icmpcodes[] = {
790 { "net", ICMP_UNREACH_NET },
791 { "host", ICMP_UNREACH_HOST },
792 { "protocol", ICMP_UNREACH_PROTOCOL },
793 { "port", ICMP_UNREACH_PORT },
794 { "needfrag", ICMP_UNREACH_NEEDFRAG },
795 { "srcfail", ICMP_UNREACH_SRCFAIL },
796 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
797 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
798 { "isolated", ICMP_UNREACH_ISOLATED },
799 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
800 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
801 { "tosnet", ICMP_UNREACH_TOSNET },
802 { "toshost", ICMP_UNREACH_TOSHOST },
803 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
804 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
805 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
810 fill_reject_code(u_short *codep, char *str)
815 val = strtoul(str, &s, 0);
816 if (s == str || *s != '\0' || val >= 0x100)
817 val = match_token(icmpcodes, str);
819 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
825 print_reject_code(uint16_t code)
827 char const *s = match_value(icmpcodes, code);
830 printf("unreach %s", s);
832 printf("unreach %u", code);
836 * Returns the number of bits set (from left) in a contiguous bitmask,
837 * or -1 if the mask is not contiguous.
838 * XXX this needs a proper fix.
839 * This effectively works on masks in big-endian (network) format.
840 * when compiled on little endian architectures.
842 * First bit is bit 7 of the first byte -- note, for MAC addresses,
843 * the first bit on the wire is bit 0 of the first byte.
844 * len is the max length in bits.
847 contigmask(uint8_t *p, int len)
851 for (i=0; i<len ; i++)
852 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
854 for (n=i+1; n < len; n++)
855 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
856 return -1; /* mask not contiguous */
861 * print flags set/clear in the two bitmasks passed as parameters.
862 * There is a specialized check for f_tcpflags.
865 print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list)
867 char const *comma = "";
869 uint8_t set = cmd->arg1 & 0xff;
870 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
872 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
877 printf(" %s ", name);
878 for (i=0; list[i].x != 0; i++) {
879 if (set & list[i].x) {
881 printf("%s%s", comma, list[i].s);
884 if (clear & list[i].x) {
886 printf("%s!%s", comma, list[i].s);
893 * Print the ip address contained in a command.
896 print_ip(ipfw_insn_ip *cmd, char const *s)
898 struct hostent *he = NULL;
899 uint32_t len = F_LEN((ipfw_insn *)cmd);
900 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
902 if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
904 const char *arg = "<invalid>";
906 if (d < sizeof(lookup_key)/sizeof(lookup_key[0]))
907 arg = match_value(rule_options, lookup_key[d]);
908 printf("%s lookup %s %d", cmd->o.len & F_NOT ? " not": "",
912 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
914 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
918 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
919 cmd->o.opcode == O_IP_DST_LOOKUP) {
920 printf("table(%u", ((ipfw_insn *)cmd)->arg1);
921 if (len == F_INSN_SIZE(ipfw_insn_u32))
926 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
927 uint32_t x, *map = (uint32_t *)&(cmd->mask);
933 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
934 printf("%s/%d", inet_ntoa(cmd->addr),
935 contigmask((uint8_t *)&x, 32));
936 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
937 x &= 0xff; /* base */
939 * Print bits and ranges.
940 * Locate first bit set (i), then locate first bit unset (j).
941 * If we have 3+ consecutive bits set, then print them as a
942 * range, otherwise only print the initial bit and rescan.
944 for (i=0; i < cmd->o.arg1; i++)
945 if (map[i/32] & (1<<(i & 31))) {
946 for (j=i+1; j < cmd->o.arg1; j++)
947 if (!(map[ j/32] & (1<<(j & 31))))
949 printf("%c%d", comma, i+x);
950 if (j>i+2) { /* range has at least 3 elements */
951 printf("-%d", j-1+x);
960 * len == 2 indicates a single IP, whereas lists of 1 or more
961 * addr/mask pairs have len = (2n+1). We convert len to n so we
962 * use that to count the number of entries.
964 for (len = len / 2; len > 0; len--, a += 2) {
965 int mb = /* mask length */
966 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
967 32 : contigmask((uint8_t *)&(a[1]), 32);
968 if (mb == 32 && co.do_resolv)
969 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
970 if (he != NULL) /* resolved to name */
971 printf("%s", he->h_name);
972 else if (mb == 0) /* any */
974 else { /* numeric IP followed by some kind of mask */
975 printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) );
977 printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) );
987 * prints a MAC address/mask pair
990 print_mac(uint8_t *addr, uint8_t *mask)
992 int l = contigmask(mask, 48);
997 printf(" %02x:%02x:%02x:%02x:%02x:%02x",
998 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1000 printf("&%02x:%02x:%02x:%02x:%02x:%02x",
1001 mask[0], mask[1], mask[2],
1002 mask[3], mask[4], mask[5]);
1009 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1018 type = strtoul(av, &av, 0);
1020 if (*av != ',' && *av != '\0')
1021 errx(EX_DATAERR, "invalid ICMP type");
1024 errx(EX_DATAERR, "ICMP type out of range");
1026 cmd->d[0] |= 1 << type;
1028 cmd->o.opcode = O_ICMPTYPE;
1029 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1033 print_icmptypes(ipfw_insn_u32 *cmd)
1038 printf(" icmptypes");
1039 for (i = 0; i < 32; i++) {
1040 if ( (cmd->d[0] & (1 << (i))) == 0)
1042 printf("%c%d", sep, i);
1048 print_dscp(ipfw_insn_u32 *cmd)
1060 if (*v & (1 << i)) {
1061 if ((code = match_value(f_ipdscp, i)) != NULL)
1062 printf("%c%s", sep, code);
1064 printf("%c%d", sep, i);
1068 if ((++i % 32) == 0)
1074 * show_ipfw() prints the body of an ipfw rule.
1075 * Because the standard rule has at least proto src_ip dst_ip, we use
1076 * a helper function to produce these entries if not provided explicitly.
1077 * The first argument is the list of fields we have, the second is
1078 * the list of fields we want to be printed.
1080 * Special cases if we have provided a MAC header:
1081 * + if the rule does not contain IP addresses/ports, do not print them;
1082 * + if the rule does not contain an IP proto, print "all" instead of "ip";
1084 * Once we have 'have_options', IP header fields are printed as options.
1086 #define HAVE_PROTO 0x0001
1087 #define HAVE_SRCIP 0x0002
1088 #define HAVE_DSTIP 0x0004
1089 #define HAVE_PROTO4 0x0008
1090 #define HAVE_PROTO6 0x0010
1091 #define HAVE_IP 0x0100
1092 #define HAVE_OPTIONS 0x8000
1095 show_prerequisites(int *flags, int want, int cmd __unused)
1097 if (co.comment_only)
1099 if ( (*flags & HAVE_IP) == HAVE_IP)
1100 *flags |= HAVE_OPTIONS;
1102 if ( !(*flags & HAVE_OPTIONS)) {
1103 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) {
1104 if ( (*flags & HAVE_PROTO4))
1106 else if ( (*flags & HAVE_PROTO6))
1111 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
1112 printf(" from any");
1113 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
1120 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth)
1122 static int twidth = 0;
1124 ipfw_insn *cmd, *tagptr = NULL;
1125 const char *comment = NULL; /* ptr to comment if we have one */
1126 int proto = 0; /* default */
1127 int flags = 0; /* prerequisites */
1128 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
1129 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
1130 int or_block = 0; /* we are in an or block */
1131 uint32_t set_disable;
1133 bcopy(&rule->next_rule, &set_disable, sizeof(set_disable));
1135 if (set_disable & (1 << rule->set)) { /* disabled */
1139 printf("# DISABLED ");
1141 printf("%05u ", rule->rulenum);
1143 if (pcwidth > 0 || bcwidth > 0) {
1144 pr_u64(&rule->pcnt, pcwidth);
1145 pr_u64(&rule->bcnt, bcwidth);
1148 if (co.do_time == 2)
1149 printf("%10u ", rule->timestamp);
1150 else if (co.do_time == 1) {
1152 time_t t = (time_t)0;
1155 strcpy(timestr, ctime(&t));
1156 *strchr(timestr, '\n') = '\0';
1157 twidth = strlen(timestr);
1159 if (rule->timestamp) {
1160 t = _long_to_time(rule->timestamp);
1162 strcpy(timestr, ctime(&t));
1163 *strchr(timestr, '\n') = '\0';
1164 printf("%s ", timestr);
1166 printf("%*s", twidth, " ");
1171 printf("set %d ", rule->set);
1174 * print the optional "match probability"
1176 if (rule->cmd_len > 0) {
1178 if (cmd->opcode == O_PROB) {
1179 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1180 double d = 1.0 * p->d[0];
1182 d = (d / 0x7fffffff);
1183 printf("prob %f ", d);
1188 * first print actions
1190 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1191 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1192 switch(cmd->opcode) {
1194 printf("check-state");
1195 /* avoid printing anything else */
1196 flags = HAVE_PROTO | HAVE_SRCIP |
1197 HAVE_DSTIP | HAVE_IP;
1213 if (cmd->arg1 == ICMP_REJECT_RST)
1215 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1218 print_reject_code(cmd->arg1);
1222 if (cmd->arg1 == ICMP6_UNREACH_RST)
1225 print_unreach6_code(cmd->arg1);
1229 PRINT_UINT_ARG("skipto ", cmd->arg1);
1233 PRINT_UINT_ARG("pipe ", cmd->arg1);
1237 PRINT_UINT_ARG("queue ", cmd->arg1);
1241 PRINT_UINT_ARG("divert ", cmd->arg1);
1245 PRINT_UINT_ARG("tee ", cmd->arg1);
1249 PRINT_UINT_ARG("netgraph ", cmd->arg1);
1253 PRINT_UINT_ARG("ngtee ", cmd->arg1);
1258 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1260 if (s->sa.sin_addr.s_addr == INADDR_ANY) {
1261 printf("fwd tablearg");
1263 printf("fwd %s", inet_ntoa(s->sa.sin_addr));
1266 printf(",%d", s->sa.sin_port);
1272 char buf[4 + INET6_ADDRSTRLEN + 1];
1273 ipfw_insn_sa6 *s = (ipfw_insn_sa6 *)cmd;
1275 printf("fwd %s", inet_ntop(AF_INET6, &s->sa.sin6_addr,
1277 if (s->sa.sin6_port)
1278 printf(",%d", s->sa.sin6_port);
1282 case O_LOG: /* O_LOG is printed last */
1283 logptr = (ipfw_insn_log *)cmd;
1286 case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1287 altqptr = (ipfw_insn_altq *)cmd;
1296 PRINT_UINT_ARG("nat ", cmd->arg1);
1298 printf("nat global");
1302 PRINT_UINT_ARG("setfib ", cmd->arg1);
1309 if ((code = match_value(f_ipdscp, cmd->arg1)) != NULL)
1310 printf("setdscp %s", code);
1312 PRINT_UINT_ARG("setdscp ", cmd->arg1);
1321 if (cmd->len & F_NOT)
1324 PRINT_UINT_ARG("call ", cmd->arg1);
1328 printf("** unrecognized action %d len %d ",
1329 cmd->opcode, cmd->len);
1333 if (logptr->max_log > 0)
1334 printf(" log logamount %d", logptr->max_log);
1340 print_altq_cmd(altqptr);
1344 if (tagptr->len & F_NOT)
1345 PRINT_UINT_ARG(" untag ", tagptr->arg1);
1347 PRINT_UINT_ARG(" tag ", tagptr->arg1);
1351 * then print the body.
1353 for (l = rule->act_ofs, cmd = rule->cmd ;
1354 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1355 if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1357 if (cmd->opcode == O_IP4) {
1358 flags |= HAVE_PROTO4;
1360 } else if (cmd->opcode == O_IP6) {
1361 flags |= HAVE_PROTO6;
1365 if (rule->_pad & 1) { /* empty rules before options */
1366 if (!co.do_compact) {
1367 show_prerequisites(&flags, HAVE_PROTO, 0);
1368 printf(" from any to any");
1370 flags |= HAVE_IP | HAVE_OPTIONS | HAVE_PROTO |
1371 HAVE_SRCIP | HAVE_DSTIP;
1374 if (co.comment_only)
1377 for (l = rule->act_ofs, cmd = rule->cmd ;
1378 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1380 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1382 if (co.comment_only) {
1383 if (cmd->opcode != O_NOP)
1385 printf(" // %s\n", (char *)(cmd + 1));
1389 show_prerequisites(&flags, 0, cmd->opcode);
1391 switch(cmd->opcode) {
1393 break; /* done already */
1396 break; /* no need to print anything here */
1399 case O_IP_SRC_LOOKUP:
1403 show_prerequisites(&flags, HAVE_PROTO, 0);
1404 if (!(flags & HAVE_SRCIP))
1406 if ((cmd->len & F_OR) && !or_block)
1408 print_ip((ipfw_insn_ip *)cmd,
1409 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1410 flags |= HAVE_SRCIP;
1414 case O_IP_DST_LOOKUP:
1418 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1419 if (!(flags & HAVE_DSTIP))
1421 if ((cmd->len & F_OR) && !or_block)
1423 print_ip((ipfw_insn_ip *)cmd,
1424 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1425 flags |= HAVE_DSTIP;
1429 case O_IP6_SRC_MASK:
1431 show_prerequisites(&flags, HAVE_PROTO, 0);
1432 if (!(flags & HAVE_SRCIP))
1434 if ((cmd->len & F_OR) && !or_block)
1436 print_ip6((ipfw_insn_ip6 *)cmd,
1437 (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1438 flags |= HAVE_SRCIP | HAVE_PROTO;
1442 case O_IP6_DST_MASK:
1444 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1445 if (!(flags & HAVE_DSTIP))
1447 if ((cmd->len & F_OR) && !or_block)
1449 print_ip6((ipfw_insn_ip6 *)cmd,
1450 (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1451 flags |= HAVE_DSTIP;
1455 print_flow6id( (ipfw_insn_u32 *) cmd );
1456 flags |= HAVE_OPTIONS;
1460 show_prerequisites(&flags,
1461 HAVE_PROTO | HAVE_SRCIP |
1462 HAVE_DSTIP | HAVE_IP, 0);
1464 if (flags & HAVE_DSTIP)
1466 show_prerequisites(&flags,
1467 HAVE_PROTO | HAVE_SRCIP, 0);
1468 if ((cmd->len & F_OR) && !or_block)
1470 if (cmd->len & F_NOT)
1472 print_newports((ipfw_insn_u16 *)cmd, proto,
1473 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1477 struct protoent *pe = NULL;
1479 if ((cmd->len & F_OR) && !or_block)
1481 if (cmd->len & F_NOT)
1484 pe = getprotobynumber(cmd->arg1);
1485 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1486 !(flags & HAVE_PROTO))
1487 show_prerequisites(&flags,
1488 HAVE_PROTO | HAVE_IP | HAVE_SRCIP |
1489 HAVE_DSTIP | HAVE_OPTIONS, 0);
1490 if (flags & HAVE_OPTIONS)
1493 printf(" %s", pe->p_name);
1495 printf(" %u", cmd->arg1);
1497 flags |= HAVE_PROTO;
1500 default: /*options ... */
1501 if (!(cmd->len & (F_OR|F_NOT)))
1502 if (((cmd->opcode == O_IP6) &&
1503 (flags & HAVE_PROTO6)) ||
1504 ((cmd->opcode == O_IP4) &&
1505 (flags & HAVE_PROTO4)))
1507 show_prerequisites(&flags, HAVE_PROTO | HAVE_SRCIP |
1508 HAVE_DSTIP | HAVE_IP | HAVE_OPTIONS, 0);
1509 if ((cmd->len & F_OR) && !or_block)
1511 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1513 switch(cmd->opcode) {
1515 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1518 print_mac(m->addr, m->mask);
1519 print_mac(m->addr + 6, m->mask + 6);
1524 print_newports((ipfw_insn_u16 *)cmd,
1525 IPPROTO_ETHERTYPE, cmd->opcode);
1534 printf(" fib %u", cmd->arg1 );
1541 printf(cmd->len & F_NOT ? " out" : " in");
1545 switch (cmd->arg1) {
1547 printf(" diverted");
1550 printf(" diverted-loopback");
1553 printf(" diverted-output");
1556 printf(" diverted-?<%u>", cmd->arg1);
1569 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1571 if (cmd->opcode == O_XMIT)
1573 else if (cmd->opcode == O_RECV)
1575 else /* if (cmd->opcode == O_VIA) */
1577 if (cmdif->name[0] == '\0')
1579 inet_ntoa(cmdif->p.ip));
1580 else if (cmdif->name[0] == '\1') /* interface table */
1581 printf(" %s table(%d)", s, cmdif->p.glob);
1583 printf(" %s %s", s, cmdif->name);
1588 if (F_LEN(cmd) == 1)
1589 printf(" ipid %u", cmd->arg1 );
1591 print_newports((ipfw_insn_u16 *)cmd, 0,
1596 if (F_LEN(cmd) == 1)
1597 printf(" ipttl %u", cmd->arg1 );
1599 print_newports((ipfw_insn_u16 *)cmd, 0,
1604 printf(" ipver %u", cmd->arg1 );
1607 case O_IPPRECEDENCE:
1608 printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1612 print_dscp((ipfw_insn_u32 *)cmd);
1616 if (F_LEN(cmd) == 1)
1617 printf(" iplen %u", cmd->arg1 );
1619 print_newports((ipfw_insn_u16 *)cmd, 0,
1624 print_flags("ipoptions", cmd, f_ipopts);
1628 print_flags("iptos", cmd, f_iptos);
1632 print_icmptypes((ipfw_insn_u32 *)cmd);
1636 printf(" established");
1640 if (F_LEN(cmd) == 1)
1641 printf(" tcpdatalen %u", cmd->arg1 );
1643 print_newports((ipfw_insn_u16 *)cmd, 0,
1648 print_flags("tcpflags", cmd, f_tcpflags);
1652 print_flags("tcpoptions", cmd, f_tcpopts);
1656 if (F_LEN(cmd) == 1)
1657 printf(" tcpwin %u", cmd->arg1);
1659 print_newports((ipfw_insn_u16 *)cmd, 0,
1664 printf(" tcpack %d", ntohl(cmd32->d[0]));
1668 printf(" tcpseq %d", ntohl(cmd32->d[0]));
1673 struct passwd *pwd = getpwuid(cmd32->d[0]);
1676 printf(" uid %s", pwd->pw_name);
1678 printf(" uid %u", cmd32->d[0]);
1684 struct group *grp = getgrgid(cmd32->d[0]);
1687 printf(" gid %s", grp->gr_name);
1689 printf(" gid %u", cmd32->d[0]);
1694 printf(" jail %d", cmd32->d[0]);
1698 printf(" verrevpath");
1702 printf(" versrcreach");
1706 printf(" antispoof");
1714 comment = (char *)(cmd + 1);
1718 printf(" keep-state");
1722 struct _s_x *p = limit_masks;
1723 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1724 uint8_t x = c->limit_mask;
1725 char const *comma = " ";
1728 for (; p->x != 0 ; p++)
1729 if ((x & p->x) == p->x) {
1731 printf("%s%s", comma, p->s);
1734 PRINT_UINT_ARG(" ", c->conn_limit);
1747 print_icmp6types((ipfw_insn_u32 *)cmd);
1751 print_ext6hdr( (ipfw_insn *) cmd );
1755 if (F_LEN(cmd) == 1)
1756 PRINT_UINT_ARG(" tagged ", cmd->arg1);
1758 print_newports((ipfw_insn_u16 *)cmd, 0,
1763 printf(" [opcode %d len %d]",
1764 cmd->opcode, cmd->len);
1767 if (cmd->len & F_OR) {
1770 } else if (or_block) {
1775 show_prerequisites(&flags, HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP
1778 printf(" // %s", comment);
1783 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth)
1785 struct protoent *pe;
1788 char buf[INET6_ADDRSTRLEN];
1790 if (!co.do_expired) {
1791 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1794 bcopy(&d->rule, &rulenum, sizeof(rulenum));
1795 printf("%05d", rulenum);
1796 if (pcwidth > 0 || bcwidth > 0) {
1798 pr_u64(&d->pcnt, pcwidth);
1799 pr_u64(&d->bcnt, bcwidth);
1800 printf("(%ds)", d->expire);
1802 switch (d->dyn_type) {
1803 case O_LIMIT_PARENT:
1804 printf(" PARENT %d", d->count);
1809 case O_KEEP_STATE: /* bidir, no mask */
1814 if ((pe = getprotobynumber(d->id.proto)) != NULL)
1815 printf(" %s", pe->p_name);
1817 printf(" proto %u", d->id.proto);
1819 if (d->id.addr_type == 4) {
1820 a.s_addr = htonl(d->id.src_ip);
1821 printf(" %s %d", inet_ntoa(a), d->id.src_port);
1823 a.s_addr = htonl(d->id.dst_ip);
1824 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
1825 } else if (d->id.addr_type == 6) {
1826 printf(" %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
1827 sizeof(buf)), d->id.src_port);
1828 printf(" <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6, buf,
1829 sizeof(buf)), d->id.dst_port);
1831 printf(" UNKNOWN <-> UNKNOWN\n");
1837 * This one handles all set-related commands
1838 * ipfw set { show | enable | disable }
1840 * ipfw set move X to Y
1841 * ipfw set move rule X to Y
1844 ipfw_sets_handler(char *av[])
1846 uint32_t set_disable, masks[2];
1849 uint8_t cmd, new_set;
1854 errx(EX_USAGE, "set needs command");
1855 if (_substrcmp(*av, "show") == 0) {
1860 nalloc = nbytes = sizeof(struct ip_fw);
1861 while (nbytes >= nalloc) {
1864 nalloc = nalloc * 2 + 200;
1866 data = safe_calloc(1, nbytes);
1867 if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0)
1868 err(EX_OSERR, "getsockopt(IP_FW_GET)");
1871 bcopy(&((struct ip_fw *)data)->next_rule,
1872 &set_disable, sizeof(set_disable));
1874 for (i = 0, msg = "disable" ; i < RESVD_SET; i++)
1875 if ((set_disable & (1<<i))) {
1876 printf("%s %d", msg, i);
1879 msg = (set_disable) ? " enable" : "enable";
1880 for (i = 0; i < RESVD_SET; i++)
1881 if (!(set_disable & (1<<i))) {
1882 printf("%s %d", msg, i);
1886 } else if (_substrcmp(*av, "swap") == 0) {
1888 if ( av[0] == NULL || av[1] == NULL )
1889 errx(EX_USAGE, "set swap needs 2 set numbers\n");
1890 rulenum = atoi(av[0]);
1891 new_set = atoi(av[1]);
1892 if (!isdigit(*(av[0])) || rulenum > RESVD_SET)
1893 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
1894 if (!isdigit(*(av[1])) || new_set > RESVD_SET)
1895 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
1896 masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
1897 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
1898 } else if (_substrcmp(*av, "move") == 0) {
1900 if (av[0] && _substrcmp(*av, "rule") == 0) {
1905 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
1906 av[3] != NULL || _substrcmp(av[1], "to") != 0)
1907 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
1908 rulenum = atoi(av[0]);
1909 new_set = atoi(av[2]);
1910 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) ||
1911 (cmd == 2 && rulenum == IPFW_DEFAULT_RULE) )
1912 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
1913 if (!isdigit(*(av[2])) || new_set > RESVD_SET)
1914 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
1915 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
1916 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
1917 } else if (_substrcmp(*av, "disable") == 0 ||
1918 _substrcmp(*av, "enable") == 0 ) {
1919 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
1922 masks[0] = masks[1] = 0;
1925 if (isdigit(**av)) {
1927 if (i < 0 || i > RESVD_SET)
1929 "invalid set number %d\n", i);
1930 masks[which] |= (1<<i);
1931 } else if (_substrcmp(*av, "disable") == 0)
1933 else if (_substrcmp(*av, "enable") == 0)
1937 "invalid set command %s\n", *av);
1940 if ( (masks[0] & masks[1]) != 0 )
1942 "cannot enable and disable the same set\n");
1944 i = do_cmd(IP_FW_DEL, masks, sizeof(masks));
1946 warn("set enable/disable: setsockopt(IP_FW_DEL)");
1948 errx(EX_USAGE, "invalid set command %s\n", *av);
1952 ipfw_sysctl_handler(char *av[], int which)
1956 if (av[0] == NULL) {
1957 warnx("missing keyword to enable/disable\n");
1958 } else if (_substrcmp(*av, "firewall") == 0) {
1959 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
1960 &which, sizeof(which));
1961 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
1962 &which, sizeof(which));
1963 } else if (_substrcmp(*av, "one_pass") == 0) {
1964 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
1965 &which, sizeof(which));
1966 } else if (_substrcmp(*av, "debug") == 0) {
1967 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
1968 &which, sizeof(which));
1969 } else if (_substrcmp(*av, "verbose") == 0) {
1970 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
1971 &which, sizeof(which));
1972 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
1973 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
1974 &which, sizeof(which));
1976 } else if (_substrcmp(*av, "altq") == 0) {
1977 altq_set_enabled(which);
1980 warnx("unrecognize enable/disable keyword: %s\n", *av);
1985 ipfw_list(int ac, char *av[], int show_counters)
1988 ipfw_dyn_rule *dynrules, *d;
1990 #define NEXT(r) ((struct ip_fw *)((char *)r + RULESIZE(r)))
1993 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
1994 int exitval = EX_OK;
2002 const int ocmd = co.do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
2003 int nalloc = 1024; /* start somewhere... */
2008 fprintf(stderr, "Testing only, list disabled\n");
2012 dummynet_list(ac, av, show_counters);
2019 /* get rules or pipes from kernel, resizing array as necessary */
2022 while (nbytes >= nalloc) {
2023 nalloc = nalloc * 2 + 200;
2025 data = safe_realloc(data, nbytes);
2026 if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0)
2027 err(EX_OSERR, "getsockopt(IP_%s_GET)",
2028 co.do_pipe ? "DUMMYNET" : "FW");
2032 * Count static rules. They have variable size so we
2033 * need to scan the list to count them.
2035 for (nstat = 1, r = data, lim = (char *)data + nbytes;
2036 r->rulenum < IPFW_DEFAULT_RULE && (char *)r < lim;
2037 ++nstat, r = NEXT(r) )
2041 * Count dynamic rules. This is easier as they have
2045 dynrules = (ipfw_dyn_rule *)r ;
2046 n = (char *)r - (char *)data;
2047 ndyn = (nbytes - n) / sizeof *dynrules;
2049 /* if showing stats, figure out column widths ahead of time */
2050 bcwidth = pcwidth = 0;
2051 if (show_counters) {
2052 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
2053 /* skip rules from another set */
2054 if (co.use_set && r->set != co.use_set - 1)
2057 /* packet counter */
2058 width = pr_u64(&r->pcnt, 0);
2059 if (width > pcwidth)
2063 width = pr_u64(&r->bcnt, 0);
2064 if (width > bcwidth)
2068 if (co.do_dynamic && ndyn) {
2069 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2071 /* skip rules from another set */
2072 bcopy((char *)&d->rule + sizeof(uint16_t),
2073 &set, sizeof(uint8_t));
2074 if (set != co.use_set - 1)
2077 width = pr_u64(&d->pcnt, 0);
2078 if (width > pcwidth)
2081 width = pr_u64(&d->bcnt, 0);
2082 if (width > bcwidth)
2086 /* if no rule numbers were specified, list all rules */
2088 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
2089 if (co.use_set && r->set != co.use_set - 1)
2091 show_ipfw(r, pcwidth, bcwidth);
2094 if (co.do_dynamic && ndyn) {
2095 printf("## Dynamic rules (%d):\n", ndyn);
2096 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2098 bcopy((char *)&d->rule + sizeof(uint16_t),
2099 &set, sizeof(uint8_t));
2100 if (set != co.use_set - 1)
2103 show_dyn_ipfw(d, pcwidth, bcwidth);
2109 /* display specific rules requested on command line */
2111 for (lac = ac, lav = av; lac != 0; lac--) {
2112 /* convert command line rule # */
2113 last = rnum = strtoul(*lav++, &endptr, 10);
2115 last = strtoul(endptr+1, &endptr, 10);
2118 warnx("invalid rule number: %s", *(lav - 1));
2121 for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) {
2122 if (r->rulenum > last)
2124 if (co.use_set && r->set != co.use_set - 1)
2126 if (r->rulenum >= rnum && r->rulenum <= last) {
2127 show_ipfw(r, pcwidth, bcwidth);
2132 /* give precedence to other error(s) */
2133 if (exitval == EX_OK)
2134 exitval = EX_UNAVAILABLE;
2135 warnx("rule %lu does not exist", rnum);
2139 if (co.do_dynamic && ndyn) {
2140 printf("## Dynamic rules:\n");
2141 for (lac = ac, lav = av; lac != 0; lac--) {
2142 last = rnum = strtoul(*lav++, &endptr, 10);
2144 last = strtoul(endptr+1, &endptr, 10);
2146 /* already warned */
2148 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2151 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2155 bcopy((char *)&d->rule + sizeof(uint16_t),
2156 &set, sizeof(uint8_t));
2157 if (set != co.use_set - 1)
2160 if (r->rulenum >= rnum && r->rulenum <= last)
2161 show_dyn_ipfw(d, pcwidth, bcwidth);
2171 if (exitval != EX_OK)
2177 lookup_host (char *host, struct in_addr *ipaddr)
2181 if (!inet_aton(host, ipaddr)) {
2182 if ((he = gethostbyname(host)) == NULL)
2184 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2190 * fills the addr and mask fields in the instruction as appropriate from av.
2191 * Update length as appropriate.
2192 * The following formats are allowed:
2193 * me returns O_IP_*_ME
2194 * 1.2.3.4 single IP address
2195 * 1.2.3.4:5.6.7.8 address:mask
2196 * 1.2.3.4/24 address/mask
2197 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
2198 * We can have multiple comma-separated address/mask entries.
2201 fill_ip(ipfw_insn_ip *cmd, char *av, int cblen)
2204 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2206 cmd->o.len &= ~F_LEN_MASK; /* zero len */
2208 if (_substrcmp(av, "any") == 0)
2211 if (_substrcmp(av, "me") == 0) {
2212 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2216 if (strncmp(av, "table(", 6) == 0) {
2217 char *p = strchr(av + 6, ',');
2221 cmd->o.opcode = O_IP_DST_LOOKUP;
2222 cmd->o.arg1 = strtoul(av + 6, NULL, 0);
2224 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2225 d[0] = strtoul(p, NULL, 0);
2227 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2233 * After the address we can have '/' or ':' indicating a mask,
2234 * ',' indicating another address follows, '{' indicating a
2235 * set of addresses of unspecified size.
2237 char *t = NULL, *p = strpbrk(av, "/:,{");
2241 CHECK_LENGTH(cblen, F_INSN_SIZE(ipfw_insn) + 2 + len);
2246 if ((t = strpbrk(p, ",{")) != NULL) {
2253 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2254 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2257 if (!inet_aton(p, (struct in_addr *)&d[1]))
2258 errx(EX_DATAERR, "bad netmask ``%s''", p);
2263 d[1] = htonl(0); /* mask */
2264 else if (masklen > 32)
2265 errx(EX_DATAERR, "bad width ``%s''", p);
2267 d[1] = htonl(~0 << (32 - masklen));
2269 case '{': /* no mask, assume /24 and put back the '{' */
2270 d[1] = htonl(~0 << (32 - 24));
2274 case ',': /* single address plus continuation */
2277 case 0: /* initialization value */
2279 d[1] = htonl(~0); /* force /32 */
2282 d[0] &= d[1]; /* mask base address with mask */
2285 /* find next separator */
2287 p = strpbrk(p, ",{");
2288 if (p && *p == '{') {
2290 * We have a set of addresses. They are stored as follows:
2291 * arg1 is the set size (powers of 2, 2..256)
2292 * addr is the base address IN HOST FORMAT
2293 * mask.. is an array of arg1 bits (rounded up to
2294 * the next multiple of 32) with bits set
2295 * for each host in the map.
2297 uint32_t *map = (uint32_t *)&cmd->mask;
2299 int i = contigmask((uint8_t *)&(d[1]), 32);
2302 errx(EX_DATAERR, "address set cannot be in a list");
2303 if (i < 24 || i > 31)
2304 errx(EX_DATAERR, "invalid set with mask %d\n", i);
2305 cmd->o.arg1 = 1<<(32-i); /* map length */
2306 d[0] = ntohl(d[0]); /* base addr in host format */
2307 cmd->o.opcode = O_IP_DST_SET; /* default */
2308 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2309 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2310 map[i] = 0; /* clear map */
2314 high = low + cmd->o.arg1 - 1;
2316 * Here, i stores the previous value when we specify a range
2317 * of addresses within a mask, e.g. 45-63. i = -1 means we
2318 * have no previous value.
2320 i = -1; /* previous value in a range */
2321 while (isdigit(*av)) {
2323 int a = strtol(av, &s, 0);
2325 if (s == av) { /* no parameter */
2327 errx(EX_DATAERR, "set not closed\n");
2329 errx(EX_DATAERR, "incomplete range %d-", i);
2332 if (a < low || a > high)
2333 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
2336 if (i == -1) /* no previous in range */
2338 else { /* check that range is valid */
2340 errx(EX_DATAERR, "invalid range %d-%d",
2343 errx(EX_DATAERR, "double '-' in range");
2346 map[i/32] |= 1<<(i & 31);
2357 if (av) /* then *av must be a ',' */
2360 /* Check this entry */
2361 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2363 * 'any' turns the entire list into a NOP.
2364 * 'not any' never matches, so it is removed from the
2365 * list unless it is the only item, in which case we
2368 if (cmd->o.len & F_NOT) { /* "not any" never matches */
2369 if (av == NULL && len == 0) /* only this entry */
2370 errx(EX_DATAERR, "not any never matches");
2372 /* else do nothing and skip this entry */
2375 /* A single IP can be stored in an optimized format */
2376 if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
2377 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2380 len += 2; /* two words... */
2383 if (len + 1 > F_LEN_MASK)
2384 errx(EX_DATAERR, "address list too long");
2385 cmd->o.len |= len+1;
2389 /* n2mask sets n bits of the mask */
2391 n2mask(struct in6_addr *mask, int n)
2393 static int minimask[9] =
2394 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
2397 memset(mask, 0, sizeof(struct in6_addr));
2398 p = (u_char *) mask;
2399 for (; n > 0; p++, n -= 8) {
2409 * helper function to process a set of flags and set bits in the
2410 * appropriate masks.
2413 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
2414 struct _s_x *flags, char *p)
2416 uint8_t set=0, clear=0;
2419 char *q; /* points to the separator */
2421 uint8_t *which; /* mask we are working on */
2431 val = match_token(flags, p);
2433 errx(EX_DATAERR, "invalid flag %s", p);
2434 *which |= (uint8_t)val;
2437 cmd->opcode = opcode;
2438 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
2439 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
2444 ipfw_delete(char *av[])
2448 int exitval = EX_OK;
2452 NEED1("missing rule specification");
2453 if ( *av && _substrcmp(*av, "set") == 0) {
2454 /* Do not allow using the following syntax:
2455 * ipfw set N delete set M
2458 errx(EX_DATAERR, "invalid syntax");
2459 do_set = 1; /* delete set */
2464 while (*av && isdigit(**av)) {
2465 i = atoi(*av); av++;
2467 exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
2469 exitval = EX_UNAVAILABLE;
2470 warn("rule %u not available", i);
2472 } else if (co.do_pipe) {
2473 exitval = ipfw_delete_pipe(co.do_pipe, i);
2476 rulenum = (i & 0xffff) | (5 << 24) |
2477 ((co.use_set - 1) << 16);
2479 rulenum = (i & 0xffff) | (do_set << 24);
2480 i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum);
2482 exitval = EX_UNAVAILABLE;
2483 warn("rule %u: setsockopt(IP_FW_DEL)",
2488 if (exitval != EX_OK)
2494 * fill the interface structure. We do not check the name as we can
2495 * create interfaces dynamically, so checking them at insert time
2496 * makes relatively little sense.
2497 * Interface names containing '*', '?', or '[' are assumed to be shell
2498 * patterns which match interfaces.
2501 fill_iface(ipfw_insn_if *cmd, char *arg, int cblen)
2503 cmd->name[0] = '\0';
2504 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
2508 /* Parse the interface or address */
2509 if (strcmp(arg, "any") == 0)
2510 cmd->o.len = 0; /* effectively ignore this command */
2511 else if (strncmp(arg, "table(", 6) == 0) {
2512 char *p = strchr(arg + 6, ',');
2515 cmd->name[0] = '\1'; /* Special value indicating table */
2516 cmd->p.glob = strtoul(arg + 6, NULL, 0);
2517 } else if (!isdigit(*arg)) {
2518 strlcpy(cmd->name, arg, sizeof(cmd->name));
2519 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
2520 } else if (!inet_aton(arg, &cmd->p.ip))
2521 errx(EX_DATAERR, "bad ip address ``%s''", arg);
2525 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
2529 char *ap, *ptr, *optr;
2530 struct ether_addr *mac;
2531 const char *macset = "0123456789abcdefABCDEF:";
2533 if (strcmp(p, "any") == 0) {
2534 for (i = 0; i < ETHER_ADDR_LEN; i++)
2535 addr[i] = mask[i] = 0;
2539 optr = ptr = strdup(p);
2540 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
2542 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
2543 errx(EX_DATAERR, "Incorrect MAC address");
2544 bcopy(mac, addr, ETHER_ADDR_LEN);
2546 errx(EX_DATAERR, "Incorrect MAC address");
2548 if (ptr != NULL) { /* we have mask? */
2549 if (p[ptr - optr - 1] == '/') { /* mask len */
2550 long ml = strtol(ptr, &ap, 10);
2551 if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
2552 errx(EX_DATAERR, "Incorrect mask length");
2553 for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
2554 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
2557 if (strspn(ptr, macset) != l ||
2558 (mac = ether_aton(ptr)) == NULL)
2559 errx(EX_DATAERR, "Incorrect mask");
2560 bcopy(mac, mask, ETHER_ADDR_LEN);
2562 } else { /* default mask: ff:ff:ff:ff:ff:ff */
2563 for (i = 0; i < ETHER_ADDR_LEN; i++)
2566 for (i = 0; i < ETHER_ADDR_LEN; i++)
2573 * helper function, updates the pointer to cmd with the length
2574 * of the current command, and also cleans up the first word of
2575 * the new command in case it has been clobbered before.
2578 next_cmd(ipfw_insn *cmd, int *len)
2581 CHECK_LENGTH(*len, 0);
2583 bzero(cmd, sizeof(*cmd));
2588 * Takes arguments and copies them into a comment
2591 fill_comment(ipfw_insn *cmd, char **av, int cblen)
2594 char *p = (char *)(cmd + 1);
2596 cmd->opcode = O_NOP;
2597 cmd->len = (cmd->len & (F_NOT | F_OR));
2599 /* Compute length of comment string. */
2600 for (i = 0, l = 0; av[i] != NULL; i++)
2601 l += strlen(av[i]) + 1;
2606 "comment too long (max 80 chars)");
2608 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
2611 for (i = 0; av[i] != NULL; i++) {
2620 * A function to fill simple commands of size 1.
2621 * Existing flags are preserved.
2624 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
2626 cmd->opcode = opcode;
2627 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
2632 * Fetch and add the MAC address and type, with masks. This generates one or
2633 * two microinstructions, and returns the pointer to the last one.
2636 add_mac(ipfw_insn *cmd, char *av[], int cblen)
2640 if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
2641 errx(EX_DATAERR, "MAC dst src");
2643 cmd->opcode = O_MACADDR2;
2644 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
2647 mac = (ipfw_insn_mac *)cmd;
2648 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
2649 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
2650 &(mac->mask[ETHER_ADDR_LEN])); /* src */
2655 add_mactype(ipfw_insn *cmd, char *av, int cblen)
2658 errx(EX_DATAERR, "missing MAC type");
2659 if (strcmp(av, "any") != 0) { /* we have a non-null type */
2660 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
2662 cmd->opcode = O_MAC_TYPE;
2669 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
2671 struct protoent *pe;
2675 proto = strtol(av, &ep, 10);
2676 if (*ep != '\0' || proto <= 0) {
2677 if ((pe = getprotobyname(av)) == NULL)
2679 proto = pe->p_proto;
2682 fill_cmd(cmd, O_PROTO, 0, proto);
2688 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
2690 u_char proto = IPPROTO_IP;
2692 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2693 ; /* do not set O_IP4 nor O_IP6 */
2694 else if (strcmp(av, "ip4") == 0)
2695 /* explicit "just IPv4" rule */
2696 fill_cmd(cmd, O_IP4, 0, 0);
2697 else if (strcmp(av, "ip6") == 0) {
2698 /* explicit "just IPv6" rule */
2699 proto = IPPROTO_IPV6;
2700 fill_cmd(cmd, O_IP6, 0, 0);
2702 return add_proto0(cmd, av, protop);
2709 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
2711 u_char proto = IPPROTO_IP;
2713 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2714 ; /* do not set O_IP4 nor O_IP6 */
2715 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
2716 /* explicit "just IPv4" rule */
2717 fill_cmd(cmd, O_IP4, 0, 0);
2718 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
2719 /* explicit "just IPv6" rule */
2720 proto = IPPROTO_IPV6;
2721 fill_cmd(cmd, O_IP6, 0, 0);
2723 return add_proto0(cmd, av, protop);
2730 add_srcip(ipfw_insn *cmd, char *av, int cblen)
2732 fill_ip((ipfw_insn_ip *)cmd, av, cblen);
2733 if (cmd->opcode == O_IP_DST_SET) /* set */
2734 cmd->opcode = O_IP_SRC_SET;
2735 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
2736 cmd->opcode = O_IP_SRC_LOOKUP;
2737 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2738 cmd->opcode = O_IP_SRC_ME;
2739 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2740 cmd->opcode = O_IP_SRC;
2741 else /* addr/mask */
2742 cmd->opcode = O_IP_SRC_MASK;
2747 add_dstip(ipfw_insn *cmd, char *av, int cblen)
2749 fill_ip((ipfw_insn_ip *)cmd, av, cblen);
2750 if (cmd->opcode == O_IP_DST_SET) /* set */
2752 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
2754 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2755 cmd->opcode = O_IP_DST_ME;
2756 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2757 cmd->opcode = O_IP_DST;
2758 else /* addr/mask */
2759 cmd->opcode = O_IP_DST_MASK;
2764 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
2766 /* XXX "any" is trapped before. Perhaps "to" */
2767 if (_substrcmp(av, "any") == 0) {
2769 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
2770 /* XXX todo: check that we have a protocol with ports */
2771 cmd->opcode = opcode;
2778 add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen)
2782 ipfw_insn *ret = NULL;
2784 if ((host = strdup(av)) == NULL)
2786 if ((ch = strrchr(host, '/')) != NULL)
2789 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
2790 inet_pton(AF_INET6, host, &a) == 1)
2791 ret = add_srcip6(cmd, av, cblen);
2792 /* XXX: should check for IPv4, not !IPv6 */
2793 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2794 inet_pton(AF_INET6, host, &a) != 1))
2795 ret = add_srcip(cmd, av, cblen);
2796 if (ret == NULL && strcmp(av, "any") != 0)
2804 add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen)
2808 ipfw_insn *ret = NULL;
2810 if ((host = strdup(av)) == NULL)
2812 if ((ch = strrchr(host, '/')) != NULL)
2815 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
2816 inet_pton(AF_INET6, host, &a) == 1)
2817 ret = add_dstip6(cmd, av, cblen);
2818 /* XXX: should check for IPv4, not !IPv6 */
2819 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2820 inet_pton(AF_INET6, host, &a) != 1))
2821 ret = add_dstip(cmd, av, cblen);
2822 if (ret == NULL && strcmp(av, "any") != 0)
2830 * Parse arguments and assemble the microinstructions which make up a rule.
2831 * Rules are added into the 'rulebuf' and then copied in the correct order
2832 * into the actual rule.
2834 * The syntax for a rule starts with the action, followed by
2835 * optional action parameters, and the various match patterns.
2836 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
2837 * (generated if the rule includes a keep-state option), then the
2838 * various match patterns, log/altq actions, and the actual action.
2842 ipfw_add(char *av[])
2845 * rules are added into the 'rulebuf' and then copied in
2846 * the correct order into the actual rule.
2847 * Some things that need to go out of order (prob, action etc.)
2850 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255];
2851 int rblen, ablen, cblen;
2853 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
2854 ipfw_insn *first_cmd; /* first match pattern */
2859 * various flags used to record that we entered some fields.
2861 ipfw_insn *have_state = NULL; /* check-state or keep-state */
2862 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
2867 int open_par = 0; /* open parenthesis ( */
2869 /* proto is here because it is used to fetch ports */
2870 u_char proto = IPPROTO_IP; /* default protocol */
2872 double match_prob = 1; /* match probability, default is always match */
2874 bzero(actbuf, sizeof(actbuf)); /* actions go here */
2875 bzero(cmdbuf, sizeof(cmdbuf));
2876 bzero(rulebuf, sizeof(rulebuf));
2878 rule = (struct ip_fw *)rulebuf;
2879 cmd = (ipfw_insn *)cmdbuf;
2880 action = (ipfw_insn *)actbuf;
2882 rblen = sizeof(rulebuf) / sizeof(rulebuf[0]);
2883 rblen -= offsetof(struct ip_fw, cmd) / sizeof(rulebuf[0]);
2884 ablen = sizeof(actbuf) / sizeof(actbuf[0]);
2885 cblen = sizeof(cmdbuf) / sizeof(cmdbuf[0]);
2886 cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
2888 #define CHECK_RBUFLEN(len) { CHECK_LENGTH(rblen, len); rblen -= len; }
2889 #define CHECK_ACTLEN CHECK_LENGTH(ablen, action->len)
2893 /* [rule N] -- Rule number optional */
2894 if (av[0] && isdigit(**av)) {
2895 rule->rulenum = atoi(*av);
2899 /* [set N] -- set number (0..RESVD_SET), optional */
2900 if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
2901 int set = strtoul(av[1], NULL, 10);
2902 if (set < 0 || set > RESVD_SET)
2903 errx(EX_DATAERR, "illegal set %s", av[1]);
2908 /* [prob D] -- match probability, optional */
2909 if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
2910 match_prob = strtod(av[1], NULL);
2912 if (match_prob <= 0 || match_prob > 1)
2913 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
2917 /* action -- mandatory */
2918 NEED1("missing action");
2919 i = match_token(rule_actions, *av);
2921 action->len = 1; /* default */
2924 case TOK_CHECKSTATE:
2925 have_state = action;
2926 action->opcode = O_CHECK_STATE;
2930 action->opcode = O_ACCEPT;
2934 action->opcode = O_DENY;
2939 action->opcode = O_REJECT;
2940 action->arg1 = ICMP_UNREACH_HOST;
2944 action->opcode = O_REJECT;
2945 action->arg1 = ICMP_REJECT_RST;
2949 action->opcode = O_UNREACH6;
2950 action->arg1 = ICMP6_UNREACH_RST;
2954 action->opcode = O_REJECT;
2955 NEED1("missing reject code");
2956 fill_reject_code(&action->arg1, *av);
2961 action->opcode = O_UNREACH6;
2962 NEED1("missing unreach code");
2963 fill_unreach6_code(&action->arg1, *av);
2968 action->opcode = O_COUNT;
2972 action->opcode = O_NAT;
2973 action->len = F_INSN_SIZE(ipfw_insn_nat);
2975 if (_substrcmp(*av, "global") == 0) {
2983 action->opcode = O_QUEUE;
2986 action->opcode = O_PIPE;
2989 action->opcode = O_SKIPTO;
2992 action->opcode = O_NETGRAPH;
2995 action->opcode = O_NGTEE;
2998 action->opcode = O_DIVERT;
3001 action->opcode = O_TEE;
3004 action->opcode = O_CALLRETURN;
3007 errx(EX_USAGE, "missing argument for %s", *(av - 1));
3008 if (isdigit(**av)) {
3009 action->arg1 = strtoul(*av, NULL, 10);
3010 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
3011 errx(EX_DATAERR, "illegal argument for %s",
3013 } else if (_substrcmp(*av, "tablearg") == 0) {
3014 action->arg1 = IP_FW_TABLEARG;
3015 } else if (i == TOK_DIVERT || i == TOK_TEE) {
3018 s = getservbyname(av[0], "divert");
3020 action->arg1 = ntohs(s->s_port);
3022 errx(EX_DATAERR, "illegal divert/tee port");
3024 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
3030 * Locate the address-port separator (':' or ',').
3031 * Could be one of the following:
3035 * IPv6 w:x:y::z,port
3036 * The ':' can only be used with hostname and IPv4 address.
3037 * XXX-BZ Should we also support [w:x:y::z]:port?
3039 struct sockaddr_storage result;
3040 struct addrinfo *res;
3043 u_short port_number;
3045 NEED1("missing forward address[:port]");
3048 * locate the address-port separator (':' or ',')
3050 s = strchr(*av, ',');
3052 /* Distinguish between IPv4:port and IPv6 cases. */
3053 s = strchr(*av, ':');
3054 if (s && strchr(s+1, ':'))
3055 s = NULL; /* no port */
3060 /* Terminate host portion and set s to start of port. */
3062 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
3065 "illegal forwarding port ``%s''", s);
3066 port_number = (u_short)i;
3069 if (_substrcmp(*av, "tablearg") == 0) {
3071 ((struct sockaddr_in*)&result)->sin_addr.s_addr =
3075 * Resolve the host name or address to a family and a
3076 * network representation of the addres.
3078 if (getaddrinfo(*av, NULL, NULL, &res))
3079 errx(EX_DATAERR, NULL);
3080 /* Just use the first host in the answer. */
3081 family = res->ai_family;
3082 memcpy(&result, res->ai_addr, res->ai_addrlen);
3086 if (family == PF_INET) {
3087 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
3089 action->opcode = O_FORWARD_IP;
3090 action->len = F_INSN_SIZE(ipfw_insn_sa);
3094 * In the kernel we assume AF_INET and use only
3095 * sin_port and sin_addr. Remember to set sin_len as
3096 * the routing code seems to use it too.
3098 p->sa.sin_len = sizeof(struct sockaddr_in);
3099 p->sa.sin_family = AF_INET;
3100 p->sa.sin_port = port_number;
3101 p->sa.sin_addr.s_addr =
3102 ((struct sockaddr_in *)&result)->sin_addr.s_addr;
3103 } else if (family == PF_INET6) {
3104 ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
3106 action->opcode = O_FORWARD_IP6;
3107 action->len = F_INSN_SIZE(ipfw_insn_sa6);
3110 p->sa.sin6_len = sizeof(struct sockaddr_in6);
3111 p->sa.sin6_family = AF_INET6;
3112 p->sa.sin6_port = port_number;
3113 p->sa.sin6_flowinfo = 0;
3114 p->sa.sin6_scope_id = 0;
3115 /* No table support for v6 yet. */
3116 bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
3117 &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
3119 errx(EX_DATAERR, "Invalid address family in forward action");
3125 /* pretend it is a 'count' rule followed by the comment */
3126 action->opcode = O_COUNT;
3127 av--; /* go back... */
3133 size_t intsize = sizeof(int);
3135 action->opcode = O_SETFIB;
3136 NEED1("missing fib number");
3137 if (_substrcmp(*av, "tablearg") == 0) {
3138 action->arg1 = IP_FW_TABLEARG;
3140 action->arg1 = strtoul(*av, NULL, 10);
3141 if (sysctlbyname("net.fibs", &numfibs, &intsize,
3143 errx(EX_DATAERR, "fibs not suported.\n");
3144 if (action->arg1 >= numfibs) /* Temporary */
3145 errx(EX_DATAERR, "fib too large.\n");
3155 action->opcode = O_SETDSCP;
3156 NEED1("missing DSCP code");
3157 if (_substrcmp(*av, "tablearg") == 0) {
3158 action->arg1 = IP_FW_TABLEARG;
3159 } else if (isalpha(*av[0])) {
3160 if ((code = match_token(f_ipdscp, *av)) == -1)
3161 errx(EX_DATAERR, "Unknown DSCP code");
3162 action->arg1 = code;
3164 action->arg1 = strtoul(*av, NULL, 10);
3170 action->opcode = O_REASS;
3174 fill_cmd(action, O_CALLRETURN, F_NOT, 0);
3178 errx(EX_DATAERR, "invalid action %s\n", av[-1]);
3180 action = next_cmd(action, &ablen);
3183 * [altq queuename] -- altq tag, optional
3184 * [log [logamount N]] -- log, optional
3186 * If they exist, it go first in the cmdbuf, but then it is
3187 * skipped in the copy section to the end of the buffer.
3189 while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
3194 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
3199 "log cannot be specified more than once");
3200 have_log = (ipfw_insn *)c;
3201 cmd->len = F_INSN_SIZE(ipfw_insn_log);
3203 cmd->opcode = O_LOG;
3204 if (av[0] && _substrcmp(*av, "logamount") == 0) {
3206 NEED1("logamount requires argument");
3210 "logamount must be positive");
3214 len = sizeof(c->max_log);
3215 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
3216 &c->max_log, &len, NULL, 0) == -1) {
3221 errx(1, "sysctlbyname(\"%s\")",
3222 "net.inet.ip.fw.verbose_limit");
3231 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
3233 NEED1("missing altq queue name");
3236 "altq cannot be specified more than once");
3237 have_altq = (ipfw_insn *)a;
3238 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
3240 cmd->opcode = O_ALTQ;
3241 a->qid = altq_name_to_qid(*av);
3252 errx(EX_USAGE, "tag and untag cannot be "
3253 "specified more than once");
3254 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
3255 rule_action_params);
3257 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
3265 cmd = next_cmd(cmd, &cblen);
3268 if (have_state) /* must be a check-state, we are done */
3271 #define OR_START(target) \
3272 if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
3274 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
3277 if ( (av[0])[1] == '\0') { \
3288 strcmp(*av, ")") == 0 || \
3289 strcmp(*av, "}") == 0)) { \
3294 errx(EX_USAGE, "missing \")\"\n"); \
3298 if (av[0] && _substrcmp(*av, "not") == 0) { \
3299 if (cmd->len & F_NOT) \
3300 errx(EX_USAGE, "double \"not\" not allowed\n"); \
3301 cmd->len |= F_NOT; \
3305 #define OR_BLOCK(target) \
3306 if (av[0] && _substrcmp(*av, "or") == 0) { \
3307 if (prev == NULL || open_par == 0) \
3308 errx(EX_DATAERR, "invalid OR block"); \
3309 prev->len |= F_OR; \
3319 * MAC addresses, optional.
3320 * If we have this, we skip the part "proto from src to dst"
3321 * and jump straight to the option parsing.
3324 NEED1("missing protocol");
3325 if (_substrcmp(*av, "MAC") == 0 ||
3326 _substrcmp(*av, "mac") == 0) {
3327 av++; /* the "MAC" keyword */
3328 add_mac(cmd, av); /* exits in case of errors */
3329 cmd = next_cmd(cmd);
3330 av += 2; /* dst-mac and src-mac */
3332 NEED1("missing mac type");
3333 if (add_mactype(cmd, av[0]))
3334 cmd = next_cmd(cmd);
3335 av++; /* any or mac-type */
3341 * protocol, mandatory
3343 OR_START(get_proto);
3345 NEED1("missing protocol");
3346 if (add_proto_compat(cmd, *av, &proto)) {
3348 if (F_LEN(cmd) != 0) {
3350 cmd = next_cmd(cmd, &cblen);
3352 } else if (first_cmd != cmd) {
3353 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
3356 OR_BLOCK(get_proto);
3361 if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
3362 errx(EX_USAGE, "missing ``from''");
3366 * source IP, mandatory
3368 OR_START(source_ip);
3369 NOT_BLOCK; /* optional "not" */
3370 NEED1("missing source address");
3371 if (add_src(cmd, *av, proto, cblen)) {
3373 if (F_LEN(cmd) != 0) { /* ! any */
3375 cmd = next_cmd(cmd, &cblen);
3378 errx(EX_USAGE, "bad source address %s", *av);
3379 OR_BLOCK(source_ip);
3382 * source ports, optional
3384 NOT_BLOCK; /* optional "not" */
3385 if ( av[0] != NULL ) {
3386 if (_substrcmp(*av, "any") == 0 ||
3387 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
3389 if (F_LEN(cmd) != 0)
3390 cmd = next_cmd(cmd, &cblen);
3397 if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
3398 errx(EX_USAGE, "missing ``to''");
3402 * destination, mandatory
3405 NOT_BLOCK; /* optional "not" */
3406 NEED1("missing dst address");
3407 if (add_dst(cmd, *av, proto, cblen)) {
3409 if (F_LEN(cmd) != 0) { /* ! any */
3411 cmd = next_cmd(cmd, &cblen);
3414 errx( EX_USAGE, "bad destination address %s", *av);
3418 * dest. ports, optional
3420 NOT_BLOCK; /* optional "not" */
3422 if (_substrcmp(*av, "any") == 0 ||
3423 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
3425 if (F_LEN(cmd) != 0)
3426 cmd = next_cmd(cmd, &cblen);
3431 if (av[0] && first_cmd == cmd) {
3433 * nothing specified so far, store in the rule to ease
3439 while ( av[0] != NULL ) {
3441 ipfw_insn_u32 *cmd32; /* alias for cmd */
3444 cmd32 = (ipfw_insn_u32 *)cmd;
3446 if (*s == '!') { /* alternate syntax for NOT */
3447 if (cmd->len & F_NOT)
3448 errx(EX_USAGE, "double \"not\" not allowed\n");
3452 i = match_token(rule_options, s);
3456 if (cmd->len & F_NOT)
3457 errx(EX_USAGE, "double \"not\" not allowed\n");
3462 if (open_par == 0 || prev == NULL)
3463 errx(EX_USAGE, "invalid \"or\" block\n");
3467 case TOK_STARTBRACE:
3469 errx(EX_USAGE, "+nested \"(\" not allowed\n");
3475 errx(EX_USAGE, "+missing \")\"\n");
3481 fill_cmd(cmd, O_IN, 0, 0);
3485 cmd->len ^= F_NOT; /* toggle F_NOT */
3486 fill_cmd(cmd, O_IN, 0, 0);
3490 fill_cmd(cmd, O_DIVERTED, 0, 3);
3493 case TOK_DIVERTEDLOOPBACK:
3494 fill_cmd(cmd, O_DIVERTED, 0, 1);
3497 case TOK_DIVERTEDOUTPUT:
3498 fill_cmd(cmd, O_DIVERTED, 0, 2);
3502 fill_cmd(cmd, O_FRAG, 0, 0);
3506 fill_cmd(cmd, O_LAYER2, 0, 0);
3512 NEED1("recv, xmit, via require interface name"
3514 fill_iface((ipfw_insn_if *)cmd, av[0], cblen);
3516 if (F_LEN(cmd) == 0) /* not a valid address */
3519 cmd->opcode = O_XMIT;
3520 else if (i == TOK_RECV)
3521 cmd->opcode = O_RECV;
3522 else if (i == TOK_VIA)
3523 cmd->opcode = O_VIA;
3527 NEED1("icmptypes requires list of types");
3528 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
3532 case TOK_ICMP6TYPES:
3533 NEED1("icmptypes requires list of types");
3534 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
3539 NEED1("ipttl requires TTL");
3540 if (strpbrk(*av, "-,")) {
3541 if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
3542 errx(EX_DATAERR, "invalid ipttl %s", *av);
3544 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
3549 NEED1("ipid requires id");
3550 if (strpbrk(*av, "-,")) {
3551 if (!add_ports(cmd, *av, 0, O_IPID, cblen))
3552 errx(EX_DATAERR, "invalid ipid %s", *av);
3554 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
3559 NEED1("iplen requires length");
3560 if (strpbrk(*av, "-,")) {
3561 if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
3562 errx(EX_DATAERR, "invalid ip len %s", *av);
3564 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
3569 NEED1("ipver requires version");
3570 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
3574 case TOK_IPPRECEDENCE:
3575 NEED1("ipprecedence requires value");
3576 fill_cmd(cmd, O_IPPRECEDENCE, 0,
3577 (strtoul(*av, NULL, 0) & 7) << 5);
3582 NEED1("missing DSCP code");
3583 fill_dscp(cmd, *av, cblen);
3588 NEED1("missing argument for ipoptions");
3589 fill_flags(cmd, O_IPOPT, f_ipopts, *av);
3594 NEED1("missing argument for iptos");
3595 fill_flags(cmd, O_IPTOS, f_iptos, *av);
3600 NEED1("uid requires argument");
3606 cmd->opcode = O_UID;
3607 uid = strtoul(*av, &end, 0);
3608 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
3610 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
3611 cmd32->d[0] = pwd->pw_uid;
3612 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3618 NEED1("gid requires argument");
3624 cmd->opcode = O_GID;
3625 gid = strtoul(*av, &end, 0);
3626 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
3628 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
3629 cmd32->d[0] = grp->gr_gid;
3630 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3636 NEED1("jail requires argument");
3641 cmd->opcode = O_JAIL;
3642 jid = (int)strtol(*av, &end, 0);
3643 if (jid < 0 || *end != '\0')
3644 errx(EX_DATAERR, "jail requires prison ID");
3645 cmd32->d[0] = (uint32_t)jid;
3646 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3652 fill_cmd(cmd, O_ESTAB, 0, 0);
3656 fill_cmd(cmd, O_TCPFLAGS, 0,
3657 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
3660 case TOK_TCPDATALEN:
3661 NEED1("tcpdatalen requires length");
3662 if (strpbrk(*av, "-,")) {
3663 if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
3664 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
3666 fill_cmd(cmd, O_TCPDATALEN, 0,
3667 strtoul(*av, NULL, 0));
3672 NEED1("missing argument for tcpoptions");
3673 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
3679 NEED1("tcpseq/tcpack requires argument");
3680 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3681 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
3682 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
3687 NEED1("tcpwin requires length");
3688 if (strpbrk(*av, "-,")) {
3689 if (!add_ports(cmd, *av, 0, O_TCPWIN, cblen))
3690 errx(EX_DATAERR, "invalid tcpwin len %s", *av);
3692 fill_cmd(cmd, O_TCPWIN, 0,
3693 strtoul(*av, NULL, 0));
3698 NEED1("missing argument for tcpflags");
3699 cmd->opcode = O_TCPFLAGS;
3700 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
3706 errx(EX_USAGE, "keep-state cannot be part "
3709 errx(EX_USAGE, "only one of keep-state "
3710 "and limit is allowed");
3712 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
3716 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
3721 "limit cannot be part of an or block");
3723 errx(EX_USAGE, "only one of keep-state and "
3724 "limit is allowed");
3727 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
3729 cmd->opcode = O_LIMIT;
3730 c->limit_mask = c->conn_limit = 0;
3732 while ( av[0] != NULL ) {
3733 if ((val = match_token(limit_masks, *av)) <= 0)
3735 c->limit_mask |= val;
3739 if (c->limit_mask == 0)
3740 errx(EX_USAGE, "limit: missing limit mask");
3742 GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
3743 TOK_LIMIT, rule_options);
3750 NEED1("missing protocol");
3751 if (add_proto(cmd, *av, &proto)) {
3754 errx(EX_DATAERR, "invalid protocol ``%s''",
3759 NEED1("missing source IP");
3760 if (add_srcip(cmd, *av, cblen)) {
3766 NEED1("missing destination IP");
3767 if (add_dstip(cmd, *av, cblen)) {
3773 NEED1("missing source IP6");
3774 if (add_srcip6(cmd, *av, cblen)) {
3780 NEED1("missing destination IP6");
3781 if (add_dstip6(cmd, *av, cblen)) {
3787 NEED1("missing source port");
3788 if (_substrcmp(*av, "any") == 0 ||
3789 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
3792 errx(EX_DATAERR, "invalid source port %s", *av);
3796 NEED1("missing destination port");
3797 if (_substrcmp(*av, "any") == 0 ||
3798 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
3801 errx(EX_DATAERR, "invalid destination port %s",
3806 if (add_mac(cmd, av, cblen))
3811 NEED1("missing mac type");
3812 if (!add_mactype(cmd, *av, cblen))
3813 errx(EX_DATAERR, "invalid mac type %s", *av);
3817 case TOK_VERREVPATH:
3818 fill_cmd(cmd, O_VERREVPATH, 0, 0);
3821 case TOK_VERSRCREACH:
3822 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
3826 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
3830 fill_cmd(cmd, O_IPSEC, 0, 0);
3834 fill_cmd(cmd, O_IP6, 0, 0);
3838 fill_cmd(cmd, O_IP4, 0, 0);
3842 fill_ext6hdr( cmd, *av );
3847 if (proto != IPPROTO_IPV6 )
3848 errx( EX_USAGE, "flow-id filter is active "
3849 "only for ipv6 protocol\n");
3850 fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
3855 fill_comment(cmd, av, cblen);
3860 if (av[0] && strpbrk(*av, "-,")) {
3861 if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
3862 errx(EX_DATAERR, "tagged: invalid tag"
3868 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
3869 TOK_TAGGED, rule_options);
3870 fill_cmd(cmd, O_TAGGED, 0, tag);
3876 NEED1("fib requires fib number");
3877 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
3881 fill_cmd(cmd, O_SOCKARG, 0, 0);
3885 ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
3889 if (!av[0] || !av[1])
3890 errx(EX_USAGE, "format: lookup argument tablenum");
3891 cmd->opcode = O_IP_DST_LOOKUP;
3892 cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
3893 i = match_token(rule_options, *av);
3894 for (j = 0; lookup_key[j] >= 0 ; j++) {
3895 if (i == lookup_key[j])
3898 if (lookup_key[j] <= 0)
3899 errx(EX_USAGE, "format: cannot lookup on %s", *av);
3900 __PAST_END(c->d, 1) = j; // i converted to option
3902 cmd->arg1 = strtoul(*av, &p, 0);
3904 errx(EX_USAGE, "format: lookup argument tablenum");
3910 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
3912 if (F_LEN(cmd) > 0) { /* prepare to advance */
3914 cmd = next_cmd(cmd, &cblen);
3920 * Now copy stuff into the rule.
3921 * If we have a keep-state option, the first instruction
3922 * must be a PROBE_STATE (which is generated here).
3923 * If we have a LOG option, it was stored as the first command,
3924 * and now must be moved to the top of the action part.
3926 dst = (ipfw_insn *)rule->cmd;
3929 * First thing to write into the command stream is the match probability.
3931 if (match_prob != 1) { /* 1 means always match */
3932 dst->opcode = O_PROB;
3934 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
3939 * generate O_PROBE_STATE if necessary
3941 if (have_state && have_state->opcode != O_CHECK_STATE) {
3942 fill_cmd(dst, O_PROBE_STATE, 0, 0);
3943 dst = next_cmd(dst, &rblen);
3946 /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
3947 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
3951 switch (src->opcode) {
3959 bcopy(src, dst, i * sizeof(uint32_t));
3965 * put back the have_state command as last opcode
3967 if (have_state && have_state->opcode != O_CHECK_STATE) {
3968 i = F_LEN(have_state);
3970 bcopy(have_state, dst, i * sizeof(uint32_t));
3974 * start action section
3976 rule->act_ofs = dst - rule->cmd;
3978 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
3980 i = F_LEN(have_log);
3982 bcopy(have_log, dst, i * sizeof(uint32_t));
3986 i = F_LEN(have_altq);
3988 bcopy(have_altq, dst, i * sizeof(uint32_t));
3992 i = F_LEN(have_tag);
3994 bcopy(have_tag, dst, i * sizeof(uint32_t));
3999 * copy all other actions
4001 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
4004 bcopy(src, dst, i * sizeof(uint32_t));
4008 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
4009 i = (char *)dst - (char *)rule;
4010 if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1)
4011 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
4013 show_ipfw(rule, 0, 0);
4017 * clear the counters or the log counters.
4020 ipfw_zero(int ac, char *av[], int optname /* 0 = IP_FW_ZERO, 1 = IP_FW_RESETLOG */)
4022 uint32_t arg, saved_arg;
4025 char const *name = optname ? "RESETLOG" : "ZERO";
4027 optname = optname ? IP_FW_RESETLOG : IP_FW_ZERO;
4032 /* clear all entries */
4033 if (do_cmd(optname, NULL, 0) < 0)
4034 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name);
4036 printf("%s.\n", optname == IP_FW_ZERO ?
4037 "Accounting cleared":"Logging counts reset");
4044 if (isdigit(**av)) {
4045 arg = strtonum(*av, 0, 0xffff, &errstr);
4048 "invalid rule number %s\n", *av);
4051 arg |= (1 << 24) | ((co.use_set - 1) << 16);
4054 if (do_cmd(optname, &arg, sizeof(arg))) {
4055 warn("rule %u: setsockopt(IP_FW_%s)",
4057 failed = EX_UNAVAILABLE;
4058 } else if (!co.do_quiet)
4059 printf("Entry %d %s.\n", saved_arg,
4060 optname == IP_FW_ZERO ?
4061 "cleared" : "logging count reset");
4063 errx(EX_USAGE, "invalid rule number ``%s''", *av);
4066 if (failed != EX_OK)
4071 ipfw_flush(int force)
4073 int cmd = co.do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
4075 if (!force && !co.do_quiet) { /* need to ask user */
4078 printf("Are you sure? [yn] ");
4081 c = toupper(getc(stdin));
4082 while (c != '\n' && getc(stdin) != '\n')
4084 return; /* and do not flush */
4085 } while (c != 'Y' && c != 'N');
4087 if (c == 'N') /* user said no */
4094 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
4096 uint32_t arg = ((co.use_set - 1) & 0xffff) | (1 << 24);
4097 if (do_cmd(IP_FW_DEL, &arg, sizeof(arg)) < 0)
4098 err(EX_UNAVAILABLE, "setsockopt(IP_FW_DEL)");
4099 } else if (do_cmd(cmd, NULL, 0) < 0)
4100 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
4101 co.do_pipe ? "DUMMYNET" : "FW");
4103 printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
4107 static void table_list(uint16_t num, int need_header);
4108 static void table_fill_xentry(char *arg, ipfw_table_xentry *xent);
4111 * This one handles all table-related commands
4112 * ipfw table N add addr[/masklen] [value]
4113 * ipfw table N delete addr[/masklen]
4114 * ipfw table {N | all} flush
4115 * ipfw table {N | all} list
4118 ipfw_table_handler(int ac, char *av[])
4120 ipfw_table_xentry xent;
4125 uint32_t tables_max;
4127 len = sizeof(tables_max);
4128 if (sysctlbyname("net.inet.ip.fw.tables_max", &tables_max, &len,
4131 tables_max = 128; /* Old conservative default */
4133 errx(1, "Can't determine maximum number of ipfw tables."
4134 " Perhaps you forgot to load ipfw module?");
4137 memset(&xent, 0, sizeof(xent));
4140 if (ac && isdigit(**av)) {
4141 xent.tbl = atoi(*av);
4144 } else if (ac && _substrcmp(*av, "all") == 0) {
4149 errx(EX_USAGE, "table number or 'all' keyword required");
4150 if (xent.tbl >= tables_max)
4151 errx(EX_USAGE, "The table number exceeds the maximum allowed "
4152 "value (%d)", tables_max - 1);
4153 NEED1("table needs command");
4154 if (is_all && _substrcmp(*av, "list") != 0
4155 && _substrcmp(*av, "flush") != 0)
4156 errx(EX_USAGE, "table number required");
4158 if (_substrcmp(*av, "add") == 0 ||
4159 _substrcmp(*av, "delete") == 0) {
4160 do_add = **av == 'a';
4163 errx(EX_USAGE, "address required");
4165 table_fill_xentry(*av, &xent);
4170 /* isdigit is a bit of a hack here.. */
4171 if (strchr(*av, (int)'.') == NULL && isdigit(**av)) {
4172 xent.value = strtoul(*av, NULL, 0);
4174 if (lookup_host(*av, (struct in_addr *)&tval) == 0) {
4175 /* The value must be stored in host order *
4176 * so that the values < 65k can be distinguished */
4177 xent.value = ntohl(tval);
4179 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
4184 if (do_setcmd3(do_add ? IP_FW_TABLE_XADD : IP_FW_TABLE_XDEL,
4185 &xent, xent.len) < 0) {
4186 /* If running silent, don't bomb out on these errors. */
4187 if (!(co.do_quiet && (errno == (do_add ? EEXIST : ESRCH))))
4188 err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)",
4189 do_add ? "XADD" : "XDEL");
4190 /* In silent mode, react to a failed add by deleting */
4192 do_setcmd3(IP_FW_TABLE_XDEL, &xent, xent.len);
4193 if (do_setcmd3(IP_FW_TABLE_XADD, &xent, xent.len) < 0)
4195 "setsockopt(IP_FW_TABLE_XADD)");
4198 } else if (_substrcmp(*av, "flush") == 0) {
4199 a = is_all ? tables_max : (uint32_t)(xent.tbl + 1);
4201 if (do_cmd(IP_FW_TABLE_FLUSH, &xent.tbl,
4202 sizeof(xent.tbl)) < 0)
4203 err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)");
4204 } while (++xent.tbl < a);
4205 } else if (_substrcmp(*av, "list") == 0) {
4206 a = is_all ? tables_max : (uint32_t)(xent.tbl + 1);
4208 table_list(xent.tbl, is_all);
4209 } while (++xent.tbl < a);
4211 errx(EX_USAGE, "invalid table command %s", *av);
4215 table_fill_xentry(char *arg, ipfw_table_xentry *xent)
4217 int addrlen, mask, masklen, type;
4218 struct in6_addr *paddr;
4229 * Let's try to guess type by agrument.
4234 * 4) port, uid/gid or other u32 key (base 10 format)
4237 paddr = &xent->k.addr6;
4238 if (ishexnumber(*arg) != 0 || *arg == ':') {
4239 /* Remove / if exists */
4240 if ((p = strchr(arg, '/')) != NULL) {
4245 if (inet_pton(AF_INET, arg, paddr) == 1) {
4246 if (p != NULL && mask > 32)
4247 errx(EX_DATAERR, "bad IPv4 mask width: %s",
4250 type = IPFW_TABLE_CIDR;
4251 masklen = p ? mask : 32;
4252 addrlen = sizeof(struct in_addr);
4253 } else if (inet_pton(AF_INET6, arg, paddr) == 1) {
4254 if (IN6_IS_ADDR_V4COMPAT(paddr))
4256 "Use IPv4 instead of v4-compatible");
4257 if (p != NULL && mask > 128)
4258 errx(EX_DATAERR, "bad IPv6 mask width: %s",
4261 type = IPFW_TABLE_CIDR;
4262 masklen = p ? mask : 128;
4263 addrlen = sizeof(struct in6_addr);
4265 /* Port or any other key */
4266 key = strtol(arg, &p, 10);
4267 /* Skip non-base 10 entries like 'fa1' */
4269 pkey = (uint32_t *)paddr;
4271 type = IPFW_TABLE_CIDR;
4272 addrlen = sizeof(uint32_t);
4277 if (type == 0 && strchr(arg, '.') == NULL) {
4278 /* Assume interface name. Copy significant data only */
4279 mask = MIN(strlen(arg), IF_NAMESIZE - 1);
4280 memcpy(xent->k.iface, arg, mask);
4281 /* Set mask to exact match */
4282 masklen = 8 * IF_NAMESIZE;
4283 type = IPFW_TABLE_INTERFACE;
4284 addrlen = IF_NAMESIZE;
4288 if (lookup_host(arg, (struct in_addr *)paddr) != 0)
4289 errx(EX_NOHOST, "hostname ``%s'' unknown", arg);
4292 type = IPFW_TABLE_CIDR;
4293 addrlen = sizeof(struct in_addr);
4297 xent->masklen = masklen;
4298 xent->len = offsetof(ipfw_table_xentry, k) + addrlen;
4302 table_list(uint16_t num, int need_header)
4305 ipfw_table_xentry *xent;
4307 uint32_t *a, sz, tval;
4309 struct in6_addr *addr6;
4310 ip_fw3_opheader *op3;
4312 /* Prepend value with IP_FW3 header */
4313 l = sizeof(ip_fw3_opheader) + sizeof(uint32_t);
4315 /* Zero reserved fields */
4316 memset(op3, 0, sizeof(ip_fw3_opheader));
4317 a = (uint32_t *)(op3 + 1);
4319 op3->opcode = IP_FW_TABLE_XGETSIZE;
4320 if (do_cmd(IP_FW3, op3, (uintptr_t)&l) < 0)
4321 err(EX_OSERR, "getsockopt(IP_FW_TABLE_XGETSIZE)");
4323 /* If a is zero we have nothing to do, the table is empty. */
4328 tbl = safe_calloc(1, l);
4329 tbl->opheader.opcode = IP_FW_TABLE_XLIST;
4331 if (do_cmd(IP_FW3, tbl, (uintptr_t)&l) < 0)
4332 err(EX_OSERR, "getsockopt(IP_FW_TABLE_XLIST)");
4333 if (tbl->cnt && need_header)
4334 printf("---table(%d)---\n", tbl->tbl);
4335 sz = tbl->size - sizeof(ipfw_xtable);
4336 xent = &tbl->xent[0];
4338 switch (tbl->type) {
4339 case IPFW_TABLE_CIDR:
4340 /* IPv4 or IPv6 prefixes */
4342 addr6 = &xent->k.addr6;
4345 if (IN6_IS_ADDR_V4COMPAT(addr6)) {
4347 inet_ntop(AF_INET, &addr6->s6_addr32[3], tbuf, sizeof(tbuf));
4350 inet_ntop(AF_INET6, addr6, tbuf, sizeof(tbuf));
4353 if (co.do_value_as_ip) {
4355 printf("%s/%u %s\n", tbuf, xent->masklen,
4356 inet_ntoa(*(struct in_addr *)&tval));
4358 printf("%s/%u %u\n", tbuf, xent->masklen, tval);
4360 case IPFW_TABLE_INTERFACE:
4361 /* Interface names */
4363 if (co.do_value_as_ip) {
4365 printf("%s %s\n", xent->k.iface,
4366 inet_ntoa(*(struct in_addr *)&tval));
4368 printf("%s %u\n", xent->k.iface, tval);
4374 xent = (void *)xent + xent->len;