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;
63 uint32_t ipfw_tables_max = 0; /* Number of tables supported by kernel */
66 #define s6_addr32 __u6_addr.__u6_addr32
69 #define CHECK_LENGTH(v, len) do { \
71 errx(EX_DATAERR, "Rule too long"); \
74 * Check if we have enough space in cmd buffer. Note that since
75 * first 8? u32 words are reserved by reserved header, full cmd
76 * buffer can't be used, so we need to protect from buffer overrun
77 * only. At the beginnig, cblen is less than actual buffer size by
78 * size of ipfw_insn_u32 instruction + 1 u32 work. This eliminates need
79 * for checking small instructions fitting in given range.
80 * We also (ab)use the fact that ipfw_insn is always the first field
81 * for any custom instruction.
83 #define CHECK_CMDLEN CHECK_LENGTH(cblen, F_LEN((ipfw_insn *)cmd))
85 #define GET_UINT_ARG(arg, min, max, tok, s_x) do { \
87 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
88 if (_substrcmp(*av, "tablearg") == 0) { \
89 arg = IP_FW_TABLEARG; \
97 _xval = strtol(*av, &end, 10); \
99 if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
100 errx(EX_DATAERR, "%s: invalid argument: %s", \
101 match_value(s_x, tok), *av); \
103 if (errno == ERANGE || _xval < min || _xval > max) \
104 errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
105 match_value(s_x, tok), min, max, *av); \
107 if (_xval == IP_FW_TABLEARG) \
108 errx(EX_DATAERR, "%s: illegal argument value: %s", \
109 match_value(s_x, tok), *av); \
115 PRINT_UINT_ARG(const char *str, uint32_t arg)
119 if (arg == IP_FW_TABLEARG)
125 static struct _s_x f_tcpflags[] = {
136 static struct _s_x f_tcpopts[] = {
137 { "mss", IP_FW_TCPOPT_MSS },
138 { "maxseg", IP_FW_TCPOPT_MSS },
139 { "window", IP_FW_TCPOPT_WINDOW },
140 { "sack", IP_FW_TCPOPT_SACK },
141 { "ts", IP_FW_TCPOPT_TS },
142 { "timestamp", IP_FW_TCPOPT_TS },
143 { "cc", IP_FW_TCPOPT_CC },
149 * IP options span the range 0 to 255 so we need to remap them
150 * (though in fact only the low 5 bits are significant).
152 static struct _s_x f_ipopts[] = {
153 { "ssrr", IP_FW_IPOPT_SSRR},
154 { "lsrr", IP_FW_IPOPT_LSRR},
155 { "rr", IP_FW_IPOPT_RR},
156 { "ts", IP_FW_IPOPT_TS},
161 static struct _s_x f_iptos[] = {
162 { "lowdelay", IPTOS_LOWDELAY},
163 { "throughput", IPTOS_THROUGHPUT},
164 { "reliability", IPTOS_RELIABILITY},
165 { "mincost", IPTOS_MINCOST},
166 { "congestion", IPTOS_ECN_CE},
167 { "ecntransport", IPTOS_ECN_ECT0},
168 { "ip tos option", 0},
172 static struct _s_x f_ipdscp[] = {
173 { "af11", IPTOS_DSCP_AF11 >> 2 }, /* 001010 */
174 { "af12", IPTOS_DSCP_AF12 >> 2 }, /* 001100 */
175 { "af13", IPTOS_DSCP_AF13 >> 2 }, /* 001110 */
176 { "af21", IPTOS_DSCP_AF21 >> 2 }, /* 010010 */
177 { "af22", IPTOS_DSCP_AF22 >> 2 }, /* 010100 */
178 { "af23", IPTOS_DSCP_AF23 >> 2 }, /* 010110 */
179 { "af31", IPTOS_DSCP_AF31 >> 2 }, /* 011010 */
180 { "af32", IPTOS_DSCP_AF32 >> 2 }, /* 011100 */
181 { "af33", IPTOS_DSCP_AF33 >> 2 }, /* 011110 */
182 { "af41", IPTOS_DSCP_AF41 >> 2 }, /* 100010 */
183 { "af42", IPTOS_DSCP_AF42 >> 2 }, /* 100100 */
184 { "af43", IPTOS_DSCP_AF43 >> 2 }, /* 100110 */
185 { "be", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
186 { "ef", IPTOS_DSCP_EF >> 2 }, /* 101110 */
187 { "cs0", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
188 { "cs1", IPTOS_DSCP_CS1 >> 2 }, /* 001000 */
189 { "cs2", IPTOS_DSCP_CS2 >> 2 }, /* 010000 */
190 { "cs3", IPTOS_DSCP_CS3 >> 2 }, /* 011000 */
191 { "cs4", IPTOS_DSCP_CS4 >> 2 }, /* 100000 */
192 { "cs5", IPTOS_DSCP_CS5 >> 2 }, /* 101000 */
193 { "cs6", IPTOS_DSCP_CS6 >> 2 }, /* 110000 */
194 { "cs7", IPTOS_DSCP_CS7 >> 2 }, /* 100000 */
198 static struct _s_x limit_masks[] = {
199 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
200 {"src-addr", DYN_SRC_ADDR},
201 {"src-port", DYN_SRC_PORT},
202 {"dst-addr", DYN_DST_ADDR},
203 {"dst-port", DYN_DST_PORT},
208 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
209 * This is only used in this code.
211 #define IPPROTO_ETHERTYPE 0x1000
212 static struct _s_x ether_types[] = {
214 * Note, we cannot use "-:&/" in the names because they are field
215 * separators in the type specifications. Also, we use s = NULL as
216 * end-delimiter, because a type of 0 can be legal.
229 { "pppoe_disc", 0x8863 },
230 { "pppoe_sess", 0x8864 },
231 { "ipx_8022", 0x00E0 },
232 { "ipx_8023", 0x0000 },
233 { "ipx_ii", 0x8137 },
234 { "ipx_snap", 0x8137 },
241 static struct _s_x rule_actions[] = {
242 { "accept", TOK_ACCEPT },
243 { "pass", TOK_ACCEPT },
244 { "allow", TOK_ACCEPT },
245 { "permit", TOK_ACCEPT },
246 { "count", TOK_COUNT },
247 { "pipe", TOK_PIPE },
248 { "queue", TOK_QUEUE },
249 { "divert", TOK_DIVERT },
251 { "netgraph", TOK_NETGRAPH },
252 { "ngtee", TOK_NGTEE },
253 { "fwd", TOK_FORWARD },
254 { "forward", TOK_FORWARD },
255 { "skipto", TOK_SKIPTO },
256 { "deny", TOK_DENY },
257 { "drop", TOK_DENY },
258 { "reject", TOK_REJECT },
259 { "reset6", TOK_RESET6 },
260 { "reset", TOK_RESET },
261 { "unreach6", TOK_UNREACH6 },
262 { "unreach", TOK_UNREACH },
263 { "check-state", TOK_CHECKSTATE },
264 { "//", TOK_COMMENT },
266 { "reass", TOK_REASS },
267 { "setfib", TOK_SETFIB },
268 { "setdscp", TOK_SETDSCP },
269 { "call", TOK_CALL },
270 { "return", TOK_RETURN },
271 { NULL, 0 } /* terminator */
274 static struct _s_x rule_action_params[] = {
275 { "altq", TOK_ALTQ },
278 { "untag", TOK_UNTAG },
279 { NULL, 0 } /* terminator */
283 * The 'lookup' instruction accepts one of the following arguments.
284 * -1 is a terminator for the list.
285 * Arguments are passed as v[1] in O_DST_LOOKUP options.
287 static int lookup_key[] = {
288 TOK_DSTIP, TOK_SRCIP, TOK_DSTPORT, TOK_SRCPORT,
289 TOK_UID, TOK_JAIL, TOK_DSCP, -1 };
291 static struct _s_x rule_options[] = {
292 { "tagged", TOK_TAGGED },
295 { "jail", TOK_JAIL },
297 { "limit", TOK_LIMIT },
298 { "keep-state", TOK_KEEPSTATE },
299 { "bridged", TOK_LAYER2 },
300 { "layer2", TOK_LAYER2 },
302 { "diverted", TOK_DIVERTED },
303 { "diverted-loopback", TOK_DIVERTEDLOOPBACK },
304 { "diverted-output", TOK_DIVERTEDOUTPUT },
305 { "xmit", TOK_XMIT },
306 { "recv", TOK_RECV },
308 { "fragment", TOK_FRAG },
309 { "frag", TOK_FRAG },
311 { "ipoptions", TOK_IPOPTS },
312 { "ipopts", TOK_IPOPTS },
313 { "iplen", TOK_IPLEN },
314 { "ipid", TOK_IPID },
315 { "ipprecedence", TOK_IPPRECEDENCE },
316 { "dscp", TOK_DSCP },
317 { "iptos", TOK_IPTOS },
318 { "ipttl", TOK_IPTTL },
319 { "ipversion", TOK_IPVER },
320 { "ipver", TOK_IPVER },
321 { "estab", TOK_ESTAB },
322 { "established", TOK_ESTAB },
323 { "setup", TOK_SETUP },
324 { "sockarg", TOK_SOCKARG },
325 { "tcpdatalen", TOK_TCPDATALEN },
326 { "tcpflags", TOK_TCPFLAGS },
327 { "tcpflgs", TOK_TCPFLAGS },
328 { "tcpoptions", TOK_TCPOPTS },
329 { "tcpopts", TOK_TCPOPTS },
330 { "tcpseq", TOK_TCPSEQ },
331 { "tcpack", TOK_TCPACK },
332 { "tcpwin", TOK_TCPWIN },
333 { "icmptype", TOK_ICMPTYPES },
334 { "icmptypes", TOK_ICMPTYPES },
335 { "dst-ip", TOK_DSTIP },
336 { "src-ip", TOK_SRCIP },
337 { "dst-port", TOK_DSTPORT },
338 { "src-port", TOK_SRCPORT },
339 { "proto", TOK_PROTO },
342 { "mac-type", TOK_MACTYPE },
343 { "verrevpath", TOK_VERREVPATH },
344 { "versrcreach", TOK_VERSRCREACH },
345 { "antispoof", TOK_ANTISPOOF },
346 { "ipsec", TOK_IPSEC },
347 { "icmp6type", TOK_ICMP6TYPES },
348 { "icmp6types", TOK_ICMP6TYPES },
349 { "ext6hdr", TOK_EXT6HDR},
350 { "flow-id", TOK_FLOWID},
355 { "dst-ipv6", TOK_DSTIP6},
356 { "dst-ip6", TOK_DSTIP6},
357 { "src-ipv6", TOK_SRCIP6},
358 { "src-ip6", TOK_SRCIP6},
359 { "lookup", TOK_LOOKUP},
360 { "//", TOK_COMMENT },
362 { "not", TOK_NOT }, /* pseudo option */
363 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
364 { "or", TOK_OR }, /* pseudo option */
365 { "|", /* escape */ TOK_OR }, /* pseudo option */
366 { "{", TOK_STARTBRACE }, /* pseudo option */
367 { "(", TOK_STARTBRACE }, /* pseudo option */
368 { "}", TOK_ENDBRACE }, /* pseudo option */
369 { ")", TOK_ENDBRACE }, /* pseudo option */
370 { NULL, 0 } /* terminator */
374 * Helper routine to print a possibly unaligned uint64_t on
375 * various platform. If width > 0, print the value with
376 * the desired width, followed by a space;
377 * otherwise, return the required width.
380 pr_u64(uint64_t *pd, int width)
383 #define U64_FMT "I64"
385 #define U64_FMT "llu"
388 unsigned long long d;
390 bcopy (pd, &u, sizeof(u));
393 printf("%*" U64_FMT " ", width, d) :
394 snprintf(NULL, 0, "%" U64_FMT, d) ;
399 safe_calloc(size_t number, size_t size)
401 void *ret = calloc(number, size);
404 err(EX_OSERR, "calloc");
409 safe_realloc(void *ptr, size_t size)
411 void *ret = realloc(ptr, size);
414 err(EX_OSERR, "realloc");
419 * conditionally runs the command.
420 * Selected options or negative -> getsockopt
423 do_cmd(int optname, void *optval, uintptr_t optlen)
430 if (ipfw_socket == -1)
431 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
433 err(EX_UNAVAILABLE, "socket");
435 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
436 optname == IP_FW_ADD || optname == IP_FW3 ||
437 optname == IP_FW_NAT_GET_CONFIG ||
439 optname == IP_FW_NAT_GET_LOG) {
442 i = getsockopt(ipfw_socket, IPPROTO_IP, optname, optval,
443 (socklen_t *)optlen);
445 i = setsockopt(ipfw_socket, IPPROTO_IP, optname, optval, optlen);
451 * do_setcmd3 - pass ipfw control cmd to kernel
452 * @optname: option name
453 * @optval: pointer to option data
454 * @optlen: option length
456 * Function encapsulates option value in IP_FW3 socket option
457 * and calls setsockopt().
458 * Function returns 0 on success or -1 otherwise.
461 do_setcmd3(int optname, void *optval, socklen_t optlen)
464 ip_fw3_opheader *op3;
469 if (ipfw_socket == -1)
470 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
472 err(EX_UNAVAILABLE, "socket");
474 len = sizeof(ip_fw3_opheader) + optlen;
476 /* Zero reserved fields */
477 memset(op3, 0, sizeof(ip_fw3_opheader));
478 memcpy(op3 + 1, optval, optlen);
479 op3->opcode = optname;
481 return setsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, len);
485 * match_token takes a table and a string, returns the value associated
486 * with the string (-1 in case of failure).
489 match_token(struct _s_x *table, char *string)
492 uint i = strlen(string);
494 for (pt = table ; i && pt->s != NULL ; pt++)
495 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
501 * match_value takes a table and a value, returns the string associated
502 * with the value (NULL in case of failure).
505 match_value(struct _s_x *p, int value)
507 for (; p->s != NULL; p++)
514 * _substrcmp takes two strings and returns 1 if they do not match,
515 * and 0 if they match exactly or the first string is a sub-string
516 * of the second. A warning is printed to stderr in the case that the
517 * first string is a sub-string of the second.
519 * This function will be removed in the future through the usual
520 * deprecation process.
523 _substrcmp(const char *str1, const char* str2)
526 if (strncmp(str1, str2, strlen(str1)) != 0)
529 if (strlen(str1) != strlen(str2))
530 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
536 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
537 * and 0 if they match exactly or the second string is a sub-string
538 * of the first. A warning is printed to stderr in the case that the
539 * first string does not match the third.
541 * This function exists to warn about the bizarre construction
542 * strncmp(str, "by", 2) which is used to allow people to use a shortcut
543 * for "bytes". The problem is that in addition to accepting "by",
544 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
545 * other string beginning with "by".
547 * This function will be removed in the future through the usual
548 * deprecation process.
551 _substrcmp2(const char *str1, const char* str2, const char* str3)
554 if (strncmp(str1, str2, strlen(str2)) != 0)
557 if (strcmp(str1, str3) != 0)
558 warnx("DEPRECATED: '%s' matched '%s'",
564 * prints one port, symbolic or numeric
567 print_port(int proto, uint16_t port)
570 if (proto == IPPROTO_ETHERTYPE) {
573 if (co.do_resolv && (s = match_value(ether_types, port)) )
576 printf("0x%04x", port);
578 struct servent *se = NULL;
580 struct protoent *pe = getprotobynumber(proto);
582 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
585 printf("%s", se->s_name);
591 static struct _s_x _port_name[] = {
592 {"dst-port", O_IP_DSTPORT},
593 {"src-port", O_IP_SRCPORT},
597 {"mac-type", O_MAC_TYPE},
598 {"tcpdatalen", O_TCPDATALEN},
599 {"tcpwin", O_TCPWIN},
600 {"tagged", O_TAGGED},
605 * Print the values in a list 16-bit items of the types above.
606 * XXX todo: add support for mask.
609 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode)
611 uint16_t *p = cmd->ports;
616 sep = match_value(_port_name, opcode);
622 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
624 print_port(proto, p[0]);
627 print_port(proto, p[1]);
634 * Like strtol, but also translates service names into port numbers
635 * for some protocols.
637 * proto == -1 disables the protocol check;
638 * proto == IPPROTO_ETHERTYPE looks up an internal table
639 * proto == <some value in /etc/protocols> matches the values there.
640 * Returns *end == s in case the parameter is not found.
643 strtoport(char *s, char **end, int base, int proto)
649 *end = s; /* default - not found */
651 return 0; /* not found */
654 return strtol(s, end, base);
657 * find separator. '\\' escapes the next char.
659 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
660 if (*s1 == '\\' && s1[1] != '\0')
663 buf = safe_calloc(s1 - s + 1, 1);
666 * copy into a buffer skipping backslashes
668 for (p = s, i = 0; p != s1 ; p++)
673 if (proto == IPPROTO_ETHERTYPE) {
674 i = match_token(ether_types, buf);
676 if (i != -1) { /* found */
681 struct protoent *pe = NULL;
685 pe = getprotobynumber(proto);
687 se = getservbyname(buf, pe ? pe->p_name : NULL);
691 return ntohs(se->s_port);
694 return 0; /* not found */
698 * Fill the body of the command with the list of port ranges.
701 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
703 uint16_t a, b, *p = cmd->ports;
708 a = strtoport(av, &s, 0, proto);
709 if (s == av) /* empty or invalid argument */
712 CHECK_LENGTH(cblen, i + 2);
715 case '-': /* a range */
717 b = strtoport(av, &s, 0, proto);
718 /* Reject expressions like '1-abc' or '1-2-3'. */
719 if (s == av || (*s != ',' && *s != '\0'))
724 case ',': /* comma separated list */
729 warnx("port list: invalid separator <%c> in <%s>",
739 if (i + 1 > F_LEN_MASK)
740 errx(EX_DATAERR, "too many ports/ranges\n");
741 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
747 * Fill the body of the command with the list of DiffServ codepoints.
750 fill_dscp(ipfw_insn *cmd, char *av, int cblen)
752 uint32_t *low, *high;
756 cmd->opcode = O_DSCP;
757 cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
761 low = (uint32_t *)(cmd + 1);
774 if ((code = match_token(f_ipdscp, s)) == -1)
775 errx(EX_DATAERR, "Unknown DSCP code");
777 code = strtoul(s, NULL, 10);
778 if (code < 0 || code > 63)
779 errx(EX_DATAERR, "Invalid DSCP value");
783 *high |= 1 << (code - 32);
791 static struct _s_x icmpcodes[] = {
792 { "net", ICMP_UNREACH_NET },
793 { "host", ICMP_UNREACH_HOST },
794 { "protocol", ICMP_UNREACH_PROTOCOL },
795 { "port", ICMP_UNREACH_PORT },
796 { "needfrag", ICMP_UNREACH_NEEDFRAG },
797 { "srcfail", ICMP_UNREACH_SRCFAIL },
798 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
799 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
800 { "isolated", ICMP_UNREACH_ISOLATED },
801 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
802 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
803 { "tosnet", ICMP_UNREACH_TOSNET },
804 { "toshost", ICMP_UNREACH_TOSHOST },
805 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
806 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
807 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
812 fill_reject_code(u_short *codep, char *str)
817 val = strtoul(str, &s, 0);
818 if (s == str || *s != '\0' || val >= 0x100)
819 val = match_token(icmpcodes, str);
821 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
827 print_reject_code(uint16_t code)
829 char const *s = match_value(icmpcodes, code);
832 printf("unreach %s", s);
834 printf("unreach %u", code);
838 * Returns the number of bits set (from left) in a contiguous bitmask,
839 * or -1 if the mask is not contiguous.
840 * XXX this needs a proper fix.
841 * This effectively works on masks in big-endian (network) format.
842 * when compiled on little endian architectures.
844 * First bit is bit 7 of the first byte -- note, for MAC addresses,
845 * the first bit on the wire is bit 0 of the first byte.
846 * len is the max length in bits.
849 contigmask(uint8_t *p, int len)
853 for (i=0; i<len ; i++)
854 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
856 for (n=i+1; n < len; n++)
857 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
858 return -1; /* mask not contiguous */
863 * print flags set/clear in the two bitmasks passed as parameters.
864 * There is a specialized check for f_tcpflags.
867 print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list)
869 char const *comma = "";
871 uint8_t set = cmd->arg1 & 0xff;
872 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
874 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
879 printf(" %s ", name);
880 for (i=0; list[i].x != 0; i++) {
881 if (set & list[i].x) {
883 printf("%s%s", comma, list[i].s);
886 if (clear & list[i].x) {
888 printf("%s!%s", comma, list[i].s);
895 * Print the ip address contained in a command.
898 print_ip(ipfw_insn_ip *cmd, char const *s)
900 struct hostent *he = NULL;
901 uint32_t len = F_LEN((ipfw_insn *)cmd);
902 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
904 if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
906 const char *arg = "<invalid>";
908 if (d < sizeof(lookup_key)/sizeof(lookup_key[0]))
909 arg = match_value(rule_options, lookup_key[d]);
910 printf("%s lookup %s %d", cmd->o.len & F_NOT ? " not": "",
914 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
916 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
920 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
921 cmd->o.opcode == O_IP_DST_LOOKUP) {
922 printf("table(%u", ((ipfw_insn *)cmd)->arg1);
923 if (len == F_INSN_SIZE(ipfw_insn_u32))
928 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
929 uint32_t x, *map = (uint32_t *)&(cmd->mask);
935 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
936 printf("%s/%d", inet_ntoa(cmd->addr),
937 contigmask((uint8_t *)&x, 32));
938 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
939 x &= 0xff; /* base */
941 * Print bits and ranges.
942 * Locate first bit set (i), then locate first bit unset (j).
943 * If we have 3+ consecutive bits set, then print them as a
944 * range, otherwise only print the initial bit and rescan.
946 for (i=0; i < cmd->o.arg1; i++)
947 if (map[i/32] & (1<<(i & 31))) {
948 for (j=i+1; j < cmd->o.arg1; j++)
949 if (!(map[ j/32] & (1<<(j & 31))))
951 printf("%c%d", comma, i+x);
952 if (j>i+2) { /* range has at least 3 elements */
953 printf("-%d", j-1+x);
962 * len == 2 indicates a single IP, whereas lists of 1 or more
963 * addr/mask pairs have len = (2n+1). We convert len to n so we
964 * use that to count the number of entries.
966 for (len = len / 2; len > 0; len--, a += 2) {
967 int mb = /* mask length */
968 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
969 32 : contigmask((uint8_t *)&(a[1]), 32);
970 if (mb == 32 && co.do_resolv)
971 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
972 if (he != NULL) /* resolved to name */
973 printf("%s", he->h_name);
974 else if (mb == 0) /* any */
976 else { /* numeric IP followed by some kind of mask */
977 printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) );
979 printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) );
989 * prints a MAC address/mask pair
992 print_mac(uint8_t *addr, uint8_t *mask)
994 int l = contigmask(mask, 48);
999 printf(" %02x:%02x:%02x:%02x:%02x:%02x",
1000 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1002 printf("&%02x:%02x:%02x:%02x:%02x:%02x",
1003 mask[0], mask[1], mask[2],
1004 mask[3], mask[4], mask[5]);
1011 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1020 type = strtoul(av, &av, 0);
1022 if (*av != ',' && *av != '\0')
1023 errx(EX_DATAERR, "invalid ICMP type");
1026 errx(EX_DATAERR, "ICMP type out of range");
1028 cmd->d[0] |= 1 << type;
1030 cmd->o.opcode = O_ICMPTYPE;
1031 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1035 print_icmptypes(ipfw_insn_u32 *cmd)
1040 printf(" icmptypes");
1041 for (i = 0; i < 32; i++) {
1042 if ( (cmd->d[0] & (1 << (i))) == 0)
1044 printf("%c%d", sep, i);
1050 print_dscp(ipfw_insn_u32 *cmd)
1062 if (*v & (1 << i)) {
1063 if ((code = match_value(f_ipdscp, i)) != NULL)
1064 printf("%c%s", sep, code);
1066 printf("%c%d", sep, i);
1070 if ((++i % 32) == 0)
1076 * show_ipfw() prints the body of an ipfw rule.
1077 * Because the standard rule has at least proto src_ip dst_ip, we use
1078 * a helper function to produce these entries if not provided explicitly.
1079 * The first argument is the list of fields we have, the second is
1080 * the list of fields we want to be printed.
1082 * Special cases if we have provided a MAC header:
1083 * + if the rule does not contain IP addresses/ports, do not print them;
1084 * + if the rule does not contain an IP proto, print "all" instead of "ip";
1086 * Once we have 'have_options', IP header fields are printed as options.
1088 #define HAVE_PROTO 0x0001
1089 #define HAVE_SRCIP 0x0002
1090 #define HAVE_DSTIP 0x0004
1091 #define HAVE_PROTO4 0x0008
1092 #define HAVE_PROTO6 0x0010
1093 #define HAVE_IP 0x0100
1094 #define HAVE_OPTIONS 0x8000
1097 show_prerequisites(int *flags, int want, int cmd)
1099 (void)cmd; /* UNUSED */
1100 if (co.comment_only)
1102 if ( (*flags & HAVE_IP) == HAVE_IP)
1103 *flags |= HAVE_OPTIONS;
1105 if ( !(*flags & HAVE_OPTIONS)) {
1106 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) {
1107 if ( (*flags & HAVE_PROTO4))
1109 else if ( (*flags & HAVE_PROTO6))
1114 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
1115 printf(" from any");
1116 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
1123 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth)
1125 static int twidth = 0;
1127 ipfw_insn *cmd, *tagptr = NULL;
1128 const char *comment = NULL; /* ptr to comment if we have one */
1129 int proto = 0; /* default */
1130 int flags = 0; /* prerequisites */
1131 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
1132 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
1133 int or_block = 0; /* we are in an or block */
1134 uint32_t set_disable;
1136 bcopy(&rule->next_rule, &set_disable, sizeof(set_disable));
1138 if (set_disable & (1 << rule->set)) { /* disabled */
1142 printf("# DISABLED ");
1144 printf("%05u ", rule->rulenum);
1146 if (pcwidth > 0 || bcwidth > 0) {
1147 pr_u64(&rule->pcnt, pcwidth);
1148 pr_u64(&rule->bcnt, bcwidth);
1151 if (co.do_time == 2)
1152 printf("%10u ", rule->timestamp);
1153 else if (co.do_time == 1) {
1155 time_t t = (time_t)0;
1158 strcpy(timestr, ctime(&t));
1159 *strchr(timestr, '\n') = '\0';
1160 twidth = strlen(timestr);
1162 if (rule->timestamp) {
1163 t = _long_to_time(rule->timestamp);
1165 strcpy(timestr, ctime(&t));
1166 *strchr(timestr, '\n') = '\0';
1167 printf("%s ", timestr);
1169 printf("%*s", twidth, " ");
1174 printf("set %d ", rule->set);
1177 * print the optional "match probability"
1179 if (rule->cmd_len > 0) {
1181 if (cmd->opcode == O_PROB) {
1182 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1183 double d = 1.0 * p->d[0];
1185 d = (d / 0x7fffffff);
1186 printf("prob %f ", d);
1191 * first print actions
1193 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1194 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1195 switch(cmd->opcode) {
1197 printf("check-state");
1198 /* avoid printing anything else */
1199 flags = HAVE_PROTO | HAVE_SRCIP |
1200 HAVE_DSTIP | HAVE_IP;
1216 if (cmd->arg1 == ICMP_REJECT_RST)
1218 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1221 print_reject_code(cmd->arg1);
1225 if (cmd->arg1 == ICMP6_UNREACH_RST)
1228 print_unreach6_code(cmd->arg1);
1232 PRINT_UINT_ARG("skipto ", cmd->arg1);
1236 PRINT_UINT_ARG("pipe ", cmd->arg1);
1240 PRINT_UINT_ARG("queue ", cmd->arg1);
1244 PRINT_UINT_ARG("divert ", cmd->arg1);
1248 PRINT_UINT_ARG("tee ", cmd->arg1);
1252 PRINT_UINT_ARG("netgraph ", cmd->arg1);
1256 PRINT_UINT_ARG("ngtee ", cmd->arg1);
1261 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1263 if (s->sa.sin_addr.s_addr == INADDR_ANY) {
1264 printf("fwd tablearg");
1266 printf("fwd %s", inet_ntoa(s->sa.sin_addr));
1269 printf(",%d", s->sa.sin_port);
1275 char buf[4 + INET6_ADDRSTRLEN + 1];
1276 ipfw_insn_sa6 *s = (ipfw_insn_sa6 *)cmd;
1278 printf("fwd %s", inet_ntop(AF_INET6, &s->sa.sin6_addr,
1280 if (s->sa.sin6_port)
1281 printf(",%d", s->sa.sin6_port);
1285 case O_LOG: /* O_LOG is printed last */
1286 logptr = (ipfw_insn_log *)cmd;
1289 case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1290 altqptr = (ipfw_insn_altq *)cmd;
1299 PRINT_UINT_ARG("nat ", cmd->arg1);
1301 printf("nat global");
1305 PRINT_UINT_ARG("setfib ", cmd->arg1);
1312 if ((code = match_value(f_ipdscp, cmd->arg1)) != NULL)
1313 printf("setdscp %s", code);
1315 PRINT_UINT_ARG("setdscp ", cmd->arg1);
1324 if (cmd->len & F_NOT)
1327 PRINT_UINT_ARG("call ", cmd->arg1);
1331 printf("** unrecognized action %d len %d ",
1332 cmd->opcode, cmd->len);
1336 if (logptr->max_log > 0)
1337 printf(" log logamount %d", logptr->max_log);
1343 print_altq_cmd(altqptr);
1347 if (tagptr->len & F_NOT)
1348 PRINT_UINT_ARG(" untag ", tagptr->arg1);
1350 PRINT_UINT_ARG(" tag ", tagptr->arg1);
1354 * then print the body.
1356 for (l = rule->act_ofs, cmd = rule->cmd ;
1357 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1358 if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1360 if (cmd->opcode == O_IP4) {
1361 flags |= HAVE_PROTO4;
1363 } else if (cmd->opcode == O_IP6) {
1364 flags |= HAVE_PROTO6;
1368 if (rule->_pad & 1) { /* empty rules before options */
1369 if (!co.do_compact) {
1370 show_prerequisites(&flags, HAVE_PROTO, 0);
1371 printf(" from any to any");
1373 flags |= HAVE_IP | HAVE_OPTIONS | HAVE_PROTO |
1374 HAVE_SRCIP | HAVE_DSTIP;
1377 if (co.comment_only)
1380 for (l = rule->act_ofs, cmd = rule->cmd ;
1381 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1383 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1385 if (co.comment_only) {
1386 if (cmd->opcode != O_NOP)
1388 printf(" // %s\n", (char *)(cmd + 1));
1392 show_prerequisites(&flags, 0, cmd->opcode);
1394 switch(cmd->opcode) {
1396 break; /* done already */
1399 break; /* no need to print anything here */
1402 case O_IP_SRC_LOOKUP:
1406 show_prerequisites(&flags, HAVE_PROTO, 0);
1407 if (!(flags & HAVE_SRCIP))
1409 if ((cmd->len & F_OR) && !or_block)
1411 print_ip((ipfw_insn_ip *)cmd,
1412 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1413 flags |= HAVE_SRCIP;
1417 case O_IP_DST_LOOKUP:
1421 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1422 if (!(flags & HAVE_DSTIP))
1424 if ((cmd->len & F_OR) && !or_block)
1426 print_ip((ipfw_insn_ip *)cmd,
1427 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1428 flags |= HAVE_DSTIP;
1432 case O_IP6_SRC_MASK:
1434 show_prerequisites(&flags, HAVE_PROTO, 0);
1435 if (!(flags & HAVE_SRCIP))
1437 if ((cmd->len & F_OR) && !or_block)
1439 print_ip6((ipfw_insn_ip6 *)cmd,
1440 (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1441 flags |= HAVE_SRCIP | HAVE_PROTO;
1445 case O_IP6_DST_MASK:
1447 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1448 if (!(flags & HAVE_DSTIP))
1450 if ((cmd->len & F_OR) && !or_block)
1452 print_ip6((ipfw_insn_ip6 *)cmd,
1453 (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1454 flags |= HAVE_DSTIP;
1458 print_flow6id( (ipfw_insn_u32 *) cmd );
1459 flags |= HAVE_OPTIONS;
1463 show_prerequisites(&flags,
1464 HAVE_PROTO | HAVE_SRCIP |
1465 HAVE_DSTIP | HAVE_IP, 0);
1467 if (flags & HAVE_DSTIP)
1469 show_prerequisites(&flags,
1470 HAVE_PROTO | HAVE_SRCIP, 0);
1471 if ((cmd->len & F_OR) && !or_block)
1473 if (cmd->len & F_NOT)
1475 print_newports((ipfw_insn_u16 *)cmd, proto,
1476 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1480 struct protoent *pe = NULL;
1482 if ((cmd->len & F_OR) && !or_block)
1484 if (cmd->len & F_NOT)
1487 pe = getprotobynumber(cmd->arg1);
1488 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1489 !(flags & HAVE_PROTO))
1490 show_prerequisites(&flags,
1491 HAVE_PROTO | HAVE_IP | HAVE_SRCIP |
1492 HAVE_DSTIP | HAVE_OPTIONS, 0);
1493 if (flags & HAVE_OPTIONS)
1496 printf(" %s", pe->p_name);
1498 printf(" %u", cmd->arg1);
1500 flags |= HAVE_PROTO;
1503 default: /*options ... */
1504 if (!(cmd->len & (F_OR|F_NOT)))
1505 if (((cmd->opcode == O_IP6) &&
1506 (flags & HAVE_PROTO6)) ||
1507 ((cmd->opcode == O_IP4) &&
1508 (flags & HAVE_PROTO4)))
1510 show_prerequisites(&flags, HAVE_PROTO | HAVE_SRCIP |
1511 HAVE_DSTIP | HAVE_IP | HAVE_OPTIONS, 0);
1512 if ((cmd->len & F_OR) && !or_block)
1514 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1516 switch(cmd->opcode) {
1518 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1521 print_mac(m->addr, m->mask);
1522 print_mac(m->addr + 6, m->mask + 6);
1527 print_newports((ipfw_insn_u16 *)cmd,
1528 IPPROTO_ETHERTYPE, cmd->opcode);
1537 printf(" fib %u", cmd->arg1 );
1544 printf(cmd->len & F_NOT ? " out" : " in");
1548 switch (cmd->arg1) {
1550 printf(" diverted");
1553 printf(" diverted-loopback");
1556 printf(" diverted-output");
1559 printf(" diverted-?<%u>", cmd->arg1);
1572 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1574 if (cmd->opcode == O_XMIT)
1576 else if (cmd->opcode == O_RECV)
1578 else /* if (cmd->opcode == O_VIA) */
1580 if (cmdif->name[0] == '\0')
1582 inet_ntoa(cmdif->p.ip));
1583 else if (cmdif->name[0] == '\1') /* interface table */
1584 printf(" %s table(%d)", s, cmdif->p.glob);
1586 printf(" %s %s", s, cmdif->name);
1591 if (F_LEN(cmd) == 1)
1592 printf(" ipid %u", cmd->arg1 );
1594 print_newports((ipfw_insn_u16 *)cmd, 0,
1599 if (F_LEN(cmd) == 1)
1600 printf(" ipttl %u", cmd->arg1 );
1602 print_newports((ipfw_insn_u16 *)cmd, 0,
1607 printf(" ipver %u", cmd->arg1 );
1610 case O_IPPRECEDENCE:
1611 printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1615 print_dscp((ipfw_insn_u32 *)cmd);
1619 if (F_LEN(cmd) == 1)
1620 printf(" iplen %u", cmd->arg1 );
1622 print_newports((ipfw_insn_u16 *)cmd, 0,
1627 print_flags("ipoptions", cmd, f_ipopts);
1631 print_flags("iptos", cmd, f_iptos);
1635 print_icmptypes((ipfw_insn_u32 *)cmd);
1639 printf(" established");
1643 if (F_LEN(cmd) == 1)
1644 printf(" tcpdatalen %u", cmd->arg1 );
1646 print_newports((ipfw_insn_u16 *)cmd, 0,
1651 print_flags("tcpflags", cmd, f_tcpflags);
1655 print_flags("tcpoptions", cmd, f_tcpopts);
1659 if (F_LEN(cmd) == 1)
1660 printf(" tcpwin %u", cmd->arg1);
1662 print_newports((ipfw_insn_u16 *)cmd, 0,
1667 printf(" tcpack %d", ntohl(cmd32->d[0]));
1671 printf(" tcpseq %d", ntohl(cmd32->d[0]));
1676 struct passwd *pwd = getpwuid(cmd32->d[0]);
1679 printf(" uid %s", pwd->pw_name);
1681 printf(" uid %u", cmd32->d[0]);
1687 struct group *grp = getgrgid(cmd32->d[0]);
1690 printf(" gid %s", grp->gr_name);
1692 printf(" gid %u", cmd32->d[0]);
1697 printf(" jail %d", cmd32->d[0]);
1701 printf(" verrevpath");
1705 printf(" versrcreach");
1709 printf(" antispoof");
1717 comment = (char *)(cmd + 1);
1721 printf(" keep-state");
1725 struct _s_x *p = limit_masks;
1726 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1727 uint8_t x = c->limit_mask;
1728 char const *comma = " ";
1731 for (; p->x != 0 ; p++)
1732 if ((x & p->x) == p->x) {
1734 printf("%s%s", comma, p->s);
1737 PRINT_UINT_ARG(" ", c->conn_limit);
1750 print_icmp6types((ipfw_insn_u32 *)cmd);
1754 print_ext6hdr( (ipfw_insn *) cmd );
1758 if (F_LEN(cmd) == 1)
1759 PRINT_UINT_ARG(" tagged ", cmd->arg1);
1761 print_newports((ipfw_insn_u16 *)cmd, 0,
1766 printf(" [opcode %d len %d]",
1767 cmd->opcode, cmd->len);
1770 if (cmd->len & F_OR) {
1773 } else if (or_block) {
1778 show_prerequisites(&flags, HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP
1781 printf(" // %s", comment);
1786 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth)
1788 struct protoent *pe;
1791 char buf[INET6_ADDRSTRLEN];
1793 if (!co.do_expired) {
1794 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1797 bcopy(&d->rule, &rulenum, sizeof(rulenum));
1798 printf("%05d", rulenum);
1799 if (pcwidth > 0 || bcwidth > 0) {
1801 pr_u64(&d->pcnt, pcwidth);
1802 pr_u64(&d->bcnt, bcwidth);
1803 printf("(%ds)", d->expire);
1805 switch (d->dyn_type) {
1806 case O_LIMIT_PARENT:
1807 printf(" PARENT %d", d->count);
1812 case O_KEEP_STATE: /* bidir, no mask */
1817 if ((pe = getprotobynumber(d->id.proto)) != NULL)
1818 printf(" %s", pe->p_name);
1820 printf(" proto %u", d->id.proto);
1822 if (d->id.addr_type == 4) {
1823 a.s_addr = htonl(d->id.src_ip);
1824 printf(" %s %d", inet_ntoa(a), d->id.src_port);
1826 a.s_addr = htonl(d->id.dst_ip);
1827 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
1828 } else if (d->id.addr_type == 6) {
1829 printf(" %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
1830 sizeof(buf)), d->id.src_port);
1831 printf(" <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6, buf,
1832 sizeof(buf)), d->id.dst_port);
1834 printf(" UNKNOWN <-> UNKNOWN\n");
1840 * This one handles all set-related commands
1841 * ipfw set { show | enable | disable }
1843 * ipfw set move X to Y
1844 * ipfw set move rule X to Y
1847 ipfw_sets_handler(char *av[])
1849 uint32_t set_disable, masks[2];
1852 uint8_t cmd, new_set;
1857 errx(EX_USAGE, "set needs command");
1858 if (_substrcmp(*av, "show") == 0) {
1863 nalloc = nbytes = sizeof(struct ip_fw);
1864 while (nbytes >= nalloc) {
1867 nalloc = nalloc * 2 + 200;
1869 data = safe_calloc(1, nbytes);
1870 if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0)
1871 err(EX_OSERR, "getsockopt(IP_FW_GET)");
1874 bcopy(&((struct ip_fw *)data)->next_rule,
1875 &set_disable, sizeof(set_disable));
1877 for (i = 0, msg = "disable" ; i < RESVD_SET; i++)
1878 if ((set_disable & (1<<i))) {
1879 printf("%s %d", msg, i);
1882 msg = (set_disable) ? " enable" : "enable";
1883 for (i = 0; i < RESVD_SET; i++)
1884 if (!(set_disable & (1<<i))) {
1885 printf("%s %d", msg, i);
1889 } else if (_substrcmp(*av, "swap") == 0) {
1891 if ( av[0] == NULL || av[1] == NULL )
1892 errx(EX_USAGE, "set swap needs 2 set numbers\n");
1893 rulenum = atoi(av[0]);
1894 new_set = atoi(av[1]);
1895 if (!isdigit(*(av[0])) || rulenum > RESVD_SET)
1896 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
1897 if (!isdigit(*(av[1])) || new_set > RESVD_SET)
1898 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
1899 masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
1900 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
1901 } else if (_substrcmp(*av, "move") == 0) {
1903 if (av[0] && _substrcmp(*av, "rule") == 0) {
1908 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
1909 av[3] != NULL || _substrcmp(av[1], "to") != 0)
1910 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
1911 rulenum = atoi(av[0]);
1912 new_set = atoi(av[2]);
1913 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) ||
1914 (cmd == 2 && rulenum == IPFW_DEFAULT_RULE) )
1915 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
1916 if (!isdigit(*(av[2])) || new_set > RESVD_SET)
1917 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
1918 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
1919 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
1920 } else if (_substrcmp(*av, "disable") == 0 ||
1921 _substrcmp(*av, "enable") == 0 ) {
1922 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
1925 masks[0] = masks[1] = 0;
1928 if (isdigit(**av)) {
1930 if (i < 0 || i > RESVD_SET)
1932 "invalid set number %d\n", i);
1933 masks[which] |= (1<<i);
1934 } else if (_substrcmp(*av, "disable") == 0)
1936 else if (_substrcmp(*av, "enable") == 0)
1940 "invalid set command %s\n", *av);
1943 if ( (masks[0] & masks[1]) != 0 )
1945 "cannot enable and disable the same set\n");
1947 i = do_cmd(IP_FW_DEL, masks, sizeof(masks));
1949 warn("set enable/disable: setsockopt(IP_FW_DEL)");
1951 errx(EX_USAGE, "invalid set command %s\n", *av);
1955 ipfw_sysctl_handler(char *av[], int which)
1959 if (av[0] == NULL) {
1960 warnx("missing keyword to enable/disable\n");
1961 } else if (_substrcmp(*av, "firewall") == 0) {
1962 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
1963 &which, sizeof(which));
1964 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
1965 &which, sizeof(which));
1966 } else if (_substrcmp(*av, "one_pass") == 0) {
1967 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
1968 &which, sizeof(which));
1969 } else if (_substrcmp(*av, "debug") == 0) {
1970 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
1971 &which, sizeof(which));
1972 } else if (_substrcmp(*av, "verbose") == 0) {
1973 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
1974 &which, sizeof(which));
1975 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
1976 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
1977 &which, sizeof(which));
1979 } else if (_substrcmp(*av, "altq") == 0) {
1980 altq_set_enabled(which);
1983 warnx("unrecognize enable/disable keyword: %s\n", *av);
1988 ipfw_list(int ac, char *av[], int show_counters)
1991 ipfw_dyn_rule *dynrules, *d;
1993 #define NEXT(r) ((struct ip_fw *)((char *)r + RULESIZE(r)))
1996 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
1997 int exitval = EX_OK;
2005 const int ocmd = co.do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
2006 int nalloc = 1024; /* start somewhere... */
2011 fprintf(stderr, "Testing only, list disabled\n");
2015 dummynet_list(ac, av, show_counters);
2022 /* get rules or pipes from kernel, resizing array as necessary */
2025 while (nbytes >= nalloc) {
2026 nalloc = nalloc * 2 + 200;
2028 data = safe_realloc(data, nbytes);
2029 if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0)
2030 err(EX_OSERR, "getsockopt(IP_%s_GET)",
2031 co.do_pipe ? "DUMMYNET" : "FW");
2035 * Count static rules. They have variable size so we
2036 * need to scan the list to count them.
2038 for (nstat = 1, r = data, lim = (char *)data + nbytes;
2039 r->rulenum < IPFW_DEFAULT_RULE && (char *)r < lim;
2040 ++nstat, r = NEXT(r) )
2044 * Count dynamic rules. This is easier as they have
2048 dynrules = (ipfw_dyn_rule *)r ;
2049 n = (char *)r - (char *)data;
2050 ndyn = (nbytes - n) / sizeof *dynrules;
2052 /* if showing stats, figure out column widths ahead of time */
2053 bcwidth = pcwidth = 0;
2054 if (show_counters) {
2055 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
2056 /* skip rules from another set */
2057 if (co.use_set && r->set != co.use_set - 1)
2060 /* packet counter */
2061 width = pr_u64(&r->pcnt, 0);
2062 if (width > pcwidth)
2066 width = pr_u64(&r->bcnt, 0);
2067 if (width > bcwidth)
2071 if (co.do_dynamic && ndyn) {
2072 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2074 /* skip rules from another set */
2075 bcopy((char *)&d->rule + sizeof(uint16_t),
2076 &set, sizeof(uint8_t));
2077 if (set != co.use_set - 1)
2080 width = pr_u64(&d->pcnt, 0);
2081 if (width > pcwidth)
2084 width = pr_u64(&d->bcnt, 0);
2085 if (width > bcwidth)
2089 /* if no rule numbers were specified, list all rules */
2091 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
2092 if (co.use_set && r->set != co.use_set - 1)
2094 show_ipfw(r, pcwidth, bcwidth);
2097 if (co.do_dynamic && ndyn) {
2098 printf("## Dynamic rules (%d):\n", ndyn);
2099 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2101 bcopy((char *)&d->rule + sizeof(uint16_t),
2102 &set, sizeof(uint8_t));
2103 if (set != co.use_set - 1)
2106 show_dyn_ipfw(d, pcwidth, bcwidth);
2112 /* display specific rules requested on command line */
2114 for (lac = ac, lav = av; lac != 0; lac--) {
2115 /* convert command line rule # */
2116 last = rnum = strtoul(*lav++, &endptr, 10);
2118 last = strtoul(endptr+1, &endptr, 10);
2121 warnx("invalid rule number: %s", *(lav - 1));
2124 for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) {
2125 if (r->rulenum > last)
2127 if (co.use_set && r->set != co.use_set - 1)
2129 if (r->rulenum >= rnum && r->rulenum <= last) {
2130 show_ipfw(r, pcwidth, bcwidth);
2135 /* give precedence to other error(s) */
2136 if (exitval == EX_OK)
2137 exitval = EX_UNAVAILABLE;
2138 warnx("rule %lu does not exist", rnum);
2142 if (co.do_dynamic && ndyn) {
2143 printf("## Dynamic rules:\n");
2144 for (lac = ac, lav = av; lac != 0; lac--) {
2145 last = rnum = strtoul(*lav++, &endptr, 10);
2147 last = strtoul(endptr+1, &endptr, 10);
2149 /* already warned */
2151 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2154 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2158 bcopy((char *)&d->rule + sizeof(uint16_t),
2159 &set, sizeof(uint8_t));
2160 if (set != co.use_set - 1)
2163 if (r->rulenum >= rnum && r->rulenum <= last)
2164 show_dyn_ipfw(d, pcwidth, bcwidth);
2174 if (exitval != EX_OK)
2180 lookup_host (char *host, struct in_addr *ipaddr)
2184 if (!inet_aton(host, ipaddr)) {
2185 if ((he = gethostbyname(host)) == NULL)
2187 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2193 * fills the addr and mask fields in the instruction as appropriate from av.
2194 * Update length as appropriate.
2195 * The following formats are allowed:
2196 * me returns O_IP_*_ME
2197 * 1.2.3.4 single IP address
2198 * 1.2.3.4:5.6.7.8 address:mask
2199 * 1.2.3.4/24 address/mask
2200 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
2201 * We can have multiple comma-separated address/mask entries.
2204 fill_ip(ipfw_insn_ip *cmd, char *av, int cblen)
2207 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2208 uint32_t tables_max;
2210 cmd->o.len &= ~F_LEN_MASK; /* zero len */
2212 if (_substrcmp(av, "any") == 0)
2215 if (_substrcmp(av, "me") == 0) {
2216 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2220 if (strncmp(av, "table(", 6) == 0) {
2221 char *p = strchr(av + 6, ',');
2225 cmd->o.opcode = O_IP_DST_LOOKUP;
2226 cmd->o.arg1 = strtoul(av + 6, NULL, 0);
2227 tables_max = ipfw_get_tables_max();
2228 if (cmd->o.arg1 > tables_max)
2229 errx(EX_USAGE, "The table number exceeds the maximum "
2230 "allowed value (%u)", tables_max - 1);
2232 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2233 d[0] = strtoul(p, NULL, 0);
2235 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2241 * After the address we can have '/' or ':' indicating a mask,
2242 * ',' indicating another address follows, '{' indicating a
2243 * set of addresses of unspecified size.
2245 char *t = NULL, *p = strpbrk(av, "/:,{");
2249 CHECK_LENGTH(cblen, F_INSN_SIZE(ipfw_insn) + 2 + len);
2254 if ((t = strpbrk(p, ",{")) != NULL) {
2261 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2262 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2265 if (!inet_aton(p, (struct in_addr *)&d[1]))
2266 errx(EX_DATAERR, "bad netmask ``%s''", p);
2271 d[1] = htonl(0); /* mask */
2272 else if (masklen > 32)
2273 errx(EX_DATAERR, "bad width ``%s''", p);
2275 d[1] = htonl(~0 << (32 - masklen));
2277 case '{': /* no mask, assume /24 and put back the '{' */
2278 d[1] = htonl(~0 << (32 - 24));
2282 case ',': /* single address plus continuation */
2285 case 0: /* initialization value */
2287 d[1] = htonl(~0); /* force /32 */
2290 d[0] &= d[1]; /* mask base address with mask */
2293 /* find next separator */
2295 p = strpbrk(p, ",{");
2296 if (p && *p == '{') {
2298 * We have a set of addresses. They are stored as follows:
2299 * arg1 is the set size (powers of 2, 2..256)
2300 * addr is the base address IN HOST FORMAT
2301 * mask.. is an array of arg1 bits (rounded up to
2302 * the next multiple of 32) with bits set
2303 * for each host in the map.
2305 uint32_t *map = (uint32_t *)&cmd->mask;
2307 int i = contigmask((uint8_t *)&(d[1]), 32);
2310 errx(EX_DATAERR, "address set cannot be in a list");
2311 if (i < 24 || i > 31)
2312 errx(EX_DATAERR, "invalid set with mask %d\n", i);
2313 cmd->o.arg1 = 1<<(32-i); /* map length */
2314 d[0] = ntohl(d[0]); /* base addr in host format */
2315 cmd->o.opcode = O_IP_DST_SET; /* default */
2316 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2317 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2318 map[i] = 0; /* clear map */
2322 high = low + cmd->o.arg1 - 1;
2324 * Here, i stores the previous value when we specify a range
2325 * of addresses within a mask, e.g. 45-63. i = -1 means we
2326 * have no previous value.
2328 i = -1; /* previous value in a range */
2329 while (isdigit(*av)) {
2331 int a = strtol(av, &s, 0);
2333 if (s == av) { /* no parameter */
2335 errx(EX_DATAERR, "set not closed\n");
2337 errx(EX_DATAERR, "incomplete range %d-", i);
2340 if (a < low || a > high)
2341 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
2344 if (i == -1) /* no previous in range */
2346 else { /* check that range is valid */
2348 errx(EX_DATAERR, "invalid range %d-%d",
2351 errx(EX_DATAERR, "double '-' in range");
2354 map[i/32] |= 1<<(i & 31);
2365 if (av) /* then *av must be a ',' */
2368 /* Check this entry */
2369 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2371 * 'any' turns the entire list into a NOP.
2372 * 'not any' never matches, so it is removed from the
2373 * list unless it is the only item, in which case we
2376 if (cmd->o.len & F_NOT) { /* "not any" never matches */
2377 if (av == NULL && len == 0) /* only this entry */
2378 errx(EX_DATAERR, "not any never matches");
2380 /* else do nothing and skip this entry */
2383 /* A single IP can be stored in an optimized format */
2384 if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
2385 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2388 len += 2; /* two words... */
2391 if (len + 1 > F_LEN_MASK)
2392 errx(EX_DATAERR, "address list too long");
2393 cmd->o.len |= len+1;
2397 /* n2mask sets n bits of the mask */
2399 n2mask(struct in6_addr *mask, int n)
2401 static int minimask[9] =
2402 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
2405 memset(mask, 0, sizeof(struct in6_addr));
2406 p = (u_char *) mask;
2407 for (; n > 0; p++, n -= 8) {
2417 * helper function to process a set of flags and set bits in the
2418 * appropriate masks.
2421 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
2422 struct _s_x *flags, char *p)
2424 uint8_t set=0, clear=0;
2427 char *q; /* points to the separator */
2429 uint8_t *which; /* mask we are working on */
2439 val = match_token(flags, p);
2441 errx(EX_DATAERR, "invalid flag %s", p);
2442 *which |= (uint8_t)val;
2445 cmd->opcode = opcode;
2446 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
2447 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
2452 ipfw_delete(char *av[])
2456 int exitval = EX_OK;
2460 NEED1("missing rule specification");
2461 if ( *av && _substrcmp(*av, "set") == 0) {
2462 /* Do not allow using the following syntax:
2463 * ipfw set N delete set M
2466 errx(EX_DATAERR, "invalid syntax");
2467 do_set = 1; /* delete set */
2472 while (*av && isdigit(**av)) {
2473 i = atoi(*av); av++;
2475 exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
2477 exitval = EX_UNAVAILABLE;
2478 warn("rule %u not available", i);
2480 } else if (co.do_pipe) {
2481 exitval = ipfw_delete_pipe(co.do_pipe, i);
2484 rulenum = (i & 0xffff) | (5 << 24) |
2485 ((co.use_set - 1) << 16);
2487 rulenum = (i & 0xffff) | (do_set << 24);
2488 i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum);
2490 exitval = EX_UNAVAILABLE;
2491 warn("rule %u: setsockopt(IP_FW_DEL)",
2496 if (exitval != EX_OK)
2502 * fill the interface structure. We do not check the name as we can
2503 * create interfaces dynamically, so checking them at insert time
2504 * makes relatively little sense.
2505 * Interface names containing '*', '?', or '[' are assumed to be shell
2506 * patterns which match interfaces.
2509 fill_iface(ipfw_insn_if *cmd, char *arg, int cblen)
2511 cmd->name[0] = '\0';
2512 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
2516 /* Parse the interface or address */
2517 if (strcmp(arg, "any") == 0)
2518 cmd->o.len = 0; /* effectively ignore this command */
2519 else if (strncmp(arg, "table(", 6) == 0) {
2520 char *p = strchr(arg + 6, ',');
2523 cmd->name[0] = '\1'; /* Special value indicating table */
2524 cmd->p.glob = strtoul(arg + 6, NULL, 0);
2525 } else if (!isdigit(*arg)) {
2526 strlcpy(cmd->name, arg, sizeof(cmd->name));
2527 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
2528 } else if (!inet_aton(arg, &cmd->p.ip))
2529 errx(EX_DATAERR, "bad ip address ``%s''", arg);
2533 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
2537 char *ap, *ptr, *optr;
2538 struct ether_addr *mac;
2539 const char *macset = "0123456789abcdefABCDEF:";
2541 if (strcmp(p, "any") == 0) {
2542 for (i = 0; i < ETHER_ADDR_LEN; i++)
2543 addr[i] = mask[i] = 0;
2547 optr = ptr = strdup(p);
2548 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
2550 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
2551 errx(EX_DATAERR, "Incorrect MAC address");
2552 bcopy(mac, addr, ETHER_ADDR_LEN);
2554 errx(EX_DATAERR, "Incorrect MAC address");
2556 if (ptr != NULL) { /* we have mask? */
2557 if (p[ptr - optr - 1] == '/') { /* mask len */
2558 long ml = strtol(ptr, &ap, 10);
2559 if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
2560 errx(EX_DATAERR, "Incorrect mask length");
2561 for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
2562 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
2565 if (strspn(ptr, macset) != l ||
2566 (mac = ether_aton(ptr)) == NULL)
2567 errx(EX_DATAERR, "Incorrect mask");
2568 bcopy(mac, mask, ETHER_ADDR_LEN);
2570 } else { /* default mask: ff:ff:ff:ff:ff:ff */
2571 for (i = 0; i < ETHER_ADDR_LEN; i++)
2574 for (i = 0; i < ETHER_ADDR_LEN; i++)
2581 * helper function, updates the pointer to cmd with the length
2582 * of the current command, and also cleans up the first word of
2583 * the new command in case it has been clobbered before.
2586 next_cmd(ipfw_insn *cmd, int *len)
2589 CHECK_LENGTH(*len, 0);
2591 bzero(cmd, sizeof(*cmd));
2596 * Takes arguments and copies them into a comment
2599 fill_comment(ipfw_insn *cmd, char **av, int cblen)
2602 char *p = (char *)(cmd + 1);
2604 cmd->opcode = O_NOP;
2605 cmd->len = (cmd->len & (F_NOT | F_OR));
2607 /* Compute length of comment string. */
2608 for (i = 0, l = 0; av[i] != NULL; i++)
2609 l += strlen(av[i]) + 1;
2614 "comment too long (max 80 chars)");
2616 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
2619 for (i = 0; av[i] != NULL; i++) {
2628 * A function to fill simple commands of size 1.
2629 * Existing flags are preserved.
2632 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
2634 cmd->opcode = opcode;
2635 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
2640 * Fetch and add the MAC address and type, with masks. This generates one or
2641 * two microinstructions, and returns the pointer to the last one.
2644 add_mac(ipfw_insn *cmd, char *av[], int cblen)
2648 if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
2649 errx(EX_DATAERR, "MAC dst src");
2651 cmd->opcode = O_MACADDR2;
2652 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
2655 mac = (ipfw_insn_mac *)cmd;
2656 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
2657 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
2658 &(mac->mask[ETHER_ADDR_LEN])); /* src */
2663 add_mactype(ipfw_insn *cmd, char *av, int cblen)
2666 errx(EX_DATAERR, "missing MAC type");
2667 if (strcmp(av, "any") != 0) { /* we have a non-null type */
2668 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
2670 cmd->opcode = O_MAC_TYPE;
2677 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
2679 struct protoent *pe;
2683 proto = strtol(av, &ep, 10);
2684 if (*ep != '\0' || proto <= 0) {
2685 if ((pe = getprotobyname(av)) == NULL)
2687 proto = pe->p_proto;
2690 fill_cmd(cmd, O_PROTO, 0, proto);
2696 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
2698 u_char proto = IPPROTO_IP;
2700 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2701 ; /* do not set O_IP4 nor O_IP6 */
2702 else if (strcmp(av, "ip4") == 0)
2703 /* explicit "just IPv4" rule */
2704 fill_cmd(cmd, O_IP4, 0, 0);
2705 else if (strcmp(av, "ip6") == 0) {
2706 /* explicit "just IPv6" rule */
2707 proto = IPPROTO_IPV6;
2708 fill_cmd(cmd, O_IP6, 0, 0);
2710 return add_proto0(cmd, av, protop);
2717 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
2719 u_char proto = IPPROTO_IP;
2721 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2722 ; /* do not set O_IP4 nor O_IP6 */
2723 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
2724 /* explicit "just IPv4" rule */
2725 fill_cmd(cmd, O_IP4, 0, 0);
2726 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
2727 /* explicit "just IPv6" rule */
2728 proto = IPPROTO_IPV6;
2729 fill_cmd(cmd, O_IP6, 0, 0);
2731 return add_proto0(cmd, av, protop);
2738 add_srcip(ipfw_insn *cmd, char *av, int cblen)
2740 fill_ip((ipfw_insn_ip *)cmd, av, cblen);
2741 if (cmd->opcode == O_IP_DST_SET) /* set */
2742 cmd->opcode = O_IP_SRC_SET;
2743 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
2744 cmd->opcode = O_IP_SRC_LOOKUP;
2745 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2746 cmd->opcode = O_IP_SRC_ME;
2747 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2748 cmd->opcode = O_IP_SRC;
2749 else /* addr/mask */
2750 cmd->opcode = O_IP_SRC_MASK;
2755 add_dstip(ipfw_insn *cmd, char *av, int cblen)
2757 fill_ip((ipfw_insn_ip *)cmd, av, cblen);
2758 if (cmd->opcode == O_IP_DST_SET) /* set */
2760 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
2762 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2763 cmd->opcode = O_IP_DST_ME;
2764 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2765 cmd->opcode = O_IP_DST;
2766 else /* addr/mask */
2767 cmd->opcode = O_IP_DST_MASK;
2772 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
2774 /* XXX "any" is trapped before. Perhaps "to" */
2775 if (_substrcmp(av, "any") == 0) {
2777 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
2778 /* XXX todo: check that we have a protocol with ports */
2779 cmd->opcode = opcode;
2786 add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen)
2789 char *host, *ch, buf[INET6_ADDRSTRLEN];
2790 ipfw_insn *ret = NULL;
2793 /* Copy first address in set if needed */
2794 if ((ch = strpbrk(av, "/,")) != NULL) {
2796 strlcpy(buf, av, sizeof(buf));
2797 if (len < sizeof(buf))
2803 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
2804 inet_pton(AF_INET6, host, &a) == 1)
2805 ret = add_srcip6(cmd, av, cblen);
2806 /* XXX: should check for IPv4, not !IPv6 */
2807 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2808 inet_pton(AF_INET6, host, &a) != 1))
2809 ret = add_srcip(cmd, av, cblen);
2810 if (ret == NULL && strcmp(av, "any") != 0)
2817 add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen)
2820 char *host, *ch, buf[INET6_ADDRSTRLEN];
2821 ipfw_insn *ret = NULL;
2824 /* Copy first address in set if needed */
2825 if ((ch = strpbrk(av, "/,")) != NULL) {
2827 strlcpy(buf, av, sizeof(buf));
2828 if (len < sizeof(buf))
2834 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
2835 inet_pton(AF_INET6, host, &a) == 1)
2836 ret = add_dstip6(cmd, av, cblen);
2837 /* XXX: should check for IPv4, not !IPv6 */
2838 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2839 inet_pton(AF_INET6, host, &a) != 1))
2840 ret = add_dstip(cmd, av, cblen);
2841 if (ret == NULL && strcmp(av, "any") != 0)
2848 * Parse arguments and assemble the microinstructions which make up a rule.
2849 * Rules are added into the 'rulebuf' and then copied in the correct order
2850 * into the actual rule.
2852 * The syntax for a rule starts with the action, followed by
2853 * optional action parameters, and the various match patterns.
2854 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
2855 * (generated if the rule includes a keep-state option), then the
2856 * various match patterns, log/altq actions, and the actual action.
2860 ipfw_add(char *av[])
2863 * rules are added into the 'rulebuf' and then copied in
2864 * the correct order into the actual rule.
2865 * Some things that need to go out of order (prob, action etc.)
2868 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255];
2869 int rblen, ablen, cblen;
2871 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
2872 ipfw_insn *first_cmd; /* first match pattern */
2877 * various flags used to record that we entered some fields.
2879 ipfw_insn *have_state = NULL; /* check-state or keep-state */
2880 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
2885 int open_par = 0; /* open parenthesis ( */
2887 /* proto is here because it is used to fetch ports */
2888 u_char proto = IPPROTO_IP; /* default protocol */
2890 double match_prob = 1; /* match probability, default is always match */
2892 bzero(actbuf, sizeof(actbuf)); /* actions go here */
2893 bzero(cmdbuf, sizeof(cmdbuf));
2894 bzero(rulebuf, sizeof(rulebuf));
2896 rule = (struct ip_fw *)rulebuf;
2897 cmd = (ipfw_insn *)cmdbuf;
2898 action = (ipfw_insn *)actbuf;
2900 rblen = sizeof(rulebuf) / sizeof(rulebuf[0]);
2901 rblen -= offsetof(struct ip_fw, cmd) / sizeof(rulebuf[0]);
2902 ablen = sizeof(actbuf) / sizeof(actbuf[0]);
2903 cblen = sizeof(cmdbuf) / sizeof(cmdbuf[0]);
2904 cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
2906 #define CHECK_RBUFLEN(len) { CHECK_LENGTH(rblen, len); rblen -= len; }
2907 #define CHECK_ACTLEN CHECK_LENGTH(ablen, action->len)
2911 /* [rule N] -- Rule number optional */
2912 if (av[0] && isdigit(**av)) {
2913 rule->rulenum = atoi(*av);
2917 /* [set N] -- set number (0..RESVD_SET), optional */
2918 if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
2919 int set = strtoul(av[1], NULL, 10);
2920 if (set < 0 || set > RESVD_SET)
2921 errx(EX_DATAERR, "illegal set %s", av[1]);
2926 /* [prob D] -- match probability, optional */
2927 if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
2928 match_prob = strtod(av[1], NULL);
2930 if (match_prob <= 0 || match_prob > 1)
2931 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
2935 /* action -- mandatory */
2936 NEED1("missing action");
2937 i = match_token(rule_actions, *av);
2939 action->len = 1; /* default */
2942 case TOK_CHECKSTATE:
2943 have_state = action;
2944 action->opcode = O_CHECK_STATE;
2948 action->opcode = O_ACCEPT;
2952 action->opcode = O_DENY;
2957 action->opcode = O_REJECT;
2958 action->arg1 = ICMP_UNREACH_HOST;
2962 action->opcode = O_REJECT;
2963 action->arg1 = ICMP_REJECT_RST;
2967 action->opcode = O_UNREACH6;
2968 action->arg1 = ICMP6_UNREACH_RST;
2972 action->opcode = O_REJECT;
2973 NEED1("missing reject code");
2974 fill_reject_code(&action->arg1, *av);
2979 action->opcode = O_UNREACH6;
2980 NEED1("missing unreach code");
2981 fill_unreach6_code(&action->arg1, *av);
2986 action->opcode = O_COUNT;
2990 action->opcode = O_NAT;
2991 action->len = F_INSN_SIZE(ipfw_insn_nat);
2993 if (_substrcmp(*av, "global") == 0) {
3001 action->opcode = O_QUEUE;
3004 action->opcode = O_PIPE;
3007 action->opcode = O_SKIPTO;
3010 action->opcode = O_NETGRAPH;
3013 action->opcode = O_NGTEE;
3016 action->opcode = O_DIVERT;
3019 action->opcode = O_TEE;
3022 action->opcode = O_CALLRETURN;
3025 errx(EX_USAGE, "missing argument for %s", *(av - 1));
3026 if (isdigit(**av)) {
3027 action->arg1 = strtoul(*av, NULL, 10);
3028 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
3029 errx(EX_DATAERR, "illegal argument for %s",
3031 } else if (_substrcmp(*av, "tablearg") == 0) {
3032 action->arg1 = IP_FW_TABLEARG;
3033 } else if (i == TOK_DIVERT || i == TOK_TEE) {
3036 s = getservbyname(av[0], "divert");
3038 action->arg1 = ntohs(s->s_port);
3040 errx(EX_DATAERR, "illegal divert/tee port");
3042 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
3048 * Locate the address-port separator (':' or ',').
3049 * Could be one of the following:
3053 * IPv6 w:x:y::z,port
3054 * The ':' can only be used with hostname and IPv4 address.
3055 * XXX-BZ Should we also support [w:x:y::z]:port?
3057 struct sockaddr_storage result;
3058 struct addrinfo *res;
3061 u_short port_number;
3063 NEED1("missing forward address[:port]");
3066 * locate the address-port separator (':' or ',')
3068 s = strchr(*av, ',');
3070 /* Distinguish between IPv4:port and IPv6 cases. */
3071 s = strchr(*av, ':');
3072 if (s && strchr(s+1, ':'))
3073 s = NULL; /* no port */
3078 /* Terminate host portion and set s to start of port. */
3080 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
3083 "illegal forwarding port ``%s''", s);
3084 port_number = (u_short)i;
3087 if (_substrcmp(*av, "tablearg") == 0) {
3089 ((struct sockaddr_in*)&result)->sin_addr.s_addr =
3093 * Resolve the host name or address to a family and a
3094 * network representation of the address.
3096 if (getaddrinfo(*av, NULL, NULL, &res))
3097 errx(EX_DATAERR, NULL);
3098 /* Just use the first host in the answer. */
3099 family = res->ai_family;
3100 memcpy(&result, res->ai_addr, res->ai_addrlen);
3104 if (family == PF_INET) {
3105 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
3107 action->opcode = O_FORWARD_IP;
3108 action->len = F_INSN_SIZE(ipfw_insn_sa);
3112 * In the kernel we assume AF_INET and use only
3113 * sin_port and sin_addr. Remember to set sin_len as
3114 * the routing code seems to use it too.
3116 p->sa.sin_len = sizeof(struct sockaddr_in);
3117 p->sa.sin_family = AF_INET;
3118 p->sa.sin_port = port_number;
3119 p->sa.sin_addr.s_addr =
3120 ((struct sockaddr_in *)&result)->sin_addr.s_addr;
3121 } else if (family == PF_INET6) {
3122 ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
3124 action->opcode = O_FORWARD_IP6;
3125 action->len = F_INSN_SIZE(ipfw_insn_sa6);
3128 p->sa.sin6_len = sizeof(struct sockaddr_in6);
3129 p->sa.sin6_family = AF_INET6;
3130 p->sa.sin6_port = port_number;
3131 p->sa.sin6_flowinfo = 0;
3132 p->sa.sin6_scope_id = 0;
3133 /* No table support for v6 yet. */
3134 bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
3135 &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
3137 errx(EX_DATAERR, "Invalid address family in forward action");
3143 /* pretend it is a 'count' rule followed by the comment */
3144 action->opcode = O_COUNT;
3145 av--; /* go back... */
3151 size_t intsize = sizeof(int);
3153 action->opcode = O_SETFIB;
3154 NEED1("missing fib number");
3155 if (_substrcmp(*av, "tablearg") == 0) {
3156 action->arg1 = IP_FW_TABLEARG;
3158 action->arg1 = strtoul(*av, NULL, 10);
3159 if (sysctlbyname("net.fibs", &numfibs, &intsize,
3161 errx(EX_DATAERR, "fibs not suported.\n");
3162 if (action->arg1 >= numfibs) /* Temporary */
3163 errx(EX_DATAERR, "fib too large.\n");
3173 action->opcode = O_SETDSCP;
3174 NEED1("missing DSCP code");
3175 if (_substrcmp(*av, "tablearg") == 0) {
3176 action->arg1 = IP_FW_TABLEARG;
3177 } else if (isalpha(*av[0])) {
3178 if ((code = match_token(f_ipdscp, *av)) == -1)
3179 errx(EX_DATAERR, "Unknown DSCP code");
3180 action->arg1 = code;
3182 action->arg1 = strtoul(*av, NULL, 10);
3188 action->opcode = O_REASS;
3192 fill_cmd(action, O_CALLRETURN, F_NOT, 0);
3196 errx(EX_DATAERR, "invalid action %s\n", av[-1]);
3198 action = next_cmd(action, &ablen);
3201 * [altq queuename] -- altq tag, optional
3202 * [log [logamount N]] -- log, optional
3204 * If they exist, it go first in the cmdbuf, but then it is
3205 * skipped in the copy section to the end of the buffer.
3207 while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
3212 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
3217 "log cannot be specified more than once");
3218 have_log = (ipfw_insn *)c;
3219 cmd->len = F_INSN_SIZE(ipfw_insn_log);
3221 cmd->opcode = O_LOG;
3222 if (av[0] && _substrcmp(*av, "logamount") == 0) {
3224 NEED1("logamount requires argument");
3228 "logamount must be positive");
3232 len = sizeof(c->max_log);
3233 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
3234 &c->max_log, &len, NULL, 0) == -1) {
3239 errx(1, "sysctlbyname(\"%s\")",
3240 "net.inet.ip.fw.verbose_limit");
3249 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
3251 NEED1("missing altq queue name");
3254 "altq cannot be specified more than once");
3255 have_altq = (ipfw_insn *)a;
3256 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
3258 cmd->opcode = O_ALTQ;
3259 a->qid = altq_name_to_qid(*av);
3270 errx(EX_USAGE, "tag and untag cannot be "
3271 "specified more than once");
3272 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
3273 rule_action_params);
3275 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
3283 cmd = next_cmd(cmd, &cblen);
3286 if (have_state) /* must be a check-state, we are done */
3289 #define OR_START(target) \
3290 if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
3292 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
3295 if ( (av[0])[1] == '\0') { \
3306 strcmp(*av, ")") == 0 || \
3307 strcmp(*av, "}") == 0)) { \
3312 errx(EX_USAGE, "missing \")\"\n"); \
3316 if (av[0] && _substrcmp(*av, "not") == 0) { \
3317 if (cmd->len & F_NOT) \
3318 errx(EX_USAGE, "double \"not\" not allowed\n"); \
3319 cmd->len |= F_NOT; \
3323 #define OR_BLOCK(target) \
3324 if (av[0] && _substrcmp(*av, "or") == 0) { \
3325 if (prev == NULL || open_par == 0) \
3326 errx(EX_DATAERR, "invalid OR block"); \
3327 prev->len |= F_OR; \
3337 * MAC addresses, optional.
3338 * If we have this, we skip the part "proto from src to dst"
3339 * and jump straight to the option parsing.
3342 NEED1("missing protocol");
3343 if (_substrcmp(*av, "MAC") == 0 ||
3344 _substrcmp(*av, "mac") == 0) {
3345 av++; /* the "MAC" keyword */
3346 add_mac(cmd, av); /* exits in case of errors */
3347 cmd = next_cmd(cmd);
3348 av += 2; /* dst-mac and src-mac */
3350 NEED1("missing mac type");
3351 if (add_mactype(cmd, av[0]))
3352 cmd = next_cmd(cmd);
3353 av++; /* any or mac-type */
3359 * protocol, mandatory
3361 OR_START(get_proto);
3363 NEED1("missing protocol");
3364 if (add_proto_compat(cmd, *av, &proto)) {
3366 if (F_LEN(cmd) != 0) {
3368 cmd = next_cmd(cmd, &cblen);
3370 } else if (first_cmd != cmd) {
3371 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
3374 OR_BLOCK(get_proto);
3379 if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
3380 errx(EX_USAGE, "missing ``from''");
3384 * source IP, mandatory
3386 OR_START(source_ip);
3387 NOT_BLOCK; /* optional "not" */
3388 NEED1("missing source address");
3389 if (add_src(cmd, *av, proto, cblen)) {
3391 if (F_LEN(cmd) != 0) { /* ! any */
3393 cmd = next_cmd(cmd, &cblen);
3396 errx(EX_USAGE, "bad source address %s", *av);
3397 OR_BLOCK(source_ip);
3400 * source ports, optional
3402 NOT_BLOCK; /* optional "not" */
3403 if ( av[0] != NULL ) {
3404 if (_substrcmp(*av, "any") == 0 ||
3405 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
3407 if (F_LEN(cmd) != 0)
3408 cmd = next_cmd(cmd, &cblen);
3415 if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
3416 errx(EX_USAGE, "missing ``to''");
3420 * destination, mandatory
3423 NOT_BLOCK; /* optional "not" */
3424 NEED1("missing dst address");
3425 if (add_dst(cmd, *av, proto, cblen)) {
3427 if (F_LEN(cmd) != 0) { /* ! any */
3429 cmd = next_cmd(cmd, &cblen);
3432 errx( EX_USAGE, "bad destination address %s", *av);
3436 * dest. ports, optional
3438 NOT_BLOCK; /* optional "not" */
3440 if (_substrcmp(*av, "any") == 0 ||
3441 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
3443 if (F_LEN(cmd) != 0)
3444 cmd = next_cmd(cmd, &cblen);
3449 if (av[0] && first_cmd == cmd) {
3451 * nothing specified so far, store in the rule to ease
3457 while ( av[0] != NULL ) {
3459 ipfw_insn_u32 *cmd32; /* alias for cmd */
3462 cmd32 = (ipfw_insn_u32 *)cmd;
3464 if (*s == '!') { /* alternate syntax for NOT */
3465 if (cmd->len & F_NOT)
3466 errx(EX_USAGE, "double \"not\" not allowed\n");
3470 i = match_token(rule_options, s);
3474 if (cmd->len & F_NOT)
3475 errx(EX_USAGE, "double \"not\" not allowed\n");
3480 if (open_par == 0 || prev == NULL)
3481 errx(EX_USAGE, "invalid \"or\" block\n");
3485 case TOK_STARTBRACE:
3487 errx(EX_USAGE, "+nested \"(\" not allowed\n");
3493 errx(EX_USAGE, "+missing \")\"\n");
3499 fill_cmd(cmd, O_IN, 0, 0);
3503 cmd->len ^= F_NOT; /* toggle F_NOT */
3504 fill_cmd(cmd, O_IN, 0, 0);
3508 fill_cmd(cmd, O_DIVERTED, 0, 3);
3511 case TOK_DIVERTEDLOOPBACK:
3512 fill_cmd(cmd, O_DIVERTED, 0, 1);
3515 case TOK_DIVERTEDOUTPUT:
3516 fill_cmd(cmd, O_DIVERTED, 0, 2);
3520 fill_cmd(cmd, O_FRAG, 0, 0);
3524 fill_cmd(cmd, O_LAYER2, 0, 0);
3530 NEED1("recv, xmit, via require interface name"
3532 fill_iface((ipfw_insn_if *)cmd, av[0], cblen);
3534 if (F_LEN(cmd) == 0) /* not a valid address */
3537 cmd->opcode = O_XMIT;
3538 else if (i == TOK_RECV)
3539 cmd->opcode = O_RECV;
3540 else if (i == TOK_VIA)
3541 cmd->opcode = O_VIA;
3545 NEED1("icmptypes requires list of types");
3546 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
3550 case TOK_ICMP6TYPES:
3551 NEED1("icmptypes requires list of types");
3552 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
3557 NEED1("ipttl requires TTL");
3558 if (strpbrk(*av, "-,")) {
3559 if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
3560 errx(EX_DATAERR, "invalid ipttl %s", *av);
3562 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
3567 NEED1("ipid requires id");
3568 if (strpbrk(*av, "-,")) {
3569 if (!add_ports(cmd, *av, 0, O_IPID, cblen))
3570 errx(EX_DATAERR, "invalid ipid %s", *av);
3572 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
3577 NEED1("iplen requires length");
3578 if (strpbrk(*av, "-,")) {
3579 if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
3580 errx(EX_DATAERR, "invalid ip len %s", *av);
3582 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
3587 NEED1("ipver requires version");
3588 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
3592 case TOK_IPPRECEDENCE:
3593 NEED1("ipprecedence requires value");
3594 fill_cmd(cmd, O_IPPRECEDENCE, 0,
3595 (strtoul(*av, NULL, 0) & 7) << 5);
3600 NEED1("missing DSCP code");
3601 fill_dscp(cmd, *av, cblen);
3606 NEED1("missing argument for ipoptions");
3607 fill_flags(cmd, O_IPOPT, f_ipopts, *av);
3612 NEED1("missing argument for iptos");
3613 fill_flags(cmd, O_IPTOS, f_iptos, *av);
3618 NEED1("uid requires argument");
3624 cmd->opcode = O_UID;
3625 uid = strtoul(*av, &end, 0);
3626 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
3628 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
3629 cmd32->d[0] = pwd->pw_uid;
3630 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3636 NEED1("gid requires argument");
3642 cmd->opcode = O_GID;
3643 gid = strtoul(*av, &end, 0);
3644 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
3646 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
3647 cmd32->d[0] = grp->gr_gid;
3648 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3654 NEED1("jail requires argument");
3659 cmd->opcode = O_JAIL;
3660 jid = (int)strtol(*av, &end, 0);
3661 if (jid < 0 || *end != '\0')
3662 errx(EX_DATAERR, "jail requires prison ID");
3663 cmd32->d[0] = (uint32_t)jid;
3664 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3670 fill_cmd(cmd, O_ESTAB, 0, 0);
3674 fill_cmd(cmd, O_TCPFLAGS, 0,
3675 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
3678 case TOK_TCPDATALEN:
3679 NEED1("tcpdatalen requires length");
3680 if (strpbrk(*av, "-,")) {
3681 if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
3682 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
3684 fill_cmd(cmd, O_TCPDATALEN, 0,
3685 strtoul(*av, NULL, 0));
3690 NEED1("missing argument for tcpoptions");
3691 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
3697 NEED1("tcpseq/tcpack requires argument");
3698 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3699 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
3700 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
3705 NEED1("tcpwin requires length");
3706 if (strpbrk(*av, "-,")) {
3707 if (!add_ports(cmd, *av, 0, O_TCPWIN, cblen))
3708 errx(EX_DATAERR, "invalid tcpwin len %s", *av);
3710 fill_cmd(cmd, O_TCPWIN, 0,
3711 strtoul(*av, NULL, 0));
3716 NEED1("missing argument for tcpflags");
3717 cmd->opcode = O_TCPFLAGS;
3718 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
3724 errx(EX_USAGE, "keep-state cannot be part "
3727 errx(EX_USAGE, "only one of keep-state "
3728 "and limit is allowed");
3730 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
3734 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
3739 "limit cannot be part of an or block");
3741 errx(EX_USAGE, "only one of keep-state and "
3742 "limit is allowed");
3745 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
3747 cmd->opcode = O_LIMIT;
3748 c->limit_mask = c->conn_limit = 0;
3750 while ( av[0] != NULL ) {
3751 if ((val = match_token(limit_masks, *av)) <= 0)
3753 c->limit_mask |= val;
3757 if (c->limit_mask == 0)
3758 errx(EX_USAGE, "limit: missing limit mask");
3760 GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
3761 TOK_LIMIT, rule_options);
3768 NEED1("missing protocol");
3769 if (add_proto(cmd, *av, &proto)) {
3772 errx(EX_DATAERR, "invalid protocol ``%s''",
3777 NEED1("missing source IP");
3778 if (add_srcip(cmd, *av, cblen)) {
3784 NEED1("missing destination IP");
3785 if (add_dstip(cmd, *av, cblen)) {
3791 NEED1("missing source IP6");
3792 if (add_srcip6(cmd, *av, cblen)) {
3798 NEED1("missing destination IP6");
3799 if (add_dstip6(cmd, *av, cblen)) {
3805 NEED1("missing source port");
3806 if (_substrcmp(*av, "any") == 0 ||
3807 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
3810 errx(EX_DATAERR, "invalid source port %s", *av);
3814 NEED1("missing destination port");
3815 if (_substrcmp(*av, "any") == 0 ||
3816 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
3819 errx(EX_DATAERR, "invalid destination port %s",
3824 if (add_mac(cmd, av, cblen))
3829 NEED1("missing mac type");
3830 if (!add_mactype(cmd, *av, cblen))
3831 errx(EX_DATAERR, "invalid mac type %s", *av);
3835 case TOK_VERREVPATH:
3836 fill_cmd(cmd, O_VERREVPATH, 0, 0);
3839 case TOK_VERSRCREACH:
3840 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
3844 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
3848 fill_cmd(cmd, O_IPSEC, 0, 0);
3852 fill_cmd(cmd, O_IP6, 0, 0);
3856 fill_cmd(cmd, O_IP4, 0, 0);
3860 fill_ext6hdr( cmd, *av );
3865 if (proto != IPPROTO_IPV6 )
3866 errx( EX_USAGE, "flow-id filter is active "
3867 "only for ipv6 protocol\n");
3868 fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
3873 fill_comment(cmd, av, cblen);
3878 if (av[0] && strpbrk(*av, "-,")) {
3879 if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
3880 errx(EX_DATAERR, "tagged: invalid tag"
3886 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
3887 TOK_TAGGED, rule_options);
3888 fill_cmd(cmd, O_TAGGED, 0, tag);
3894 NEED1("fib requires fib number");
3895 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
3899 fill_cmd(cmd, O_SOCKARG, 0, 0);
3903 ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
3907 if (!av[0] || !av[1])
3908 errx(EX_USAGE, "format: lookup argument tablenum");
3909 cmd->opcode = O_IP_DST_LOOKUP;
3910 cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
3911 i = match_token(rule_options, *av);
3912 for (j = 0; lookup_key[j] >= 0 ; j++) {
3913 if (i == lookup_key[j])
3916 if (lookup_key[j] <= 0)
3917 errx(EX_USAGE, "format: cannot lookup on %s", *av);
3918 __PAST_END(c->d, 1) = j; // i converted to option
3920 cmd->arg1 = strtoul(*av, &p, 0);
3922 errx(EX_USAGE, "format: lookup argument tablenum");
3928 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
3930 if (F_LEN(cmd) > 0) { /* prepare to advance */
3932 cmd = next_cmd(cmd, &cblen);
3938 * Now copy stuff into the rule.
3939 * If we have a keep-state option, the first instruction
3940 * must be a PROBE_STATE (which is generated here).
3941 * If we have a LOG option, it was stored as the first command,
3942 * and now must be moved to the top of the action part.
3944 dst = (ipfw_insn *)rule->cmd;
3947 * First thing to write into the command stream is the match probability.
3949 if (match_prob != 1) { /* 1 means always match */
3950 dst->opcode = O_PROB;
3952 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
3957 * generate O_PROBE_STATE if necessary
3959 if (have_state && have_state->opcode != O_CHECK_STATE) {
3960 fill_cmd(dst, O_PROBE_STATE, 0, 0);
3961 dst = next_cmd(dst, &rblen);
3964 /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
3965 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
3969 switch (src->opcode) {
3977 bcopy(src, dst, i * sizeof(uint32_t));
3983 * put back the have_state command as last opcode
3985 if (have_state && have_state->opcode != O_CHECK_STATE) {
3986 i = F_LEN(have_state);
3988 bcopy(have_state, dst, i * sizeof(uint32_t));
3992 * start action section
3994 rule->act_ofs = dst - rule->cmd;
3996 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
3998 i = F_LEN(have_log);
4000 bcopy(have_log, dst, i * sizeof(uint32_t));
4004 i = F_LEN(have_altq);
4006 bcopy(have_altq, dst, i * sizeof(uint32_t));
4010 i = F_LEN(have_tag);
4012 bcopy(have_tag, dst, i * sizeof(uint32_t));
4017 * copy all other actions
4019 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
4022 bcopy(src, dst, i * sizeof(uint32_t));
4026 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
4027 i = (char *)dst - (char *)rule;
4028 if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1)
4029 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
4031 show_ipfw(rule, 0, 0);
4035 * clear the counters or the log counters.
4038 ipfw_zero(int ac, char *av[], int optname /* 0 = IP_FW_ZERO, 1 = IP_FW_RESETLOG */)
4040 uint32_t arg, saved_arg;
4043 char const *name = optname ? "RESETLOG" : "ZERO";
4045 optname = optname ? IP_FW_RESETLOG : IP_FW_ZERO;
4050 /* clear all entries */
4051 if (do_cmd(optname, NULL, 0) < 0)
4052 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name);
4054 printf("%s.\n", optname == IP_FW_ZERO ?
4055 "Accounting cleared":"Logging counts reset");
4062 if (isdigit(**av)) {
4063 arg = strtonum(*av, 0, 0xffff, &errstr);
4066 "invalid rule number %s\n", *av);
4069 arg |= (1 << 24) | ((co.use_set - 1) << 16);
4072 if (do_cmd(optname, &arg, sizeof(arg))) {
4073 warn("rule %u: setsockopt(IP_FW_%s)",
4075 failed = EX_UNAVAILABLE;
4076 } else if (!co.do_quiet)
4077 printf("Entry %d %s.\n", saved_arg,
4078 optname == IP_FW_ZERO ?
4079 "cleared" : "logging count reset");
4081 errx(EX_USAGE, "invalid rule number ``%s''", *av);
4084 if (failed != EX_OK)
4089 ipfw_flush(int force)
4091 int cmd = co.do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
4093 if (!force && !co.do_quiet) { /* need to ask user */
4096 printf("Are you sure? [yn] ");
4099 c = toupper(getc(stdin));
4100 while (c != '\n' && getc(stdin) != '\n')
4102 return; /* and do not flush */
4103 } while (c != 'Y' && c != 'N');
4105 if (c == 'N') /* user said no */
4112 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
4114 uint32_t arg = ((co.use_set - 1) & 0xffff) | (1 << 24);
4115 if (do_cmd(IP_FW_DEL, &arg, sizeof(arg)) < 0)
4116 err(EX_UNAVAILABLE, "setsockopt(IP_FW_DEL)");
4117 } else if (do_cmd(cmd, NULL, 0) < 0)
4118 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
4119 co.do_pipe ? "DUMMYNET" : "FW");
4121 printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
4125 static void table_list(uint16_t num, int need_header);
4126 static void table_fill_xentry(char *arg, ipfw_table_xentry *xent);
4129 * Retrieve maximum number of tables supported by ipfw(4) module.
4132 ipfw_get_tables_max()
4135 uint32_t tables_max;
4137 if (ipfw_tables_max != 0)
4138 return (ipfw_tables_max);
4140 len = sizeof(tables_max);
4141 if (sysctlbyname("net.inet.ip.fw.tables_max", &tables_max, &len,
4144 tables_max = 128; /* Old conservative default */
4146 errx(1, "Can't determine maximum number of ipfw tables."
4147 " Perhaps you forgot to load ipfw module?");
4150 ipfw_tables_max = tables_max;
4152 return (ipfw_tables_max);
4156 * This one handles all table-related commands
4157 * ipfw table N add addr[/masklen] [value]
4158 * ipfw table N delete addr[/masklen]
4159 * ipfw table {N | all} flush
4160 * ipfw table {N | all} list
4163 ipfw_table_handler(int ac, char *av[])
4165 ipfw_table_xentry xent;
4169 uint32_t tables_max;
4171 tables_max = ipfw_get_tables_max();
4173 memset(&xent, 0, sizeof(xent));
4176 if (ac && isdigit(**av)) {
4177 xent.tbl = atoi(*av);
4180 } else if (ac && _substrcmp(*av, "all") == 0) {
4185 errx(EX_USAGE, "table number or 'all' keyword required");
4186 if (xent.tbl >= tables_max)
4187 errx(EX_USAGE, "The table number exceeds the maximum allowed "
4188 "value (%d)", tables_max - 1);
4189 NEED1("table needs command");
4190 if (is_all && _substrcmp(*av, "list") != 0
4191 && _substrcmp(*av, "flush") != 0)
4192 errx(EX_USAGE, "table number required");
4194 if (_substrcmp(*av, "add") == 0 ||
4195 _substrcmp(*av, "delete") == 0) {
4196 do_add = **av == 'a';
4199 errx(EX_USAGE, "address required");
4201 table_fill_xentry(*av, &xent);
4206 /* isdigit is a bit of a hack here.. */
4207 if (strchr(*av, (int)'.') == NULL && isdigit(**av)) {
4208 xent.value = strtoul(*av, NULL, 0);
4210 if (lookup_host(*av, (struct in_addr *)&tval) == 0) {
4211 /* The value must be stored in host order *
4212 * so that the values < 65k can be distinguished */
4213 xent.value = ntohl(tval);
4215 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
4220 if (do_setcmd3(do_add ? IP_FW_TABLE_XADD : IP_FW_TABLE_XDEL,
4221 &xent, xent.len) < 0) {
4222 /* If running silent, don't bomb out on these errors. */
4223 if (!(co.do_quiet && (errno == (do_add ? EEXIST : ESRCH))))
4224 err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)",
4225 do_add ? "XADD" : "XDEL");
4226 /* In silent mode, react to a failed add by deleting */
4228 do_setcmd3(IP_FW_TABLE_XDEL, &xent, xent.len);
4229 if (do_setcmd3(IP_FW_TABLE_XADD, &xent, xent.len) < 0)
4231 "setsockopt(IP_FW_TABLE_XADD)");
4234 } else if (_substrcmp(*av, "flush") == 0) {
4235 a = is_all ? tables_max : (uint32_t)(xent.tbl + 1);
4237 if (do_cmd(IP_FW_TABLE_FLUSH, &xent.tbl,
4238 sizeof(xent.tbl)) < 0)
4239 err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)");
4240 } while (++xent.tbl < a);
4241 } else if (_substrcmp(*av, "list") == 0) {
4242 a = is_all ? tables_max : (uint32_t)(xent.tbl + 1);
4244 table_list(xent.tbl, is_all);
4245 } while (++xent.tbl < a);
4247 errx(EX_USAGE, "invalid table command %s", *av);
4251 table_fill_xentry(char *arg, ipfw_table_xentry *xent)
4253 int addrlen, mask, masklen, type;
4254 struct in6_addr *paddr;
4265 * Let's try to guess type by agrument.
4270 * 4) port, uid/gid or other u32 key (base 10 format)
4273 paddr = &xent->k.addr6;
4274 if (ishexnumber(*arg) != 0 || *arg == ':') {
4275 /* Remove / if exists */
4276 if ((p = strchr(arg, '/')) != NULL) {
4281 if (inet_pton(AF_INET, arg, paddr) == 1) {
4282 if (p != NULL && mask > 32)
4283 errx(EX_DATAERR, "bad IPv4 mask width: %s",
4286 type = IPFW_TABLE_CIDR;
4287 masklen = p ? mask : 32;
4288 addrlen = sizeof(struct in_addr);
4289 } else if (inet_pton(AF_INET6, arg, paddr) == 1) {
4290 if (IN6_IS_ADDR_V4COMPAT(paddr))
4292 "Use IPv4 instead of v4-compatible");
4293 if (p != NULL && mask > 128)
4294 errx(EX_DATAERR, "bad IPv6 mask width: %s",
4297 type = IPFW_TABLE_CIDR;
4298 masklen = p ? mask : 128;
4299 addrlen = sizeof(struct in6_addr);
4301 /* Port or any other key */
4302 /* Skip non-base 10 entries like 'fa1' */
4303 key = strtol(arg, &p, 10);
4305 pkey = (uint32_t *)paddr;
4307 type = IPFW_TABLE_CIDR;
4309 addrlen = sizeof(uint32_t);
4310 } else if ((p != arg) && (*p == '.')) {
4312 * Warn on IPv4 address strings
4313 * which are "valid" for inet_aton() but not
4316 * Typical examples: '10.5' or '10.0.0.05'
4319 "Invalid IPv4 address: %s", arg);
4324 if (type == 0 && strchr(arg, '.') == NULL) {
4325 /* Assume interface name. Copy significant data only */
4326 mask = MIN(strlen(arg), IF_NAMESIZE - 1);
4327 memcpy(xent->k.iface, arg, mask);
4328 /* Set mask to exact match */
4329 masklen = 8 * IF_NAMESIZE;
4330 type = IPFW_TABLE_INTERFACE;
4331 addrlen = IF_NAMESIZE;
4335 if (lookup_host(arg, (struct in_addr *)paddr) != 0)
4336 errx(EX_NOHOST, "hostname ``%s'' unknown", arg);
4339 type = IPFW_TABLE_CIDR;
4340 addrlen = sizeof(struct in_addr);
4344 xent->masklen = masklen;
4345 xent->len = offsetof(ipfw_table_xentry, k) + addrlen;
4349 table_list(uint16_t num, int need_header)
4352 ipfw_table_xentry *xent;
4354 uint32_t *a, sz, tval;
4356 struct in6_addr *addr6;
4357 ip_fw3_opheader *op3;
4359 /* Prepend value with IP_FW3 header */
4360 l = sizeof(ip_fw3_opheader) + sizeof(uint32_t);
4362 /* Zero reserved fields */
4363 memset(op3, 0, sizeof(ip_fw3_opheader));
4364 a = (uint32_t *)(op3 + 1);
4366 op3->opcode = IP_FW_TABLE_XGETSIZE;
4367 if (do_cmd(IP_FW3, op3, (uintptr_t)&l) < 0)
4368 err(EX_OSERR, "getsockopt(IP_FW_TABLE_XGETSIZE)");
4370 /* If a is zero we have nothing to do, the table is empty. */
4375 tbl = safe_calloc(1, l);
4376 tbl->opheader.opcode = IP_FW_TABLE_XLIST;
4378 if (do_cmd(IP_FW3, tbl, (uintptr_t)&l) < 0)
4379 err(EX_OSERR, "getsockopt(IP_FW_TABLE_XLIST)");
4380 if (tbl->cnt && need_header)
4381 printf("---table(%d)---\n", tbl->tbl);
4382 sz = tbl->size - sizeof(ipfw_xtable);
4383 xent = &tbl->xent[0];
4385 switch (tbl->type) {
4386 case IPFW_TABLE_CIDR:
4387 /* IPv4 or IPv6 prefixes */
4389 addr6 = &xent->k.addr6;
4392 if (IN6_IS_ADDR_V4COMPAT(addr6)) {
4394 inet_ntop(AF_INET, &addr6->s6_addr32[3], tbuf, sizeof(tbuf));
4397 inet_ntop(AF_INET6, addr6, tbuf, sizeof(tbuf));
4400 if (co.do_value_as_ip) {
4402 printf("%s/%u %s\n", tbuf, xent->masklen,
4403 inet_ntoa(*(struct in_addr *)&tval));
4405 printf("%s/%u %u\n", tbuf, xent->masklen, tval);
4407 case IPFW_TABLE_INTERFACE:
4408 /* Interface names */
4410 if (co.do_value_as_ip) {
4412 printf("%s %s\n", xent->k.iface,
4413 inet_ntoa(*(struct in_addr *)&tval));
4415 printf("%s %u\n", xent->k.iface, tval);
4421 xent = (ipfw_table_xentry *)((char *)xent + xent->len);