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>
42 #include <time.h> /* ctime */
43 #include <timeconv.h> /* _long_to_time */
46 #include <stddef.h> /* offsetof */
48 #include <net/ethernet.h>
49 #include <net/if.h> /* only IFNAMSIZ */
50 #include <netinet/in.h>
51 #include <netinet/in_systm.h> /* only n_short, n_long */
52 #include <netinet/ip.h>
53 #include <netinet/ip_icmp.h>
54 #include <netinet/ip_fw.h>
55 #include <netinet/tcp.h>
56 #include <arpa/inet.h>
58 struct cmdline_opts co; /* global options */
64 uint32_t set_mask; /* enabled sets mask */
65 uint32_t flags; /* request flags */
66 uint32_t first; /* first rule to request */
67 uint32_t last; /* last rule to request */
68 uint32_t dcnt; /* number of dynamic states */
70 #define IP_FW_TARG IP_FW_TABLEARG
71 #define ip_fw_bcounter ip_fw
72 #define ip_fw_rule ip_fw
75 int resvd_set_number = RESVD_SET;
79 uint32_t ipfw_tables_max = 0; /* Number of tables supported by kernel */
82 #define s6_addr32 __u6_addr.__u6_addr32
85 #define CHECK_LENGTH(v, len) do { \
87 errx(EX_DATAERR, "Rule too long"); \
90 * Check if we have enough space in cmd buffer. Note that since
91 * first 8? u32 words are reserved by reserved header, full cmd
92 * buffer can't be used, so we need to protect from buffer overrun
93 * only. At the beginnig, cblen is less than actual buffer size by
94 * size of ipfw_insn_u32 instruction + 1 u32 work. This eliminates need
95 * for checking small instructions fitting in given range.
96 * We also (ab)use the fact that ipfw_insn is always the first field
97 * for any custom instruction.
99 #define CHECK_CMDLEN CHECK_LENGTH(cblen, F_LEN((ipfw_insn *)cmd))
101 #define GET_UINT_ARG(arg, min, max, tok, s_x) do { \
103 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
104 if (_substrcmp(*av, "tablearg") == 0) { \
113 _xval = strtol(*av, &end, 10); \
115 if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
116 errx(EX_DATAERR, "%s: invalid argument: %s", \
117 match_value(s_x, tok), *av); \
119 if (errno == ERANGE || _xval < min || _xval > max) \
120 errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
121 match_value(s_x, tok), min, max, *av); \
123 if (_xval == IP_FW_TARG) \
124 errx(EX_DATAERR, "%s: illegal argument value: %s", \
125 match_value(s_x, tok), *av); \
130 static struct _s_x f_tcpflags[] = {
141 static struct _s_x f_tcpopts[] = {
142 { "mss", IP_FW_TCPOPT_MSS },
143 { "maxseg", IP_FW_TCPOPT_MSS },
144 { "window", IP_FW_TCPOPT_WINDOW },
145 { "sack", IP_FW_TCPOPT_SACK },
146 { "ts", IP_FW_TCPOPT_TS },
147 { "timestamp", IP_FW_TCPOPT_TS },
148 { "cc", IP_FW_TCPOPT_CC },
154 * IP options span the range 0 to 255 so we need to remap them
155 * (though in fact only the low 5 bits are significant).
157 static struct _s_x f_ipopts[] = {
158 { "ssrr", IP_FW_IPOPT_SSRR},
159 { "lsrr", IP_FW_IPOPT_LSRR},
160 { "rr", IP_FW_IPOPT_RR},
161 { "ts", IP_FW_IPOPT_TS},
166 static struct _s_x f_iptos[] = {
167 { "lowdelay", IPTOS_LOWDELAY},
168 { "throughput", IPTOS_THROUGHPUT},
169 { "reliability", IPTOS_RELIABILITY},
170 { "mincost", IPTOS_MINCOST},
171 { "congestion", IPTOS_ECN_CE},
172 { "ecntransport", IPTOS_ECN_ECT0},
173 { "ip tos option", 0},
177 struct _s_x f_ipdscp[] = {
178 { "af11", IPTOS_DSCP_AF11 >> 2 }, /* 001010 */
179 { "af12", IPTOS_DSCP_AF12 >> 2 }, /* 001100 */
180 { "af13", IPTOS_DSCP_AF13 >> 2 }, /* 001110 */
181 { "af21", IPTOS_DSCP_AF21 >> 2 }, /* 010010 */
182 { "af22", IPTOS_DSCP_AF22 >> 2 }, /* 010100 */
183 { "af23", IPTOS_DSCP_AF23 >> 2 }, /* 010110 */
184 { "af31", IPTOS_DSCP_AF31 >> 2 }, /* 011010 */
185 { "af32", IPTOS_DSCP_AF32 >> 2 }, /* 011100 */
186 { "af33", IPTOS_DSCP_AF33 >> 2 }, /* 011110 */
187 { "af41", IPTOS_DSCP_AF41 >> 2 }, /* 100010 */
188 { "af42", IPTOS_DSCP_AF42 >> 2 }, /* 100100 */
189 { "af43", IPTOS_DSCP_AF43 >> 2 }, /* 100110 */
190 { "be", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
191 { "ef", IPTOS_DSCP_EF >> 2 }, /* 101110 */
192 { "cs0", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
193 { "cs1", IPTOS_DSCP_CS1 >> 2 }, /* 001000 */
194 { "cs2", IPTOS_DSCP_CS2 >> 2 }, /* 010000 */
195 { "cs3", IPTOS_DSCP_CS3 >> 2 }, /* 011000 */
196 { "cs4", IPTOS_DSCP_CS4 >> 2 }, /* 100000 */
197 { "cs5", IPTOS_DSCP_CS5 >> 2 }, /* 101000 */
198 { "cs6", IPTOS_DSCP_CS6 >> 2 }, /* 110000 */
199 { "cs7", IPTOS_DSCP_CS7 >> 2 }, /* 100000 */
203 static struct _s_x limit_masks[] = {
204 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
205 {"src-addr", DYN_SRC_ADDR},
206 {"src-port", DYN_SRC_PORT},
207 {"dst-addr", DYN_DST_ADDR},
208 {"dst-port", DYN_DST_PORT},
213 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
214 * This is only used in this code.
216 #define IPPROTO_ETHERTYPE 0x1000
217 static struct _s_x ether_types[] = {
219 * Note, we cannot use "-:&/" in the names because they are field
220 * separators in the type specifications. Also, we use s = NULL as
221 * end-delimiter, because a type of 0 can be legal.
234 { "pppoe_disc", 0x8863 },
235 { "pppoe_sess", 0x8864 },
236 { "ipx_8022", 0x00E0 },
237 { "ipx_8023", 0x0000 },
238 { "ipx_ii", 0x8137 },
239 { "ipx_snap", 0x8137 },
246 static struct _s_x rule_actions[] = {
247 { "accept", TOK_ACCEPT },
248 { "pass", TOK_ACCEPT },
249 { "allow", TOK_ACCEPT },
250 { "permit", TOK_ACCEPT },
251 { "count", TOK_COUNT },
252 { "pipe", TOK_PIPE },
253 { "queue", TOK_QUEUE },
254 { "divert", TOK_DIVERT },
256 { "netgraph", TOK_NETGRAPH },
257 { "ngtee", TOK_NGTEE },
258 { "fwd", TOK_FORWARD },
259 { "forward", TOK_FORWARD },
260 { "skipto", TOK_SKIPTO },
261 { "deny", TOK_DENY },
262 { "drop", TOK_DENY },
263 { "reject", TOK_REJECT },
264 { "reset6", TOK_RESET6 },
265 { "reset", TOK_RESET },
266 { "unreach6", TOK_UNREACH6 },
267 { "unreach", TOK_UNREACH },
268 { "check-state", TOK_CHECKSTATE },
269 { "//", TOK_COMMENT },
271 { "reass", TOK_REASS },
272 { "setfib", TOK_SETFIB },
273 { "setdscp", TOK_SETDSCP },
274 { "call", TOK_CALL },
275 { "return", TOK_RETURN },
276 { NULL, 0 } /* terminator */
279 static struct _s_x rule_action_params[] = {
280 { "altq", TOK_ALTQ },
283 { "untag", TOK_UNTAG },
284 { NULL, 0 } /* terminator */
288 * The 'lookup' instruction accepts one of the following arguments.
289 * -1 is a terminator for the list.
290 * Arguments are passed as v[1] in O_DST_LOOKUP options.
292 static int lookup_key[] = {
293 TOK_DSTIP, TOK_SRCIP, TOK_DSTPORT, TOK_SRCPORT,
294 TOK_UID, TOK_JAIL, TOK_DSCP, -1 };
296 static struct _s_x rule_options[] = {
297 { "tagged", TOK_TAGGED },
300 { "jail", TOK_JAIL },
302 { "limit", TOK_LIMIT },
303 { "keep-state", TOK_KEEPSTATE },
304 { "bridged", TOK_LAYER2 },
305 { "layer2", TOK_LAYER2 },
307 { "diverted", TOK_DIVERTED },
308 { "diverted-loopback", TOK_DIVERTEDLOOPBACK },
309 { "diverted-output", TOK_DIVERTEDOUTPUT },
310 { "xmit", TOK_XMIT },
311 { "recv", TOK_RECV },
313 { "fragment", TOK_FRAG },
314 { "frag", TOK_FRAG },
316 { "ipoptions", TOK_IPOPTS },
317 { "ipopts", TOK_IPOPTS },
318 { "iplen", TOK_IPLEN },
319 { "ipid", TOK_IPID },
320 { "ipprecedence", TOK_IPPRECEDENCE },
321 { "dscp", TOK_DSCP },
322 { "iptos", TOK_IPTOS },
323 { "ipttl", TOK_IPTTL },
324 { "ipversion", TOK_IPVER },
325 { "ipver", TOK_IPVER },
326 { "estab", TOK_ESTAB },
327 { "established", TOK_ESTAB },
328 { "setup", TOK_SETUP },
329 { "sockarg", TOK_SOCKARG },
330 { "tcpdatalen", TOK_TCPDATALEN },
331 { "tcpflags", TOK_TCPFLAGS },
332 { "tcpflgs", TOK_TCPFLAGS },
333 { "tcpoptions", TOK_TCPOPTS },
334 { "tcpopts", TOK_TCPOPTS },
335 { "tcpseq", TOK_TCPSEQ },
336 { "tcpack", TOK_TCPACK },
337 { "tcpwin", TOK_TCPWIN },
338 { "icmptype", TOK_ICMPTYPES },
339 { "icmptypes", TOK_ICMPTYPES },
340 { "dst-ip", TOK_DSTIP },
341 { "src-ip", TOK_SRCIP },
342 { "dst-port", TOK_DSTPORT },
343 { "src-port", TOK_SRCPORT },
344 { "proto", TOK_PROTO },
347 { "mac-type", TOK_MACTYPE },
348 { "verrevpath", TOK_VERREVPATH },
349 { "versrcreach", TOK_VERSRCREACH },
350 { "antispoof", TOK_ANTISPOOF },
351 { "ipsec", TOK_IPSEC },
352 { "icmp6type", TOK_ICMP6TYPES },
353 { "icmp6types", TOK_ICMP6TYPES },
354 { "ext6hdr", TOK_EXT6HDR},
355 { "flow-id", TOK_FLOWID},
360 { "dst-ipv6", TOK_DSTIP6},
361 { "dst-ip6", TOK_DSTIP6},
362 { "src-ipv6", TOK_SRCIP6},
363 { "src-ip6", TOK_SRCIP6},
364 { "lookup", TOK_LOOKUP},
365 { "//", TOK_COMMENT },
367 { "not", TOK_NOT }, /* pseudo option */
368 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
369 { "or", TOK_OR }, /* pseudo option */
370 { "|", /* escape */ TOK_OR }, /* pseudo option */
371 { "{", TOK_STARTBRACE }, /* pseudo option */
372 { "(", TOK_STARTBRACE }, /* pseudo option */
373 { "}", TOK_ENDBRACE }, /* pseudo option */
374 { ")", TOK_ENDBRACE }, /* pseudo option */
375 { NULL, 0 } /* terminator */
378 void bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg);
381 * Simple string buffer API.
382 * Used to simplify buffer passing between function and for
383 * transparent overrun handling.
387 * Allocates new buffer of given size @sz.
389 * Returns 0 on success.
392 bp_alloc(struct buf_pr *b, size_t size)
394 memset(b, 0, sizeof(struct buf_pr));
396 if ((b->buf = calloc(1, size)) == NULL)
407 bp_free(struct buf_pr *b)
414 * Flushes buffer so new writer start from beginning.
417 bp_flush(struct buf_pr *b)
425 * Print message specified by @format and args.
426 * Automatically manage buffer space and transparently handle
429 * Returns number of bytes that should have been printed.
432 bprintf(struct buf_pr *b, char *format, ...)
437 va_start(args, format);
439 i = vsnprintf(b->ptr, b->avail, format, args);
442 if (i > b->avail || i < 0) {
443 /* Overflow or print error */
456 * Special values printer for tablearg-aware opcodes.
459 bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg)
463 bprintf(bp, "%s", str);
464 if (arg == IP_FW_TARG)
465 bprintf(bp, "tablearg");
467 bprintf(bp, "%u", arg);
471 * Helper routine to print a possibly unaligned uint64_t on
472 * various platform. If width > 0, print the value with
473 * the desired width, followed by a space;
474 * otherwise, return the required width.
477 pr_u64(struct buf_pr *b, uint64_t *pd, int width)
480 #define U64_FMT "I64"
482 #define U64_FMT "llu"
485 unsigned long long d;
487 bcopy (pd, &u, sizeof(u));
490 bprintf(b, "%*" U64_FMT " ", width, d) :
491 snprintf(NULL, 0, "%" U64_FMT, d) ;
497 safe_calloc(size_t number, size_t size)
499 void *ret = calloc(number, size);
502 err(EX_OSERR, "calloc");
507 safe_realloc(void *ptr, size_t size)
509 void *ret = realloc(ptr, size);
512 err(EX_OSERR, "realloc");
517 * conditionally runs the command.
518 * Selected options or negative -> getsockopt
521 do_cmd(int optname, void *optval, uintptr_t optlen)
528 if (ipfw_socket == -1)
529 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
531 err(EX_UNAVAILABLE, "socket");
533 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
534 optname == IP_FW_ADD || optname == IP_FW3 ||
535 optname == IP_FW_NAT_GET_CONFIG ||
537 optname == IP_FW_NAT_GET_LOG) {
540 i = getsockopt(ipfw_socket, IPPROTO_IP, optname, optval,
541 (socklen_t *)optlen);
543 i = setsockopt(ipfw_socket, IPPROTO_IP, optname, optval, optlen);
549 * do_setcmd3 - pass ipfw control cmd to kernel
550 * @optname: option name
551 * @optval: pointer to option data
552 * @optlen: option length
554 * Function encapsulates option value in IP_FW3 socket option
555 * and calls setsockopt().
556 * Function returns 0 on success or -1 otherwise.
559 do_setcmd3(int optname, void *optval, socklen_t optlen)
562 ip_fw3_opheader *op3;
567 if (ipfw_socket == -1)
568 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
570 err(EX_UNAVAILABLE, "socket");
572 len = sizeof(ip_fw3_opheader) + optlen;
574 /* Zero reserved fields */
575 memset(op3, 0, sizeof(ip_fw3_opheader));
576 memcpy(op3 + 1, optval, optlen);
577 op3->opcode = optname;
579 return setsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, len);
583 * match_token takes a table and a string, returns the value associated
584 * with the string (-1 in case of failure).
587 match_token(struct _s_x *table, char *string)
590 uint i = strlen(string);
592 for (pt = table ; i && pt->s != NULL ; pt++)
593 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
599 * match_value takes a table and a value, returns the string associated
600 * with the value (NULL in case of failure).
603 match_value(struct _s_x *p, int value)
605 for (; p->s != NULL; p++)
612 * helper function to process a set of flags and set bits in the
616 fill_flags(struct _s_x *flags, char *p, uint8_t *set, uint8_t *clear)
618 char *q; /* points to the separator */
620 uint8_t *which; /* mask we are working on */
631 val = match_token(flags, p);
633 errx(EX_DATAERR, "invalid flag %s", p);
634 *which |= (uint8_t)val;
640 * _substrcmp takes two strings and returns 1 if they do not match,
641 * and 0 if they match exactly or the first string is a sub-string
642 * of the second. A warning is printed to stderr in the case that the
643 * first string is a sub-string of the second.
645 * This function will be removed in the future through the usual
646 * deprecation process.
649 _substrcmp(const char *str1, const char* str2)
652 if (strncmp(str1, str2, strlen(str1)) != 0)
655 if (strlen(str1) != strlen(str2))
656 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
662 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
663 * and 0 if they match exactly or the second string is a sub-string
664 * of the first. A warning is printed to stderr in the case that the
665 * first string does not match the third.
667 * This function exists to warn about the bizarre construction
668 * strncmp(str, "by", 2) which is used to allow people to use a shortcut
669 * for "bytes". The problem is that in addition to accepting "by",
670 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
671 * other string beginning with "by".
673 * This function will be removed in the future through the usual
674 * deprecation process.
677 _substrcmp2(const char *str1, const char* str2, const char* str3)
680 if (strncmp(str1, str2, strlen(str2)) != 0)
683 if (strcmp(str1, str3) != 0)
684 warnx("DEPRECATED: '%s' matched '%s'",
690 * prints one port, symbolic or numeric
693 print_port(struct buf_pr *bp, int proto, uint16_t port)
696 if (proto == IPPROTO_ETHERTYPE) {
699 if (co.do_resolv && (s = match_value(ether_types, port)) )
700 bprintf(bp, "%s", s);
702 bprintf(bp, "0x%04x", port);
704 struct servent *se = NULL;
706 struct protoent *pe = getprotobynumber(proto);
708 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
711 bprintf(bp, "%s", se->s_name);
713 bprintf(bp, "%d", port);
717 static struct _s_x _port_name[] = {
718 {"dst-port", O_IP_DSTPORT},
719 {"src-port", O_IP_SRCPORT},
723 {"mac-type", O_MAC_TYPE},
724 {"tcpdatalen", O_TCPDATALEN},
725 {"tcpwin", O_TCPWIN},
726 {"tagged", O_TAGGED},
731 * Print the values in a list 16-bit items of the types above.
732 * XXX todo: add support for mask.
735 print_newports(struct buf_pr *bp, ipfw_insn_u16 *cmd, int proto, int opcode)
737 uint16_t *p = cmd->ports;
742 sep = match_value(_port_name, opcode);
745 bprintf(bp, " %s", sep);
748 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
749 bprintf(bp, "%s", sep);
750 print_port(bp, proto, p[0]);
753 print_port(bp, proto, p[1]);
760 * Like strtol, but also translates service names into port numbers
761 * for some protocols.
763 * proto == -1 disables the protocol check;
764 * proto == IPPROTO_ETHERTYPE looks up an internal table
765 * proto == <some value in /etc/protocols> matches the values there.
766 * Returns *end == s in case the parameter is not found.
769 strtoport(char *s, char **end, int base, int proto)
775 *end = s; /* default - not found */
777 return 0; /* not found */
780 return strtol(s, end, base);
783 * find separator. '\\' escapes the next char.
785 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
786 if (*s1 == '\\' && s1[1] != '\0')
789 buf = safe_calloc(s1 - s + 1, 1);
792 * copy into a buffer skipping backslashes
794 for (p = s, i = 0; p != s1 ; p++)
799 if (proto == IPPROTO_ETHERTYPE) {
800 i = match_token(ether_types, buf);
802 if (i != -1) { /* found */
807 struct protoent *pe = NULL;
811 pe = getprotobynumber(proto);
813 se = getservbyname(buf, pe ? pe->p_name : NULL);
817 return ntohs(se->s_port);
820 return 0; /* not found */
824 * Fill the body of the command with the list of port ranges.
827 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
829 uint16_t a, b, *p = cmd->ports;
834 a = strtoport(av, &s, 0, proto);
835 if (s == av) /* empty or invalid argument */
838 CHECK_LENGTH(cblen, i + 2);
841 case '-': /* a range */
843 b = strtoport(av, &s, 0, proto);
844 /* Reject expressions like '1-abc' or '1-2-3'. */
845 if (s == av || (*s != ',' && *s != '\0'))
850 case ',': /* comma separated list */
855 warnx("port list: invalid separator <%c> in <%s>",
865 if (i + 1 > F_LEN_MASK)
866 errx(EX_DATAERR, "too many ports/ranges\n");
867 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
873 * Fill the body of the command with the list of DiffServ codepoints.
876 fill_dscp(ipfw_insn *cmd, char *av, int cblen)
878 uint32_t *low, *high;
882 cmd->opcode = O_DSCP;
883 cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
887 low = (uint32_t *)(cmd + 1);
900 if ((code = match_token(f_ipdscp, s)) == -1)
901 errx(EX_DATAERR, "Unknown DSCP code");
903 code = strtoul(s, NULL, 10);
904 if (code < 0 || code > 63)
905 errx(EX_DATAERR, "Invalid DSCP value");
909 *high |= 1 << (code - 32);
917 static struct _s_x icmpcodes[] = {
918 { "net", ICMP_UNREACH_NET },
919 { "host", ICMP_UNREACH_HOST },
920 { "protocol", ICMP_UNREACH_PROTOCOL },
921 { "port", ICMP_UNREACH_PORT },
922 { "needfrag", ICMP_UNREACH_NEEDFRAG },
923 { "srcfail", ICMP_UNREACH_SRCFAIL },
924 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
925 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
926 { "isolated", ICMP_UNREACH_ISOLATED },
927 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
928 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
929 { "tosnet", ICMP_UNREACH_TOSNET },
930 { "toshost", ICMP_UNREACH_TOSHOST },
931 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
932 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
933 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
938 fill_reject_code(u_short *codep, char *str)
943 val = strtoul(str, &s, 0);
944 if (s == str || *s != '\0' || val >= 0x100)
945 val = match_token(icmpcodes, str);
947 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
953 print_reject_code(struct buf_pr *bp, uint16_t code)
957 if ((s = match_value(icmpcodes, code)) != NULL)
958 bprintf(bp, "unreach %s", s);
960 bprintf(bp, "unreach %u", code);
964 * Returns the number of bits set (from left) in a contiguous bitmask,
965 * or -1 if the mask is not contiguous.
966 * XXX this needs a proper fix.
967 * This effectively works on masks in big-endian (network) format.
968 * when compiled on little endian architectures.
970 * First bit is bit 7 of the first byte -- note, for MAC addresses,
971 * the first bit on the wire is bit 0 of the first byte.
972 * len is the max length in bits.
975 contigmask(uint8_t *p, int len)
979 for (i=0; i<len ; i++)
980 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
982 for (n=i+1; n < len; n++)
983 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
984 return -1; /* mask not contiguous */
989 * print flags set/clear in the two bitmasks passed as parameters.
990 * There is a specialized check for f_tcpflags.
993 print_flags(struct buf_pr *bp, char const *name, ipfw_insn *cmd,
996 char const *comma = "";
998 uint8_t set = cmd->arg1 & 0xff;
999 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
1001 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
1002 bprintf(bp, " setup");
1006 bprintf(bp, " %s ", name);
1007 for (i=0; list[i].x != 0; i++) {
1008 if (set & list[i].x) {
1010 bprintf(bp, "%s%s", comma, list[i].s);
1013 if (clear & list[i].x) {
1014 clear &= ~list[i].x;
1015 bprintf(bp, "%s!%s", comma, list[i].s);
1022 * Print the ip address contained in a command.
1025 print_ip(struct buf_pr *bp, struct format_opts *fo, ipfw_insn_ip *cmd,
1028 struct hostent *he = NULL;
1030 uint32_t len = F_LEN((ipfw_insn *)cmd);
1031 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
1033 if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
1035 const char *arg = "<invalid>";
1037 if (d < sizeof(lookup_key)/sizeof(lookup_key[0]))
1038 arg = match_value(rule_options, lookup_key[d]);
1039 bprintf(bp, "%s lookup %s %d", cmd->o.len & F_NOT ? " not": "",
1043 bprintf(bp, "%s%s ", cmd->o.len & F_NOT ? " not": "", s);
1045 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
1049 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
1050 cmd->o.opcode == O_IP_DST_LOOKUP) {
1051 bprintf(bp, "table(%u", ((ipfw_insn *)cmd)->arg1);
1052 if (len == F_INSN_SIZE(ipfw_insn_u32))
1053 bprintf(bp, ",%u", *a);
1057 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
1058 uint32_t x, *map = (uint32_t *)&(cmd->mask);
1062 x = cmd->o.arg1 - 1;
1064 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1065 bprintf(bp, "%s/%d", inet_ntoa(cmd->addr),
1066 contigmask((uint8_t *)&x, 32));
1067 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1068 x &= 0xff; /* base */
1070 * Print bits and ranges.
1071 * Locate first bit set (i), then locate first bit unset (j).
1072 * If we have 3+ consecutive bits set, then print them as a
1073 * range, otherwise only print the initial bit and rescan.
1075 for (i=0; i < cmd->o.arg1; i++)
1076 if (map[i/32] & (1<<(i & 31))) {
1077 for (j=i+1; j < cmd->o.arg1; j++)
1078 if (!(map[ j/32] & (1<<(j & 31))))
1080 bprintf(bp, "%c%d", comma, i+x);
1081 if (j>i+2) { /* range has at least 3 elements */
1082 bprintf(bp, "-%d", j-1+x);
1091 * len == 2 indicates a single IP, whereas lists of 1 or more
1092 * addr/mask pairs have len = (2n+1). We convert len to n so we
1093 * use that to count the number of entries.
1095 for (len = len / 2; len > 0; len--, a += 2) {
1096 int mb = /* mask length */
1097 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1098 32 : contigmask((uint8_t *)&(a[1]), 32);
1099 if (mb == 32 && co.do_resolv)
1100 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
1101 if (he != NULL) /* resolved to name */
1102 bprintf(bp, "%s", he->h_name);
1103 else if (mb == 0) /* any */
1105 else { /* numeric IP followed by some kind of mask */
1106 ia = (struct in_addr *)&a[0];
1107 bprintf(bp, "%s", inet_ntoa(*ia));
1109 bprintf(bp, ":%s", inet_ntoa(*ia ) );
1111 bprintf(bp, "/%d", mb);
1119 * prints a MAC address/mask pair
1122 print_mac(struct buf_pr *bp, uint8_t *addr, uint8_t *mask)
1124 int l = contigmask(mask, 48);
1127 bprintf(bp, " any");
1129 bprintf(bp, " %02x:%02x:%02x:%02x:%02x:%02x",
1130 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1132 bprintf(bp, "&%02x:%02x:%02x:%02x:%02x:%02x",
1133 mask[0], mask[1], mask[2],
1134 mask[3], mask[4], mask[5]);
1136 bprintf(bp, "/%d", l);
1141 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1150 type = strtoul(av, &av, 0);
1152 if (*av != ',' && *av != '\0')
1153 errx(EX_DATAERR, "invalid ICMP type");
1156 errx(EX_DATAERR, "ICMP type out of range");
1158 cmd->d[0] |= 1 << type;
1160 cmd->o.opcode = O_ICMPTYPE;
1161 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1165 print_icmptypes(struct buf_pr *bp, ipfw_insn_u32 *cmd)
1170 bprintf(bp, " icmptypes");
1171 for (i = 0; i < 32; i++) {
1172 if ( (cmd->d[0] & (1 << (i))) == 0)
1174 bprintf(bp, "%c%d", sep, i);
1180 print_dscp(struct buf_pr *bp, ipfw_insn_u32 *cmd)
1187 bprintf(bp, " dscp");
1192 if (*v & (1 << i)) {
1193 if ((code = match_value(f_ipdscp, i)) != NULL)
1194 bprintf(bp, "%c%s", sep, code);
1196 bprintf(bp, "%c%d", sep, i);
1200 if ((++i % 32) == 0)
1206 * show_ipfw() prints the body of an ipfw rule.
1207 * Because the standard rule has at least proto src_ip dst_ip, we use
1208 * a helper function to produce these entries if not provided explicitly.
1209 * The first argument is the list of fields we have, the second is
1210 * the list of fields we want to be printed.
1212 * Special cases if we have provided a MAC header:
1213 * + if the rule does not contain IP addresses/ports, do not print them;
1214 * + if the rule does not contain an IP proto, print "all" instead of "ip";
1216 * Once we have 'have_options', IP header fields are printed as options.
1218 #define HAVE_PROTO 0x0001
1219 #define HAVE_SRCIP 0x0002
1220 #define HAVE_DSTIP 0x0004
1221 #define HAVE_PROTO4 0x0008
1222 #define HAVE_PROTO6 0x0010
1223 #define HAVE_IP 0x0100
1224 #define HAVE_OPTIONS 0x8000
1227 show_prerequisites(struct buf_pr *bp, int *flags, int want, int cmd)
1229 (void)cmd; /* UNUSED */
1230 if (co.comment_only)
1232 if ( (*flags & HAVE_IP) == HAVE_IP)
1233 *flags |= HAVE_OPTIONS;
1235 if ( !(*flags & HAVE_OPTIONS)) {
1236 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) {
1237 if ( (*flags & HAVE_PROTO4))
1238 bprintf(bp, " ip4");
1239 else if ( (*flags & HAVE_PROTO6))
1240 bprintf(bp, " ip6");
1244 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
1245 bprintf(bp, " from any");
1246 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
1247 bprintf(bp, " to any");
1253 show_static_rule(struct cmdline_opts *co, struct format_opts *fo,
1254 struct buf_pr *bp, struct ip_fw_rule *rule, struct ip_fw_bcounter *cntr)
1256 static int twidth = 0;
1258 ipfw_insn *cmd, *tagptr = NULL;
1259 const char *comment = NULL; /* ptr to comment if we have one */
1260 int proto = 0; /* default */
1261 int flags = 0; /* prerequisites */
1262 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
1263 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
1264 int or_block = 0; /* we are in an or block */
1265 uint32_t set_disable;
1268 bcopy(&rule->next_rule, &set_disable, sizeof(set_disable));
1270 if (set_disable & (1 << rule->set)) {
1275 bprintf(bp, "# DISABLED ");
1277 bprintf(bp, "%05u ", rule->rulenum);
1279 /* Print counters if enabled */
1280 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
1281 pr_u64(bp, &cntr->pcnt, fo->pcwidth);
1282 pr_u64(bp, &cntr->bcnt, fo->bcwidth);
1285 if (co->do_time == 2)
1286 bprintf(bp, "%10u ", cntr->timestamp);
1287 else if (co->do_time == 1) {
1289 time_t t = (time_t)0;
1292 strcpy(timestr, ctime(&t));
1293 *strchr(timestr, '\n') = '\0';
1294 twidth = strlen(timestr);
1296 if (cntr->timestamp > 0) {
1297 t = _long_to_time(cntr->timestamp);
1299 strcpy(timestr, ctime(&t));
1300 *strchr(timestr, '\n') = '\0';
1301 bprintf(bp, "%s ", timestr);
1303 bprintf(bp, "%*s", twidth, " ");
1308 bprintf(bp, "set %d ", rule->set);
1311 * print the optional "match probability"
1313 if (rule->cmd_len > 0) {
1315 if (cmd->opcode == O_PROB) {
1316 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1317 double d = 1.0 * p->d[0];
1319 d = (d / 0x7fffffff);
1320 bprintf(bp, "prob %f ", d);
1325 * first print actions
1327 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1328 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1329 switch(cmd->opcode) {
1331 bprintf(bp, "check-state");
1332 /* avoid printing anything else */
1333 flags = HAVE_PROTO | HAVE_SRCIP |
1334 HAVE_DSTIP | HAVE_IP;
1338 bprintf(bp, "allow");
1342 bprintf(bp, "count");
1346 bprintf(bp, "deny");
1350 if (cmd->arg1 == ICMP_REJECT_RST)
1351 bprintf(bp, "reset");
1352 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1353 bprintf(bp, "reject");
1355 print_reject_code(bp, cmd->arg1);
1359 if (cmd->arg1 == ICMP6_UNREACH_RST)
1360 bprintf(bp, "reset6");
1362 print_unreach6_code(cmd->arg1);
1366 bprint_uint_arg(bp, "skipto ", cmd->arg1);
1370 bprint_uint_arg(bp, "pipe ", cmd->arg1);
1374 bprint_uint_arg(bp, "queue ", cmd->arg1);
1378 bprint_uint_arg(bp, "divert ", cmd->arg1);
1382 bprint_uint_arg(bp, "tee ", cmd->arg1);
1386 bprint_uint_arg(bp, "netgraph ", cmd->arg1);
1390 bprint_uint_arg(bp, "ngtee ", cmd->arg1);
1395 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1397 if (s->sa.sin_addr.s_addr == INADDR_ANY) {
1398 bprintf(bp, "fwd tablearg");
1400 bprintf(bp, "fwd %s",inet_ntoa(s->sa.sin_addr));
1403 bprintf(bp, ",%d", s->sa.sin_port);
1409 char buf[4 + INET6_ADDRSTRLEN + 1];
1410 ipfw_insn_sa6 *s = (ipfw_insn_sa6 *)cmd;
1412 bprintf(bp, "fwd %s", inet_ntop(AF_INET6,
1413 &s->sa.sin6_addr, buf, sizeof(buf)));
1414 if (s->sa.sin6_port)
1415 bprintf(bp, ",%d", s->sa.sin6_port);
1419 case O_LOG: /* O_LOG is printed last */
1420 logptr = (ipfw_insn_log *)cmd;
1423 case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1424 altqptr = (ipfw_insn_altq *)cmd;
1433 bprint_uint_arg(bp, "nat ", cmd->arg1);
1435 bprintf(bp, "nat global");
1439 bprint_uint_arg(bp, "setfib ", cmd->arg1 & 0x7FFF);
1446 if (cmd->arg1 == IP_FW_TARG) {
1447 bprint_uint_arg(bp, "setdscp ", cmd->arg1);
1450 uval = cmd->arg1 & 0x3F;
1451 if ((code = match_value(f_ipdscp, uval)) != NULL)
1452 bprintf(bp, "setdscp %s", code);
1454 bprint_uint_arg(bp, "setdscp ", uval);
1459 bprintf(bp, "reass");
1463 if (cmd->len & F_NOT)
1464 bprintf(bp, "return");
1466 bprint_uint_arg(bp, "call ", cmd->arg1);
1470 bprintf(bp, "** unrecognized action %d len %d ",
1471 cmd->opcode, cmd->len);
1475 if (logptr->max_log > 0)
1476 bprintf(bp, " log logamount %d", logptr->max_log);
1478 bprintf(bp, " log");
1482 print_altq_cmd(bp, altqptr);
1486 if (tagptr->len & F_NOT)
1487 bprint_uint_arg(bp, " untag ", tagptr->arg1);
1489 bprint_uint_arg(bp, " tag ", tagptr->arg1);
1493 * then print the body.
1495 for (l = rule->act_ofs, cmd = rule->cmd;
1496 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1497 if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1499 if (cmd->opcode == O_IP4) {
1500 flags |= HAVE_PROTO4;
1502 } else if (cmd->opcode == O_IP6) {
1503 flags |= HAVE_PROTO6;
1507 if (rule->_pad & 1) { /* empty rules before options */
1508 if (!co->do_compact) {
1509 show_prerequisites(bp, &flags, HAVE_PROTO, 0);
1510 bprintf(bp, " from any to any");
1512 flags |= HAVE_IP | HAVE_OPTIONS | HAVE_PROTO |
1513 HAVE_SRCIP | HAVE_DSTIP;
1516 if (co->comment_only)
1519 for (l = rule->act_ofs, cmd = rule->cmd;
1520 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1522 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1524 if (co->comment_only) {
1525 if (cmd->opcode != O_NOP)
1527 bprintf(bp, " // %s\n", (char *)(cmd + 1));
1531 show_prerequisites(bp, &flags, 0, cmd->opcode);
1533 switch(cmd->opcode) {
1535 break; /* done already */
1538 break; /* no need to print anything here */
1541 case O_IP_SRC_LOOKUP:
1545 show_prerequisites(bp, &flags, HAVE_PROTO, 0);
1546 if (!(flags & HAVE_SRCIP))
1547 bprintf(bp, " from");
1548 if ((cmd->len & F_OR) && !or_block)
1550 print_ip(bp, fo, (ipfw_insn_ip *)cmd,
1551 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1552 flags |= HAVE_SRCIP;
1556 case O_IP_DST_LOOKUP:
1560 show_prerequisites(bp, &flags, HAVE_PROTO|HAVE_SRCIP, 0);
1561 if (!(flags & HAVE_DSTIP))
1563 if ((cmd->len & F_OR) && !or_block)
1565 print_ip(bp, fo, (ipfw_insn_ip *)cmd,
1566 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1567 flags |= HAVE_DSTIP;
1571 case O_IP6_SRC_MASK:
1573 show_prerequisites(bp, &flags, HAVE_PROTO, 0);
1574 if (!(flags & HAVE_SRCIP))
1575 bprintf(bp, " from");
1576 if ((cmd->len & F_OR) && !or_block)
1578 print_ip6(bp, (ipfw_insn_ip6 *)cmd,
1579 (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1580 flags |= HAVE_SRCIP | HAVE_PROTO;
1584 case O_IP6_DST_MASK:
1586 show_prerequisites(bp, &flags, HAVE_PROTO|HAVE_SRCIP, 0);
1587 if (!(flags & HAVE_DSTIP))
1589 if ((cmd->len & F_OR) && !or_block)
1591 print_ip6(bp, (ipfw_insn_ip6 *)cmd,
1592 (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1593 flags |= HAVE_DSTIP;
1597 print_flow6id(bp, (ipfw_insn_u32 *) cmd );
1598 flags |= HAVE_OPTIONS;
1602 show_prerequisites(bp, &flags,
1603 HAVE_PROTO | HAVE_SRCIP |
1604 HAVE_DSTIP | HAVE_IP, 0);
1606 if (flags & HAVE_DSTIP)
1608 show_prerequisites(bp, &flags,
1609 HAVE_PROTO | HAVE_SRCIP, 0);
1610 if ((cmd->len & F_OR) && !or_block)
1612 if (cmd->len & F_NOT)
1613 bprintf(bp, " not");
1614 print_newports(bp, (ipfw_insn_u16 *)cmd, proto,
1615 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1619 struct protoent *pe = NULL;
1621 if ((cmd->len & F_OR) && !or_block)
1623 if (cmd->len & F_NOT)
1624 bprintf(bp, " not");
1626 pe = getprotobynumber(cmd->arg1);
1627 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1628 !(flags & HAVE_PROTO))
1629 show_prerequisites(bp, &flags,
1630 HAVE_PROTO | HAVE_IP | HAVE_SRCIP |
1631 HAVE_DSTIP | HAVE_OPTIONS, 0);
1632 if (flags & HAVE_OPTIONS)
1633 bprintf(bp, " proto");
1635 bprintf(bp, " %s", pe->p_name);
1637 bprintf(bp, " %u", cmd->arg1);
1639 flags |= HAVE_PROTO;
1642 default: /*options ... */
1643 if (!(cmd->len & (F_OR|F_NOT)))
1644 if (((cmd->opcode == O_IP6) &&
1645 (flags & HAVE_PROTO6)) ||
1646 ((cmd->opcode == O_IP4) &&
1647 (flags & HAVE_PROTO4)))
1649 show_prerequisites(bp, &flags, HAVE_PROTO | HAVE_SRCIP |
1650 HAVE_DSTIP | HAVE_IP | HAVE_OPTIONS, 0);
1651 if ((cmd->len & F_OR) && !or_block)
1653 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1654 bprintf(bp, " not");
1655 switch(cmd->opcode) {
1657 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1659 bprintf(bp, " MAC");
1660 print_mac(bp, m->addr, m->mask);
1661 print_mac(bp, m->addr + 6, m->mask + 6);
1666 print_newports(bp, (ipfw_insn_u16 *)cmd,
1667 IPPROTO_ETHERTYPE, cmd->opcode);
1672 bprintf(bp, " frag");
1676 bprintf(bp, " fib %u", cmd->arg1 );
1679 bprintf(bp, " sockarg");
1683 bprintf(bp, cmd->len & F_NOT ? " out" : " in");
1687 switch (cmd->arg1) {
1689 bprintf(bp, " diverted");
1692 bprintf(bp, " diverted-loopback");
1695 bprintf(bp, " diverted-output");
1698 bprintf(bp, " diverted-?<%u>", cmd->arg1);
1704 bprintf(bp, " layer2");
1711 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1713 if (cmd->opcode == O_XMIT)
1715 else if (cmd->opcode == O_RECV)
1717 else /* if (cmd->opcode == O_VIA) */
1719 if (cmdif->name[0] == '\0')
1720 bprintf(bp, " %s %s", s,
1721 inet_ntoa(cmdif->p.ip));
1722 else if (cmdif->name[0] == '\1') /* interface table */
1723 bprintf(bp, " %s table(%d)", s, cmdif->p.glob);
1725 bprintf(bp, " %s %s", s, cmdif->name);
1729 if (F_LEN(cmd) == 1)
1730 bprintf(bp, " ipid %u", cmd->arg1 );
1732 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1737 if (F_LEN(cmd) == 1)
1738 bprintf(bp, " ipttl %u", cmd->arg1 );
1740 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1745 bprintf(bp, " ipver %u", cmd->arg1 );
1748 case O_IPPRECEDENCE:
1749 bprintf(bp, " ipprecedence %u", cmd->arg1 >> 5);
1753 print_dscp(bp, (ipfw_insn_u32 *)cmd);
1757 if (F_LEN(cmd) == 1)
1758 bprintf(bp, " iplen %u", cmd->arg1 );
1760 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1765 print_flags(bp, "ipoptions", cmd, f_ipopts);
1769 print_flags(bp, "iptos", cmd, f_iptos);
1773 print_icmptypes(bp, (ipfw_insn_u32 *)cmd);
1777 bprintf(bp, " established");
1781 if (F_LEN(cmd) == 1)
1782 bprintf(bp, " tcpdatalen %u", cmd->arg1 );
1784 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1789 print_flags(bp, "tcpflags", cmd, f_tcpflags);
1793 print_flags(bp, "tcpoptions", cmd, f_tcpopts);
1797 if (F_LEN(cmd) == 1)
1798 bprintf(bp, " tcpwin %u", cmd->arg1);
1800 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1805 bprintf(bp, " tcpack %d", ntohl(cmd32->d[0]));
1809 bprintf(bp, " tcpseq %d", ntohl(cmd32->d[0]));
1814 struct passwd *pwd = getpwuid(cmd32->d[0]);
1817 bprintf(bp, " uid %s", pwd->pw_name);
1819 bprintf(bp, " uid %u", cmd32->d[0]);
1825 struct group *grp = getgrgid(cmd32->d[0]);
1828 bprintf(bp, " gid %s", grp->gr_name);
1830 bprintf(bp, " gid %u", cmd32->d[0]);
1835 bprintf(bp, " jail %d", cmd32->d[0]);
1839 bprintf(bp, " verrevpath");
1843 bprintf(bp, " versrcreach");
1847 bprintf(bp, " antispoof");
1851 bprintf(bp, " ipsec");
1855 comment = (char *)(cmd + 1);
1859 bprintf(bp, " keep-state");
1863 struct _s_x *p = limit_masks;
1864 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1865 uint8_t x = c->limit_mask;
1866 char const *comma = " ";
1868 bprintf(bp, " limit");
1869 for (; p->x != 0 ; p++)
1870 if ((x & p->x) == p->x) {
1872 bprintf(bp, "%s%s", comma,p->s);
1875 bprint_uint_arg(bp, " ", c->conn_limit);
1880 bprintf(bp, " ip6");
1884 bprintf(bp, " ip4");
1888 print_icmp6types(bp, (ipfw_insn_u32 *)cmd);
1892 print_ext6hdr(bp, (ipfw_insn *)cmd);
1896 if (F_LEN(cmd) == 1)
1897 bprint_uint_arg(bp, " tagged ",
1900 print_newports(bp, (ipfw_insn_u16 *)cmd,
1905 bprintf(bp, " [opcode %d len %d]",
1906 cmd->opcode, cmd->len);
1909 if (cmd->len & F_OR) {
1912 } else if (or_block) {
1917 show_prerequisites(bp, &flags, HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP
1920 bprintf(bp, " // %s", comment);
1925 show_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
1926 struct buf_pr *bp, ipfw_dyn_rule *d)
1928 struct protoent *pe;
1931 char buf[INET6_ADDRSTRLEN];
1933 if (!co->do_expired) {
1934 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1937 bcopy(&d->rule, &rulenum, sizeof(rulenum));
1938 bprintf(bp, "%05d", rulenum);
1939 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
1941 pr_u64(bp, &d->pcnt, fo->pcwidth);
1942 pr_u64(bp, &d->bcnt, fo->bcwidth);
1943 bprintf(bp, "(%ds)", d->expire);
1945 switch (d->dyn_type) {
1946 case O_LIMIT_PARENT:
1947 bprintf(bp, " PARENT %d", d->count);
1950 bprintf(bp, " LIMIT");
1952 case O_KEEP_STATE: /* bidir, no mask */
1953 bprintf(bp, " STATE");
1957 if ((pe = getprotobynumber(d->id.proto)) != NULL)
1958 bprintf(bp, " %s", pe->p_name);
1960 bprintf(bp, " proto %u", d->id.proto);
1962 if (d->id.addr_type == 4) {
1963 a.s_addr = htonl(d->id.src_ip);
1964 bprintf(bp, " %s %d", inet_ntoa(a), d->id.src_port);
1966 a.s_addr = htonl(d->id.dst_ip);
1967 bprintf(bp, " <-> %s %d", inet_ntoa(a), d->id.dst_port);
1968 } else if (d->id.addr_type == 6) {
1969 bprintf(bp, " %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
1970 sizeof(buf)), d->id.src_port);
1971 bprintf(bp, " <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6,
1972 buf, sizeof(buf)), d->id.dst_port);
1974 bprintf(bp, " UNKNOWN <-> UNKNOWN\n");
1978 * This one handles all set-related commands
1979 * ipfw set { show | enable | disable }
1981 * ipfw set move X to Y
1982 * ipfw set move rule X to Y
1985 ipfw_sets_handler(char *av[])
1987 uint32_t set_disable, masks[2];
1990 uint8_t cmd, new_set;
1995 errx(EX_USAGE, "set needs command");
1996 if (_substrcmp(*av, "show") == 0) {
2001 nalloc = nbytes = sizeof(struct ip_fw);
2002 while (nbytes >= nalloc) {
2005 nalloc = nalloc * 2 + 200;
2007 data = safe_calloc(1, nbytes);
2008 if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0)
2009 err(EX_OSERR, "getsockopt(IP_FW_GET)");
2012 bcopy(&((struct ip_fw *)data)->next_rule,
2013 &set_disable, sizeof(set_disable));
2015 for (i = 0, msg = "disable" ; i < RESVD_SET; i++)
2016 if ((set_disable & (1<<i))) {
2017 printf("%s %d", msg, i);
2020 msg = (set_disable) ? " enable" : "enable";
2021 for (i = 0; i < RESVD_SET; i++)
2022 if (!(set_disable & (1<<i))) {
2023 printf("%s %d", msg, i);
2027 } else if (_substrcmp(*av, "swap") == 0) {
2029 if ( av[0] == NULL || av[1] == NULL )
2030 errx(EX_USAGE, "set swap needs 2 set numbers\n");
2031 rulenum = atoi(av[0]);
2032 new_set = atoi(av[1]);
2033 if (!isdigit(*(av[0])) || rulenum > RESVD_SET)
2034 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2035 if (!isdigit(*(av[1])) || new_set > RESVD_SET)
2036 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2037 masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
2038 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
2039 } else if (_substrcmp(*av, "move") == 0) {
2041 if (av[0] && _substrcmp(*av, "rule") == 0) {
2046 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
2047 av[3] != NULL || _substrcmp(av[1], "to") != 0)
2048 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2049 rulenum = atoi(av[0]);
2050 new_set = atoi(av[2]);
2051 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) ||
2052 (cmd == 2 && rulenum == IPFW_DEFAULT_RULE) )
2053 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2054 if (!isdigit(*(av[2])) || new_set > RESVD_SET)
2055 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2056 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
2057 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
2058 } else if (_substrcmp(*av, "disable") == 0 ||
2059 _substrcmp(*av, "enable") == 0 ) {
2060 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2063 masks[0] = masks[1] = 0;
2066 if (isdigit(**av)) {
2068 if (i < 0 || i > RESVD_SET)
2070 "invalid set number %d\n", i);
2071 masks[which] |= (1<<i);
2072 } else if (_substrcmp(*av, "disable") == 0)
2074 else if (_substrcmp(*av, "enable") == 0)
2078 "invalid set command %s\n", *av);
2081 if ( (masks[0] & masks[1]) != 0 )
2083 "cannot enable and disable the same set\n");
2085 i = do_cmd(IP_FW_DEL, masks, sizeof(masks));
2087 warn("set enable/disable: setsockopt(IP_FW_DEL)");
2089 errx(EX_USAGE, "invalid set command %s\n", *av);
2093 ipfw_sysctl_handler(char *av[], int which)
2097 if (av[0] == NULL) {
2098 warnx("missing keyword to enable/disable\n");
2099 } else if (_substrcmp(*av, "firewall") == 0) {
2100 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2101 &which, sizeof(which));
2102 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
2103 &which, sizeof(which));
2104 } else if (_substrcmp(*av, "one_pass") == 0) {
2105 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2106 &which, sizeof(which));
2107 } else if (_substrcmp(*av, "debug") == 0) {
2108 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2109 &which, sizeof(which));
2110 } else if (_substrcmp(*av, "verbose") == 0) {
2111 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2112 &which, sizeof(which));
2113 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2114 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2115 &which, sizeof(which));
2117 } else if (_substrcmp(*av, "altq") == 0) {
2118 altq_set_enabled(which);
2121 warnx("unrecognize enable/disable keyword: %s\n", *av);
2126 ipfw_list(int ac, char *av[], int show_counters)
2129 ipfw_dyn_rule *dynrules, *d;
2131 #define NEXT(r) ((struct ip_fw *)((char *)r + RULESIZE(r)))
2134 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
2135 int exitval = EX_OK;
2140 struct format_opts fo;
2145 const int ocmd = co.do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
2146 int nalloc = 1024; /* start somewhere... */
2151 fprintf(stderr, "Testing only, list disabled\n");
2155 dummynet_list(ac, av, show_counters);
2162 /* get rules or pipes from kernel, resizing array as necessary */
2165 while (nbytes >= nalloc) {
2166 nalloc = nalloc * 2 + 200;
2168 data = safe_realloc(data, nbytes);
2169 if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0)
2170 err(EX_OSERR, "getsockopt(IP_%s_GET)",
2171 co.do_pipe ? "DUMMYNET" : "FW");
2175 * Count static rules. They have variable size so we
2176 * need to scan the list to count them.
2178 for (nstat = 1, r = data, lim = (char *)data + nbytes;
2179 r->rulenum < IPFW_DEFAULT_RULE && (char *)r < lim;
2180 ++nstat, r = NEXT(r) )
2184 * Count dynamic rules. This is easier as they have
2188 dynrules = (ipfw_dyn_rule *)r ;
2189 n = (char *)r - (char *)data;
2190 ndyn = (nbytes - n) / sizeof *dynrules;
2192 /* if showing stats, figure out column widths ahead of time */
2193 bcwidth = pcwidth = 0;
2194 if (show_counters) {
2195 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
2196 /* skip rules from another set */
2197 if (co.use_set && r->set != co.use_set - 1)
2200 /* packet counter */
2201 width = pr_u64(&bp, &r->pcnt, 0);
2202 if (width > pcwidth)
2206 width = pr_u64(&bp, &r->bcnt, 0);
2207 if (width > bcwidth)
2211 if (co.do_dynamic && ndyn) {
2212 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2214 /* skip rules from another set */
2215 bcopy((char *)&d->rule + sizeof(uint16_t),
2216 &set, sizeof(uint8_t));
2217 if (set != co.use_set - 1)
2220 width = pr_u64(&bp, &d->pcnt, 0);
2221 if (width > pcwidth)
2224 width = pr_u64(&bp, &d->bcnt, 0);
2225 if (width > bcwidth)
2230 memset(&fo, 0, sizeof(fo));
2231 fo.pcwidth = pcwidth;
2232 fo.bcwidth = bcwidth;
2233 bp_alloc(&bp, 4096);
2234 /* if no rule numbers were specified, list all rules */
2236 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
2237 if (co.use_set && r->set != co.use_set - 1)
2239 show_static_rule(&co, &fo, &bp, r, r);
2240 printf("%s", bp.buf);
2244 if (co.do_dynamic && ndyn) {
2245 printf("## Dynamic rules (%d):\n", ndyn);
2246 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2248 bcopy((char *)&d->rule + sizeof(uint16_t),
2249 &set, sizeof(uint8_t));
2250 if (set != co.use_set - 1)
2253 show_dyn_state(&co, &fo, &bp, d);
2254 printf("%s\n", bp.buf);
2261 /* display specific rules requested on command line */
2263 for (lac = ac, lav = av; lac != 0; lac--) {
2264 /* convert command line rule # */
2265 last = rnum = strtoul(*lav++, &endptr, 10);
2267 last = strtoul(endptr+1, &endptr, 10);
2270 warnx("invalid rule number: %s", *(lav - 1));
2273 for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) {
2274 if (r->rulenum > last)
2276 if (co.use_set && r->set != co.use_set - 1)
2278 if (r->rulenum >= rnum && r->rulenum <= last) {
2279 show_static_rule(&co, &fo, &bp, r, r);
2280 printf("%s", bp.buf);
2286 /* give precedence to other error(s) */
2287 if (exitval == EX_OK)
2288 exitval = EX_UNAVAILABLE;
2289 warnx("rule %lu does not exist", rnum);
2293 if (co.do_dynamic && ndyn) {
2294 printf("## Dynamic rules:\n");
2295 for (lac = ac, lav = av; lac != 0; lac--) {
2296 last = rnum = strtoul(*lav++, &endptr, 10);
2298 last = strtoul(endptr+1, &endptr, 10);
2300 /* already warned */
2302 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2305 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2309 bcopy((char *)&d->rule + sizeof(uint16_t),
2310 &set, sizeof(uint8_t));
2311 if (set != co.use_set - 1)
2314 if (r->rulenum >= rnum && r->rulenum <= last) {
2315 show_dyn_state(&co, &fo, &bp, d);
2316 printf("%s\n", bp.buf);
2328 if (exitval != EX_OK)
2334 lookup_host (char *host, struct in_addr *ipaddr)
2338 if (!inet_aton(host, ipaddr)) {
2339 if ((he = gethostbyname(host)) == NULL)
2341 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2347 * fills the addr and mask fields in the instruction as appropriate from av.
2348 * Update length as appropriate.
2349 * The following formats are allowed:
2350 * me returns O_IP_*_ME
2351 * 1.2.3.4 single IP address
2352 * 1.2.3.4:5.6.7.8 address:mask
2353 * 1.2.3.4/24 address/mask
2354 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
2355 * We can have multiple comma-separated address/mask entries.
2358 fill_ip(ipfw_insn_ip *cmd, char *av, int cblen, struct tidx *tstate)
2361 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2362 uint32_t tables_max;
2364 cmd->o.len &= ~F_LEN_MASK; /* zero len */
2366 if (_substrcmp(av, "any") == 0)
2369 if (_substrcmp(av, "me") == 0) {
2370 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2374 if (strncmp(av, "table(", 6) == 0) {
2375 char *p = strchr(av + 6, ',');
2379 cmd->o.opcode = O_IP_DST_LOOKUP;
2380 cmd->o.arg1 = strtoul(av + 6, NULL, 0);
2381 tables_max = ipfw_get_tables_max();
2382 if (cmd->o.arg1 > tables_max)
2383 errx(EX_USAGE, "The table number exceeds the maximum "
2384 "allowed value (%u)", tables_max - 1);
2386 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2387 d[0] = strtoul(p, NULL, 0);
2389 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2395 * After the address we can have '/' or ':' indicating a mask,
2396 * ',' indicating another address follows, '{' indicating a
2397 * set of addresses of unspecified size.
2399 char *t = NULL, *p = strpbrk(av, "/:,{");
2403 CHECK_LENGTH(cblen, F_INSN_SIZE(ipfw_insn) + 2 + len);
2408 if ((t = strpbrk(p, ",{")) != NULL) {
2415 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2416 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2419 if (!inet_aton(p, (struct in_addr *)&d[1]))
2420 errx(EX_DATAERR, "bad netmask ``%s''", p);
2425 d[1] = htonl(0); /* mask */
2426 else if (masklen > 32)
2427 errx(EX_DATAERR, "bad width ``%s''", p);
2429 d[1] = htonl(~0 << (32 - masklen));
2431 case '{': /* no mask, assume /24 and put back the '{' */
2432 d[1] = htonl(~0 << (32 - 24));
2436 case ',': /* single address plus continuation */
2439 case 0: /* initialization value */
2441 d[1] = htonl(~0); /* force /32 */
2444 d[0] &= d[1]; /* mask base address with mask */
2447 /* find next separator */
2449 p = strpbrk(p, ",{");
2450 if (p && *p == '{') {
2452 * We have a set of addresses. They are stored as follows:
2453 * arg1 is the set size (powers of 2, 2..256)
2454 * addr is the base address IN HOST FORMAT
2455 * mask.. is an array of arg1 bits (rounded up to
2456 * the next multiple of 32) with bits set
2457 * for each host in the map.
2459 uint32_t *map = (uint32_t *)&cmd->mask;
2461 int i = contigmask((uint8_t *)&(d[1]), 32);
2464 errx(EX_DATAERR, "address set cannot be in a list");
2465 if (i < 24 || i > 31)
2466 errx(EX_DATAERR, "invalid set with mask %d\n", i);
2467 cmd->o.arg1 = 1<<(32-i); /* map length */
2468 d[0] = ntohl(d[0]); /* base addr in host format */
2469 cmd->o.opcode = O_IP_DST_SET; /* default */
2470 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2471 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2472 map[i] = 0; /* clear map */
2476 high = low + cmd->o.arg1 - 1;
2478 * Here, i stores the previous value when we specify a range
2479 * of addresses within a mask, e.g. 45-63. i = -1 means we
2480 * have no previous value.
2482 i = -1; /* previous value in a range */
2483 while (isdigit(*av)) {
2485 int a = strtol(av, &s, 0);
2487 if (s == av) { /* no parameter */
2489 errx(EX_DATAERR, "set not closed\n");
2491 errx(EX_DATAERR, "incomplete range %d-", i);
2494 if (a < low || a > high)
2495 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
2498 if (i == -1) /* no previous in range */
2500 else { /* check that range is valid */
2502 errx(EX_DATAERR, "invalid range %d-%d",
2505 errx(EX_DATAERR, "double '-' in range");
2508 map[i/32] |= 1<<(i & 31);
2519 if (av) /* then *av must be a ',' */
2522 /* Check this entry */
2523 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2525 * 'any' turns the entire list into a NOP.
2526 * 'not any' never matches, so it is removed from the
2527 * list unless it is the only item, in which case we
2530 if (cmd->o.len & F_NOT) { /* "not any" never matches */
2531 if (av == NULL && len == 0) /* only this entry */
2532 errx(EX_DATAERR, "not any never matches");
2534 /* else do nothing and skip this entry */
2537 /* A single IP can be stored in an optimized format */
2538 if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
2539 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2542 len += 2; /* two words... */
2545 if (len + 1 > F_LEN_MASK)
2546 errx(EX_DATAERR, "address list too long");
2547 cmd->o.len |= len+1;
2551 /* n2mask sets n bits of the mask */
2553 n2mask(struct in6_addr *mask, int n)
2555 static int minimask[9] =
2556 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
2559 memset(mask, 0, sizeof(struct in6_addr));
2560 p = (u_char *) mask;
2561 for (; n > 0; p++, n -= 8) {
2571 * helper function to process a set of flags and set bits in the
2572 * appropriate masks.
2575 fill_flags_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode,
2576 struct _s_x *flags, char *p)
2578 uint8_t set = 0, clear = 0;
2580 fill_flags(flags, p, &set, &clear);
2581 cmd->opcode = opcode;
2582 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
2583 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
2588 ipfw_delete(char *av[])
2592 int exitval = EX_OK;
2596 NEED1("missing rule specification");
2597 if ( *av && _substrcmp(*av, "set") == 0) {
2598 /* Do not allow using the following syntax:
2599 * ipfw set N delete set M
2602 errx(EX_DATAERR, "invalid syntax");
2603 do_set = 1; /* delete set */
2608 while (*av && isdigit(**av)) {
2609 i = atoi(*av); av++;
2611 exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
2613 exitval = EX_UNAVAILABLE;
2614 warn("rule %u not available", i);
2616 } else if (co.do_pipe) {
2617 exitval = ipfw_delete_pipe(co.do_pipe, i);
2620 rulenum = (i & 0xffff) | (5 << 24) |
2621 ((co.use_set - 1) << 16);
2623 rulenum = (i & 0xffff) | (do_set << 24);
2624 i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum);
2626 exitval = EX_UNAVAILABLE;
2627 warn("rule %u: setsockopt(IP_FW_DEL)",
2632 if (exitval != EX_OK)
2638 * fill the interface structure. We do not check the name as we can
2639 * create interfaces dynamically, so checking them at insert time
2640 * makes relatively little sense.
2641 * Interface names containing '*', '?', or '[' are assumed to be shell
2642 * patterns which match interfaces.
2645 fill_iface(ipfw_insn_if *cmd, char *arg, int cblen, struct tidx *tstate)
2647 cmd->name[0] = '\0';
2648 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
2652 /* Parse the interface or address */
2653 if (strcmp(arg, "any") == 0)
2654 cmd->o.len = 0; /* effectively ignore this command */
2655 else if (strncmp(arg, "table(", 6) == 0) {
2656 char *p = strchr(arg + 6, ',');
2659 cmd->name[0] = '\1'; /* Special value indicating table */
2660 cmd->p.glob = strtoul(arg + 6, NULL, 0);
2661 } else if (!isdigit(*arg)) {
2662 strlcpy(cmd->name, arg, sizeof(cmd->name));
2663 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
2664 } else if (!inet_aton(arg, &cmd->p.ip))
2665 errx(EX_DATAERR, "bad ip address ``%s''", arg);
2669 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
2673 char *ap, *ptr, *optr;
2674 struct ether_addr *mac;
2675 const char *macset = "0123456789abcdefABCDEF:";
2677 if (strcmp(p, "any") == 0) {
2678 for (i = 0; i < ETHER_ADDR_LEN; i++)
2679 addr[i] = mask[i] = 0;
2683 optr = ptr = strdup(p);
2684 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
2686 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
2687 errx(EX_DATAERR, "Incorrect MAC address");
2688 bcopy(mac, addr, ETHER_ADDR_LEN);
2690 errx(EX_DATAERR, "Incorrect MAC address");
2692 if (ptr != NULL) { /* we have mask? */
2693 if (p[ptr - optr - 1] == '/') { /* mask len */
2694 long ml = strtol(ptr, &ap, 10);
2695 if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
2696 errx(EX_DATAERR, "Incorrect mask length");
2697 for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
2698 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
2701 if (strspn(ptr, macset) != l ||
2702 (mac = ether_aton(ptr)) == NULL)
2703 errx(EX_DATAERR, "Incorrect mask");
2704 bcopy(mac, mask, ETHER_ADDR_LEN);
2706 } else { /* default mask: ff:ff:ff:ff:ff:ff */
2707 for (i = 0; i < ETHER_ADDR_LEN; i++)
2710 for (i = 0; i < ETHER_ADDR_LEN; i++)
2717 * helper function, updates the pointer to cmd with the length
2718 * of the current command, and also cleans up the first word of
2719 * the new command in case it has been clobbered before.
2722 next_cmd(ipfw_insn *cmd, int *len)
2725 CHECK_LENGTH(*len, 0);
2727 bzero(cmd, sizeof(*cmd));
2732 * Takes arguments and copies them into a comment
2735 fill_comment(ipfw_insn *cmd, char **av, int cblen)
2738 char *p = (char *)(cmd + 1);
2740 cmd->opcode = O_NOP;
2741 cmd->len = (cmd->len & (F_NOT | F_OR));
2743 /* Compute length of comment string. */
2744 for (i = 0, l = 0; av[i] != NULL; i++)
2745 l += strlen(av[i]) + 1;
2750 "comment too long (max 80 chars)");
2752 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
2755 for (i = 0; av[i] != NULL; i++) {
2764 * A function to fill simple commands of size 1.
2765 * Existing flags are preserved.
2768 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
2770 cmd->opcode = opcode;
2771 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
2776 * Fetch and add the MAC address and type, with masks. This generates one or
2777 * two microinstructions, and returns the pointer to the last one.
2780 add_mac(ipfw_insn *cmd, char *av[], int cblen)
2784 if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
2785 errx(EX_DATAERR, "MAC dst src");
2787 cmd->opcode = O_MACADDR2;
2788 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
2791 mac = (ipfw_insn_mac *)cmd;
2792 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
2793 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
2794 &(mac->mask[ETHER_ADDR_LEN])); /* src */
2799 add_mactype(ipfw_insn *cmd, char *av, int cblen)
2802 errx(EX_DATAERR, "missing MAC type");
2803 if (strcmp(av, "any") != 0) { /* we have a non-null type */
2804 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
2806 cmd->opcode = O_MAC_TYPE;
2813 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
2815 struct protoent *pe;
2819 proto = strtol(av, &ep, 10);
2820 if (*ep != '\0' || proto <= 0) {
2821 if ((pe = getprotobyname(av)) == NULL)
2823 proto = pe->p_proto;
2826 fill_cmd(cmd, O_PROTO, 0, proto);
2832 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
2834 u_char proto = IPPROTO_IP;
2836 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2837 ; /* do not set O_IP4 nor O_IP6 */
2838 else if (strcmp(av, "ip4") == 0)
2839 /* explicit "just IPv4" rule */
2840 fill_cmd(cmd, O_IP4, 0, 0);
2841 else if (strcmp(av, "ip6") == 0) {
2842 /* explicit "just IPv6" rule */
2843 proto = IPPROTO_IPV6;
2844 fill_cmd(cmd, O_IP6, 0, 0);
2846 return add_proto0(cmd, av, protop);
2853 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
2855 u_char proto = IPPROTO_IP;
2857 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
2858 ; /* do not set O_IP4 nor O_IP6 */
2859 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
2860 /* explicit "just IPv4" rule */
2861 fill_cmd(cmd, O_IP4, 0, 0);
2862 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
2863 /* explicit "just IPv6" rule */
2864 proto = IPPROTO_IPV6;
2865 fill_cmd(cmd, O_IP6, 0, 0);
2867 return add_proto0(cmd, av, protop);
2874 add_srcip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
2876 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
2877 if (cmd->opcode == O_IP_DST_SET) /* set */
2878 cmd->opcode = O_IP_SRC_SET;
2879 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
2880 cmd->opcode = O_IP_SRC_LOOKUP;
2881 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2882 cmd->opcode = O_IP_SRC_ME;
2883 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2884 cmd->opcode = O_IP_SRC;
2885 else /* addr/mask */
2886 cmd->opcode = O_IP_SRC_MASK;
2891 add_dstip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
2893 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
2894 if (cmd->opcode == O_IP_DST_SET) /* set */
2896 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
2898 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2899 cmd->opcode = O_IP_DST_ME;
2900 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2901 cmd->opcode = O_IP_DST;
2902 else /* addr/mask */
2903 cmd->opcode = O_IP_DST_MASK;
2907 static struct _s_x f_reserved_keywords[] = {
2910 { "diverted", TOK_OR },
2911 { "dst-port", TOK_OR },
2912 { "src-port", TOK_OR },
2913 { "established", TOK_OR },
2914 { "keep-state", TOK_OR },
2916 { "icmptypes", TOK_OR },
2924 { NULL, 0 } /* terminator */
2928 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
2931 if (match_token(f_reserved_keywords, av) != -1)
2934 if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
2935 /* XXX todo: check that we have a protocol with ports */
2936 cmd->opcode = opcode;
2943 add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
2946 char *host, *ch, buf[INET6_ADDRSTRLEN];
2947 ipfw_insn *ret = NULL;
2950 /* Copy first address in set if needed */
2951 if ((ch = strpbrk(av, "/,")) != NULL) {
2953 strlcpy(buf, av, sizeof(buf));
2954 if (len < sizeof(buf))
2960 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
2961 inet_pton(AF_INET6, host, &a) == 1)
2962 ret = add_srcip6(cmd, av, cblen);
2963 /* XXX: should check for IPv4, not !IPv6 */
2964 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2965 inet_pton(AF_INET6, host, &a) != 1))
2966 ret = add_srcip(cmd, av, cblen, tstate);
2967 if (ret == NULL && strcmp(av, "any") != 0)
2974 add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
2977 char *host, *ch, buf[INET6_ADDRSTRLEN];
2978 ipfw_insn *ret = NULL;
2981 /* Copy first address in set if needed */
2982 if ((ch = strpbrk(av, "/,")) != NULL) {
2984 strlcpy(buf, av, sizeof(buf));
2985 if (len < sizeof(buf))
2991 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
2992 inet_pton(AF_INET6, host, &a) == 1)
2993 ret = add_dstip6(cmd, av, cblen);
2994 /* XXX: should check for IPv4, not !IPv6 */
2995 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
2996 inet_pton(AF_INET6, host, &a) != 1))
2997 ret = add_dstip(cmd, av, cblen, tstate);
2998 if (ret == NULL && strcmp(av, "any") != 0)
3005 * Parse arguments and assemble the microinstructions which make up a rule.
3006 * Rules are added into the 'rulebuf' and then copied in the correct order
3007 * into the actual rule.
3009 * The syntax for a rule starts with the action, followed by
3010 * optional action parameters, and the various match patterns.
3011 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
3012 * (generated if the rule includes a keep-state option), then the
3013 * various match patterns, log/altq actions, and the actual action.
3017 ipfw_add(char *av[])
3020 * rules are added into the 'rulebuf' and then copied in
3021 * the correct order into the actual rule.
3022 * Some things that need to go out of order (prob, action etc.)
3025 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255];
3026 void *tstate = NULL;
3027 int rblen, ablen, cblen;
3029 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
3030 ipfw_insn *first_cmd; /* first match pattern */
3032 struct ip_fw_rule *rule;
3035 * various flags used to record that we entered some fields.
3037 ipfw_insn *have_state = NULL; /* check-state or keep-state */
3038 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
3043 int open_par = 0; /* open parenthesis ( */
3045 /* proto is here because it is used to fetch ports */
3046 u_char proto = IPPROTO_IP; /* default protocol */
3048 double match_prob = 1; /* match probability, default is always match */
3050 bzero(actbuf, sizeof(actbuf)); /* actions go here */
3051 bzero(cmdbuf, sizeof(cmdbuf));
3052 bzero(rulebuf, sizeof(rulebuf));
3054 rule = (struct ip_fw *)rulebuf;
3055 cmd = (ipfw_insn *)cmdbuf;
3056 action = (ipfw_insn *)actbuf;
3058 rblen = sizeof(rulebuf) / sizeof(rulebuf[0]);
3059 rblen -= offsetof(struct ip_fw, cmd) / sizeof(rulebuf[0]);
3060 ablen = sizeof(actbuf) / sizeof(actbuf[0]);
3061 cblen = sizeof(cmdbuf) / sizeof(cmdbuf[0]);
3062 cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
3064 #define CHECK_RBUFLEN(len) { CHECK_LENGTH(rblen, len); rblen -= len; }
3065 #define CHECK_ACTLEN CHECK_LENGTH(ablen, action->len)
3069 /* [rule N] -- Rule number optional */
3070 if (av[0] && isdigit(**av)) {
3071 rule->rulenum = atoi(*av);
3075 /* [set N] -- set number (0..RESVD_SET), optional */
3076 if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
3077 int set = strtoul(av[1], NULL, 10);
3078 if (set < 0 || set > RESVD_SET)
3079 errx(EX_DATAERR, "illegal set %s", av[1]);
3084 /* [prob D] -- match probability, optional */
3085 if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
3086 match_prob = strtod(av[1], NULL);
3088 if (match_prob <= 0 || match_prob > 1)
3089 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
3093 /* action -- mandatory */
3094 NEED1("missing action");
3095 i = match_token(rule_actions, *av);
3097 action->len = 1; /* default */
3100 case TOK_CHECKSTATE:
3101 have_state = action;
3102 action->opcode = O_CHECK_STATE;
3106 action->opcode = O_ACCEPT;
3110 action->opcode = O_DENY;
3115 action->opcode = O_REJECT;
3116 action->arg1 = ICMP_UNREACH_HOST;
3120 action->opcode = O_REJECT;
3121 action->arg1 = ICMP_REJECT_RST;
3125 action->opcode = O_UNREACH6;
3126 action->arg1 = ICMP6_UNREACH_RST;
3130 action->opcode = O_REJECT;
3131 NEED1("missing reject code");
3132 fill_reject_code(&action->arg1, *av);
3137 action->opcode = O_UNREACH6;
3138 NEED1("missing unreach code");
3139 fill_unreach6_code(&action->arg1, *av);
3144 action->opcode = O_COUNT;
3148 action->opcode = O_NAT;
3149 action->len = F_INSN_SIZE(ipfw_insn_nat);
3151 if (_substrcmp(*av, "global") == 0) {
3159 action->opcode = O_QUEUE;
3162 action->opcode = O_PIPE;
3165 action->opcode = O_SKIPTO;
3168 action->opcode = O_NETGRAPH;
3171 action->opcode = O_NGTEE;
3174 action->opcode = O_DIVERT;
3177 action->opcode = O_TEE;
3180 action->opcode = O_CALLRETURN;
3183 errx(EX_USAGE, "missing argument for %s", *(av - 1));
3184 if (isdigit(**av)) {
3185 action->arg1 = strtoul(*av, NULL, 10);
3186 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TARG)
3187 errx(EX_DATAERR, "illegal argument for %s",
3189 } else if (_substrcmp(*av, "tablearg") == 0) {
3190 action->arg1 = IP_FW_TARG;
3191 } else if (i == TOK_DIVERT || i == TOK_TEE) {
3194 s = getservbyname(av[0], "divert");
3196 action->arg1 = ntohs(s->s_port);
3198 errx(EX_DATAERR, "illegal divert/tee port");
3200 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
3206 * Locate the address-port separator (':' or ',').
3207 * Could be one of the following:
3211 * IPv6 w:x:y::z,port
3212 * The ':' can only be used with hostname and IPv4 address.
3213 * XXX-BZ Should we also support [w:x:y::z]:port?
3215 struct sockaddr_storage result;
3216 struct addrinfo *res;
3219 u_short port_number;
3221 NEED1("missing forward address[:port]");
3224 * locate the address-port separator (':' or ',')
3226 s = strchr(*av, ',');
3228 /* Distinguish between IPv4:port and IPv6 cases. */
3229 s = strchr(*av, ':');
3230 if (s && strchr(s+1, ':'))
3231 s = NULL; /* no port */
3236 /* Terminate host portion and set s to start of port. */
3238 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
3241 "illegal forwarding port ``%s''", s);
3242 port_number = (u_short)i;
3245 if (_substrcmp(*av, "tablearg") == 0) {
3247 ((struct sockaddr_in*)&result)->sin_addr.s_addr =
3251 * Resolve the host name or address to a family and a
3252 * network representation of the address.
3254 if (getaddrinfo(*av, NULL, NULL, &res))
3255 errx(EX_DATAERR, NULL);
3256 /* Just use the first host in the answer. */
3257 family = res->ai_family;
3258 memcpy(&result, res->ai_addr, res->ai_addrlen);
3262 if (family == PF_INET) {
3263 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
3265 action->opcode = O_FORWARD_IP;
3266 action->len = F_INSN_SIZE(ipfw_insn_sa);
3270 * In the kernel we assume AF_INET and use only
3271 * sin_port and sin_addr. Remember to set sin_len as
3272 * the routing code seems to use it too.
3274 p->sa.sin_len = sizeof(struct sockaddr_in);
3275 p->sa.sin_family = AF_INET;
3276 p->sa.sin_port = port_number;
3277 p->sa.sin_addr.s_addr =
3278 ((struct sockaddr_in *)&result)->sin_addr.s_addr;
3279 } else if (family == PF_INET6) {
3280 ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
3282 action->opcode = O_FORWARD_IP6;
3283 action->len = F_INSN_SIZE(ipfw_insn_sa6);
3286 p->sa.sin6_len = sizeof(struct sockaddr_in6);
3287 p->sa.sin6_family = AF_INET6;
3288 p->sa.sin6_port = port_number;
3289 p->sa.sin6_flowinfo = 0;
3290 p->sa.sin6_scope_id = 0;
3291 /* No table support for v6 yet. */
3292 bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
3293 &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
3295 errx(EX_DATAERR, "Invalid address family in forward action");
3301 /* pretend it is a 'count' rule followed by the comment */
3302 action->opcode = O_COUNT;
3303 av--; /* go back... */
3309 size_t intsize = sizeof(int);
3311 action->opcode = O_SETFIB;
3312 NEED1("missing fib number");
3313 if (_substrcmp(*av, "tablearg") == 0) {
3314 action->arg1 = IP_FW_TARG;
3316 action->arg1 = strtoul(*av, NULL, 10);
3317 if (sysctlbyname("net.fibs", &numfibs, &intsize,
3319 errx(EX_DATAERR, "fibs not suported.\n");
3320 if (action->arg1 >= numfibs) /* Temporary */
3321 errx(EX_DATAERR, "fib too large.\n");
3331 action->opcode = O_SETDSCP;
3332 NEED1("missing DSCP code");
3333 if (_substrcmp(*av, "tablearg") == 0) {
3334 action->arg1 = IP_FW_TARG;
3335 } else if (isalpha(*av[0])) {
3336 if ((code = match_token(f_ipdscp, *av)) == -1)
3337 errx(EX_DATAERR, "Unknown DSCP code");
3338 action->arg1 = code;
3340 action->arg1 = strtoul(*av, NULL, 10);
3346 action->opcode = O_REASS;
3350 fill_cmd(action, O_CALLRETURN, F_NOT, 0);
3354 errx(EX_DATAERR, "invalid action %s\n", av[-1]);
3356 action = next_cmd(action, &ablen);
3359 * [altq queuename] -- altq tag, optional
3360 * [log [logamount N]] -- log, optional
3362 * If they exist, it go first in the cmdbuf, but then it is
3363 * skipped in the copy section to the end of the buffer.
3365 while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
3370 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
3375 "log cannot be specified more than once");
3376 have_log = (ipfw_insn *)c;
3377 cmd->len = F_INSN_SIZE(ipfw_insn_log);
3379 cmd->opcode = O_LOG;
3380 if (av[0] && _substrcmp(*av, "logamount") == 0) {
3382 NEED1("logamount requires argument");
3386 "logamount must be positive");
3390 len = sizeof(c->max_log);
3391 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
3392 &c->max_log, &len, NULL, 0) == -1) {
3397 errx(1, "sysctlbyname(\"%s\")",
3398 "net.inet.ip.fw.verbose_limit");
3407 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
3409 NEED1("missing altq queue name");
3412 "altq cannot be specified more than once");
3413 have_altq = (ipfw_insn *)a;
3414 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
3416 cmd->opcode = O_ALTQ;
3417 a->qid = altq_name_to_qid(*av);
3428 errx(EX_USAGE, "tag and untag cannot be "
3429 "specified more than once");
3430 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
3431 rule_action_params);
3433 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
3441 cmd = next_cmd(cmd, &cblen);
3444 if (have_state) /* must be a check-state, we are done */
3447 #define OR_START(target) \
3448 if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
3450 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
3453 if ( (av[0])[1] == '\0') { \
3464 strcmp(*av, ")") == 0 || \
3465 strcmp(*av, "}") == 0)) { \
3470 errx(EX_USAGE, "missing \")\"\n"); \
3474 if (av[0] && _substrcmp(*av, "not") == 0) { \
3475 if (cmd->len & F_NOT) \
3476 errx(EX_USAGE, "double \"not\" not allowed\n"); \
3477 cmd->len |= F_NOT; \
3481 #define OR_BLOCK(target) \
3482 if (av[0] && _substrcmp(*av, "or") == 0) { \
3483 if (prev == NULL || open_par == 0) \
3484 errx(EX_DATAERR, "invalid OR block"); \
3485 prev->len |= F_OR; \
3495 * MAC addresses, optional.
3496 * If we have this, we skip the part "proto from src to dst"
3497 * and jump straight to the option parsing.
3500 NEED1("missing protocol");
3501 if (_substrcmp(*av, "MAC") == 0 ||
3502 _substrcmp(*av, "mac") == 0) {
3503 av++; /* the "MAC" keyword */
3504 add_mac(cmd, av); /* exits in case of errors */
3505 cmd = next_cmd(cmd);
3506 av += 2; /* dst-mac and src-mac */
3508 NEED1("missing mac type");
3509 if (add_mactype(cmd, av[0]))
3510 cmd = next_cmd(cmd);
3511 av++; /* any or mac-type */
3517 * protocol, mandatory
3519 OR_START(get_proto);
3521 NEED1("missing protocol");
3522 if (add_proto_compat(cmd, *av, &proto)) {
3524 if (F_LEN(cmd) != 0) {
3526 cmd = next_cmd(cmd, &cblen);
3528 } else if (first_cmd != cmd) {
3529 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
3532 OR_BLOCK(get_proto);
3537 if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
3538 errx(EX_USAGE, "missing ``from''");
3542 * source IP, mandatory
3544 OR_START(source_ip);
3545 NOT_BLOCK; /* optional "not" */
3546 NEED1("missing source address");
3547 if (add_src(cmd, *av, proto, cblen, tstate)) {
3549 if (F_LEN(cmd) != 0) { /* ! any */
3551 cmd = next_cmd(cmd, &cblen);
3554 errx(EX_USAGE, "bad source address %s", *av);
3555 OR_BLOCK(source_ip);
3558 * source ports, optional
3560 NOT_BLOCK; /* optional "not" */
3561 if ( av[0] != NULL ) {
3562 if (_substrcmp(*av, "any") == 0 ||
3563 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
3565 if (F_LEN(cmd) != 0)
3566 cmd = next_cmd(cmd, &cblen);
3573 if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
3574 errx(EX_USAGE, "missing ``to''");
3578 * destination, mandatory
3581 NOT_BLOCK; /* optional "not" */
3582 NEED1("missing dst address");
3583 if (add_dst(cmd, *av, proto, cblen, tstate)) {
3585 if (F_LEN(cmd) != 0) { /* ! any */
3587 cmd = next_cmd(cmd, &cblen);
3590 errx( EX_USAGE, "bad destination address %s", *av);
3594 * dest. ports, optional
3596 NOT_BLOCK; /* optional "not" */
3598 if (_substrcmp(*av, "any") == 0 ||
3599 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
3601 if (F_LEN(cmd) != 0)
3602 cmd = next_cmd(cmd, &cblen);
3607 if (av[0] && first_cmd == cmd) {
3609 * nothing specified so far, store in the rule to ease
3615 while ( av[0] != NULL ) {
3617 ipfw_insn_u32 *cmd32; /* alias for cmd */
3620 cmd32 = (ipfw_insn_u32 *)cmd;
3622 if (*s == '!') { /* alternate syntax for NOT */
3623 if (cmd->len & F_NOT)
3624 errx(EX_USAGE, "double \"not\" not allowed\n");
3628 i = match_token(rule_options, s);
3632 if (cmd->len & F_NOT)
3633 errx(EX_USAGE, "double \"not\" not allowed\n");
3638 if (open_par == 0 || prev == NULL)
3639 errx(EX_USAGE, "invalid \"or\" block\n");
3643 case TOK_STARTBRACE:
3645 errx(EX_USAGE, "+nested \"(\" not allowed\n");
3651 errx(EX_USAGE, "+missing \")\"\n");
3657 fill_cmd(cmd, O_IN, 0, 0);
3661 cmd->len ^= F_NOT; /* toggle F_NOT */
3662 fill_cmd(cmd, O_IN, 0, 0);
3666 fill_cmd(cmd, O_DIVERTED, 0, 3);
3669 case TOK_DIVERTEDLOOPBACK:
3670 fill_cmd(cmd, O_DIVERTED, 0, 1);
3673 case TOK_DIVERTEDOUTPUT:
3674 fill_cmd(cmd, O_DIVERTED, 0, 2);
3678 fill_cmd(cmd, O_FRAG, 0, 0);
3682 fill_cmd(cmd, O_LAYER2, 0, 0);
3688 NEED1("recv, xmit, via require interface name"
3690 fill_iface((ipfw_insn_if *)cmd, av[0], cblen, tstate);
3692 if (F_LEN(cmd) == 0) /* not a valid address */
3695 cmd->opcode = O_XMIT;
3696 else if (i == TOK_RECV)
3697 cmd->opcode = O_RECV;
3698 else if (i == TOK_VIA)
3699 cmd->opcode = O_VIA;
3703 NEED1("icmptypes requires list of types");
3704 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
3708 case TOK_ICMP6TYPES:
3709 NEED1("icmptypes requires list of types");
3710 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
3715 NEED1("ipttl requires TTL");
3716 if (strpbrk(*av, "-,")) {
3717 if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
3718 errx(EX_DATAERR, "invalid ipttl %s", *av);
3720 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
3725 NEED1("ipid requires id");
3726 if (strpbrk(*av, "-,")) {
3727 if (!add_ports(cmd, *av, 0, O_IPID, cblen))
3728 errx(EX_DATAERR, "invalid ipid %s", *av);
3730 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
3735 NEED1("iplen requires length");
3736 if (strpbrk(*av, "-,")) {
3737 if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
3738 errx(EX_DATAERR, "invalid ip len %s", *av);
3740 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
3745 NEED1("ipver requires version");
3746 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
3750 case TOK_IPPRECEDENCE:
3751 NEED1("ipprecedence requires value");
3752 fill_cmd(cmd, O_IPPRECEDENCE, 0,
3753 (strtoul(*av, NULL, 0) & 7) << 5);
3758 NEED1("missing DSCP code");
3759 fill_dscp(cmd, *av, cblen);
3764 NEED1("missing argument for ipoptions");
3765 fill_flags_cmd(cmd, O_IPOPT, f_ipopts, *av);
3770 NEED1("missing argument for iptos");
3771 fill_flags_cmd(cmd, O_IPTOS, f_iptos, *av);
3776 NEED1("uid requires argument");
3782 cmd->opcode = O_UID;
3783 uid = strtoul(*av, &end, 0);
3784 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
3786 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
3787 cmd32->d[0] = pwd->pw_uid;
3788 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3794 NEED1("gid requires argument");
3800 cmd->opcode = O_GID;
3801 gid = strtoul(*av, &end, 0);
3802 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
3804 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
3805 cmd32->d[0] = grp->gr_gid;
3806 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3812 NEED1("jail requires argument");
3817 cmd->opcode = O_JAIL;
3818 jid = (int)strtol(*av, &end, 0);
3819 if (jid < 0 || *end != '\0')
3820 errx(EX_DATAERR, "jail requires prison ID");
3821 cmd32->d[0] = (uint32_t)jid;
3822 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
3828 fill_cmd(cmd, O_ESTAB, 0, 0);
3832 fill_cmd(cmd, O_TCPFLAGS, 0,
3833 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
3836 case TOK_TCPDATALEN:
3837 NEED1("tcpdatalen requires length");
3838 if (strpbrk(*av, "-,")) {
3839 if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
3840 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
3842 fill_cmd(cmd, O_TCPDATALEN, 0,
3843 strtoul(*av, NULL, 0));
3848 NEED1("missing argument for tcpoptions");
3849 fill_flags_cmd(cmd, O_TCPOPTS, f_tcpopts, *av);
3855 NEED1("tcpseq/tcpack requires argument");
3856 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3857 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
3858 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
3863 NEED1("tcpwin requires length");
3864 if (strpbrk(*av, "-,")) {
3865 if (!add_ports(cmd, *av, 0, O_TCPWIN, cblen))
3866 errx(EX_DATAERR, "invalid tcpwin len %s", *av);
3868 fill_cmd(cmd, O_TCPWIN, 0,
3869 strtoul(*av, NULL, 0));
3874 NEED1("missing argument for tcpflags");
3875 cmd->opcode = O_TCPFLAGS;
3876 fill_flags_cmd(cmd, O_TCPFLAGS, f_tcpflags, *av);
3882 errx(EX_USAGE, "keep-state cannot be part "
3885 errx(EX_USAGE, "only one of keep-state "
3886 "and limit is allowed");
3888 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
3892 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
3897 "limit cannot be part of an or block");
3899 errx(EX_USAGE, "only one of keep-state and "
3900 "limit is allowed");
3903 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
3905 cmd->opcode = O_LIMIT;
3906 c->limit_mask = c->conn_limit = 0;
3908 while ( av[0] != NULL ) {
3909 if ((val = match_token(limit_masks, *av)) <= 0)
3911 c->limit_mask |= val;
3915 if (c->limit_mask == 0)
3916 errx(EX_USAGE, "limit: missing limit mask");
3918 GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
3919 TOK_LIMIT, rule_options);
3926 NEED1("missing protocol");
3927 if (add_proto(cmd, *av, &proto)) {
3930 errx(EX_DATAERR, "invalid protocol ``%s''",
3935 NEED1("missing source IP");
3936 if (add_srcip(cmd, *av, cblen, tstate)) {
3942 NEED1("missing destination IP");
3943 if (add_dstip(cmd, *av, cblen, tstate)) {
3949 NEED1("missing source IP6");
3950 if (add_srcip6(cmd, *av, cblen)) {
3956 NEED1("missing destination IP6");
3957 if (add_dstip6(cmd, *av, cblen)) {
3963 NEED1("missing source port");
3964 if (_substrcmp(*av, "any") == 0 ||
3965 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
3968 errx(EX_DATAERR, "invalid source port %s", *av);
3972 NEED1("missing destination port");
3973 if (_substrcmp(*av, "any") == 0 ||
3974 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
3977 errx(EX_DATAERR, "invalid destination port %s",
3982 if (add_mac(cmd, av, cblen))
3987 NEED1("missing mac type");
3988 if (!add_mactype(cmd, *av, cblen))
3989 errx(EX_DATAERR, "invalid mac type %s", *av);
3993 case TOK_VERREVPATH:
3994 fill_cmd(cmd, O_VERREVPATH, 0, 0);
3997 case TOK_VERSRCREACH:
3998 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
4002 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
4006 fill_cmd(cmd, O_IPSEC, 0, 0);
4010 fill_cmd(cmd, O_IP6, 0, 0);
4014 fill_cmd(cmd, O_IP4, 0, 0);
4018 fill_ext6hdr( cmd, *av );
4023 if (proto != IPPROTO_IPV6 )
4024 errx( EX_USAGE, "flow-id filter is active "
4025 "only for ipv6 protocol\n");
4026 fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
4031 fill_comment(cmd, av, cblen);
4036 if (av[0] && strpbrk(*av, "-,")) {
4037 if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
4038 errx(EX_DATAERR, "tagged: invalid tag"
4044 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
4045 TOK_TAGGED, rule_options);
4046 fill_cmd(cmd, O_TAGGED, 0, tag);
4052 NEED1("fib requires fib number");
4053 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
4057 fill_cmd(cmd, O_SOCKARG, 0, 0);
4061 ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
4065 if (!av[0] || !av[1])
4066 errx(EX_USAGE, "format: lookup argument tablenum");
4067 cmd->opcode = O_IP_DST_LOOKUP;
4068 cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
4069 i = match_token(rule_options, *av);
4070 for (j = 0; lookup_key[j] >= 0 ; j++) {
4071 if (i == lookup_key[j])
4074 if (lookup_key[j] <= 0)
4075 errx(EX_USAGE, "format: cannot lookup on %s", *av);
4076 __PAST_END(c->d, 1) = j; // i converted to option
4078 cmd->arg1 = strtoul(*av, &p, 0);
4080 errx(EX_USAGE, "format: lookup argument tablenum");
4086 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
4088 if (F_LEN(cmd) > 0) { /* prepare to advance */
4090 cmd = next_cmd(cmd, &cblen);
4096 * Now copy stuff into the rule.
4097 * If we have a keep-state option, the first instruction
4098 * must be a PROBE_STATE (which is generated here).
4099 * If we have a LOG option, it was stored as the first command,
4100 * and now must be moved to the top of the action part.
4102 dst = (ipfw_insn *)rule->cmd;
4105 * First thing to write into the command stream is the match probability.
4107 if (match_prob != 1) { /* 1 means always match */
4108 dst->opcode = O_PROB;
4110 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
4115 * generate O_PROBE_STATE if necessary
4117 if (have_state && have_state->opcode != O_CHECK_STATE) {
4118 fill_cmd(dst, O_PROBE_STATE, 0, 0);
4119 dst = next_cmd(dst, &rblen);
4122 /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
4123 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
4127 switch (src->opcode) {
4135 bcopy(src, dst, i * sizeof(uint32_t));
4141 * put back the have_state command as last opcode
4143 if (have_state && have_state->opcode != O_CHECK_STATE) {
4144 i = F_LEN(have_state);
4146 bcopy(have_state, dst, i * sizeof(uint32_t));
4150 * start action section
4152 rule->act_ofs = dst - rule->cmd;
4154 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
4156 i = F_LEN(have_log);
4158 bcopy(have_log, dst, i * sizeof(uint32_t));
4162 i = F_LEN(have_altq);
4164 bcopy(have_altq, dst, i * sizeof(uint32_t));
4168 i = F_LEN(have_tag);
4170 bcopy(have_tag, dst, i * sizeof(uint32_t));
4175 * copy all other actions
4177 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
4180 bcopy(src, dst, i * sizeof(uint32_t));
4184 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
4185 i = (char *)dst - (char *)rule;
4186 if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1)
4187 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
4189 struct format_opts sfo;
4191 memset(&sfo, 0, sizeof(sfo));
4192 sfo.set_mask = (uint32_t)(-1);
4193 bp_alloc(&bp, 4096);
4194 show_static_rule(&co, &sfo, &bp, rule, rule);
4195 printf("%s", bp.buf);
4201 * clear the counters or the log counters.
4202 * optname has the following values:
4203 * 0 (zero both counters and logging)
4204 * 1 (zero logging only)
4207 ipfw_zero(int ac, char *av[], int optname)
4209 uint32_t arg, saved_arg;
4212 char const *name = optname ? "RESETLOG" : "ZERO";
4214 optname = optname ? IP_FW_RESETLOG : IP_FW_ZERO;
4219 /* clear all entries */
4220 if (do_cmd(optname, NULL, 0) < 0)
4221 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name);
4223 printf("%s.\n", optname == IP_FW_ZERO ?
4224 "Accounting cleared":"Logging counts reset");
4231 if (isdigit(**av)) {
4232 arg = strtonum(*av, 0, 0xffff, &errstr);
4235 "invalid rule number %s\n", *av);
4238 arg |= (1 << 24) | ((co.use_set - 1) << 16);
4241 if (do_cmd(optname, &arg, sizeof(arg))) {
4242 warn("rule %u: setsockopt(IP_FW_%s)",
4244 failed = EX_UNAVAILABLE;
4245 } else if (!co.do_quiet)
4246 printf("Entry %d %s.\n", saved_arg,
4247 optname == IP_FW_ZERO ?
4248 "cleared" : "logging count reset");
4250 errx(EX_USAGE, "invalid rule number ``%s''", *av);
4253 if (failed != EX_OK)
4258 ipfw_flush(int force)
4260 int cmd = co.do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
4262 if (!force && !co.do_quiet) { /* need to ask user */
4265 printf("Are you sure? [yn] ");
4268 c = toupper(getc(stdin));
4269 while (c != '\n' && getc(stdin) != '\n')
4271 return; /* and do not flush */
4272 } while (c != 'Y' && c != 'N');
4274 if (c == 'N') /* user said no */
4281 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
4283 uint32_t arg = ((co.use_set - 1) & 0xffff) | (1 << 24);
4284 if (do_cmd(IP_FW_DEL, &arg, sizeof(arg)) < 0)
4285 err(EX_UNAVAILABLE, "setsockopt(IP_FW_DEL)");
4286 } else if (do_cmd(cmd, NULL, 0) < 0)
4287 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
4288 co.do_pipe ? "DUMMYNET" : "FW");
4290 printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
4294 static void table_list(uint16_t num, int need_header);
4295 static void table_fill_xentry(char *arg, ipfw_table_xentry *xent);
4298 * Retrieve maximum number of tables supported by ipfw(4) module.
4301 ipfw_get_tables_max()
4304 uint32_t tables_max;
4306 if (ipfw_tables_max != 0)
4307 return (ipfw_tables_max);
4309 len = sizeof(tables_max);
4310 if (sysctlbyname("net.inet.ip.fw.tables_max", &tables_max, &len,
4313 tables_max = 128; /* Old conservative default */
4315 errx(1, "Can't determine maximum number of ipfw tables."
4316 " Perhaps you forgot to load ipfw module?");
4319 ipfw_tables_max = tables_max;
4321 return (ipfw_tables_max);
4325 * This one handles all table-related commands
4326 * ipfw table N add addr[/masklen] [value]
4327 * ipfw table N delete addr[/masklen]
4328 * ipfw table {N | all} flush
4329 * ipfw table {N | all} list
4332 ipfw_table_handler(int ac, char *av[])
4334 ipfw_table_xentry xent;
4338 uint32_t tables_max;
4340 tables_max = ipfw_get_tables_max();
4342 memset(&xent, 0, sizeof(xent));
4345 if (ac && isdigit(**av)) {
4346 xent.tbl = atoi(*av);
4349 } else if (ac && _substrcmp(*av, "all") == 0) {
4354 errx(EX_USAGE, "table number or 'all' keyword required");
4355 if (xent.tbl >= tables_max)
4356 errx(EX_USAGE, "The table number exceeds the maximum allowed "
4357 "value (%d)", tables_max - 1);
4358 NEED1("table needs command");
4359 if (is_all && _substrcmp(*av, "list") != 0
4360 && _substrcmp(*av, "flush") != 0)
4361 errx(EX_USAGE, "table number required");
4363 if (_substrcmp(*av, "add") == 0 ||
4364 _substrcmp(*av, "delete") == 0) {
4365 do_add = **av == 'a';
4368 errx(EX_USAGE, "address required");
4370 table_fill_xentry(*av, &xent);
4375 /* isdigit is a bit of a hack here.. */
4376 if (strchr(*av, (int)'.') == NULL && isdigit(**av)) {
4377 xent.value = strtoul(*av, NULL, 0);
4379 if (lookup_host(*av, (struct in_addr *)&tval) == 0) {
4380 /* The value must be stored in host order *
4381 * so that the values < 65k can be distinguished */
4382 xent.value = ntohl(tval);
4384 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
4389 if (do_setcmd3(do_add ? IP_FW_TABLE_XADD : IP_FW_TABLE_XDEL,
4390 &xent, xent.len) < 0) {
4391 /* If running silent, don't bomb out on these errors. */
4392 if (!(co.do_quiet && (errno == (do_add ? EEXIST : ESRCH))))
4393 err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)",
4394 do_add ? "XADD" : "XDEL");
4395 /* In silent mode, react to a failed add by deleting */
4397 do_setcmd3(IP_FW_TABLE_XDEL, &xent, xent.len);
4398 if (do_setcmd3(IP_FW_TABLE_XADD, &xent, xent.len) < 0)
4400 "setsockopt(IP_FW_TABLE_XADD)");
4403 } else if (_substrcmp(*av, "flush") == 0) {
4404 a = is_all ? tables_max : (uint32_t)(xent.tbl + 1);
4406 if (do_cmd(IP_FW_TABLE_FLUSH, &xent.tbl,
4407 sizeof(xent.tbl)) < 0)
4408 err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)");
4409 } while (++xent.tbl < a);
4410 } else if (_substrcmp(*av, "list") == 0) {
4411 a = is_all ? tables_max : (uint32_t)(xent.tbl + 1);
4413 table_list(xent.tbl, is_all);
4414 } while (++xent.tbl < a);
4416 errx(EX_USAGE, "invalid table command %s", *av);
4420 table_fill_xentry(char *arg, ipfw_table_xentry *xent)
4422 int addrlen, mask, masklen, type;
4423 struct in6_addr *paddr;
4434 * Let's try to guess type by agrument.
4439 * 4) port, uid/gid or other u32 key (base 10 format)
4442 paddr = &xent->k.addr6;
4443 if (ishexnumber(*arg) != 0 || *arg == ':') {
4444 /* Remove / if exists */
4445 if ((p = strchr(arg, '/')) != NULL) {
4450 if (inet_pton(AF_INET, arg, paddr) == 1) {
4451 if (p != NULL && mask > 32)
4452 errx(EX_DATAERR, "bad IPv4 mask width: %s",
4455 type = IPFW_TABLE_CIDR;
4456 masklen = p ? mask : 32;
4457 addrlen = sizeof(struct in_addr);
4458 } else if (inet_pton(AF_INET6, arg, paddr) == 1) {
4459 if (IN6_IS_ADDR_V4COMPAT(paddr))
4461 "Use IPv4 instead of v4-compatible");
4462 if (p != NULL && mask > 128)
4463 errx(EX_DATAERR, "bad IPv6 mask width: %s",
4466 type = IPFW_TABLE_CIDR;
4467 masklen = p ? mask : 128;
4468 addrlen = sizeof(struct in6_addr);
4470 /* Port or any other key */
4471 /* Skip non-base 10 entries like 'fa1' */
4472 key = strtol(arg, &p, 10);
4474 pkey = (uint32_t *)paddr;
4476 type = IPFW_TABLE_CIDR;
4478 addrlen = sizeof(uint32_t);
4479 } else if ((p != arg) && (*p == '.')) {
4481 * Warn on IPv4 address strings
4482 * which are "valid" for inet_aton() but not
4485 * Typical examples: '10.5' or '10.0.0.05'
4488 "Invalid IPv4 address: %s", arg);
4493 if (type == 0 && strchr(arg, '.') == NULL) {
4494 /* Assume interface name. Copy significant data only */
4495 mask = MIN(strlen(arg), IF_NAMESIZE - 1);
4496 memcpy(xent->k.iface, arg, mask);
4497 /* Set mask to exact match */
4498 masklen = 8 * IF_NAMESIZE;
4499 type = IPFW_TABLE_INTERFACE;
4500 addrlen = IF_NAMESIZE;
4504 if (lookup_host(arg, (struct in_addr *)paddr) != 0)
4505 errx(EX_NOHOST, "hostname ``%s'' unknown", arg);
4508 type = IPFW_TABLE_CIDR;
4509 addrlen = sizeof(struct in_addr);
4513 xent->masklen = masklen;
4514 xent->len = offsetof(ipfw_table_xentry, k) + addrlen;
4518 table_list(uint16_t num, int need_header)
4521 ipfw_table_xentry *xent;
4523 uint32_t *a, sz, tval;
4525 struct in6_addr *addr6;
4526 ip_fw3_opheader *op3;
4528 /* Prepend value with IP_FW3 header */
4529 l = sizeof(ip_fw3_opheader) + sizeof(uint32_t);
4531 /* Zero reserved fields */
4532 memset(op3, 0, sizeof(ip_fw3_opheader));
4533 a = (uint32_t *)(op3 + 1);
4535 op3->opcode = IP_FW_TABLE_XGETSIZE;
4536 if (do_cmd(IP_FW3, op3, (uintptr_t)&l) < 0)
4537 err(EX_OSERR, "getsockopt(IP_FW_TABLE_XGETSIZE)");
4539 /* If a is zero we have nothing to do, the table is empty. */
4544 tbl = safe_calloc(1, l);
4545 tbl->opheader.opcode = IP_FW_TABLE_XLIST;
4547 if (do_cmd(IP_FW3, tbl, (uintptr_t)&l) < 0)
4548 err(EX_OSERR, "getsockopt(IP_FW_TABLE_XLIST)");
4549 if (tbl->cnt && need_header)
4550 printf("---table(%d)---\n", tbl->tbl);
4551 sz = tbl->size - sizeof(ipfw_xtable);
4552 xent = &tbl->xent[0];
4554 switch (tbl->type) {
4555 case IPFW_TABLE_CIDR:
4556 /* IPv4 or IPv6 prefixes */
4558 addr6 = &xent->k.addr6;
4561 if ((xent->flags & IPFW_TCF_INET) != 0) {
4563 inet_ntop(AF_INET, &addr6->s6_addr32[3], tbuf, sizeof(tbuf));
4566 inet_ntop(AF_INET6, addr6, tbuf, sizeof(tbuf));
4569 if (co.do_value_as_ip) {
4571 printf("%s/%u %s\n", tbuf, xent->masklen,
4572 inet_ntoa(*(struct in_addr *)&tval));
4574 printf("%s/%u %u\n", tbuf, xent->masklen, tval);
4576 case IPFW_TABLE_INTERFACE:
4577 /* Interface names */
4579 if (co.do_value_as_ip) {
4581 printf("%s %s\n", xent->k.iface,
4582 inet_ntoa(*(struct in_addr *)&tval));
4584 printf("%s %u\n", xent->k.iface, tval);
4590 xent = (ipfw_table_xentry *)((char *)xent + xent->len);