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 bizarre construction
540 * strncmp(str, "by", 2) which is used to allow people to use a shortcut
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)
1097 (void)cmd; /* UNUSED */
1098 if (co.comment_only)
1100 if ( (*flags & HAVE_IP) == HAVE_IP)
1101 *flags |= HAVE_OPTIONS;
1103 if ( !(*flags & HAVE_OPTIONS)) {
1104 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) {
1105 if ( (*flags & HAVE_PROTO4))
1107 else if ( (*flags & HAVE_PROTO6))
1112 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
1113 printf(" from any");
1114 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
1121 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth)
1123 static int twidth = 0;
1125 ipfw_insn *cmd, *tagptr = NULL;
1126 const char *comment = NULL; /* ptr to comment if we have one */
1127 int proto = 0; /* default */
1128 int flags = 0; /* prerequisites */
1129 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
1130 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
1131 int or_block = 0; /* we are in an or block */
1132 uint32_t set_disable;
1134 bcopy(&rule->next_rule, &set_disable, sizeof(set_disable));
1136 if (set_disable & (1 << rule->set)) { /* disabled */
1140 printf("# DISABLED ");
1142 printf("%05u ", rule->rulenum);
1144 if (pcwidth > 0 || bcwidth > 0) {
1145 pr_u64(&rule->pcnt, pcwidth);
1146 pr_u64(&rule->bcnt, bcwidth);
1149 if (co.do_time == 2)
1150 printf("%10u ", rule->timestamp);
1151 else if (co.do_time == 1) {
1153 time_t t = (time_t)0;
1156 strcpy(timestr, ctime(&t));
1157 *strchr(timestr, '\n') = '\0';
1158 twidth = strlen(timestr);
1160 if (rule->timestamp) {
1161 t = _long_to_time(rule->timestamp);
1163 strcpy(timestr, ctime(&t));
1164 *strchr(timestr, '\n') = '\0';
1165 printf("%s ", timestr);
1167 printf("%*s", twidth, " ");
1172 printf("set %d ", rule->set);
1175 * print the optional "match probability"
1177 if (rule->cmd_len > 0) {
1179 if (cmd->opcode == O_PROB) {
1180 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1181 double d = 1.0 * p->d[0];
1183 d = (d / 0x7fffffff);
1184 printf("prob %f ", d);
1189 * first print actions
1191 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1192 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1193 switch(cmd->opcode) {
1195 printf("check-state");
1196 /* avoid printing anything else */
1197 flags = HAVE_PROTO | HAVE_SRCIP |
1198 HAVE_DSTIP | HAVE_IP;
1214 if (cmd->arg1 == ICMP_REJECT_RST)
1216 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1219 print_reject_code(cmd->arg1);
1223 if (cmd->arg1 == ICMP6_UNREACH_RST)
1226 print_unreach6_code(cmd->arg1);
1230 PRINT_UINT_ARG("skipto ", cmd->arg1);
1234 PRINT_UINT_ARG("pipe ", cmd->arg1);
1238 PRINT_UINT_ARG("queue ", cmd->arg1);
1242 PRINT_UINT_ARG("divert ", cmd->arg1);
1246 PRINT_UINT_ARG("tee ", cmd->arg1);
1250 PRINT_UINT_ARG("netgraph ", cmd->arg1);
1254 PRINT_UINT_ARG("ngtee ", cmd->arg1);
1259 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1261 if (s->sa.sin_addr.s_addr == INADDR_ANY) {
1262 printf("fwd tablearg");
1264 printf("fwd %s", inet_ntoa(s->sa.sin_addr));
1267 printf(",%d", s->sa.sin_port);
1273 char buf[4 + INET6_ADDRSTRLEN + 1];
1274 ipfw_insn_sa6 *s = (ipfw_insn_sa6 *)cmd;
1276 printf("fwd %s", inet_ntop(AF_INET6, &s->sa.sin6_addr,
1278 if (s->sa.sin6_port)
1279 printf(",%d", s->sa.sin6_port);
1283 case O_LOG: /* O_LOG is printed last */
1284 logptr = (ipfw_insn_log *)cmd;
1287 case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1288 altqptr = (ipfw_insn_altq *)cmd;
1297 PRINT_UINT_ARG("nat ", cmd->arg1);
1299 printf("nat global");
1303 PRINT_UINT_ARG("setfib ", cmd->arg1);
1310 if ((code = match_value(f_ipdscp, cmd->arg1)) != NULL)
1311 printf("setdscp %s", code);
1313 PRINT_UINT_ARG("setdscp ", cmd->arg1);
1322 if (cmd->len & F_NOT)
1325 PRINT_UINT_ARG("call ", cmd->arg1);
1329 printf("** unrecognized action %d len %d ",
1330 cmd->opcode, cmd->len);
1334 if (logptr->max_log > 0)
1335 printf(" log logamount %d", logptr->max_log);
1341 print_altq_cmd(altqptr);
1345 if (tagptr->len & F_NOT)
1346 PRINT_UINT_ARG(" untag ", tagptr->arg1);
1348 PRINT_UINT_ARG(" tag ", tagptr->arg1);
1352 * then print the body.
1354 for (l = rule->act_ofs, cmd = rule->cmd ;
1355 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1356 if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1358 if (cmd->opcode == O_IP4) {
1359 flags |= HAVE_PROTO4;
1361 } else if (cmd->opcode == O_IP6) {
1362 flags |= HAVE_PROTO6;
1366 if (rule->_pad & 1) { /* empty rules before options */
1367 if (!co.do_compact) {
1368 show_prerequisites(&flags, HAVE_PROTO, 0);
1369 printf(" from any to any");
1371 flags |= HAVE_IP | HAVE_OPTIONS | HAVE_PROTO |
1372 HAVE_SRCIP | HAVE_DSTIP;
1375 if (co.comment_only)
1378 for (l = rule->act_ofs, cmd = rule->cmd ;
1379 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1381 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1383 if (co.comment_only) {
1384 if (cmd->opcode != O_NOP)
1386 printf(" // %s\n", (char *)(cmd + 1));
1390 show_prerequisites(&flags, 0, cmd->opcode);
1392 switch(cmd->opcode) {
1394 break; /* done already */
1397 break; /* no need to print anything here */
1400 case O_IP_SRC_LOOKUP:
1404 show_prerequisites(&flags, HAVE_PROTO, 0);
1405 if (!(flags & HAVE_SRCIP))
1407 if ((cmd->len & F_OR) && !or_block)
1409 print_ip((ipfw_insn_ip *)cmd,
1410 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1411 flags |= HAVE_SRCIP;
1415 case O_IP_DST_LOOKUP:
1419 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1420 if (!(flags & HAVE_DSTIP))
1422 if ((cmd->len & F_OR) && !or_block)
1424 print_ip((ipfw_insn_ip *)cmd,
1425 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1426 flags |= HAVE_DSTIP;
1430 case O_IP6_SRC_MASK:
1432 show_prerequisites(&flags, HAVE_PROTO, 0);
1433 if (!(flags & HAVE_SRCIP))
1435 if ((cmd->len & F_OR) && !or_block)
1437 print_ip6((ipfw_insn_ip6 *)cmd,
1438 (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1439 flags |= HAVE_SRCIP | HAVE_PROTO;
1443 case O_IP6_DST_MASK:
1445 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1446 if (!(flags & HAVE_DSTIP))
1448 if ((cmd->len & F_OR) && !or_block)
1450 print_ip6((ipfw_insn_ip6 *)cmd,
1451 (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1452 flags |= HAVE_DSTIP;
1456 print_flow6id( (ipfw_insn_u32 *) cmd );
1457 flags |= HAVE_OPTIONS;
1461 show_prerequisites(&flags,
1462 HAVE_PROTO | HAVE_SRCIP |
1463 HAVE_DSTIP | HAVE_IP, 0);
1465 if (flags & HAVE_DSTIP)
1467 show_prerequisites(&flags,
1468 HAVE_PROTO | HAVE_SRCIP, 0);
1469 if ((cmd->len & F_OR) && !or_block)
1471 if (cmd->len & F_NOT)
1473 print_newports((ipfw_insn_u16 *)cmd, proto,
1474 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1478 struct protoent *pe = NULL;
1480 if ((cmd->len & F_OR) && !or_block)
1482 if (cmd->len & F_NOT)
1485 pe = getprotobynumber(cmd->arg1);
1486 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1487 !(flags & HAVE_PROTO))
1488 show_prerequisites(&flags,
1489 HAVE_PROTO | HAVE_IP | HAVE_SRCIP |
1490 HAVE_DSTIP | HAVE_OPTIONS, 0);
1491 if (flags & HAVE_OPTIONS)
1494 printf(" %s", pe->p_name);
1496 printf(" %u", cmd->arg1);
1498 flags |= HAVE_PROTO;
1501 default: /*options ... */
1502 if (!(cmd->len & (F_OR|F_NOT)))
1503 if (((cmd->opcode == O_IP6) &&
1504 (flags & HAVE_PROTO6)) ||
1505 ((cmd->opcode == O_IP4) &&
1506 (flags & HAVE_PROTO4)))
1508 show_prerequisites(&flags, HAVE_PROTO | HAVE_SRCIP |
1509 HAVE_DSTIP | HAVE_IP | HAVE_OPTIONS, 0);
1510 if ((cmd->len & F_OR) && !or_block)
1512 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1514 switch(cmd->opcode) {
1516 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1519 print_mac(m->addr, m->mask);
1520 print_mac(m->addr + 6, m->mask + 6);
1525 print_newports((ipfw_insn_u16 *)cmd,
1526 IPPROTO_ETHERTYPE, cmd->opcode);
1535 printf(" fib %u", cmd->arg1 );
1542 printf(cmd->len & F_NOT ? " out" : " in");
1546 switch (cmd->arg1) {
1548 printf(" diverted");
1551 printf(" diverted-loopback");
1554 printf(" diverted-output");
1557 printf(" diverted-?<%u>", cmd->arg1);
1570 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1572 if (cmd->opcode == O_XMIT)
1574 else if (cmd->opcode == O_RECV)
1576 else /* if (cmd->opcode == O_VIA) */
1578 if (cmdif->name[0] == '\0')
1580 inet_ntoa(cmdif->p.ip));
1581 else if (cmdif->name[0] == '\1') /* interface table */
1582 printf(" %s table(%d)", s, cmdif->p.glob);
1584 printf(" %s %s", s, cmdif->name);
1589 if (F_LEN(cmd) == 1)
1590 printf(" ipid %u", cmd->arg1 );
1592 print_newports((ipfw_insn_u16 *)cmd, 0,
1597 if (F_LEN(cmd) == 1)
1598 printf(" ipttl %u", cmd->arg1 );
1600 print_newports((ipfw_insn_u16 *)cmd, 0,
1605 printf(" ipver %u", cmd->arg1 );
1608 case O_IPPRECEDENCE:
1609 printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1613 print_dscp((ipfw_insn_u32 *)cmd);
1617 if (F_LEN(cmd) == 1)
1618 printf(" iplen %u", cmd->arg1 );
1620 print_newports((ipfw_insn_u16 *)cmd, 0,
1625 print_flags("ipoptions", cmd, f_ipopts);
1629 print_flags("iptos", cmd, f_iptos);
1633 print_icmptypes((ipfw_insn_u32 *)cmd);
1637 printf(" established");
1641 if (F_LEN(cmd) == 1)
1642 printf(" tcpdatalen %u", cmd->arg1 );
1644 print_newports((ipfw_insn_u16 *)cmd, 0,
1649 print_flags("tcpflags", cmd, f_tcpflags);
1653 print_flags("tcpoptions", cmd, f_tcpopts);
1657 if (F_LEN(cmd) == 1)
1658 printf(" tcpwin %u", cmd->arg1);
1660 print_newports((ipfw_insn_u16 *)cmd, 0,
1665 printf(" tcpack %d", ntohl(cmd32->d[0]));
1669 printf(" tcpseq %d", ntohl(cmd32->d[0]));
1674 struct passwd *pwd = getpwuid(cmd32->d[0]);
1677 printf(" uid %s", pwd->pw_name);
1679 printf(" uid %u", cmd32->d[0]);
1685 struct group *grp = getgrgid(cmd32->d[0]);
1688 printf(" gid %s", grp->gr_name);
1690 printf(" gid %u", cmd32->d[0]);
1695 printf(" jail %d", cmd32->d[0]);
1699 printf(" verrevpath");
1703 printf(" versrcreach");
1707 printf(" antispoof");
1715 comment = (char *)(cmd + 1);
1719 printf(" keep-state");
1723 struct _s_x *p = limit_masks;
1724 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1725 uint8_t x = c->limit_mask;
1726 char const *comma = " ";
1729 for (; p->x != 0 ; p++)
1730 if ((x & p->x) == p->x) {
1732 printf("%s%s", comma, p->s);
1735 PRINT_UINT_ARG(" ", c->conn_limit);
1748 print_icmp6types((ipfw_insn_u32 *)cmd);
1752 print_ext6hdr( (ipfw_insn *) cmd );
1756 if (F_LEN(cmd) == 1)
1757 PRINT_UINT_ARG(" tagged ", cmd->arg1);
1759 print_newports((ipfw_insn_u16 *)cmd, 0,
1764 printf(" [opcode %d len %d]",
1765 cmd->opcode, cmd->len);
1768 if (cmd->len & F_OR) {
1771 } else if (or_block) {
1776 show_prerequisites(&flags, HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP
1779 printf(" // %s", comment);
1784 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth)
1786 struct protoent *pe;
1789 char buf[INET6_ADDRSTRLEN];
1791 if (!co.do_expired) {
1792 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1795 bcopy(&d->rule, &rulenum, sizeof(rulenum));
1796 printf("%05d", rulenum);
1797 if (pcwidth > 0 || bcwidth > 0) {
1799 pr_u64(&d->pcnt, pcwidth);
1800 pr_u64(&d->bcnt, bcwidth);
1801 printf("(%ds)", d->expire);
1803 switch (d->dyn_type) {
1804 case O_LIMIT_PARENT:
1805 printf(" PARENT %d", d->count);
1810 case O_KEEP_STATE: /* bidir, no mask */
1815 if ((pe = getprotobynumber(d->id.proto)) != NULL)
1816 printf(" %s", pe->p_name);
1818 printf(" proto %u", d->id.proto);
1820 if (d->id.addr_type == 4) {
1821 a.s_addr = htonl(d->id.src_ip);
1822 printf(" %s %d", inet_ntoa(a), d->id.src_port);
1824 a.s_addr = htonl(d->id.dst_ip);
1825 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
1826 } else if (d->id.addr_type == 6) {
1827 printf(" %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
1828 sizeof(buf)), d->id.src_port);
1829 printf(" <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6, buf,
1830 sizeof(buf)), d->id.dst_port);
1832 printf(" UNKNOWN <-> UNKNOWN\n");
1838 * This one handles all set-related commands
1839 * ipfw set { show | enable | disable }
1841 * ipfw set move X to Y
1842 * ipfw set move rule X to Y
1845 ipfw_sets_handler(char *av[])
1847 uint32_t set_disable, masks[2];
1850 uint8_t cmd, new_set;
1855 errx(EX_USAGE, "set needs command");
1856 if (_substrcmp(*av, "show") == 0) {
1861 nalloc = nbytes = sizeof(struct ip_fw);
1862 while (nbytes >= nalloc) {
1865 nalloc = nalloc * 2 + 200;
1867 data = safe_calloc(1, nbytes);
1868 if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0)
1869 err(EX_OSERR, "getsockopt(IP_FW_GET)");
1872 bcopy(&((struct ip_fw *)data)->next_rule,
1873 &set_disable, sizeof(set_disable));
1875 for (i = 0, msg = "disable" ; i < RESVD_SET; i++)
1876 if ((set_disable & (1<<i))) {
1877 printf("%s %d", msg, i);
1880 msg = (set_disable) ? " enable" : "enable";
1881 for (i = 0; i < RESVD_SET; i++)
1882 if (!(set_disable & (1<<i))) {
1883 printf("%s %d", msg, i);
1887 } else if (_substrcmp(*av, "swap") == 0) {
1889 if ( av[0] == NULL || av[1] == NULL )
1890 errx(EX_USAGE, "set swap needs 2 set numbers\n");
1891 rulenum = atoi(av[0]);
1892 new_set = atoi(av[1]);
1893 if (!isdigit(*(av[0])) || rulenum > RESVD_SET)
1894 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
1895 if (!isdigit(*(av[1])) || new_set > RESVD_SET)
1896 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
1897 masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
1898 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
1899 } else if (_substrcmp(*av, "move") == 0) {
1901 if (av[0] && _substrcmp(*av, "rule") == 0) {
1906 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
1907 av[3] != NULL || _substrcmp(av[1], "to") != 0)
1908 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
1909 rulenum = atoi(av[0]);
1910 new_set = atoi(av[2]);
1911 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) ||
1912 (cmd == 2 && rulenum == IPFW_DEFAULT_RULE) )
1913 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
1914 if (!isdigit(*(av[2])) || new_set > RESVD_SET)
1915 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
1916 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
1917 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
1918 } else if (_substrcmp(*av, "disable") == 0 ||
1919 _substrcmp(*av, "enable") == 0 ) {
1920 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
1923 masks[0] = masks[1] = 0;
1926 if (isdigit(**av)) {
1928 if (i < 0 || i > RESVD_SET)
1930 "invalid set number %d\n", i);
1931 masks[which] |= (1<<i);
1932 } else if (_substrcmp(*av, "disable") == 0)
1934 else if (_substrcmp(*av, "enable") == 0)
1938 "invalid set command %s\n", *av);
1941 if ( (masks[0] & masks[1]) != 0 )
1943 "cannot enable and disable the same set\n");
1945 i = do_cmd(IP_FW_DEL, masks, sizeof(masks));
1947 warn("set enable/disable: setsockopt(IP_FW_DEL)");
1949 errx(EX_USAGE, "invalid set command %s\n", *av);
1953 ipfw_sysctl_handler(char *av[], int which)
1957 if (av[0] == NULL) {
1958 warnx("missing keyword to enable/disable\n");
1959 } else if (_substrcmp(*av, "firewall") == 0) {
1960 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
1961 &which, sizeof(which));
1962 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
1963 &which, sizeof(which));
1964 } else if (_substrcmp(*av, "one_pass") == 0) {
1965 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
1966 &which, sizeof(which));
1967 } else if (_substrcmp(*av, "debug") == 0) {
1968 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
1969 &which, sizeof(which));
1970 } else if (_substrcmp(*av, "verbose") == 0) {
1971 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
1972 &which, sizeof(which));
1973 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
1974 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
1975 &which, sizeof(which));
1977 } else if (_substrcmp(*av, "altq") == 0) {
1978 altq_set_enabled(which);
1981 warnx("unrecognize enable/disable keyword: %s\n", *av);
1986 ipfw_list(int ac, char *av[], int show_counters)
1989 ipfw_dyn_rule *dynrules, *d;
1991 #define NEXT(r) ((struct ip_fw *)((char *)r + RULESIZE(r)))
1994 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
1995 int exitval = EX_OK;
2003 const int ocmd = co.do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
2004 int nalloc = 1024; /* start somewhere... */
2009 fprintf(stderr, "Testing only, list disabled\n");
2013 dummynet_list(ac, av, show_counters);
2020 /* get rules or pipes from kernel, resizing array as necessary */
2023 while (nbytes >= nalloc) {
2024 nalloc = nalloc * 2 + 200;
2026 data = safe_realloc(data, nbytes);
2027 if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0)
2028 err(EX_OSERR, "getsockopt(IP_%s_GET)",
2029 co.do_pipe ? "DUMMYNET" : "FW");
2033 * Count static rules. They have variable size so we
2034 * need to scan the list to count them.
2036 for (nstat = 1, r = data, lim = (char *)data + nbytes;
2037 r->rulenum < IPFW_DEFAULT_RULE && (char *)r < lim;
2038 ++nstat, r = NEXT(r) )
2042 * Count dynamic rules. This is easier as they have
2046 dynrules = (ipfw_dyn_rule *)r ;
2047 n = (char *)r - (char *)data;
2048 ndyn = (nbytes - n) / sizeof *dynrules;
2050 /* if showing stats, figure out column widths ahead of time */
2051 bcwidth = pcwidth = 0;
2052 if (show_counters) {
2053 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
2054 /* skip rules from another set */
2055 if (co.use_set && r->set != co.use_set - 1)
2058 /* packet counter */
2059 width = pr_u64(&r->pcnt, 0);
2060 if (width > pcwidth)
2064 width = pr_u64(&r->bcnt, 0);
2065 if (width > bcwidth)
2069 if (co.do_dynamic && ndyn) {
2070 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2072 /* skip rules from another set */
2073 bcopy((char *)&d->rule + sizeof(uint16_t),
2074 &set, sizeof(uint8_t));
2075 if (set != co.use_set - 1)
2078 width = pr_u64(&d->pcnt, 0);
2079 if (width > pcwidth)
2082 width = pr_u64(&d->bcnt, 0);
2083 if (width > bcwidth)
2087 /* if no rule numbers were specified, list all rules */
2089 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
2090 if (co.use_set && r->set != co.use_set - 1)
2092 show_ipfw(r, pcwidth, bcwidth);
2095 if (co.do_dynamic && ndyn) {
2096 printf("## Dynamic rules (%d):\n", ndyn);
2097 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2099 bcopy((char *)&d->rule + sizeof(uint16_t),
2100 &set, sizeof(uint8_t));
2101 if (set != co.use_set - 1)
2104 show_dyn_ipfw(d, pcwidth, bcwidth);
2110 /* display specific rules requested on command line */
2112 for (lac = ac, lav = av; lac != 0; lac--) {
2113 /* convert command line rule # */
2114 last = rnum = strtoul(*lav++, &endptr, 10);
2116 last = strtoul(endptr+1, &endptr, 10);
2119 warnx("invalid rule number: %s", *(lav - 1));
2122 for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) {
2123 if (r->rulenum > last)
2125 if (co.use_set && r->set != co.use_set - 1)
2127 if (r->rulenum >= rnum && r->rulenum <= last) {
2128 show_ipfw(r, pcwidth, bcwidth);
2133 /* give precedence to other error(s) */
2134 if (exitval == EX_OK)
2135 exitval = EX_UNAVAILABLE;
2136 warnx("rule %lu does not exist", rnum);
2140 if (co.do_dynamic && ndyn) {
2141 printf("## Dynamic rules:\n");
2142 for (lac = ac, lav = av; lac != 0; lac--) {
2143 last = rnum = strtoul(*lav++, &endptr, 10);
2145 last = strtoul(endptr+1, &endptr, 10);
2147 /* already warned */
2149 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2152 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2156 bcopy((char *)&d->rule + sizeof(uint16_t),
2157 &set, sizeof(uint8_t));
2158 if (set != co.use_set - 1)
2161 if (r->rulenum >= rnum && r->rulenum <= last)
2162 show_dyn_ipfw(d, pcwidth, bcwidth);
2172 if (exitval != EX_OK)
2178 lookup_host (char *host, struct in_addr *ipaddr)
2182 if (!inet_aton(host, ipaddr)) {
2183 if ((he = gethostbyname(host)) == NULL)
2185 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2191 * fills the addr and mask fields in the instruction as appropriate from av.
2192 * Update length as appropriate.
2193 * The following formats are allowed:
2194 * me returns O_IP_*_ME
2195 * 1.2.3.4 single IP address
2196 * 1.2.3.4:5.6.7.8 address:mask
2197 * 1.2.3.4/24 address/mask
2198 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
2199 * We can have multiple comma-separated address/mask entries.
2202 fill_ip(ipfw_insn_ip *cmd, char *av, int cblen)
2205 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2207 cmd->o.len &= ~F_LEN_MASK; /* zero len */
2209 if (_substrcmp(av, "any") == 0)
2212 if (_substrcmp(av, "me") == 0) {
2213 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2217 if (strncmp(av, "table(", 6) == 0) {
2218 char *p = strchr(av + 6, ',');
2222 cmd->o.opcode = O_IP_DST_LOOKUP;
2223 cmd->o.arg1 = strtoul(av + 6, NULL, 0);
2225 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2226 d[0] = strtoul(p, NULL, 0);
2228 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2234 * After the address we can have '/' or ':' indicating a mask,
2235 * ',' indicating another address follows, '{' indicating a
2236 * set of addresses of unspecified size.
2238 char *t = NULL, *p = strpbrk(av, "/:,{");
2242 CHECK_LENGTH(cblen, F_INSN_SIZE(ipfw_insn) + 2 + len);
2247 if ((t = strpbrk(p, ",{")) != NULL) {
2254 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2255 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2258 if (!inet_aton(p, (struct in_addr *)&d[1]))
2259 errx(EX_DATAERR, "bad netmask ``%s''", p);
2264 d[1] = htonl(0); /* mask */
2265 else if (masklen > 32)
2266 errx(EX_DATAERR, "bad width ``%s''", p);
2268 d[1] = htonl(~0 << (32 - masklen));
2270 case '{': /* no mask, assume /24 and put back the '{' */
2271 d[1] = htonl(~0 << (32 - 24));
2275 case ',': /* single address plus continuation */
2278 case 0: /* initialization value */
2280 d[1] = htonl(~0); /* force /32 */
2283 d[0] &= d[1]; /* mask base address with mask */
2286 /* find next separator */
2288 p = strpbrk(p, ",{");
2289 if (p && *p == '{') {
2291 * We have a set of addresses. They are stored as follows:
2292 * arg1 is the set size (powers of 2, 2..256)
2293 * addr is the base address IN HOST FORMAT
2294 * mask.. is an array of arg1 bits (rounded up to
2295 * the next multiple of 32) with bits set
2296 * for each host in the map.
2298 uint32_t *map = (uint32_t *)&cmd->mask;
2300 int i = contigmask((uint8_t *)&(d[1]), 32);
2303 errx(EX_DATAERR, "address set cannot be in a list");
2304 if (i < 24 || i > 31)
2305 errx(EX_DATAERR, "invalid set with mask %d\n", i);
2306 cmd->o.arg1 = 1<<(32-i); /* map length */
2307 d[0] = ntohl(d[0]); /* base addr in host format */
2308 cmd->o.opcode = O_IP_DST_SET; /* default */
2309 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2310 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2311 map[i] = 0; /* clear map */
2315 high = low + cmd->o.arg1 - 1;
2317 * Here, i stores the previous value when we specify a range
2318 * of addresses within a mask, e.g. 45-63. i = -1 means we
2319 * have no previous value.
2321 i = -1; /* previous value in a range */
2322 while (isdigit(*av)) {
2324 int a = strtol(av, &s, 0);
2326 if (s == av) { /* no parameter */
2328 errx(EX_DATAERR, "set not closed\n");
2330 errx(EX_DATAERR, "incomplete range %d-", i);
2333 if (a < low || a > high)
2334 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
2337 if (i == -1) /* no previous in range */
2339 else { /* check that range is valid */
2341 errx(EX_DATAERR, "invalid range %d-%d",
2344 errx(EX_DATAERR, "double '-' in range");
2347 map[i/32] |= 1<<(i & 31);
2358 if (av) /* then *av must be a ',' */
2361 /* Check this entry */
2362 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2364 * 'any' turns the entire list into a NOP.
2365 * 'not any' never matches, so it is removed from the
2366 * list unless it is the only item, in which case we
2369 if (cmd->o.len & F_NOT) { /* "not any" never matches */
2370 if (av == NULL && len == 0) /* only this entry */
2371 errx(EX_DATAERR, "not any never matches");
2373 /* else do nothing and skip this entry */
2376 /* A single IP can be stored in an optimized format */
2377 if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
2378 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2381 len += 2; /* two words... */
2384 if (len + 1 > F_LEN_MASK)
2385 errx(EX_DATAERR, "address list too long");
2386 cmd->o.len |= len+1;
2390 /* n2mask sets n bits of the mask */
2392 n2mask(struct in6_addr *mask, int n)
2394 static int minimask[9] =
2395 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
2398 memset(mask, 0, sizeof(struct in6_addr));
2399 p = (u_char *) mask;
2400 for (; n > 0; p++, n -= 8) {
2410 * helper function to process a set of flags and set bits in the
2411 * appropriate masks.
2414 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
2415 struct _s_x *flags, char *p)
2417 uint8_t set=0, clear=0;
2420 char *q; /* points to the separator */
2422 uint8_t *which; /* mask we are working on */
2432 val = match_token(flags, p);
2434 errx(EX_DATAERR, "invalid flag %s", p);
2435 *which |= (uint8_t)val;
2438 cmd->opcode = opcode;
2439 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
2440 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
2445 ipfw_delete(char *av[])
2449 int exitval = EX_OK;
2453 NEED1("missing rule specification");
2454 if ( *av && _substrcmp(*av, "set") == 0) {
2455 /* Do not allow using the following syntax:
2456 * ipfw set N delete set M
2459 errx(EX_DATAERR, "invalid syntax");
2460 do_set = 1; /* delete set */
2465 while (*av && isdigit(**av)) {
2466 i = atoi(*av); av++;
2468 exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
2470 exitval = EX_UNAVAILABLE;
2471 warn("rule %u not available", i);
2473 } else if (co.do_pipe) {
2474 exitval = ipfw_delete_pipe(co.do_pipe, i);
2477 rulenum = (i & 0xffff) | (5 << 24) |
2478 ((co.use_set - 1) << 16);
2480 rulenum = (i & 0xffff) | (do_set << 24);
2481 i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum);
2483 exitval = EX_UNAVAILABLE;
2484 warn("rule %u: setsockopt(IP_FW_DEL)",
2489 if (exitval != EX_OK)
2495 * fill the interface structure. We do not check the name as we can
2496 * create interfaces dynamically, so checking them at insert time
2497 * makes relatively little sense.
2498 * Interface names containing '*', '?', or '[' are assumed to be shell
2499 * patterns which match interfaces.
2502 fill_iface(ipfw_insn_if *cmd, char *arg, int cblen)
2504 cmd->name[0] = '\0';
2505 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
2509 /* Parse the interface or address */
2510 if (strcmp(arg, "any") == 0)
2511 cmd->o.len = 0; /* effectively ignore this command */
2512 else if (strncmp(arg, "table(", 6) == 0) {
2513 char *p = strchr(arg + 6, ',');
2516 cmd->name[0] = '\1'; /* Special value indicating table */
2517 cmd->p.glob = strtoul(arg + 6, NULL, 0);
2518 } else if (!isdigit(*arg)) {
2519 strlcpy(cmd->name, arg, sizeof(cmd->name));
2520 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
2521 } else if (!inet_aton(arg, &cmd->p.ip))
2522 errx(EX_DATAERR, "bad ip address ``%s''", arg);
2526 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
2530 char *ap, *ptr, *optr;
2531 struct ether_addr *mac;
2532 const char *macset = "0123456789abcdefABCDEF:";
2534 if (strcmp(p, "any") == 0) {
2535 for (i = 0; i < ETHER_ADDR_LEN; i++)
2536 addr[i] = mask[i] = 0;
2540 optr = ptr = strdup(p);
2541 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
2543 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
2544 errx(EX_DATAERR, "Incorrect MAC address");
2545 bcopy(mac, addr, ETHER_ADDR_LEN);
2547 errx(EX_DATAERR, "Incorrect MAC address");
2549 if (ptr != NULL) { /* we have mask? */
2550 if (p[ptr - optr - 1] == '/') { /* mask len */
2551 long ml = strtol(ptr, &ap, 10);
2552 if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
2553 errx(EX_DATAERR, "Incorrect mask length");
2554 for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
2555 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
2558 if (strspn(ptr, macset) != l ||
2559 (mac = ether_aton(ptr)) == NULL)
2560 errx(EX_DATAERR, "Incorrect mask");
2561 bcopy(mac, mask, ETHER_ADDR_LEN);
2563 } else { /* default mask: ff:ff:ff:ff:ff:ff */
2564 for (i = 0; i < ETHER_ADDR_LEN; i++)
2567 for (i = 0; i < ETHER_ADDR_LEN; i++)
2574 * helper function, updates the pointer to cmd with the length
2575 * of the current command, and also cleans up the first word of
2576 * the new command in case it has been clobbered before.
2579 next_cmd(ipfw_insn *cmd, int *len)
2582 CHECK_LENGTH(*len, 0);
2584 bzero(cmd, sizeof(*cmd));
2589 * Takes arguments and copies them into a comment
2592 fill_comment(ipfw_insn *cmd, char **av, int cblen)
2595 char *p = (char *)(cmd + 1);
2597 cmd->opcode = O_NOP;
2598 cmd->len = (cmd->len & (F_NOT | F_OR));
2600 /* Compute length of comment string. */
2601 for (i = 0, l = 0; av[i] != NULL; i++)
2602 l += strlen(av[i]) + 1;
2607 "comment too long (max 80 chars)");
2609 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
2612 for (i = 0; av[i] != NULL; i++) {
2621 * A function to fill simple commands of size 1.
2622 * Existing flags are preserved.
2625 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
2627 cmd->opcode = opcode;
2628 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
2633 * Fetch and add the MAC address and type, with masks. This generates one or
2634 * two microinstructions, and returns the pointer to the last one.
2637 add_mac(ipfw_insn *cmd, char *av[], int cblen)
2641 if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
2642 errx(EX_DATAERR, "MAC dst src");
2644 cmd->opcode = O_MACADDR2;
2645 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
2648 mac = (ipfw_insn_mac *)cmd;
2649 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
2650 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
2651 &(mac->mask[ETHER_ADDR_LEN])); /* src */
2656 add_mactype(ipfw_insn *cmd, char *av, int cblen)
2659 errx(EX_DATAERR, "missing MAC type");
2660 if (strcmp(av, "any") != 0) { /* we have a non-null type */
2661 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
2663 cmd->opcode = O_MAC_TYPE;
2670 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
2672 struct protoent *pe;
2676 proto = strtol(av, &ep, 10);
2677 if (*ep != '\0' || proto <= 0) {
2678 if ((pe = getprotobyname(av)) == NULL)
2680 proto = pe->p_proto;
2683 fill_cmd(cmd, O_PROTO, 0, proto);
2689 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
2691 u_char proto = IPPROTO_IP;
2693 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2694 ; /* do not set O_IP4 nor O_IP6 */
2695 else if (strcmp(av, "ip4") == 0)
2696 /* explicit "just IPv4" rule */
2697 fill_cmd(cmd, O_IP4, 0, 0);
2698 else if (strcmp(av, "ip6") == 0) {
2699 /* explicit "just IPv6" rule */
2700 proto = IPPROTO_IPV6;
2701 fill_cmd(cmd, O_IP6, 0, 0);
2703 return add_proto0(cmd, av, protop);
2710 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
2712 u_char proto = IPPROTO_IP;
2714 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2715 ; /* do not set O_IP4 nor O_IP6 */
2716 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
2717 /* explicit "just IPv4" rule */
2718 fill_cmd(cmd, O_IP4, 0, 0);
2719 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
2720 /* explicit "just IPv6" rule */
2721 proto = IPPROTO_IPV6;
2722 fill_cmd(cmd, O_IP6, 0, 0);
2724 return add_proto0(cmd, av, protop);
2731 add_srcip(ipfw_insn *cmd, char *av, int cblen)
2733 fill_ip((ipfw_insn_ip *)cmd, av, cblen);
2734 if (cmd->opcode == O_IP_DST_SET) /* set */
2735 cmd->opcode = O_IP_SRC_SET;
2736 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
2737 cmd->opcode = O_IP_SRC_LOOKUP;
2738 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2739 cmd->opcode = O_IP_SRC_ME;
2740 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2741 cmd->opcode = O_IP_SRC;
2742 else /* addr/mask */
2743 cmd->opcode = O_IP_SRC_MASK;
2748 add_dstip(ipfw_insn *cmd, char *av, int cblen)
2750 fill_ip((ipfw_insn_ip *)cmd, av, cblen);
2751 if (cmd->opcode == O_IP_DST_SET) /* set */
2753 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
2755 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2756 cmd->opcode = O_IP_DST_ME;
2757 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2758 cmd->opcode = O_IP_DST;
2759 else /* addr/mask */
2760 cmd->opcode = O_IP_DST_MASK;
2765 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
2767 /* XXX "any" is trapped before. Perhaps "to" */
2768 if (_substrcmp(av, "any") == 0) {
2770 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
2771 /* XXX todo: check that we have a protocol with ports */
2772 cmd->opcode = opcode;
2779 add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen)
2782 char *host, *ch, buf[INET6_ADDRSTRLEN];
2783 ipfw_insn *ret = NULL;
2786 /* Copy first address in set if needed */
2787 if ((ch = strpbrk(av, "/,")) != NULL) {
2789 strlcpy(buf, av, sizeof(buf));
2790 if (len < sizeof(buf))
2796 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
2797 inet_pton(AF_INET6, host, &a) == 1)
2798 ret = add_srcip6(cmd, av, cblen);
2799 /* XXX: should check for IPv4, not !IPv6 */
2800 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2801 inet_pton(AF_INET6, host, &a) != 1))
2802 ret = add_srcip(cmd, av, cblen);
2803 if (ret == NULL && strcmp(av, "any") != 0)
2810 add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen)
2813 char *host, *ch, buf[INET6_ADDRSTRLEN];
2814 ipfw_insn *ret = NULL;
2817 /* Copy first address in set if needed */
2818 if ((ch = strpbrk(av, "/,")) != NULL) {
2820 strlcpy(buf, av, sizeof(buf));
2821 if (len < sizeof(buf))
2827 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
2828 inet_pton(AF_INET6, host, &a) == 1)
2829 ret = add_dstip6(cmd, av, cblen);
2830 /* XXX: should check for IPv4, not !IPv6 */
2831 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2832 inet_pton(AF_INET6, host, &a) != 1))
2833 ret = add_dstip(cmd, av, cblen);
2834 if (ret == NULL && strcmp(av, "any") != 0)
2841 * Parse arguments and assemble the microinstructions which make up a rule.
2842 * Rules are added into the 'rulebuf' and then copied in the correct order
2843 * into the actual rule.
2845 * The syntax for a rule starts with the action, followed by
2846 * optional action parameters, and the various match patterns.
2847 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
2848 * (generated if the rule includes a keep-state option), then the
2849 * various match patterns, log/altq actions, and the actual action.
2853 ipfw_add(char *av[])
2856 * rules are added into the 'rulebuf' and then copied in
2857 * the correct order into the actual rule.
2858 * Some things that need to go out of order (prob, action etc.)
2861 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255];
2862 int rblen, ablen, cblen;
2864 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
2865 ipfw_insn *first_cmd; /* first match pattern */
2870 * various flags used to record that we entered some fields.
2872 ipfw_insn *have_state = NULL; /* check-state or keep-state */
2873 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
2878 int open_par = 0; /* open parenthesis ( */
2880 /* proto is here because it is used to fetch ports */
2881 u_char proto = IPPROTO_IP; /* default protocol */
2883 double match_prob = 1; /* match probability, default is always match */
2885 bzero(actbuf, sizeof(actbuf)); /* actions go here */
2886 bzero(cmdbuf, sizeof(cmdbuf));
2887 bzero(rulebuf, sizeof(rulebuf));
2889 rule = (struct ip_fw *)rulebuf;
2890 cmd = (ipfw_insn *)cmdbuf;
2891 action = (ipfw_insn *)actbuf;
2893 rblen = sizeof(rulebuf) / sizeof(rulebuf[0]);
2894 rblen -= offsetof(struct ip_fw, cmd) / sizeof(rulebuf[0]);
2895 ablen = sizeof(actbuf) / sizeof(actbuf[0]);
2896 cblen = sizeof(cmdbuf) / sizeof(cmdbuf[0]);
2897 cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
2899 #define CHECK_RBUFLEN(len) { CHECK_LENGTH(rblen, len); rblen -= len; }
2900 #define CHECK_ACTLEN CHECK_LENGTH(ablen, action->len)
2904 /* [rule N] -- Rule number optional */
2905 if (av[0] && isdigit(**av)) {
2906 rule->rulenum = atoi(*av);
2910 /* [set N] -- set number (0..RESVD_SET), optional */
2911 if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
2912 int set = strtoul(av[1], NULL, 10);
2913 if (set < 0 || set > RESVD_SET)
2914 errx(EX_DATAERR, "illegal set %s", av[1]);
2919 /* [prob D] -- match probability, optional */
2920 if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
2921 match_prob = strtod(av[1], NULL);
2923 if (match_prob <= 0 || match_prob > 1)
2924 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
2928 /* action -- mandatory */
2929 NEED1("missing action");
2930 i = match_token(rule_actions, *av);
2932 action->len = 1; /* default */
2935 case TOK_CHECKSTATE:
2936 have_state = action;
2937 action->opcode = O_CHECK_STATE;
2941 action->opcode = O_ACCEPT;
2945 action->opcode = O_DENY;
2950 action->opcode = O_REJECT;
2951 action->arg1 = ICMP_UNREACH_HOST;
2955 action->opcode = O_REJECT;
2956 action->arg1 = ICMP_REJECT_RST;
2960 action->opcode = O_UNREACH6;
2961 action->arg1 = ICMP6_UNREACH_RST;
2965 action->opcode = O_REJECT;
2966 NEED1("missing reject code");
2967 fill_reject_code(&action->arg1, *av);
2972 action->opcode = O_UNREACH6;
2973 NEED1("missing unreach code");
2974 fill_unreach6_code(&action->arg1, *av);
2979 action->opcode = O_COUNT;
2983 action->opcode = O_NAT;
2984 action->len = F_INSN_SIZE(ipfw_insn_nat);
2986 if (_substrcmp(*av, "global") == 0) {
2994 action->opcode = O_QUEUE;
2997 action->opcode = O_PIPE;
3000 action->opcode = O_SKIPTO;
3003 action->opcode = O_NETGRAPH;
3006 action->opcode = O_NGTEE;
3009 action->opcode = O_DIVERT;
3012 action->opcode = O_TEE;
3015 action->opcode = O_CALLRETURN;
3018 errx(EX_USAGE, "missing argument for %s", *(av - 1));
3019 if (isdigit(**av)) {
3020 action->arg1 = strtoul(*av, NULL, 10);
3021 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
3022 errx(EX_DATAERR, "illegal argument for %s",
3024 } else if (_substrcmp(*av, "tablearg") == 0) {
3025 action->arg1 = IP_FW_TABLEARG;
3026 } else if (i == TOK_DIVERT || i == TOK_TEE) {
3029 s = getservbyname(av[0], "divert");
3031 action->arg1 = ntohs(s->s_port);
3033 errx(EX_DATAERR, "illegal divert/tee port");
3035 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
3041 * Locate the address-port separator (':' or ',').
3042 * Could be one of the following:
3046 * IPv6 w:x:y::z,port
3047 * The ':' can only be used with hostname and IPv4 address.
3048 * XXX-BZ Should we also support [w:x:y::z]:port?
3050 struct sockaddr_storage result;
3051 struct addrinfo *res;
3054 u_short port_number;
3056 NEED1("missing forward address[:port]");
3059 * locate the address-port separator (':' or ',')
3061 s = strchr(*av, ',');
3063 /* Distinguish between IPv4:port and IPv6 cases. */
3064 s = strchr(*av, ':');
3065 if (s && strchr(s+1, ':'))
3066 s = NULL; /* no port */
3071 /* Terminate host portion and set s to start of port. */
3073 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
3076 "illegal forwarding port ``%s''", s);
3077 port_number = (u_short)i;
3080 if (_substrcmp(*av, "tablearg") == 0) {
3082 ((struct sockaddr_in*)&result)->sin_addr.s_addr =
3086 * Resolve the host name or address to a family and a
3087 * network representation of the address.
3089 if (getaddrinfo(*av, NULL, NULL, &res))
3090 errx(EX_DATAERR, NULL);
3091 /* Just use the first host in the answer. */
3092 family = res->ai_family;
3093 memcpy(&result, res->ai_addr, res->ai_addrlen);
3097 if (family == PF_INET) {
3098 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
3100 action->opcode = O_FORWARD_IP;
3101 action->len = F_INSN_SIZE(ipfw_insn_sa);
3105 * In the kernel we assume AF_INET and use only
3106 * sin_port and sin_addr. Remember to set sin_len as
3107 * the routing code seems to use it too.
3109 p->sa.sin_len = sizeof(struct sockaddr_in);
3110 p->sa.sin_family = AF_INET;
3111 p->sa.sin_port = port_number;
3112 p->sa.sin_addr.s_addr =
3113 ((struct sockaddr_in *)&result)->sin_addr.s_addr;
3114 } else if (family == PF_INET6) {
3115 ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
3117 action->opcode = O_FORWARD_IP6;
3118 action->len = F_INSN_SIZE(ipfw_insn_sa6);
3121 p->sa.sin6_len = sizeof(struct sockaddr_in6);
3122 p->sa.sin6_family = AF_INET6;
3123 p->sa.sin6_port = port_number;
3124 p->sa.sin6_flowinfo = 0;
3125 p->sa.sin6_scope_id = 0;
3126 /* No table support for v6 yet. */
3127 bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
3128 &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
3130 errx(EX_DATAERR, "Invalid address family in forward action");
3136 /* pretend it is a 'count' rule followed by the comment */
3137 action->opcode = O_COUNT;
3138 av--; /* go back... */
3144 size_t intsize = sizeof(int);
3146 action->opcode = O_SETFIB;
3147 NEED1("missing fib number");
3148 if (_substrcmp(*av, "tablearg") == 0) {
3149 action->arg1 = IP_FW_TABLEARG;
3151 action->arg1 = strtoul(*av, NULL, 10);
3152 if (sysctlbyname("net.fibs", &numfibs, &intsize,
3154 errx(EX_DATAERR, "fibs not suported.\n");
3155 if (action->arg1 >= numfibs) /* Temporary */
3156 errx(EX_DATAERR, "fib too large.\n");
3166 action->opcode = O_SETDSCP;
3167 NEED1("missing DSCP code");
3168 if (_substrcmp(*av, "tablearg") == 0) {
3169 action->arg1 = IP_FW_TABLEARG;
3170 } else if (isalpha(*av[0])) {
3171 if ((code = match_token(f_ipdscp, *av)) == -1)
3172 errx(EX_DATAERR, "Unknown DSCP code");
3173 action->arg1 = code;
3175 action->arg1 = strtoul(*av, NULL, 10);
3181 action->opcode = O_REASS;
3185 fill_cmd(action, O_CALLRETURN, F_NOT, 0);
3189 errx(EX_DATAERR, "invalid action %s\n", av[-1]);
3191 action = next_cmd(action, &ablen);
3194 * [altq queuename] -- altq tag, optional
3195 * [log [logamount N]] -- log, optional
3197 * If they exist, it go first in the cmdbuf, but then it is
3198 * skipped in the copy section to the end of the buffer.
3200 while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
3205 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
3210 "log cannot be specified more than once");
3211 have_log = (ipfw_insn *)c;
3212 cmd->len = F_INSN_SIZE(ipfw_insn_log);
3214 cmd->opcode = O_LOG;
3215 if (av[0] && _substrcmp(*av, "logamount") == 0) {
3217 NEED1("logamount requires argument");
3221 "logamount must be positive");
3225 len = sizeof(c->max_log);
3226 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
3227 &c->max_log, &len, NULL, 0) == -1) {
3232 errx(1, "sysctlbyname(\"%s\")",
3233 "net.inet.ip.fw.verbose_limit");
3242 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
3244 NEED1("missing altq queue name");
3247 "altq cannot be specified more than once");
3248 have_altq = (ipfw_insn *)a;
3249 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
3251 cmd->opcode = O_ALTQ;
3252 a->qid = altq_name_to_qid(*av);
3263 errx(EX_USAGE, "tag and untag cannot be "
3264 "specified more than once");
3265 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
3266 rule_action_params);
3268 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
3276 cmd = next_cmd(cmd, &cblen);
3279 if (have_state) /* must be a check-state, we are done */
3282 #define OR_START(target) \
3283 if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
3285 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
3288 if ( (av[0])[1] == '\0') { \
3299 strcmp(*av, ")") == 0 || \
3300 strcmp(*av, "}") == 0)) { \
3305 errx(EX_USAGE, "missing \")\"\n"); \
3309 if (av[0] && _substrcmp(*av, "not") == 0) { \
3310 if (cmd->len & F_NOT) \
3311 errx(EX_USAGE, "double \"not\" not allowed\n"); \
3312 cmd->len |= F_NOT; \
3316 #define OR_BLOCK(target) \
3317 if (av[0] && _substrcmp(*av, "or") == 0) { \
3318 if (prev == NULL || open_par == 0) \
3319 errx(EX_DATAERR, "invalid OR block"); \
3320 prev->len |= F_OR; \
3330 * MAC addresses, optional.
3331 * If we have this, we skip the part "proto from src to dst"
3332 * and jump straight to the option parsing.
3335 NEED1("missing protocol");
3336 if (_substrcmp(*av, "MAC") == 0 ||
3337 _substrcmp(*av, "mac") == 0) {
3338 av++; /* the "MAC" keyword */
3339 add_mac(cmd, av); /* exits in case of errors */
3340 cmd = next_cmd(cmd);
3341 av += 2; /* dst-mac and src-mac */
3343 NEED1("missing mac type");
3344 if (add_mactype(cmd, av[0]))
3345 cmd = next_cmd(cmd);
3346 av++; /* any or mac-type */
3352 * protocol, mandatory
3354 OR_START(get_proto);
3356 NEED1("missing protocol");
3357 if (add_proto_compat(cmd, *av, &proto)) {
3359 if (F_LEN(cmd) != 0) {
3361 cmd = next_cmd(cmd, &cblen);
3363 } else if (first_cmd != cmd) {
3364 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
3367 OR_BLOCK(get_proto);
3372 if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
3373 errx(EX_USAGE, "missing ``from''");
3377 * source IP, mandatory
3379 OR_START(source_ip);
3380 NOT_BLOCK; /* optional "not" */
3381 NEED1("missing source address");
3382 if (add_src(cmd, *av, proto, cblen)) {
3384 if (F_LEN(cmd) != 0) { /* ! any */
3386 cmd = next_cmd(cmd, &cblen);
3389 errx(EX_USAGE, "bad source address %s", *av);
3390 OR_BLOCK(source_ip);
3393 * source ports, optional
3395 NOT_BLOCK; /* optional "not" */
3396 if ( av[0] != NULL ) {
3397 if (_substrcmp(*av, "any") == 0 ||
3398 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
3400 if (F_LEN(cmd) != 0)
3401 cmd = next_cmd(cmd, &cblen);
3408 if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
3409 errx(EX_USAGE, "missing ``to''");
3413 * destination, mandatory
3416 NOT_BLOCK; /* optional "not" */
3417 NEED1("missing dst address");
3418 if (add_dst(cmd, *av, proto, cblen)) {
3420 if (F_LEN(cmd) != 0) { /* ! any */
3422 cmd = next_cmd(cmd, &cblen);
3425 errx( EX_USAGE, "bad destination address %s", *av);
3429 * dest. ports, optional
3431 NOT_BLOCK; /* optional "not" */
3433 if (_substrcmp(*av, "any") == 0 ||
3434 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
3436 if (F_LEN(cmd) != 0)
3437 cmd = next_cmd(cmd, &cblen);
3442 if (av[0] && first_cmd == cmd) {
3444 * nothing specified so far, store in the rule to ease
3450 while ( av[0] != NULL ) {
3452 ipfw_insn_u32 *cmd32; /* alias for cmd */
3455 cmd32 = (ipfw_insn_u32 *)cmd;
3457 if (*s == '!') { /* alternate syntax for NOT */
3458 if (cmd->len & F_NOT)
3459 errx(EX_USAGE, "double \"not\" not allowed\n");
3463 i = match_token(rule_options, s);
3467 if (cmd->len & F_NOT)
3468 errx(EX_USAGE, "double \"not\" not allowed\n");
3473 if (open_par == 0 || prev == NULL)
3474 errx(EX_USAGE, "invalid \"or\" block\n");
3478 case TOK_STARTBRACE:
3480 errx(EX_USAGE, "+nested \"(\" not allowed\n");
3486 errx(EX_USAGE, "+missing \")\"\n");
3492 fill_cmd(cmd, O_IN, 0, 0);
3496 cmd->len ^= F_NOT; /* toggle F_NOT */
3497 fill_cmd(cmd, O_IN, 0, 0);
3501 fill_cmd(cmd, O_DIVERTED, 0, 3);
3504 case TOK_DIVERTEDLOOPBACK:
3505 fill_cmd(cmd, O_DIVERTED, 0, 1);
3508 case TOK_DIVERTEDOUTPUT:
3509 fill_cmd(cmd, O_DIVERTED, 0, 2);
3513 fill_cmd(cmd, O_FRAG, 0, 0);
3517 fill_cmd(cmd, O_LAYER2, 0, 0);
3523 NEED1("recv, xmit, via require interface name"
3525 fill_iface((ipfw_insn_if *)cmd, av[0], cblen);
3527 if (F_LEN(cmd) == 0) /* not a valid address */
3530 cmd->opcode = O_XMIT;
3531 else if (i == TOK_RECV)
3532 cmd->opcode = O_RECV;
3533 else if (i == TOK_VIA)
3534 cmd->opcode = O_VIA;
3538 NEED1("icmptypes requires list of types");
3539 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
3543 case TOK_ICMP6TYPES:
3544 NEED1("icmptypes requires list of types");
3545 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
3550 NEED1("ipttl requires TTL");
3551 if (strpbrk(*av, "-,")) {
3552 if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
3553 errx(EX_DATAERR, "invalid ipttl %s", *av);
3555 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
3560 NEED1("ipid requires id");
3561 if (strpbrk(*av, "-,")) {
3562 if (!add_ports(cmd, *av, 0, O_IPID, cblen))
3563 errx(EX_DATAERR, "invalid ipid %s", *av);
3565 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
3570 NEED1("iplen requires length");
3571 if (strpbrk(*av, "-,")) {
3572 if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
3573 errx(EX_DATAERR, "invalid ip len %s", *av);
3575 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
3580 NEED1("ipver requires version");
3581 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
3585 case TOK_IPPRECEDENCE:
3586 NEED1("ipprecedence requires value");
3587 fill_cmd(cmd, O_IPPRECEDENCE, 0,
3588 (strtoul(*av, NULL, 0) & 7) << 5);
3593 NEED1("missing DSCP code");
3594 fill_dscp(cmd, *av, cblen);
3599 NEED1("missing argument for ipoptions");
3600 fill_flags(cmd, O_IPOPT, f_ipopts, *av);
3605 NEED1("missing argument for iptos");
3606 fill_flags(cmd, O_IPTOS, f_iptos, *av);
3611 NEED1("uid requires argument");
3617 cmd->opcode = O_UID;
3618 uid = strtoul(*av, &end, 0);
3619 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
3621 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
3622 cmd32->d[0] = pwd->pw_uid;
3623 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3629 NEED1("gid requires argument");
3635 cmd->opcode = O_GID;
3636 gid = strtoul(*av, &end, 0);
3637 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
3639 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
3640 cmd32->d[0] = grp->gr_gid;
3641 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3647 NEED1("jail requires argument");
3652 cmd->opcode = O_JAIL;
3653 jid = (int)strtol(*av, &end, 0);
3654 if (jid < 0 || *end != '\0')
3655 errx(EX_DATAERR, "jail requires prison ID");
3656 cmd32->d[0] = (uint32_t)jid;
3657 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3663 fill_cmd(cmd, O_ESTAB, 0, 0);
3667 fill_cmd(cmd, O_TCPFLAGS, 0,
3668 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
3671 case TOK_TCPDATALEN:
3672 NEED1("tcpdatalen requires length");
3673 if (strpbrk(*av, "-,")) {
3674 if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
3675 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
3677 fill_cmd(cmd, O_TCPDATALEN, 0,
3678 strtoul(*av, NULL, 0));
3683 NEED1("missing argument for tcpoptions");
3684 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
3690 NEED1("tcpseq/tcpack requires argument");
3691 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3692 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
3693 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
3698 NEED1("tcpwin requires length");
3699 if (strpbrk(*av, "-,")) {
3700 if (!add_ports(cmd, *av, 0, O_TCPWIN, cblen))
3701 errx(EX_DATAERR, "invalid tcpwin len %s", *av);
3703 fill_cmd(cmd, O_TCPWIN, 0,
3704 strtoul(*av, NULL, 0));
3709 NEED1("missing argument for tcpflags");
3710 cmd->opcode = O_TCPFLAGS;
3711 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
3717 errx(EX_USAGE, "keep-state cannot be part "
3720 errx(EX_USAGE, "only one of keep-state "
3721 "and limit is allowed");
3723 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
3727 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
3732 "limit cannot be part of an or block");
3734 errx(EX_USAGE, "only one of keep-state and "
3735 "limit is allowed");
3738 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
3740 cmd->opcode = O_LIMIT;
3741 c->limit_mask = c->conn_limit = 0;
3743 while ( av[0] != NULL ) {
3744 if ((val = match_token(limit_masks, *av)) <= 0)
3746 c->limit_mask |= val;
3750 if (c->limit_mask == 0)
3751 errx(EX_USAGE, "limit: missing limit mask");
3753 GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
3754 TOK_LIMIT, rule_options);
3761 NEED1("missing protocol");
3762 if (add_proto(cmd, *av, &proto)) {
3765 errx(EX_DATAERR, "invalid protocol ``%s''",
3770 NEED1("missing source IP");
3771 if (add_srcip(cmd, *av, cblen)) {
3777 NEED1("missing destination IP");
3778 if (add_dstip(cmd, *av, cblen)) {
3784 NEED1("missing source IP6");
3785 if (add_srcip6(cmd, *av, cblen)) {
3791 NEED1("missing destination IP6");
3792 if (add_dstip6(cmd, *av, cblen)) {
3798 NEED1("missing source port");
3799 if (_substrcmp(*av, "any") == 0 ||
3800 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
3803 errx(EX_DATAERR, "invalid source port %s", *av);
3807 NEED1("missing destination port");
3808 if (_substrcmp(*av, "any") == 0 ||
3809 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
3812 errx(EX_DATAERR, "invalid destination port %s",
3817 if (add_mac(cmd, av, cblen))
3822 NEED1("missing mac type");
3823 if (!add_mactype(cmd, *av, cblen))
3824 errx(EX_DATAERR, "invalid mac type %s", *av);
3828 case TOK_VERREVPATH:
3829 fill_cmd(cmd, O_VERREVPATH, 0, 0);
3832 case TOK_VERSRCREACH:
3833 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
3837 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
3841 fill_cmd(cmd, O_IPSEC, 0, 0);
3845 fill_cmd(cmd, O_IP6, 0, 0);
3849 fill_cmd(cmd, O_IP4, 0, 0);
3853 fill_ext6hdr( cmd, *av );
3858 if (proto != IPPROTO_IPV6 )
3859 errx( EX_USAGE, "flow-id filter is active "
3860 "only for ipv6 protocol\n");
3861 fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
3866 fill_comment(cmd, av, cblen);
3871 if (av[0] && strpbrk(*av, "-,")) {
3872 if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
3873 errx(EX_DATAERR, "tagged: invalid tag"
3879 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
3880 TOK_TAGGED, rule_options);
3881 fill_cmd(cmd, O_TAGGED, 0, tag);
3887 NEED1("fib requires fib number");
3888 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
3892 fill_cmd(cmd, O_SOCKARG, 0, 0);
3896 ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
3900 if (!av[0] || !av[1])
3901 errx(EX_USAGE, "format: lookup argument tablenum");
3902 cmd->opcode = O_IP_DST_LOOKUP;
3903 cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
3904 i = match_token(rule_options, *av);
3905 for (j = 0; lookup_key[j] >= 0 ; j++) {
3906 if (i == lookup_key[j])
3909 if (lookup_key[j] <= 0)
3910 errx(EX_USAGE, "format: cannot lookup on %s", *av);
3911 __PAST_END(c->d, 1) = j; // i converted to option
3913 cmd->arg1 = strtoul(*av, &p, 0);
3915 errx(EX_USAGE, "format: lookup argument tablenum");
3921 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
3923 if (F_LEN(cmd) > 0) { /* prepare to advance */
3925 cmd = next_cmd(cmd, &cblen);
3931 * Now copy stuff into the rule.
3932 * If we have a keep-state option, the first instruction
3933 * must be a PROBE_STATE (which is generated here).
3934 * If we have a LOG option, it was stored as the first command,
3935 * and now must be moved to the top of the action part.
3937 dst = (ipfw_insn *)rule->cmd;
3940 * First thing to write into the command stream is the match probability.
3942 if (match_prob != 1) { /* 1 means always match */
3943 dst->opcode = O_PROB;
3945 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
3950 * generate O_PROBE_STATE if necessary
3952 if (have_state && have_state->opcode != O_CHECK_STATE) {
3953 fill_cmd(dst, O_PROBE_STATE, 0, 0);
3954 dst = next_cmd(dst, &rblen);
3957 /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
3958 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
3962 switch (src->opcode) {
3970 bcopy(src, dst, i * sizeof(uint32_t));
3976 * put back the have_state command as last opcode
3978 if (have_state && have_state->opcode != O_CHECK_STATE) {
3979 i = F_LEN(have_state);
3981 bcopy(have_state, dst, i * sizeof(uint32_t));
3985 * start action section
3987 rule->act_ofs = dst - rule->cmd;
3989 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
3991 i = F_LEN(have_log);
3993 bcopy(have_log, dst, i * sizeof(uint32_t));
3997 i = F_LEN(have_altq);
3999 bcopy(have_altq, dst, i * sizeof(uint32_t));
4003 i = F_LEN(have_tag);
4005 bcopy(have_tag, dst, i * sizeof(uint32_t));
4010 * copy all other actions
4012 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
4015 bcopy(src, dst, i * sizeof(uint32_t));
4019 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
4020 i = (char *)dst - (char *)rule;
4021 if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1)
4022 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
4024 show_ipfw(rule, 0, 0);
4028 * clear the counters or the log counters.
4031 ipfw_zero(int ac, char *av[], int optname /* 0 = IP_FW_ZERO, 1 = IP_FW_RESETLOG */)
4033 uint32_t arg, saved_arg;
4036 char const *name = optname ? "RESETLOG" : "ZERO";
4038 optname = optname ? IP_FW_RESETLOG : IP_FW_ZERO;
4043 /* clear all entries */
4044 if (do_cmd(optname, NULL, 0) < 0)
4045 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name);
4047 printf("%s.\n", optname == IP_FW_ZERO ?
4048 "Accounting cleared":"Logging counts reset");
4055 if (isdigit(**av)) {
4056 arg = strtonum(*av, 0, 0xffff, &errstr);
4059 "invalid rule number %s\n", *av);
4062 arg |= (1 << 24) | ((co.use_set - 1) << 16);
4065 if (do_cmd(optname, &arg, sizeof(arg))) {
4066 warn("rule %u: setsockopt(IP_FW_%s)",
4068 failed = EX_UNAVAILABLE;
4069 } else if (!co.do_quiet)
4070 printf("Entry %d %s.\n", saved_arg,
4071 optname == IP_FW_ZERO ?
4072 "cleared" : "logging count reset");
4074 errx(EX_USAGE, "invalid rule number ``%s''", *av);
4077 if (failed != EX_OK)
4082 ipfw_flush(int force)
4084 int cmd = co.do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
4086 if (!force && !co.do_quiet) { /* need to ask user */
4089 printf("Are you sure? [yn] ");
4092 c = toupper(getc(stdin));
4093 while (c != '\n' && getc(stdin) != '\n')
4095 return; /* and do not flush */
4096 } while (c != 'Y' && c != 'N');
4098 if (c == 'N') /* user said no */
4105 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
4107 uint32_t arg = ((co.use_set - 1) & 0xffff) | (1 << 24);
4108 if (do_cmd(IP_FW_DEL, &arg, sizeof(arg)) < 0)
4109 err(EX_UNAVAILABLE, "setsockopt(IP_FW_DEL)");
4110 } else if (do_cmd(cmd, NULL, 0) < 0)
4111 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
4112 co.do_pipe ? "DUMMYNET" : "FW");
4114 printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
4118 static void table_list(uint16_t num, int need_header);
4119 static void table_fill_xentry(char *arg, ipfw_table_xentry *xent);
4122 * This one handles all table-related commands
4123 * ipfw table N add addr[/masklen] [value]
4124 * ipfw table N delete addr[/masklen]
4125 * ipfw table {N | all} flush
4126 * ipfw table {N | all} list
4129 ipfw_table_handler(int ac, char *av[])
4131 ipfw_table_xentry xent;
4136 uint32_t tables_max;
4138 len = sizeof(tables_max);
4139 if (sysctlbyname("net.inet.ip.fw.tables_max", &tables_max, &len,
4142 tables_max = 128; /* Old conservative default */
4144 errx(1, "Can't determine maximum number of ipfw tables."
4145 " Perhaps you forgot to load ipfw module?");
4148 memset(&xent, 0, sizeof(xent));
4151 if (ac && isdigit(**av)) {
4152 xent.tbl = atoi(*av);
4155 } else if (ac && _substrcmp(*av, "all") == 0) {
4160 errx(EX_USAGE, "table number or 'all' keyword required");
4161 if (xent.tbl >= tables_max)
4162 errx(EX_USAGE, "The table number exceeds the maximum allowed "
4163 "value (%d)", tables_max - 1);
4164 NEED1("table needs command");
4165 if (is_all && _substrcmp(*av, "list") != 0
4166 && _substrcmp(*av, "flush") != 0)
4167 errx(EX_USAGE, "table number required");
4169 if (_substrcmp(*av, "add") == 0 ||
4170 _substrcmp(*av, "delete") == 0) {
4171 do_add = **av == 'a';
4174 errx(EX_USAGE, "address required");
4176 table_fill_xentry(*av, &xent);
4181 /* isdigit is a bit of a hack here.. */
4182 if (strchr(*av, (int)'.') == NULL && isdigit(**av)) {
4183 xent.value = strtoul(*av, NULL, 0);
4185 if (lookup_host(*av, (struct in_addr *)&tval) == 0) {
4186 /* The value must be stored in host order *
4187 * so that the values < 65k can be distinguished */
4188 xent.value = ntohl(tval);
4190 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
4195 if (do_setcmd3(do_add ? IP_FW_TABLE_XADD : IP_FW_TABLE_XDEL,
4196 &xent, xent.len) < 0) {
4197 /* If running silent, don't bomb out on these errors. */
4198 if (!(co.do_quiet && (errno == (do_add ? EEXIST : ESRCH))))
4199 err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)",
4200 do_add ? "XADD" : "XDEL");
4201 /* In silent mode, react to a failed add by deleting */
4203 do_setcmd3(IP_FW_TABLE_XDEL, &xent, xent.len);
4204 if (do_setcmd3(IP_FW_TABLE_XADD, &xent, xent.len) < 0)
4206 "setsockopt(IP_FW_TABLE_XADD)");
4209 } else if (_substrcmp(*av, "flush") == 0) {
4210 a = is_all ? tables_max : (uint32_t)(xent.tbl + 1);
4212 if (do_cmd(IP_FW_TABLE_FLUSH, &xent.tbl,
4213 sizeof(xent.tbl)) < 0)
4214 err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)");
4215 } while (++xent.tbl < a);
4216 } else if (_substrcmp(*av, "list") == 0) {
4217 a = is_all ? tables_max : (uint32_t)(xent.tbl + 1);
4219 table_list(xent.tbl, is_all);
4220 } while (++xent.tbl < a);
4222 errx(EX_USAGE, "invalid table command %s", *av);
4226 table_fill_xentry(char *arg, ipfw_table_xentry *xent)
4228 int addrlen, mask, masklen, type;
4229 struct in6_addr *paddr;
4240 * Let's try to guess type by agrument.
4245 * 4) port, uid/gid or other u32 key (base 10 format)
4248 paddr = &xent->k.addr6;
4249 if (ishexnumber(*arg) != 0 || *arg == ':') {
4250 /* Remove / if exists */
4251 if ((p = strchr(arg, '/')) != NULL) {
4256 if (inet_pton(AF_INET, arg, paddr) == 1) {
4257 if (p != NULL && mask > 32)
4258 errx(EX_DATAERR, "bad IPv4 mask width: %s",
4261 type = IPFW_TABLE_CIDR;
4262 masklen = p ? mask : 32;
4263 addrlen = sizeof(struct in_addr);
4264 } else if (inet_pton(AF_INET6, arg, paddr) == 1) {
4265 if (IN6_IS_ADDR_V4COMPAT(paddr))
4267 "Use IPv4 instead of v4-compatible");
4268 if (p != NULL && mask > 128)
4269 errx(EX_DATAERR, "bad IPv6 mask width: %s",
4272 type = IPFW_TABLE_CIDR;
4273 masklen = p ? mask : 128;
4274 addrlen = sizeof(struct in6_addr);
4276 /* Port or any other key */
4277 key = strtol(arg, &p, 10);
4278 /* Skip non-base 10 entries like 'fa1' */
4280 pkey = (uint32_t *)paddr;
4282 type = IPFW_TABLE_CIDR;
4283 addrlen = sizeof(uint32_t);
4288 if (type == 0 && strchr(arg, '.') == NULL) {
4289 /* Assume interface name. Copy significant data only */
4290 mask = MIN(strlen(arg), IF_NAMESIZE - 1);
4291 memcpy(xent->k.iface, arg, mask);
4292 /* Set mask to exact match */
4293 masklen = 8 * IF_NAMESIZE;
4294 type = IPFW_TABLE_INTERFACE;
4295 addrlen = IF_NAMESIZE;
4299 if (lookup_host(arg, (struct in_addr *)paddr) != 0)
4300 errx(EX_NOHOST, "hostname ``%s'' unknown", arg);
4303 type = IPFW_TABLE_CIDR;
4304 addrlen = sizeof(struct in_addr);
4308 xent->masklen = masklen;
4309 xent->len = offsetof(ipfw_table_xentry, k) + addrlen;
4313 table_list(uint16_t num, int need_header)
4316 ipfw_table_xentry *xent;
4318 uint32_t *a, sz, tval;
4320 struct in6_addr *addr6;
4321 ip_fw3_opheader *op3;
4323 /* Prepend value with IP_FW3 header */
4324 l = sizeof(ip_fw3_opheader) + sizeof(uint32_t);
4326 /* Zero reserved fields */
4327 memset(op3, 0, sizeof(ip_fw3_opheader));
4328 a = (uint32_t *)(op3 + 1);
4330 op3->opcode = IP_FW_TABLE_XGETSIZE;
4331 if (do_cmd(IP_FW3, op3, (uintptr_t)&l) < 0)
4332 err(EX_OSERR, "getsockopt(IP_FW_TABLE_XGETSIZE)");
4334 /* If a is zero we have nothing to do, the table is empty. */
4339 tbl = safe_calloc(1, l);
4340 tbl->opheader.opcode = IP_FW_TABLE_XLIST;
4342 if (do_cmd(IP_FW3, tbl, (uintptr_t)&l) < 0)
4343 err(EX_OSERR, "getsockopt(IP_FW_TABLE_XLIST)");
4344 if (tbl->cnt && need_header)
4345 printf("---table(%d)---\n", tbl->tbl);
4346 sz = tbl->size - sizeof(ipfw_xtable);
4347 xent = &tbl->xent[0];
4349 switch (tbl->type) {
4350 case IPFW_TABLE_CIDR:
4351 /* IPv4 or IPv6 prefixes */
4353 addr6 = &xent->k.addr6;
4356 if (IN6_IS_ADDR_V4COMPAT(addr6)) {
4358 inet_ntop(AF_INET, &addr6->s6_addr32[3], tbuf, sizeof(tbuf));
4361 inet_ntop(AF_INET6, addr6, tbuf, sizeof(tbuf));
4364 if (co.do_value_as_ip) {
4366 printf("%s/%u %s\n", tbuf, xent->masklen,
4367 inet_ntoa(*(struct in_addr *)&tval));
4369 printf("%s/%u %u\n", tbuf, xent->masklen, tval);
4371 case IPFW_TABLE_INTERFACE:
4372 /* Interface names */
4374 if (co.do_value_as_ip) {
4376 printf("%s %s\n", xent->k.iface,
4377 inet_ntoa(*(struct in_addr *)&tval));
4379 printf("%s %u\n", xent->k.iface, tval);
4385 xent = (ipfw_table_xentry *)((char *)xent + xent->len);