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>
43 #include <time.h> /* ctime */
44 #include <timeconv.h> /* _long_to_time */
47 #include <stddef.h> /* offsetof */
49 #include <net/ethernet.h>
50 #include <net/if.h> /* only IFNAMSIZ */
51 #include <netinet/in.h>
52 #include <netinet/in_systm.h> /* only n_short, n_long */
53 #include <netinet/ip.h>
54 #include <netinet/ip_icmp.h>
55 #include <netinet/ip_fw.h>
56 #include <netinet/tcp.h>
57 #include <arpa/inet.h>
59 struct cmdline_opts co; /* global options */
65 int show_time; /* show timestamp */
66 uint32_t set_mask; /* enabled sets mask */
67 uint32_t flags; /* request flags */
68 uint32_t first; /* first rule to request */
69 uint32_t last; /* last rule to request */
70 uint32_t dcnt; /* number of dynamic states */
71 ipfw_obj_ctlv *tstate; /* table state data */
74 int resvd_set_number = RESVD_SET;
78 #define CHECK_LENGTH(v, len) do { \
80 errx(EX_DATAERR, "Rule too long"); \
83 * Check if we have enough space in cmd buffer. Note that since
84 * first 8? u32 words are reserved by reserved header, full cmd
85 * buffer can't be used, so we need to protect from buffer overrun
86 * only. At the beginning, cblen is less than actual buffer size by
87 * size of ipfw_insn_u32 instruction + 1 u32 work. This eliminates need
88 * for checking small instructions fitting in given range.
89 * We also (ab)use the fact that ipfw_insn is always the first field
90 * for any custom instruction.
92 #define CHECK_CMDLEN CHECK_LENGTH(cblen, F_LEN((ipfw_insn *)cmd))
94 #define GET_UINT_ARG(arg, min, max, tok, s_x) do { \
96 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
97 if (_substrcmp(*av, "tablearg") == 0) { \
106 _xval = strtol(*av, &end, 10); \
108 if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
109 errx(EX_DATAERR, "%s: invalid argument: %s", \
110 match_value(s_x, tok), *av); \
112 if (errno == ERANGE || _xval < min || _xval > max) \
113 errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
114 match_value(s_x, tok), min, max, *av); \
116 if (_xval == IP_FW_TARG) \
117 errx(EX_DATAERR, "%s: illegal argument value: %s", \
118 match_value(s_x, tok), *av); \
123 static struct _s_x f_tcpflags[] = {
134 static struct _s_x f_tcpopts[] = {
135 { "mss", IP_FW_TCPOPT_MSS },
136 { "maxseg", IP_FW_TCPOPT_MSS },
137 { "window", IP_FW_TCPOPT_WINDOW },
138 { "sack", IP_FW_TCPOPT_SACK },
139 { "ts", IP_FW_TCPOPT_TS },
140 { "timestamp", IP_FW_TCPOPT_TS },
141 { "cc", IP_FW_TCPOPT_CC },
147 * IP options span the range 0 to 255 so we need to remap them
148 * (though in fact only the low 5 bits are significant).
150 static struct _s_x f_ipopts[] = {
151 { "ssrr", IP_FW_IPOPT_SSRR},
152 { "lsrr", IP_FW_IPOPT_LSRR},
153 { "rr", IP_FW_IPOPT_RR},
154 { "ts", IP_FW_IPOPT_TS},
159 static struct _s_x f_iptos[] = {
160 { "lowdelay", IPTOS_LOWDELAY},
161 { "throughput", IPTOS_THROUGHPUT},
162 { "reliability", IPTOS_RELIABILITY},
163 { "mincost", IPTOS_MINCOST},
164 { "congestion", IPTOS_ECN_CE},
165 { "ecntransport", IPTOS_ECN_ECT0},
166 { "ip tos option", 0},
170 struct _s_x f_ipdscp[] = {
171 { "af11", IPTOS_DSCP_AF11 >> 2 }, /* 001010 */
172 { "af12", IPTOS_DSCP_AF12 >> 2 }, /* 001100 */
173 { "af13", IPTOS_DSCP_AF13 >> 2 }, /* 001110 */
174 { "af21", IPTOS_DSCP_AF21 >> 2 }, /* 010010 */
175 { "af22", IPTOS_DSCP_AF22 >> 2 }, /* 010100 */
176 { "af23", IPTOS_DSCP_AF23 >> 2 }, /* 010110 */
177 { "af31", IPTOS_DSCP_AF31 >> 2 }, /* 011010 */
178 { "af32", IPTOS_DSCP_AF32 >> 2 }, /* 011100 */
179 { "af33", IPTOS_DSCP_AF33 >> 2 }, /* 011110 */
180 { "af41", IPTOS_DSCP_AF41 >> 2 }, /* 100010 */
181 { "af42", IPTOS_DSCP_AF42 >> 2 }, /* 100100 */
182 { "af43", IPTOS_DSCP_AF43 >> 2 }, /* 100110 */
183 { "be", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
184 { "ef", IPTOS_DSCP_EF >> 2 }, /* 101110 */
185 { "cs0", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
186 { "cs1", IPTOS_DSCP_CS1 >> 2 }, /* 001000 */
187 { "cs2", IPTOS_DSCP_CS2 >> 2 }, /* 010000 */
188 { "cs3", IPTOS_DSCP_CS3 >> 2 }, /* 011000 */
189 { "cs4", IPTOS_DSCP_CS4 >> 2 }, /* 100000 */
190 { "cs5", IPTOS_DSCP_CS5 >> 2 }, /* 101000 */
191 { "cs6", IPTOS_DSCP_CS6 >> 2 }, /* 110000 */
192 { "cs7", IPTOS_DSCP_CS7 >> 2 }, /* 100000 */
196 static struct _s_x limit_masks[] = {
197 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
198 {"src-addr", DYN_SRC_ADDR},
199 {"src-port", DYN_SRC_PORT},
200 {"dst-addr", DYN_DST_ADDR},
201 {"dst-port", DYN_DST_PORT},
206 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
207 * This is only used in this code.
209 #define IPPROTO_ETHERTYPE 0x1000
210 static struct _s_x ether_types[] = {
212 * Note, we cannot use "-:&/" in the names because they are field
213 * separators in the type specifications. Also, we use s = NULL as
214 * end-delimiter, because a type of 0 can be legal.
227 { "pppoe_disc", 0x8863 },
228 { "pppoe_sess", 0x8864 },
229 { "ipx_8022", 0x00E0 },
230 { "ipx_8023", 0x0000 },
231 { "ipx_ii", 0x8137 },
232 { "ipx_snap", 0x8137 },
238 static struct _s_x rule_eactions[] = {
239 { "nat64lsn", TOK_NAT64LSN },
240 { "nat64stl", TOK_NAT64STL },
241 { "nptv6", TOK_NPTV6 },
242 { "tcp-setmss", TOK_TCPSETMSS },
243 { NULL, 0 } /* terminator */
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 { "eaction", TOK_EACTION },
277 { "tcp-setmss", TOK_TCPSETMSS },
278 { NULL, 0 } /* terminator */
281 static struct _s_x rule_action_params[] = {
282 { "altq", TOK_ALTQ },
285 { "untag", TOK_UNTAG },
286 { NULL, 0 } /* terminator */
290 * The 'lookup' instruction accepts one of the following arguments.
291 * -1 is a terminator for the list.
292 * Arguments are passed as v[1] in O_DST_LOOKUP options.
294 static int lookup_key[] = {
295 TOK_DSTIP, TOK_SRCIP, TOK_DSTPORT, TOK_SRCPORT,
296 TOK_UID, TOK_JAIL, TOK_DSCP, -1 };
298 static struct _s_x rule_options[] = {
299 { "tagged", TOK_TAGGED },
302 { "jail", TOK_JAIL },
304 { "limit", TOK_LIMIT },
305 { "keep-state", TOK_KEEPSTATE },
306 { "bridged", TOK_LAYER2 },
307 { "layer2", TOK_LAYER2 },
309 { "diverted", TOK_DIVERTED },
310 { "diverted-loopback", TOK_DIVERTEDLOOPBACK },
311 { "diverted-output", TOK_DIVERTEDOUTPUT },
312 { "xmit", TOK_XMIT },
313 { "recv", TOK_RECV },
315 { "fragment", TOK_FRAG },
316 { "frag", TOK_FRAG },
318 { "ipoptions", TOK_IPOPTS },
319 { "ipopts", TOK_IPOPTS },
320 { "iplen", TOK_IPLEN },
321 { "ipid", TOK_IPID },
322 { "ipprecedence", TOK_IPPRECEDENCE },
323 { "dscp", TOK_DSCP },
324 { "iptos", TOK_IPTOS },
325 { "ipttl", TOK_IPTTL },
326 { "ipversion", TOK_IPVER },
327 { "ipver", TOK_IPVER },
328 { "estab", TOK_ESTAB },
329 { "established", TOK_ESTAB },
330 { "setup", TOK_SETUP },
331 { "sockarg", TOK_SOCKARG },
332 { "tcpdatalen", TOK_TCPDATALEN },
333 { "tcpflags", TOK_TCPFLAGS },
334 { "tcpflgs", TOK_TCPFLAGS },
335 { "tcpoptions", TOK_TCPOPTS },
336 { "tcpopts", TOK_TCPOPTS },
337 { "tcpseq", TOK_TCPSEQ },
338 { "tcpack", TOK_TCPACK },
339 { "tcpwin", TOK_TCPWIN },
340 { "icmptype", TOK_ICMPTYPES },
341 { "icmptypes", TOK_ICMPTYPES },
342 { "dst-ip", TOK_DSTIP },
343 { "src-ip", TOK_SRCIP },
344 { "dst-port", TOK_DSTPORT },
345 { "src-port", TOK_SRCPORT },
346 { "proto", TOK_PROTO },
349 { "mac-type", TOK_MACTYPE },
350 { "verrevpath", TOK_VERREVPATH },
351 { "versrcreach", TOK_VERSRCREACH },
352 { "antispoof", TOK_ANTISPOOF },
353 { "ipsec", TOK_IPSEC },
354 { "icmp6type", TOK_ICMP6TYPES },
355 { "icmp6types", TOK_ICMP6TYPES },
356 { "ext6hdr", TOK_EXT6HDR},
357 { "flow-id", TOK_FLOWID},
362 { "dst-ipv6", TOK_DSTIP6},
363 { "dst-ip6", TOK_DSTIP6},
364 { "src-ipv6", TOK_SRCIP6},
365 { "src-ip6", TOK_SRCIP6},
366 { "lookup", TOK_LOOKUP},
368 { "//", TOK_COMMENT },
370 { "not", TOK_NOT }, /* pseudo option */
371 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
372 { "or", TOK_OR }, /* pseudo option */
373 { "|", /* escape */ TOK_OR }, /* pseudo option */
374 { "{", TOK_STARTBRACE }, /* pseudo option */
375 { "(", TOK_STARTBRACE }, /* pseudo option */
376 { "}", TOK_ENDBRACE }, /* pseudo option */
377 { ")", TOK_ENDBRACE }, /* pseudo option */
378 { NULL, 0 } /* terminator */
381 void bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg);
382 static int ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
383 ipfw_cfg_lheader **pcfg, size_t *psize);
384 static int ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
385 ipfw_cfg_lheader *cfg, size_t sz, int ac, char **av);
386 static void ipfw_list_tifaces(void);
389 static uint16_t pack_object(struct tidx *tstate, char *name, int otype);
390 static uint16_t pack_table(struct tidx *tstate, char *name);
392 static char *table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx);
393 static void object_sort_ctlv(ipfw_obj_ctlv *ctlv);
394 static char *object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx,
398 * Simple string buffer API.
399 * Used to simplify buffer passing between function and for
400 * transparent overrun handling.
404 * Allocates new buffer of given size @sz.
406 * Returns 0 on success.
409 bp_alloc(struct buf_pr *b, size_t size)
411 memset(b, 0, sizeof(struct buf_pr));
413 if ((b->buf = calloc(1, size)) == NULL)
424 bp_free(struct buf_pr *b)
431 * Flushes buffer so new writer start from beginning.
434 bp_flush(struct buf_pr *b)
443 * Print message specified by @format and args.
444 * Automatically manage buffer space and transparently handle
447 * Returns number of bytes that should have been printed.
450 bprintf(struct buf_pr *b, char *format, ...)
455 va_start(args, format);
457 i = vsnprintf(b->ptr, b->avail, format, args);
460 if (i > b->avail || i < 0) {
461 /* Overflow or print error */
474 * Special values printer for tablearg-aware opcodes.
477 bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg)
481 bprintf(bp, "%s", str);
482 if (arg == IP_FW_TARG)
483 bprintf(bp, "tablearg");
485 bprintf(bp, "%u", arg);
489 * Helper routine to print a possibly unaligned uint64_t on
490 * various platform. If width > 0, print the value with
491 * the desired width, followed by a space;
492 * otherwise, return the required width.
495 pr_u64(struct buf_pr *b, uint64_t *pd, int width)
498 #define U64_FMT "I64"
500 #define U64_FMT "llu"
503 unsigned long long d;
505 bcopy (pd, &u, sizeof(u));
508 bprintf(b, "%*" U64_FMT " ", width, d) :
509 snprintf(NULL, 0, "%" U64_FMT, d) ;
515 safe_calloc(size_t number, size_t size)
517 void *ret = calloc(number, size);
520 err(EX_OSERR, "calloc");
525 safe_realloc(void *ptr, size_t size)
527 void *ret = realloc(ptr, size);
530 err(EX_OSERR, "realloc");
535 * Compare things like interface or table names.
538 stringnum_cmp(const char *a, const char *b)
550 return (strcmp(a, b));
555 * conditionally runs the command.
556 * Selected options or negative -> getsockopt
559 do_cmd(int optname, void *optval, uintptr_t optlen)
566 if (ipfw_socket == -1)
567 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
569 err(EX_UNAVAILABLE, "socket");
571 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
572 optname == IP_FW_ADD || optname == IP_FW3 ||
573 optname == IP_FW_NAT_GET_CONFIG ||
575 optname == IP_FW_NAT_GET_LOG) {
578 i = getsockopt(ipfw_socket, IPPROTO_IP, optname, optval,
579 (socklen_t *)optlen);
581 i = setsockopt(ipfw_socket, IPPROTO_IP, optname, optval, optlen);
587 * do_set3 - pass ipfw control cmd to kernel
588 * @optname: option name
589 * @optval: pointer to option data
590 * @optlen: option length
592 * Assumes op3 header is already embedded.
593 * Calls setsockopt() with IP_FW3 as kernel-visible opcode.
594 * Returns 0 on success or errno otherwise.
597 do_set3(int optname, ip_fw3_opheader *op3, size_t optlen)
603 if (ipfw_socket == -1)
604 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
606 err(EX_UNAVAILABLE, "socket");
608 op3->opcode = optname;
610 return (setsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, optlen));
614 * do_get3 - pass ipfw control cmd to kernel
615 * @optname: option name
616 * @optval: pointer to option data
617 * @optlen: pointer to option length
619 * Assumes op3 header is already embedded.
620 * Calls getsockopt() with IP_FW3 as kernel-visible opcode.
621 * Returns 0 on success or errno otherwise.
624 do_get3(int optname, ip_fw3_opheader *op3, size_t *optlen)
632 if (ipfw_socket == -1)
633 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
635 err(EX_UNAVAILABLE, "socket");
637 op3->opcode = optname;
640 error = getsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, &len);
647 * match_token takes a table and a string, returns the value associated
648 * with the string (-1 in case of failure).
651 match_token(struct _s_x *table, const char *string)
654 uint i = strlen(string);
656 for (pt = table ; i && pt->s != NULL ; pt++)
657 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
663 * match_token_relaxed takes a table and a string, returns the value associated
664 * with the string for the best match.
667 * value from @table for matched records
668 * -1 for non-matched records
669 * -2 if more than one records match @string.
672 match_token_relaxed(struct _s_x *table, const char *string)
680 for (pt = table ; i != 0 && pt->s != NULL ; pt++) {
681 if (strncmp(pt->s, string, i) != 0)
690 return (c > 0 ? -2: -1);
694 get_token(struct _s_x *table, const char *string, const char *errbase)
698 if ((tcmd = match_token_relaxed(table, string)) < 0)
699 errx(EX_USAGE, "%s %s %s",
700 (tcmd == 0) ? "invalid" : "ambiguous", errbase, string);
706 * match_value takes a table and a value, returns the string associated
707 * with the value (NULL in case of failure).
710 match_value(struct _s_x *p, int value)
712 for (; p->s != NULL; p++)
719 concat_tokens(char *buf, size_t bufsize, struct _s_x *table, char *delimiter)
725 for (sz = 0, pt = table ; pt->s != NULL; pt++) {
726 l = snprintf(buf + sz, bufsize - sz, "%s%s",
727 (sz == 0) ? "" : delimiter, pt->s);
738 * helper function to process a set of flags and set bits in the
742 fill_flags(struct _s_x *flags, char *p, char **e, uint32_t *set,
745 char *q; /* points to the separator */
747 uint32_t *which; /* mask we are working on */
758 val = match_token(flags, p);
764 *which |= (uint32_t)val;
771 print_flags_buffer(char *buf, size_t sz, struct _s_x *list, uint32_t set)
773 char const *comma = "";
776 for (i = 0; list[i].x != 0; i++) {
777 if ((set & list[i].x) == 0)
781 l = snprintf(buf, sz, "%s%s", comma, list[i].s);
791 * _substrcmp takes two strings and returns 1 if they do not match,
792 * and 0 if they match exactly or the first string is a sub-string
793 * of the second. A warning is printed to stderr in the case that the
794 * first string is a sub-string of the second.
796 * This function will be removed in the future through the usual
797 * deprecation process.
800 _substrcmp(const char *str1, const char* str2)
803 if (strncmp(str1, str2, strlen(str1)) != 0)
806 if (strlen(str1) != strlen(str2))
807 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
813 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
814 * and 0 if they match exactly or the second string is a sub-string
815 * of the first. A warning is printed to stderr in the case that the
816 * first string does not match the third.
818 * This function exists to warn about the bizarre construction
819 * strncmp(str, "by", 2) which is used to allow people to use a shortcut
820 * for "bytes". The problem is that in addition to accepting "by",
821 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
822 * other string beginning with "by".
824 * This function will be removed in the future through the usual
825 * deprecation process.
828 _substrcmp2(const char *str1, const char* str2, const char* str3)
831 if (strncmp(str1, str2, strlen(str2)) != 0)
834 if (strcmp(str1, str3) != 0)
835 warnx("DEPRECATED: '%s' matched '%s'",
841 * prints one port, symbolic or numeric
844 print_port(struct buf_pr *bp, int proto, uint16_t port)
847 if (proto == IPPROTO_ETHERTYPE) {
850 if (co.do_resolv && (s = match_value(ether_types, port)) )
851 bprintf(bp, "%s", s);
853 bprintf(bp, "0x%04x", port);
855 struct servent *se = NULL;
857 struct protoent *pe = getprotobynumber(proto);
859 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
862 bprintf(bp, "%s", se->s_name);
864 bprintf(bp, "%d", port);
868 static struct _s_x _port_name[] = {
869 {"dst-port", O_IP_DSTPORT},
870 {"src-port", O_IP_SRCPORT},
874 {"mac-type", O_MAC_TYPE},
875 {"tcpdatalen", O_TCPDATALEN},
876 {"tcpwin", O_TCPWIN},
877 {"tagged", O_TAGGED},
882 * Print the values in a list 16-bit items of the types above.
883 * XXX todo: add support for mask.
886 print_newports(struct buf_pr *bp, ipfw_insn_u16 *cmd, int proto, int opcode)
888 uint16_t *p = cmd->ports;
893 sep = match_value(_port_name, opcode);
896 bprintf(bp, " %s", sep);
899 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
900 bprintf(bp, "%s", sep);
901 print_port(bp, proto, p[0]);
904 print_port(bp, proto, p[1]);
911 * Like strtol, but also translates service names into port numbers
912 * for some protocols.
914 * proto == -1 disables the protocol check;
915 * proto == IPPROTO_ETHERTYPE looks up an internal table
916 * proto == <some value in /etc/protocols> matches the values there.
917 * Returns *end == s in case the parameter is not found.
920 strtoport(char *s, char **end, int base, int proto)
926 *end = s; /* default - not found */
928 return 0; /* not found */
931 return strtol(s, end, base);
934 * find separator. '\\' escapes the next char.
936 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
937 if (*s1 == '\\' && s1[1] != '\0')
940 buf = safe_calloc(s1 - s + 1, 1);
943 * copy into a buffer skipping backslashes
945 for (p = s, i = 0; p != s1 ; p++)
950 if (proto == IPPROTO_ETHERTYPE) {
951 i = match_token(ether_types, buf);
953 if (i != -1) { /* found */
958 struct protoent *pe = NULL;
962 pe = getprotobynumber(proto);
964 se = getservbyname(buf, pe ? pe->p_name : NULL);
968 return ntohs(se->s_port);
971 return 0; /* not found */
975 * Fill the body of the command with the list of port ranges.
978 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
980 uint16_t a, b, *p = cmd->ports;
985 a = strtoport(av, &s, 0, proto);
986 if (s == av) /* empty or invalid argument */
989 CHECK_LENGTH(cblen, i + 2);
992 case '-': /* a range */
994 b = strtoport(av, &s, 0, proto);
995 /* Reject expressions like '1-abc' or '1-2-3'. */
996 if (s == av || (*s != ',' && *s != '\0'))
1001 case ',': /* comma separated list */
1006 warnx("port list: invalid separator <%c> in <%s>",
1016 if (i + 1 > F_LEN_MASK)
1017 errx(EX_DATAERR, "too many ports/ranges\n");
1018 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
1024 * Fill the body of the command with the list of DiffServ codepoints.
1027 fill_dscp(ipfw_insn *cmd, char *av, int cblen)
1029 uint32_t *low, *high;
1033 cmd->opcode = O_DSCP;
1034 cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
1038 low = (uint32_t *)(cmd + 1);
1051 if ((code = match_token(f_ipdscp, s)) == -1)
1052 errx(EX_DATAERR, "Unknown DSCP code");
1054 code = strtoul(s, NULL, 10);
1055 if (code < 0 || code > 63)
1056 errx(EX_DATAERR, "Invalid DSCP value");
1060 *high |= 1 << (code - 32);
1068 static struct _s_x icmpcodes[] = {
1069 { "net", ICMP_UNREACH_NET },
1070 { "host", ICMP_UNREACH_HOST },
1071 { "protocol", ICMP_UNREACH_PROTOCOL },
1072 { "port", ICMP_UNREACH_PORT },
1073 { "needfrag", ICMP_UNREACH_NEEDFRAG },
1074 { "srcfail", ICMP_UNREACH_SRCFAIL },
1075 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
1076 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
1077 { "isolated", ICMP_UNREACH_ISOLATED },
1078 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
1079 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
1080 { "tosnet", ICMP_UNREACH_TOSNET },
1081 { "toshost", ICMP_UNREACH_TOSHOST },
1082 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
1083 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
1084 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
1089 fill_reject_code(u_short *codep, char *str)
1094 val = strtoul(str, &s, 0);
1095 if (s == str || *s != '\0' || val >= 0x100)
1096 val = match_token(icmpcodes, str);
1098 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
1104 print_reject_code(struct buf_pr *bp, uint16_t code)
1108 if ((s = match_value(icmpcodes, code)) != NULL)
1109 bprintf(bp, "unreach %s", s);
1111 bprintf(bp, "unreach %u", code);
1115 * Returns the number of bits set (from left) in a contiguous bitmask,
1116 * or -1 if the mask is not contiguous.
1117 * XXX this needs a proper fix.
1118 * This effectively works on masks in big-endian (network) format.
1119 * when compiled on little endian architectures.
1121 * First bit is bit 7 of the first byte -- note, for MAC addresses,
1122 * the first bit on the wire is bit 0 of the first byte.
1123 * len is the max length in bits.
1126 contigmask(uint8_t *p, int len)
1130 for (i=0; i<len ; i++)
1131 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
1133 for (n=i+1; n < len; n++)
1134 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
1135 return -1; /* mask not contiguous */
1140 * print flags set/clear in the two bitmasks passed as parameters.
1141 * There is a specialized check for f_tcpflags.
1144 print_flags(struct buf_pr *bp, char const *name, ipfw_insn *cmd,
1147 char const *comma = "";
1149 uint8_t set = cmd->arg1 & 0xff;
1150 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
1152 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
1153 bprintf(bp, " setup");
1157 bprintf(bp, " %s ", name);
1158 for (i=0; list[i].x != 0; i++) {
1159 if (set & list[i].x) {
1161 bprintf(bp, "%s%s", comma, list[i].s);
1164 if (clear & list[i].x) {
1165 clear &= ~list[i].x;
1166 bprintf(bp, "%s!%s", comma, list[i].s);
1174 * Print the ip address contained in a command.
1177 print_ip(struct buf_pr *bp, struct format_opts *fo, ipfw_insn_ip *cmd,
1180 struct hostent *he = NULL;
1182 uint32_t len = F_LEN((ipfw_insn *)cmd);
1183 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
1186 if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
1188 const char *arg = "<invalid>";
1190 if (d < sizeof(lookup_key)/sizeof(lookup_key[0]))
1191 arg = match_value(rule_options, lookup_key[d]);
1192 t = table_search_ctlv(fo->tstate, ((ipfw_insn *)cmd)->arg1);
1193 bprintf(bp, "%s lookup %s %s", cmd->o.len & F_NOT ? " not": "",
1197 bprintf(bp, "%s%s ", cmd->o.len & F_NOT ? " not": "", s);
1199 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
1203 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
1204 cmd->o.opcode == O_IP_DST_LOOKUP) {
1205 t = table_search_ctlv(fo->tstate, ((ipfw_insn *)cmd)->arg1);
1206 bprintf(bp, "table(%s", t);
1207 if (len == F_INSN_SIZE(ipfw_insn_u32))
1208 bprintf(bp, ",%u", *a);
1212 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
1213 uint32_t x, *map = (uint32_t *)&(cmd->mask);
1217 x = cmd->o.arg1 - 1;
1219 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1220 bprintf(bp, "%s/%d", inet_ntoa(cmd->addr),
1221 contigmask((uint8_t *)&x, 32));
1222 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1223 x &= 0xff; /* base */
1225 * Print bits and ranges.
1226 * Locate first bit set (i), then locate first bit unset (j).
1227 * If we have 3+ consecutive bits set, then print them as a
1228 * range, otherwise only print the initial bit and rescan.
1230 for (i=0; i < cmd->o.arg1; i++)
1231 if (map[i/32] & (1<<(i & 31))) {
1232 for (j=i+1; j < cmd->o.arg1; j++)
1233 if (!(map[ j/32] & (1<<(j & 31))))
1235 bprintf(bp, "%c%d", comma, i+x);
1236 if (j>i+2) { /* range has at least 3 elements */
1237 bprintf(bp, "-%d", j-1+x);
1246 * len == 2 indicates a single IP, whereas lists of 1 or more
1247 * addr/mask pairs have len = (2n+1). We convert len to n so we
1248 * use that to count the number of entries.
1250 for (len = len / 2; len > 0; len--, a += 2) {
1251 int mb = /* mask length */
1252 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1253 32 : contigmask((uint8_t *)&(a[1]), 32);
1254 if (mb == 32 && co.do_resolv)
1255 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
1256 if (he != NULL) /* resolved to name */
1257 bprintf(bp, "%s", he->h_name);
1258 else if (mb == 0) /* any */
1260 else { /* numeric IP followed by some kind of mask */
1261 ia = (struct in_addr *)&a[0];
1262 bprintf(bp, "%s", inet_ntoa(*ia));
1264 ia = (struct in_addr *)&a[1];
1265 bprintf(bp, ":%s", inet_ntoa(*ia));
1267 bprintf(bp, "/%d", mb);
1275 * prints a MAC address/mask pair
1278 print_mac(struct buf_pr *bp, uint8_t *addr, uint8_t *mask)
1280 int l = contigmask(mask, 48);
1283 bprintf(bp, " any");
1285 bprintf(bp, " %02x:%02x:%02x:%02x:%02x:%02x",
1286 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1288 bprintf(bp, "&%02x:%02x:%02x:%02x:%02x:%02x",
1289 mask[0], mask[1], mask[2],
1290 mask[3], mask[4], mask[5]);
1292 bprintf(bp, "/%d", l);
1297 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1306 type = strtoul(av, &av, 0);
1308 if (*av != ',' && *av != '\0')
1309 errx(EX_DATAERR, "invalid ICMP type");
1312 errx(EX_DATAERR, "ICMP type out of range");
1314 cmd->d[0] |= 1 << type;
1316 cmd->o.opcode = O_ICMPTYPE;
1317 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1321 print_icmptypes(struct buf_pr *bp, ipfw_insn_u32 *cmd)
1326 bprintf(bp, " icmptypes");
1327 for (i = 0; i < 32; i++) {
1328 if ( (cmd->d[0] & (1 << (i))) == 0)
1330 bprintf(bp, "%c%d", sep, i);
1336 print_dscp(struct buf_pr *bp, ipfw_insn_u32 *cmd)
1343 bprintf(bp, " dscp");
1346 if (*v & (1 << i)) {
1347 if ((code = match_value(f_ipdscp, i)) != NULL)
1348 bprintf(bp, "%c%s", sep, code);
1350 bprintf(bp, "%c%d", sep, i);
1354 if ((++i % 32) == 0)
1360 * show_ipfw() prints the body of an ipfw rule.
1361 * Because the standard rule has at least proto src_ip dst_ip, we use
1362 * a helper function to produce these entries if not provided explicitly.
1363 * The first argument is the list of fields we have, the second is
1364 * the list of fields we want to be printed.
1366 * Special cases if we have provided a MAC header:
1367 * + if the rule does not contain IP addresses/ports, do not print them;
1368 * + if the rule does not contain an IP proto, print "all" instead of "ip";
1370 * Once we have 'have_options', IP header fields are printed as options.
1372 #define HAVE_PROTO 0x0001
1373 #define HAVE_SRCIP 0x0002
1374 #define HAVE_DSTIP 0x0004
1375 #define HAVE_PROTO4 0x0008
1376 #define HAVE_PROTO6 0x0010
1377 #define HAVE_IP 0x0100
1378 #define HAVE_OPTIONS 0x8000
1381 show_prerequisites(struct buf_pr *bp, int *flags, int want, int cmd)
1383 (void)cmd; /* UNUSED */
1384 if (co.comment_only)
1386 if ( (*flags & HAVE_IP) == HAVE_IP)
1387 *flags |= HAVE_OPTIONS;
1389 if ( !(*flags & HAVE_OPTIONS)) {
1390 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) {
1391 if ( (*flags & HAVE_PROTO4))
1392 bprintf(bp, " ip4");
1393 else if ( (*flags & HAVE_PROTO6))
1394 bprintf(bp, " ip6");
1398 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
1399 bprintf(bp, " from any");
1400 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
1401 bprintf(bp, " to any");
1407 show_static_rule(struct cmdline_opts *co, struct format_opts *fo,
1408 struct buf_pr *bp, struct ip_fw_rule *rule, struct ip_fw_bcounter *cntr)
1410 static int twidth = 0;
1412 ipfw_insn *cmd, *has_eaction = NULL, *tagptr = NULL;
1413 const char *comment = NULL; /* ptr to comment if we have one */
1415 int proto = 0; /* default */
1416 int flags = 0; /* prerequisites */
1417 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
1418 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
1419 int or_block = 0; /* we are in an or block */
1422 if ((fo->set_mask & (1 << rule->set)) == 0) {
1427 bprintf(bp, "# DISABLED ");
1429 bprintf(bp, "%05u ", rule->rulenum);
1431 /* Print counters if enabled */
1432 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
1433 pr_u64(bp, &cntr->pcnt, fo->pcwidth);
1434 pr_u64(bp, &cntr->bcnt, fo->bcwidth);
1437 if (co->do_time == 2)
1438 bprintf(bp, "%10u ", cntr->timestamp);
1439 else if (co->do_time == 1) {
1441 time_t t = (time_t)0;
1444 strcpy(timestr, ctime(&t));
1445 *strchr(timestr, '\n') = '\0';
1446 twidth = strlen(timestr);
1448 if (cntr->timestamp > 0) {
1449 t = _long_to_time(cntr->timestamp);
1451 strcpy(timestr, ctime(&t));
1452 *strchr(timestr, '\n') = '\0';
1453 bprintf(bp, "%s ", timestr);
1455 bprintf(bp, "%*s", twidth, " ");
1460 bprintf(bp, "set %d ", rule->set);
1463 * print the optional "match probability"
1465 if (rule->cmd_len > 0) {
1467 if (cmd->opcode == O_PROB) {
1468 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1469 double d = 1.0 * p->d[0];
1471 d = (d / 0x7fffffff);
1472 bprintf(bp, "prob %f ", d);
1477 * first print actions
1479 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1480 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1481 switch(cmd->opcode) {
1483 bprintf(bp, "check-state");
1485 ename = object_search_ctlv(fo->tstate,
1486 cmd->arg1, IPFW_TLV_STATE_NAME);
1489 bprintf(bp, " :%s", ename ? ename: "any");
1490 /* avoid printing anything else */
1491 flags = HAVE_PROTO | HAVE_SRCIP |
1492 HAVE_DSTIP | HAVE_IP;
1496 bprintf(bp, "allow");
1500 bprintf(bp, "count");
1504 bprintf(bp, "deny");
1508 if (cmd->arg1 == ICMP_REJECT_RST)
1509 bprintf(bp, "reset");
1510 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1511 bprintf(bp, "reject");
1513 print_reject_code(bp, cmd->arg1);
1517 if (cmd->arg1 == ICMP6_UNREACH_RST)
1518 bprintf(bp, "reset6");
1520 print_unreach6_code(bp, cmd->arg1);
1524 bprint_uint_arg(bp, "skipto ", cmd->arg1);
1528 bprint_uint_arg(bp, "pipe ", cmd->arg1);
1532 bprint_uint_arg(bp, "queue ", cmd->arg1);
1536 bprint_uint_arg(bp, "divert ", cmd->arg1);
1540 bprint_uint_arg(bp, "tee ", cmd->arg1);
1544 bprint_uint_arg(bp, "netgraph ", cmd->arg1);
1548 bprint_uint_arg(bp, "ngtee ", cmd->arg1);
1553 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1555 if (s->sa.sin_addr.s_addr == INADDR_ANY) {
1556 bprintf(bp, "fwd tablearg");
1558 bprintf(bp, "fwd %s",inet_ntoa(s->sa.sin_addr));
1561 bprintf(bp, ",%d", s->sa.sin_port);
1567 char buf[INET6_ADDRSTRLEN + IF_NAMESIZE + 2];
1568 ipfw_insn_sa6 *s = (ipfw_insn_sa6 *)cmd;
1570 bprintf(bp, "fwd ");
1571 if (getnameinfo((const struct sockaddr *)&s->sa,
1572 sizeof(struct sockaddr_in6), buf, sizeof(buf),
1573 NULL, 0, NI_NUMERICHOST) == 0)
1574 bprintf(bp, "%s", buf);
1575 if (s->sa.sin6_port)
1576 bprintf(bp, ",%d", s->sa.sin6_port);
1580 case O_LOG: /* O_LOG is printed last */
1581 logptr = (ipfw_insn_log *)cmd;
1584 case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1585 altqptr = (ipfw_insn_altq *)cmd;
1593 if (cmd->arg1 != IP_FW_NAT44_GLOBAL)
1594 bprint_uint_arg(bp, "nat ", cmd->arg1);
1596 bprintf(bp, "nat global");
1600 if (cmd->arg1 == IP_FW_TARG)
1601 bprint_uint_arg(bp, "setfib ", cmd->arg1);
1603 bprintf(bp, "setfib %u", cmd->arg1 & 0x7FFF);
1606 case O_EXTERNAL_ACTION: {
1608 * The external action can consists of two following
1609 * each other opcodes - O_EXTERNAL_ACTION and
1610 * O_EXTERNAL_INSTANCE. The first contains the ID of
1611 * name of external action. The second contains the ID
1612 * of name of external action instance.
1613 * NOTE: in case when external action has no named
1614 * instances support, the second opcode isn't needed.
1617 ename = object_search_ctlv(fo->tstate, cmd->arg1,
1619 if (match_token(rule_eactions, ename) != -1)
1620 bprintf(bp, "%s", ename);
1622 bprintf(bp, "eaction %s", ename);
1626 case O_EXTERNAL_INSTANCE: {
1627 if (has_eaction == NULL)
1630 * XXX: we need to teach ipfw(9) to rewrite opcodes
1631 * in the user buffer on rule addition. When we add
1632 * the rule, we specify zero TLV type for
1633 * O_EXTERNAL_INSTANCE object. To show correct
1634 * rule after `ipfw add` we need to search instance
1635 * name with zero type. But when we do `ipfw show`
1636 * we calculate TLV type using IPFW_TLV_EACTION_NAME()
1639 ename = object_search_ctlv(fo->tstate, cmd->arg1, 0);
1641 ename = object_search_ctlv(fo->tstate,
1643 IPFW_TLV_EACTION_NAME(has_eaction->arg1));
1644 bprintf(bp, " %s", ename);
1648 case O_EXTERNAL_DATA: {
1649 if (has_eaction == NULL)
1652 * Currently we support data formatting only for
1653 * external data with datalen u16. For unknown data
1654 * print its size in bytes.
1656 if (cmd->len == F_INSN_SIZE(ipfw_insn))
1657 bprintf(bp, " %u", cmd->arg1);
1659 bprintf(bp, " %ubytes",
1660 cmd->len * sizeof(uint32_t));
1668 if (cmd->arg1 == IP_FW_TARG) {
1669 bprint_uint_arg(bp, "setdscp ", cmd->arg1);
1672 uval = cmd->arg1 & 0x3F;
1673 if ((code = match_value(f_ipdscp, uval)) != NULL)
1674 bprintf(bp, "setdscp %s", code);
1676 bprint_uint_arg(bp, "setdscp ", uval);
1681 bprintf(bp, "reass");
1685 if (cmd->len & F_NOT)
1686 bprintf(bp, "return");
1688 bprint_uint_arg(bp, "call ", cmd->arg1);
1692 bprintf(bp, "** unrecognized action %d len %d ",
1693 cmd->opcode, cmd->len);
1697 if (logptr->max_log > 0)
1698 bprintf(bp, " log logamount %d", logptr->max_log);
1700 bprintf(bp, " log");
1704 print_altq_cmd(bp, altqptr);
1708 if (tagptr->len & F_NOT)
1709 bprint_uint_arg(bp, " untag ", tagptr->arg1);
1711 bprint_uint_arg(bp, " tag ", tagptr->arg1);
1715 * then print the body.
1717 for (l = rule->act_ofs, cmd = rule->cmd;
1718 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1719 if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1721 if (cmd->opcode == O_IP4) {
1722 flags |= HAVE_PROTO4;
1724 } else if (cmd->opcode == O_IP6) {
1725 flags |= HAVE_PROTO6;
1729 if (rule->flags & IPFW_RULE_NOOPT) { /* empty rules before options */
1730 if (!co->do_compact) {
1731 show_prerequisites(bp, &flags, HAVE_PROTO, 0);
1732 bprintf(bp, " from any to any");
1734 flags |= HAVE_IP | HAVE_OPTIONS | HAVE_PROTO |
1735 HAVE_SRCIP | HAVE_DSTIP;
1738 if (co->comment_only)
1741 for (l = rule->act_ofs, cmd = rule->cmd;
1742 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1744 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1746 if (co->comment_only) {
1747 if (cmd->opcode != O_NOP)
1749 bprintf(bp, " // %s\n", (char *)(cmd + 1));
1753 show_prerequisites(bp, &flags, 0, cmd->opcode);
1755 switch(cmd->opcode) {
1757 break; /* done already */
1760 break; /* no need to print anything here */
1763 case O_IP_SRC_LOOKUP:
1767 show_prerequisites(bp, &flags, HAVE_PROTO, 0);
1768 if (!(flags & HAVE_SRCIP))
1769 bprintf(bp, " from");
1770 if ((cmd->len & F_OR) && !or_block)
1772 print_ip(bp, fo, (ipfw_insn_ip *)cmd,
1773 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1774 flags |= HAVE_SRCIP;
1778 case O_IP_DST_LOOKUP:
1782 show_prerequisites(bp, &flags, HAVE_PROTO|HAVE_SRCIP, 0);
1783 if (!(flags & HAVE_DSTIP))
1785 if ((cmd->len & F_OR) && !or_block)
1787 print_ip(bp, fo, (ipfw_insn_ip *)cmd,
1788 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1789 flags |= HAVE_DSTIP;
1793 case O_IP6_SRC_MASK:
1795 show_prerequisites(bp, &flags, HAVE_PROTO, 0);
1796 if (!(flags & HAVE_SRCIP))
1797 bprintf(bp, " from");
1798 if ((cmd->len & F_OR) && !or_block)
1800 print_ip6(bp, (ipfw_insn_ip6 *)cmd,
1801 (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1802 flags |= HAVE_SRCIP | HAVE_PROTO;
1806 case O_IP6_DST_MASK:
1808 show_prerequisites(bp, &flags, HAVE_PROTO|HAVE_SRCIP, 0);
1809 if (!(flags & HAVE_DSTIP))
1811 if ((cmd->len & F_OR) && !or_block)
1813 print_ip6(bp, (ipfw_insn_ip6 *)cmd,
1814 (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1815 flags |= HAVE_DSTIP;
1819 print_flow6id(bp, (ipfw_insn_u32 *) cmd );
1820 flags |= HAVE_OPTIONS;
1824 show_prerequisites(bp, &flags,
1825 HAVE_PROTO | HAVE_SRCIP |
1826 HAVE_DSTIP | HAVE_IP, 0);
1828 if (flags & HAVE_DSTIP)
1830 show_prerequisites(bp, &flags,
1831 HAVE_PROTO | HAVE_SRCIP, 0);
1832 if ((cmd->len & F_OR) && !or_block)
1834 if (cmd->len & F_NOT)
1835 bprintf(bp, " not");
1836 print_newports(bp, (ipfw_insn_u16 *)cmd, proto,
1837 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1841 struct protoent *pe = NULL;
1843 if ((cmd->len & F_OR) && !or_block)
1845 if (cmd->len & F_NOT)
1846 bprintf(bp, " not");
1848 pe = getprotobynumber(cmd->arg1);
1849 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1850 !(flags & HAVE_PROTO))
1851 show_prerequisites(bp, &flags,
1852 HAVE_PROTO | HAVE_IP | HAVE_SRCIP |
1853 HAVE_DSTIP | HAVE_OPTIONS, 0);
1854 if (flags & HAVE_OPTIONS)
1855 bprintf(bp, " proto");
1857 bprintf(bp, " %s", pe->p_name);
1859 bprintf(bp, " %u", cmd->arg1);
1861 flags |= HAVE_PROTO;
1864 default: /*options ... */
1865 if (!(cmd->len & (F_OR|F_NOT)))
1866 if (((cmd->opcode == O_IP6) &&
1867 (flags & HAVE_PROTO6)) ||
1868 ((cmd->opcode == O_IP4) &&
1869 (flags & HAVE_PROTO4)))
1871 show_prerequisites(bp, &flags, HAVE_PROTO | HAVE_SRCIP |
1872 HAVE_DSTIP | HAVE_IP | HAVE_OPTIONS, 0);
1873 if ((cmd->len & F_OR) && !or_block)
1875 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1876 bprintf(bp, " not");
1877 switch(cmd->opcode) {
1879 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1881 bprintf(bp, " MAC");
1882 print_mac(bp, m->addr, m->mask);
1883 print_mac(bp, m->addr + 6, m->mask + 6);
1888 print_newports(bp, (ipfw_insn_u16 *)cmd,
1889 IPPROTO_ETHERTYPE, cmd->opcode);
1894 bprintf(bp, " frag");
1898 bprintf(bp, " fib %u", cmd->arg1 );
1901 bprintf(bp, " sockarg");
1905 bprintf(bp, cmd->len & F_NOT ? " out" : " in");
1909 switch (cmd->arg1) {
1911 bprintf(bp, " diverted");
1914 bprintf(bp, " diverted-loopback");
1917 bprintf(bp, " diverted-output");
1920 bprintf(bp, " diverted-?<%u>", cmd->arg1);
1926 bprintf(bp, " layer2");
1933 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1935 if (cmd->opcode == O_XMIT)
1937 else if (cmd->opcode == O_RECV)
1939 else /* if (cmd->opcode == O_VIA) */
1941 if (cmdif->name[0] == '\0')
1942 bprintf(bp, " %s %s", s,
1943 inet_ntoa(cmdif->p.ip));
1944 else if (cmdif->name[0] == '\1') {
1945 /* interface table */
1946 t = table_search_ctlv(fo->tstate,
1948 bprintf(bp, " %s table(%s)", s, t);
1950 bprintf(bp, " %s %s", s, cmdif->name);
1954 case O_IP_FLOW_LOOKUP:
1958 t = table_search_ctlv(fo->tstate, cmd->arg1);
1959 bprintf(bp, " flow table(%s", t);
1960 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))
1962 ((ipfw_insn_u32 *)cmd)->d[0]);
1967 if (F_LEN(cmd) == 1)
1968 bprintf(bp, " ipid %u", cmd->arg1 );
1970 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1975 if (F_LEN(cmd) == 1)
1976 bprintf(bp, " ipttl %u", cmd->arg1 );
1978 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1983 bprintf(bp, " ipver %u", cmd->arg1 );
1986 case O_IPPRECEDENCE:
1987 bprintf(bp, " ipprecedence %u", cmd->arg1 >> 5);
1991 print_dscp(bp, (ipfw_insn_u32 *)cmd);
1995 if (F_LEN(cmd) == 1)
1996 bprintf(bp, " iplen %u", cmd->arg1 );
1998 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
2003 print_flags(bp, "ipoptions", cmd, f_ipopts);
2007 print_flags(bp, "iptos", cmd, f_iptos);
2011 print_icmptypes(bp, (ipfw_insn_u32 *)cmd);
2015 bprintf(bp, " established");
2019 if (F_LEN(cmd) == 1)
2020 bprintf(bp, " tcpdatalen %u", cmd->arg1 );
2022 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
2027 print_flags(bp, "tcpflags", cmd, f_tcpflags);
2031 print_flags(bp, "tcpoptions", cmd, f_tcpopts);
2035 if (F_LEN(cmd) == 1)
2036 bprintf(bp, " tcpwin %u", cmd->arg1);
2038 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
2043 bprintf(bp, " tcpack %d", ntohl(cmd32->d[0]));
2047 bprintf(bp, " tcpseq %d", ntohl(cmd32->d[0]));
2052 struct passwd *pwd = getpwuid(cmd32->d[0]);
2055 bprintf(bp, " uid %s", pwd->pw_name);
2057 bprintf(bp, " uid %u", cmd32->d[0]);
2063 struct group *grp = getgrgid(cmd32->d[0]);
2066 bprintf(bp, " gid %s", grp->gr_name);
2068 bprintf(bp, " gid %u", cmd32->d[0]);
2073 bprintf(bp, " jail %d", cmd32->d[0]);
2077 bprintf(bp, " verrevpath");
2081 bprintf(bp, " versrcreach");
2085 bprintf(bp, " antispoof");
2089 bprintf(bp, " ipsec");
2093 comment = (char *)(cmd + 1);
2097 bprintf(bp, " keep-state");
2099 object_search_ctlv(fo->tstate, cmd->arg1,
2100 IPFW_TLV_STATE_NAME));
2104 struct _s_x *p = limit_masks;
2105 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
2106 uint8_t x = c->limit_mask;
2107 char const *comma = " ";
2109 bprintf(bp, " limit");
2110 for (; p->x != 0 ; p++)
2111 if ((x & p->x) == p->x) {
2113 bprintf(bp, "%s%s", comma,p->s);
2116 bprint_uint_arg(bp, " ", c->conn_limit);
2118 object_search_ctlv(fo->tstate, cmd->arg1,
2119 IPFW_TLV_STATE_NAME));
2124 bprintf(bp, " ip6");
2128 bprintf(bp, " ip4");
2132 print_icmp6types(bp, (ipfw_insn_u32 *)cmd);
2136 print_ext6hdr(bp, (ipfw_insn *)cmd);
2140 if (F_LEN(cmd) == 1)
2141 bprint_uint_arg(bp, " tagged ",
2144 print_newports(bp, (ipfw_insn_u16 *)cmd,
2149 bprintf(bp, " [opcode %d len %d]",
2150 cmd->opcode, cmd->len);
2153 if (cmd->len & F_OR) {
2156 } else if (or_block) {
2161 show_prerequisites(bp, &flags, HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP
2164 bprintf(bp, " // %s", comment);
2169 show_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2170 struct buf_pr *bp, ipfw_dyn_rule *d)
2172 struct protoent *pe;
2175 char buf[INET6_ADDRSTRLEN];
2177 if (!co->do_expired) {
2178 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
2181 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2182 bprintf(bp, "%05d", rulenum);
2183 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2185 pr_u64(bp, &d->pcnt, fo->pcwidth);
2186 pr_u64(bp, &d->bcnt, fo->bcwidth);
2187 bprintf(bp, "(%ds)", d->expire);
2189 switch (d->dyn_type) {
2190 case O_LIMIT_PARENT:
2191 bprintf(bp, " PARENT %d", d->count);
2194 bprintf(bp, " LIMIT");
2196 case O_KEEP_STATE: /* bidir, no mask */
2197 bprintf(bp, " STATE");
2201 if ((pe = getprotobynumber(d->id.proto)) != NULL)
2202 bprintf(bp, " %s", pe->p_name);
2204 bprintf(bp, " proto %u", d->id.proto);
2206 if (d->id.addr_type == 4) {
2207 a.s_addr = htonl(d->id.src_ip);
2208 bprintf(bp, " %s %d", inet_ntoa(a), d->id.src_port);
2210 a.s_addr = htonl(d->id.dst_ip);
2211 bprintf(bp, " <-> %s %d", inet_ntoa(a), d->id.dst_port);
2212 } else if (d->id.addr_type == 6) {
2213 bprintf(bp, " %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
2214 sizeof(buf)), d->id.src_port);
2215 bprintf(bp, " <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6,
2216 buf, sizeof(buf)), d->id.dst_port);
2218 bprintf(bp, " UNKNOWN <-> UNKNOWN");
2220 bprintf(bp, " :%s", object_search_ctlv(fo->tstate,
2221 d->kidx, IPFW_TLV_STATE_NAME));
2225 do_range_cmd(int cmd, ipfw_range_tlv *rt)
2227 ipfw_range_header rh;
2230 memset(&rh, 0, sizeof(rh));
2231 memcpy(&rh.range, rt, sizeof(*rt));
2232 rh.range.head.length = sizeof(*rt);
2233 rh.range.head.type = IPFW_TLV_RANGE;
2236 if (do_get3(cmd, &rh.opheader, &sz) != 0)
2238 /* Save number of matched objects */
2239 rt->new_set = rh.range.new_set;
2244 * This one handles all set-related commands
2245 * ipfw set { show | enable | disable }
2247 * ipfw set move X to Y
2248 * ipfw set move rule X to Y
2251 ipfw_sets_handler(char *av[])
2255 uint8_t cmd, rulenum;
2261 memset(&rt, 0, sizeof(rt));
2264 errx(EX_USAGE, "set needs command");
2265 if (_substrcmp(*av, "show") == 0) {
2266 struct format_opts fo;
2267 ipfw_cfg_lheader *cfg;
2269 memset(&fo, 0, sizeof(fo));
2270 if (ipfw_get_config(&co, &fo, &cfg, &size) != 0)
2271 err(EX_OSERR, "requesting config failed");
2273 for (i = 0, msg = "disable"; i < RESVD_SET; i++)
2274 if ((cfg->set_mask & (1<<i)) == 0) {
2275 printf("%s %d", msg, i);
2278 msg = (cfg->set_mask != (uint32_t)-1) ? " enable" : "enable";
2279 for (i = 0; i < RESVD_SET; i++)
2280 if ((cfg->set_mask & (1<<i)) != 0) {
2281 printf("%s %d", msg, i);
2286 } else if (_substrcmp(*av, "swap") == 0) {
2288 if ( av[0] == NULL || av[1] == NULL )
2289 errx(EX_USAGE, "set swap needs 2 set numbers\n");
2290 rt.set = atoi(av[0]);
2291 rt.new_set = atoi(av[1]);
2292 if (!isdigit(*(av[0])) || rt.set > RESVD_SET)
2293 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2294 if (!isdigit(*(av[1])) || rt.new_set > RESVD_SET)
2295 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2296 i = do_range_cmd(IP_FW_SET_SWAP, &rt);
2297 } else if (_substrcmp(*av, "move") == 0) {
2299 if (av[0] && _substrcmp(*av, "rule") == 0) {
2300 rt.flags = IPFW_RCFLAG_RANGE; /* move rules to new set */
2304 cmd = IP_FW_SET_MOVE; /* Move set to new one */
2305 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
2306 av[3] != NULL || _substrcmp(av[1], "to") != 0)
2307 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2308 rulenum = atoi(av[0]);
2309 rt.new_set = atoi(av[2]);
2310 if (cmd == IP_FW_XMOVE) {
2311 rt.start_rule = rulenum;
2312 rt.end_rule = rulenum;
2315 rt.new_set = atoi(av[2]);
2316 if (!isdigit(*(av[0])) || (cmd == 3 && rt.set > RESVD_SET) ||
2317 (cmd == 2 && rt.start_rule == IPFW_DEFAULT_RULE) )
2318 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2319 if (!isdigit(*(av[2])) || rt.new_set > RESVD_SET)
2320 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2321 i = do_range_cmd(cmd, &rt);
2323 err(EX_OSERR, "failed to move %s",
2324 cmd == IP_FW_SET_MOVE ? "set": "rule");
2325 } else if (_substrcmp(*av, "disable") == 0 ||
2326 _substrcmp(*av, "enable") == 0 ) {
2327 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2330 masks[0] = masks[1] = 0;
2333 if (isdigit(**av)) {
2335 if (i < 0 || i > RESVD_SET)
2337 "invalid set number %d\n", i);
2338 masks[which] |= (1<<i);
2339 } else if (_substrcmp(*av, "disable") == 0)
2341 else if (_substrcmp(*av, "enable") == 0)
2345 "invalid set command %s\n", *av);
2348 if ( (masks[0] & masks[1]) != 0 )
2350 "cannot enable and disable the same set\n");
2353 rt.new_set = masks[1];
2354 i = do_range_cmd(IP_FW_SET_ENABLE, &rt);
2356 warn("set enable/disable: setsockopt(IP_FW_SET_ENABLE)");
2358 errx(EX_USAGE, "invalid set command %s\n", *av);
2362 ipfw_sysctl_handler(char *av[], int which)
2366 if (av[0] == NULL) {
2367 warnx("missing keyword to enable/disable\n");
2368 } else if (_substrcmp(*av, "firewall") == 0) {
2369 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2370 &which, sizeof(which));
2371 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
2372 &which, sizeof(which));
2373 } else if (_substrcmp(*av, "one_pass") == 0) {
2374 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2375 &which, sizeof(which));
2376 } else if (_substrcmp(*av, "debug") == 0) {
2377 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2378 &which, sizeof(which));
2379 } else if (_substrcmp(*av, "verbose") == 0) {
2380 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2381 &which, sizeof(which));
2382 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2383 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2384 &which, sizeof(which));
2386 } else if (_substrcmp(*av, "altq") == 0) {
2387 altq_set_enabled(which);
2390 warnx("unrecognize enable/disable keyword: %s\n", *av);
2394 typedef void state_cb(struct cmdline_opts *co, struct format_opts *fo,
2395 void *arg, void *state);
2398 prepare_format_dyn(struct cmdline_opts *co, struct format_opts *fo,
2399 void *arg, void *_state)
2405 d = (ipfw_dyn_rule *)_state;
2406 /* Count _ALL_ states */
2409 if (fo->show_counters == 0)
2413 /* skip states from another set */
2414 bcopy((char *)&d->rule + sizeof(uint16_t), &set,
2416 if (set != co->use_set - 1)
2420 width = pr_u64(NULL, &d->pcnt, 0);
2421 if (width > fo->pcwidth)
2422 fo->pcwidth = width;
2424 width = pr_u64(NULL, &d->bcnt, 0);
2425 if (width > fo->bcwidth)
2426 fo->bcwidth = width;
2430 foreach_state(struct cmdline_opts *co, struct format_opts *fo,
2431 caddr_t base, size_t sz, state_cb dyn_bc, void *dyn_arg)
2437 ipfw_obj_ctlv *ctlv;
2443 ctlv = (ipfw_obj_ctlv *)base;
2444 switch (ctlv->head.type) {
2445 case IPFW_TLV_DYNSTATE_LIST:
2446 base += sizeof(*ctlv);
2447 sz -= sizeof(*ctlv);
2448 ttype = IPFW_TLV_DYN_ENT;
2457 tlv = (ipfw_obj_tlv *)base;
2458 if (tlv->type != ttype)
2461 fptr(co, fo, farg, tlv + 1);
2463 base += tlv->length;
2471 prepare_format_opts(struct cmdline_opts *co, struct format_opts *fo,
2472 ipfw_obj_tlv *rtlv, int rcnt, caddr_t dynbase, size_t dynsz)
2474 int bcwidth, pcwidth, width;
2476 struct ip_fw_bcounter *cntr;
2477 struct ip_fw_rule *r;
2481 if (fo->show_counters != 0) {
2482 for (n = 0; n < rcnt; n++,
2483 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2484 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2485 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2486 /* skip rules from another set */
2487 if (co->use_set && r->set != co->use_set - 1)
2490 /* packet counter */
2491 width = pr_u64(NULL, &cntr->pcnt, 0);
2492 if (width > pcwidth)
2496 width = pr_u64(NULL, &cntr->bcnt, 0);
2497 if (width > bcwidth)
2501 fo->bcwidth = bcwidth;
2502 fo->pcwidth = pcwidth;
2505 if (co->do_dynamic && dynsz > 0)
2506 foreach_state(co, fo, dynbase, dynsz, prepare_format_dyn, NULL);
2510 list_static_range(struct cmdline_opts *co, struct format_opts *fo,
2511 struct buf_pr *bp, ipfw_obj_tlv *rtlv, int rcnt)
2514 struct ip_fw_rule *r;
2515 struct ip_fw_bcounter *cntr;
2518 for (n = seen = 0; n < rcnt; n++,
2519 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2521 if ((fo->show_counters | fo->show_time) != 0) {
2522 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2523 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2526 r = (struct ip_fw_rule *)(rtlv + 1);
2528 if (r->rulenum > fo->last)
2530 if (co->use_set && r->set != co->use_set - 1)
2532 if (r->rulenum >= fo->first && r->rulenum <= fo->last) {
2533 show_static_rule(co, fo, bp, r, cntr);
2534 printf("%s", bp->buf);
2545 list_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2546 void *_arg, void *_state)
2553 d = (ipfw_dyn_rule *)_state;
2554 bp = (struct buf_pr *)_arg;
2556 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2557 if (rulenum > fo->last)
2560 bcopy((char *)&d->rule + sizeof(uint16_t),
2561 &set, sizeof(uint8_t));
2562 if (set != co->use_set - 1)
2565 if (rulenum >= fo->first) {
2566 show_dyn_state(co, fo, bp, d);
2567 printf("%s\n", bp->buf);
2573 list_dyn_range(struct cmdline_opts *co, struct format_opts *fo,
2574 struct buf_pr *bp, caddr_t base, size_t sz)
2577 sz = foreach_state(co, fo, base, sz, list_dyn_state, bp);
2582 ipfw_list(int ac, char *av[], int show_counters)
2584 ipfw_cfg_lheader *cfg;
2585 struct format_opts sfo;
2594 fprintf(stderr, "Testing only, list disabled\n");
2598 dummynet_list(ac, av, show_counters);
2604 memset(&sfo, 0, sizeof(sfo));
2606 /* Determine rule range to request */
2608 for (lac = ac, lav = av; lac != 0; lac--) {
2609 rnum = strtoul(*lav++, &endptr, 10);
2610 if (sfo.first == 0 || rnum < sfo.first)
2614 rnum = strtoul(endptr + 1, &endptr, 10);
2615 if (sfo.last == 0 || rnum > sfo.last)
2620 /* get configuraion from kernel */
2622 sfo.show_counters = show_counters;
2623 sfo.show_time = co.do_time;
2624 sfo.flags = IPFW_CFG_GET_STATIC;
2625 if (co.do_dynamic != 0)
2626 sfo.flags |= IPFW_CFG_GET_STATES;
2627 if ((sfo.show_counters | sfo.show_time) != 0)
2628 sfo.flags |= IPFW_CFG_GET_COUNTERS;
2629 if (ipfw_get_config(&co, &sfo, &cfg, &sz) != 0)
2630 err(EX_OSERR, "retrieving config failed");
2632 error = ipfw_show_config(&co, &sfo, cfg, sz, ac, av);
2641 ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
2642 ipfw_cfg_lheader *cfg, size_t sz, int ac, char *av[])
2647 int exitval = EX_OK;
2653 ipfw_obj_ctlv *ctlv, *tstate;
2654 ipfw_obj_tlv *rbase;
2657 * Handle tablenames TLV first, if any
2663 readsz = sizeof(*cfg);
2666 fo->set_mask = cfg->set_mask;
2668 ctlv = (ipfw_obj_ctlv *)(cfg + 1);
2670 if (cfg->flags & IPFW_CFG_GET_STATIC) {
2671 /* We've requested static rules */
2672 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2673 object_sort_ctlv(ctlv);
2675 readsz += ctlv->head.length;
2676 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2680 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2681 rbase = (ipfw_obj_tlv *)(ctlv + 1);
2683 readsz += ctlv->head.length;
2684 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2689 if ((cfg->flags & IPFW_CFG_GET_STATES) && (readsz != sz)) {
2690 /* We may have some dynamic states */
2691 dynsz = sz - readsz;
2692 /* Skip empty header */
2693 if (dynsz != sizeof(ipfw_obj_ctlv))
2694 dynbase = (caddr_t)ctlv;
2699 prepare_format_opts(co, fo, rbase, rcnt, dynbase, dynsz);
2700 bp_alloc(&bp, 4096);
2702 /* if no rule numbers were specified, list all rules */
2705 fo->last = IPFW_DEFAULT_RULE;
2706 list_static_range(co, fo, &bp, rbase, rcnt);
2708 if (co->do_dynamic && dynsz > 0) {
2709 printf("## Dynamic rules (%d %zu):\n", fo->dcnt, dynsz);
2710 list_dyn_range(co, fo, &bp, dynbase, dynsz);
2717 /* display specific rules requested on command line */
2718 for (lac = ac, lav = av; lac != 0; lac--) {
2719 /* convert command line rule # */
2720 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2722 fo->last = strtoul(endptr + 1, &endptr, 10);
2725 warnx("invalid rule number: %s", *(lav - 1));
2729 if (list_static_range(co, fo, &bp, rbase, rcnt) == 0) {
2730 /* give precedence to other error(s) */
2731 if (exitval == EX_OK)
2732 exitval = EX_UNAVAILABLE;
2733 if (fo->first == fo->last)
2734 warnx("rule %u does not exist", fo->first);
2736 warnx("no rules in range %u-%u",
2737 fo->first, fo->last);
2741 if (co->do_dynamic && dynsz > 0) {
2742 printf("## Dynamic rules:\n");
2743 for (lac = ac, lav = av; lac != 0; lac--) {
2744 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2746 fo->last = strtoul(endptr+1, &endptr, 10);
2748 /* already warned */
2750 list_dyn_range(co, fo, &bp, dynbase, dynsz);
2760 * Retrieves current ipfw configuration of given type
2761 * and stores its pointer to @pcfg.
2763 * Caller is responsible for freeing @pcfg.
2765 * Returns 0 on success.
2769 ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
2770 ipfw_cfg_lheader **pcfg, size_t *psize)
2772 ipfw_cfg_lheader *cfg;
2777 if (co->test_only != 0) {
2778 fprintf(stderr, "Testing only, list disabled\n");
2782 /* Start with some data size */
2786 for (i = 0; i < 16; i++) {
2789 if ((cfg = calloc(1, sz)) == NULL)
2792 cfg->flags = fo->flags;
2793 cfg->start_rule = fo->first;
2794 cfg->end_rule = fo->last;
2796 if (do_get3(IP_FW_XGET, &cfg->opheader, &sz) != 0) {
2797 if (errno != ENOMEM) {
2802 /* Buffer size is not enough. Try to increase */
2819 lookup_host (char *host, struct in_addr *ipaddr)
2823 if (!inet_aton(host, ipaddr)) {
2824 if ((he = gethostbyname(host)) == NULL)
2826 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2840 ipfw_check_object_name(const char *name)
2845 * Check that name is null-terminated and contains
2846 * valid symbols only. Valid mask is:
2847 * [a-zA-Z0-9\-_\.]{1,63}
2850 if (l == 0 || l >= 64)
2852 for (i = 0; i < l; i++) {
2854 if (isalpha(c) || isdigit(c) || c == '_' ||
2855 c == '-' || c == '.')
2862 static char *default_state_name = "default";
2864 state_check_name(const char *name)
2867 if (ipfw_check_object_name(name) != 0)
2869 if (strcmp(name, "any") == 0)
2875 eaction_check_name(const char *name)
2878 if (ipfw_check_object_name(name) != 0)
2880 /* Restrict some 'special' names */
2881 if (match_token(rule_actions, name) != -1 &&
2882 match_token(rule_action_params, name) != -1)
2888 pack_object(struct tidx *tstate, char *name, int otype)
2891 ipfw_obj_ntlv *ntlv;
2893 for (i = 0; i < tstate->count; i++) {
2894 if (strcmp(tstate->idx[i].name, name) != 0)
2896 if (tstate->idx[i].set != tstate->set)
2898 if (tstate->idx[i].head.type != otype)
2901 return (tstate->idx[i].idx);
2904 if (tstate->count + 1 > tstate->size) {
2906 tstate->idx = realloc(tstate->idx, tstate->size *
2907 sizeof(ipfw_obj_ntlv));
2908 if (tstate->idx == NULL)
2912 ntlv = &tstate->idx[i];
2913 memset(ntlv, 0, sizeof(ipfw_obj_ntlv));
2914 strlcpy(ntlv->name, name, sizeof(ntlv->name));
2915 ntlv->head.type = otype;
2916 ntlv->head.length = sizeof(ipfw_obj_ntlv);
2917 ntlv->set = tstate->set;
2918 ntlv->idx = ++tstate->counter;
2925 pack_table(struct tidx *tstate, char *name)
2928 if (table_check_name(name) != 0)
2931 return (pack_object(tstate, name, IPFW_TLV_TBL_NAME));
2935 fill_table(struct _ipfw_insn *cmd, char *av, uint8_t opcode,
2936 struct tidx *tstate)
2938 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2942 if ((p = strchr(av + 6, ')')) == NULL)
2943 errx(EX_DATAERR, "forgotten parenthesis: '%s'", av);
2945 p = strchr(av + 6, ',');
2949 if ((uidx = pack_table(tstate, av + 6)) == 0)
2950 errx(EX_DATAERR, "Invalid table name: %s", av + 6);
2952 cmd->opcode = opcode;
2955 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
2956 d[0] = strtoul(p, NULL, 0);
2958 cmd->len |= F_INSN_SIZE(ipfw_insn);
2963 * fills the addr and mask fields in the instruction as appropriate from av.
2964 * Update length as appropriate.
2965 * The following formats are allowed:
2966 * me returns O_IP_*_ME
2967 * 1.2.3.4 single IP address
2968 * 1.2.3.4:5.6.7.8 address:mask
2969 * 1.2.3.4/24 address/mask
2970 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
2971 * We can have multiple comma-separated address/mask entries.
2974 fill_ip(ipfw_insn_ip *cmd, char *av, int cblen, struct tidx *tstate)
2977 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2979 cmd->o.len &= ~F_LEN_MASK; /* zero len */
2981 if (_substrcmp(av, "any") == 0)
2984 if (_substrcmp(av, "me") == 0) {
2985 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2989 if (strncmp(av, "table(", 6) == 0) {
2990 fill_table(&cmd->o, av, O_IP_DST_LOOKUP, tstate);
2996 * After the address we can have '/' or ':' indicating a mask,
2997 * ',' indicating another address follows, '{' indicating a
2998 * set of addresses of unspecified size.
3000 char *t = NULL, *p = strpbrk(av, "/:,{");
3004 CHECK_LENGTH(cblen, F_INSN_SIZE(ipfw_insn) + 2 + len);
3009 if ((t = strpbrk(p, ",{")) != NULL) {
3016 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
3017 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
3020 if (!inet_aton(p, (struct in_addr *)&d[1]))
3021 errx(EX_DATAERR, "bad netmask ``%s''", p);
3026 d[1] = htonl(0U); /* mask */
3027 else if (masklen > 32)
3028 errx(EX_DATAERR, "bad width ``%s''", p);
3030 d[1] = htonl(~0U << (32 - masklen));
3032 case '{': /* no mask, assume /24 and put back the '{' */
3033 d[1] = htonl(~0U << (32 - 24));
3037 case ',': /* single address plus continuation */
3040 case 0: /* initialization value */
3042 d[1] = htonl(~0U); /* force /32 */
3045 d[0] &= d[1]; /* mask base address with mask */
3048 /* find next separator */
3050 p = strpbrk(p, ",{");
3051 if (p && *p == '{') {
3053 * We have a set of addresses. They are stored as follows:
3054 * arg1 is the set size (powers of 2, 2..256)
3055 * addr is the base address IN HOST FORMAT
3056 * mask.. is an array of arg1 bits (rounded up to
3057 * the next multiple of 32) with bits set
3058 * for each host in the map.
3060 uint32_t *map = (uint32_t *)&cmd->mask;
3062 int i = contigmask((uint8_t *)&(d[1]), 32);
3065 errx(EX_DATAERR, "address set cannot be in a list");
3066 if (i < 24 || i > 31)
3067 errx(EX_DATAERR, "invalid set with mask %d\n", i);
3068 cmd->o.arg1 = 1<<(32-i); /* map length */
3069 d[0] = ntohl(d[0]); /* base addr in host format */
3070 cmd->o.opcode = O_IP_DST_SET; /* default */
3071 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
3072 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
3073 map[i] = 0; /* clear map */
3077 high = low + cmd->o.arg1 - 1;
3079 * Here, i stores the previous value when we specify a range
3080 * of addresses within a mask, e.g. 45-63. i = -1 means we
3081 * have no previous value.
3083 i = -1; /* previous value in a range */
3084 while (isdigit(*av)) {
3086 int a = strtol(av, &s, 0);
3088 if (s == av) { /* no parameter */
3090 errx(EX_DATAERR, "set not closed\n");
3092 errx(EX_DATAERR, "incomplete range %d-", i);
3095 if (a < low || a > high)
3096 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
3099 if (i == -1) /* no previous in range */
3101 else { /* check that range is valid */
3103 errx(EX_DATAERR, "invalid range %d-%d",
3106 errx(EX_DATAERR, "double '-' in range");
3109 map[i/32] |= 1<<(i & 31);
3120 if (av) /* then *av must be a ',' */
3123 /* Check this entry */
3124 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
3126 * 'any' turns the entire list into a NOP.
3127 * 'not any' never matches, so it is removed from the
3128 * list unless it is the only item, in which case we
3131 if (cmd->o.len & F_NOT) { /* "not any" never matches */
3132 if (av == NULL && len == 0) /* only this entry */
3133 errx(EX_DATAERR, "not any never matches");
3135 /* else do nothing and skip this entry */
3138 /* A single IP can be stored in an optimized format */
3139 if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
3140 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
3143 len += 2; /* two words... */
3146 if (len + 1 > F_LEN_MASK)
3147 errx(EX_DATAERR, "address list too long");
3148 cmd->o.len |= len+1;
3152 /* n2mask sets n bits of the mask */
3154 n2mask(struct in6_addr *mask, int n)
3156 static int minimask[9] =
3157 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
3160 memset(mask, 0, sizeof(struct in6_addr));
3161 p = (u_char *) mask;
3162 for (; n > 0; p++, n -= 8) {
3172 fill_flags_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3173 struct _s_x *flags, char *p)
3176 uint32_t set = 0, clear = 0;
3178 if (fill_flags(flags, p, &e, &set, &clear) != 0)
3179 errx(EX_DATAERR, "invalid flag %s", e);
3181 cmd->opcode = opcode;
3182 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
3183 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3188 ipfw_delete(char *av[])
3191 int exitval = EX_OK;
3197 NEED1("missing rule specification");
3198 memset(&rt, 0, sizeof(rt));
3199 if ( *av && _substrcmp(*av, "set") == 0) {
3200 /* Do not allow using the following syntax:
3201 * ipfw set N delete set M
3204 errx(EX_DATAERR, "invalid syntax");
3205 do_set = 1; /* delete set */
3210 while (*av && isdigit(**av)) {
3211 i = strtol(*av, &sep, 10);
3214 j = strtol(sep + 1, NULL, 10);
3217 exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
3219 exitval = EX_UNAVAILABLE;
3220 warn("rule %u not available", i);
3222 } else if (co.do_pipe) {
3223 exitval = ipfw_delete_pipe(co.do_pipe, i);
3227 rt.flags = IPFW_RCFLAG_SET;
3229 rt.start_rule = i & 0xffff;
3230 rt.end_rule = j & 0xffff;
3231 if (rt.start_rule == 0 && rt.end_rule == 0)
3232 rt.flags |= IPFW_RCFLAG_ALL;
3234 rt.flags |= IPFW_RCFLAG_RANGE;
3235 if (co.use_set != 0) {
3236 rt.set = co.use_set - 1;
3237 rt.flags |= IPFW_RCFLAG_SET;
3240 i = do_range_cmd(IP_FW_XDEL, &rt);
3242 exitval = EX_UNAVAILABLE;
3243 warn("rule %u: setsockopt(IP_FW_XDEL)",
3245 } else if (rt.new_set == 0 && do_set == 0) {
3246 exitval = EX_UNAVAILABLE;
3247 if (rt.start_rule != rt.end_rule)
3248 warnx("no rules rules in %u-%u range",
3249 rt.start_rule, rt.end_rule);
3251 warnx("rule %u not found",
3256 if (exitval != EX_OK)
3262 * fill the interface structure. We do not check the name as we can
3263 * create interfaces dynamically, so checking them at insert time
3264 * makes relatively little sense.
3265 * Interface names containing '*', '?', or '[' are assumed to be shell
3266 * patterns which match interfaces.
3269 fill_iface(ipfw_insn_if *cmd, char *arg, int cblen, struct tidx *tstate)
3274 cmd->name[0] = '\0';
3275 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3279 /* Parse the interface or address */
3280 if (strcmp(arg, "any") == 0)
3281 cmd->o.len = 0; /* effectively ignore this command */
3282 else if (strncmp(arg, "table(", 6) == 0) {
3283 if ((p = strchr(arg + 6, ')')) == NULL)
3284 errx(EX_DATAERR, "forgotten parenthesis: '%s'", arg);
3286 p = strchr(arg + 6, ',');
3289 if ((uidx = pack_table(tstate, arg + 6)) == 0)
3290 errx(EX_DATAERR, "Invalid table name: %s", arg + 6);
3292 cmd->name[0] = '\1'; /* Special value indicating table */
3294 } else if (!isdigit(*arg)) {
3295 strlcpy(cmd->name, arg, sizeof(cmd->name));
3296 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3297 } else if (!inet_aton(arg, &cmd->p.ip))
3298 errx(EX_DATAERR, "bad ip address ``%s''", arg);
3302 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
3306 char *ap, *ptr, *optr;
3307 struct ether_addr *mac;
3308 const char *macset = "0123456789abcdefABCDEF:";
3310 if (strcmp(p, "any") == 0) {
3311 for (i = 0; i < ETHER_ADDR_LEN; i++)
3312 addr[i] = mask[i] = 0;
3316 optr = ptr = strdup(p);
3317 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
3319 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
3320 errx(EX_DATAERR, "Incorrect MAC address");
3321 bcopy(mac, addr, ETHER_ADDR_LEN);
3323 errx(EX_DATAERR, "Incorrect MAC address");
3325 if (ptr != NULL) { /* we have mask? */
3326 if (p[ptr - optr - 1] == '/') { /* mask len */
3327 long ml = strtol(ptr, &ap, 10);
3328 if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
3329 errx(EX_DATAERR, "Incorrect mask length");
3330 for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
3331 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
3334 if (strspn(ptr, macset) != l ||
3335 (mac = ether_aton(ptr)) == NULL)
3336 errx(EX_DATAERR, "Incorrect mask");
3337 bcopy(mac, mask, ETHER_ADDR_LEN);
3339 } else { /* default mask: ff:ff:ff:ff:ff:ff */
3340 for (i = 0; i < ETHER_ADDR_LEN; i++)
3343 for (i = 0; i < ETHER_ADDR_LEN; i++)
3350 * helper function, updates the pointer to cmd with the length
3351 * of the current command, and also cleans up the first word of
3352 * the new command in case it has been clobbered before.
3355 next_cmd(ipfw_insn *cmd, int *len)
3358 CHECK_LENGTH(*len, 0);
3360 bzero(cmd, sizeof(*cmd));
3365 * Takes arguments and copies them into a comment
3368 fill_comment(ipfw_insn *cmd, char **av, int cblen)
3371 char *p = (char *)(cmd + 1);
3373 cmd->opcode = O_NOP;
3374 cmd->len = (cmd->len & (F_NOT | F_OR));
3376 /* Compute length of comment string. */
3377 for (i = 0, l = 0; av[i] != NULL; i++)
3378 l += strlen(av[i]) + 1;
3383 "comment too long (max 80 chars)");
3385 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
3388 for (i = 0; av[i] != NULL; i++) {
3397 * A function to fill simple commands of size 1.
3398 * Existing flags are preserved.
3401 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3403 cmd->opcode = opcode;
3404 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3409 * Fetch and add the MAC address and type, with masks. This generates one or
3410 * two microinstructions, and returns the pointer to the last one.
3413 add_mac(ipfw_insn *cmd, char *av[], int cblen)
3417 if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
3418 errx(EX_DATAERR, "MAC dst src");
3420 cmd->opcode = O_MACADDR2;
3421 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3424 mac = (ipfw_insn_mac *)cmd;
3425 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
3426 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
3427 &(mac->mask[ETHER_ADDR_LEN])); /* src */
3432 add_mactype(ipfw_insn *cmd, char *av, int cblen)
3435 errx(EX_DATAERR, "missing MAC type");
3436 if (strcmp(av, "any") != 0) { /* we have a non-null type */
3437 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
3439 cmd->opcode = O_MAC_TYPE;
3446 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
3448 struct protoent *pe;
3452 proto = strtol(av, &ep, 10);
3453 if (*ep != '\0' || proto <= 0) {
3454 if ((pe = getprotobyname(av)) == NULL)
3456 proto = pe->p_proto;
3459 fill_cmd(cmd, O_PROTO, 0, proto);
3465 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
3467 u_char proto = IPPROTO_IP;
3469 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3470 ; /* do not set O_IP4 nor O_IP6 */
3471 else if (strcmp(av, "ip4") == 0)
3472 /* explicit "just IPv4" rule */
3473 fill_cmd(cmd, O_IP4, 0, 0);
3474 else if (strcmp(av, "ip6") == 0) {
3475 /* explicit "just IPv6" rule */
3476 proto = IPPROTO_IPV6;
3477 fill_cmd(cmd, O_IP6, 0, 0);
3479 return add_proto0(cmd, av, protop);
3486 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
3488 u_char proto = IPPROTO_IP;
3490 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3491 ; /* do not set O_IP4 nor O_IP6 */
3492 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3493 /* explicit "just IPv4" rule */
3494 fill_cmd(cmd, O_IP4, 0, 0);
3495 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3496 /* explicit "just IPv6" rule */
3497 proto = IPPROTO_IPV6;
3498 fill_cmd(cmd, O_IP6, 0, 0);
3500 return add_proto0(cmd, av, protop);
3507 add_srcip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3509 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3510 if (cmd->opcode == O_IP_DST_SET) /* set */
3511 cmd->opcode = O_IP_SRC_SET;
3512 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3513 cmd->opcode = O_IP_SRC_LOOKUP;
3514 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3515 cmd->opcode = O_IP_SRC_ME;
3516 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3517 cmd->opcode = O_IP_SRC;
3518 else /* addr/mask */
3519 cmd->opcode = O_IP_SRC_MASK;
3524 add_dstip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3526 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3527 if (cmd->opcode == O_IP_DST_SET) /* set */
3529 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3531 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3532 cmd->opcode = O_IP_DST_ME;
3533 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3534 cmd->opcode = O_IP_DST;
3535 else /* addr/mask */
3536 cmd->opcode = O_IP_DST_MASK;
3540 static struct _s_x f_reserved_keywords[] = {
3543 { "diverted", TOK_OR },
3544 { "dst-port", TOK_OR },
3545 { "src-port", TOK_OR },
3546 { "established", TOK_OR },
3547 { "keep-state", TOK_OR },
3549 { "icmptypes", TOK_OR },
3557 { NULL, 0 } /* terminator */
3561 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
3564 if (match_token(f_reserved_keywords, av) != -1)
3567 if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
3568 /* XXX todo: check that we have a protocol with ports */
3569 cmd->opcode = opcode;
3576 add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3579 char *host, *ch, buf[INET6_ADDRSTRLEN];
3580 ipfw_insn *ret = NULL;
3583 /* Copy first address in set if needed */
3584 if ((ch = strpbrk(av, "/,")) != NULL) {
3586 strlcpy(buf, av, sizeof(buf));
3587 if (len < sizeof(buf))
3593 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3594 inet_pton(AF_INET6, host, &a) == 1)
3595 ret = add_srcip6(cmd, av, cblen, tstate);
3596 /* XXX: should check for IPv4, not !IPv6 */
3597 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3598 inet_pton(AF_INET6, host, &a) != 1))
3599 ret = add_srcip(cmd, av, cblen, tstate);
3600 if (ret == NULL && strcmp(av, "any") != 0)
3607 add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3610 char *host, *ch, buf[INET6_ADDRSTRLEN];
3611 ipfw_insn *ret = NULL;
3614 /* Copy first address in set if needed */
3615 if ((ch = strpbrk(av, "/,")) != NULL) {
3617 strlcpy(buf, av, sizeof(buf));
3618 if (len < sizeof(buf))
3624 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3625 inet_pton(AF_INET6, host, &a) == 1)
3626 ret = add_dstip6(cmd, av, cblen, tstate);
3627 /* XXX: should check for IPv4, not !IPv6 */
3628 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3629 inet_pton(AF_INET6, host, &a) != 1))
3630 ret = add_dstip(cmd, av, cblen, tstate);
3631 if (ret == NULL && strcmp(av, "any") != 0)
3638 * Parse arguments and assemble the microinstructions which make up a rule.
3639 * Rules are added into the 'rulebuf' and then copied in the correct order
3640 * into the actual rule.
3642 * The syntax for a rule starts with the action, followed by
3643 * optional action parameters, and the various match patterns.
3644 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
3645 * (generated if the rule includes a keep-state option), then the
3646 * various match patterns, log/altq actions, and the actual action.
3650 compile_rule(char *av[], uint32_t *rbuf, int *rbufsize, struct tidx *tstate)
3653 * rules are added into the 'rulebuf' and then copied in
3654 * the correct order into the actual rule.
3655 * Some things that need to go out of order (prob, action etc.)
3658 static uint32_t actbuf[255], cmdbuf[255];
3659 int rblen, ablen, cblen;
3661 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
3662 ipfw_insn *first_cmd; /* first match pattern */
3664 struct ip_fw_rule *rule;
3667 * various flags used to record that we entered some fields.
3669 ipfw_insn *have_state = NULL; /* check-state or keep-state */
3670 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
3675 int open_par = 0; /* open parenthesis ( */
3677 /* proto is here because it is used to fetch ports */
3678 u_char proto = IPPROTO_IP; /* default protocol */
3680 double match_prob = 1; /* match probability, default is always match */
3682 bzero(actbuf, sizeof(actbuf)); /* actions go here */
3683 bzero(cmdbuf, sizeof(cmdbuf));
3684 bzero(rbuf, *rbufsize);
3686 rule = (struct ip_fw_rule *)rbuf;
3687 cmd = (ipfw_insn *)cmdbuf;
3688 action = (ipfw_insn *)actbuf;
3690 rblen = *rbufsize / sizeof(uint32_t);
3691 rblen -= sizeof(struct ip_fw_rule) / sizeof(uint32_t);
3692 ablen = sizeof(actbuf) / sizeof(actbuf[0]);
3693 cblen = sizeof(cmdbuf) / sizeof(cmdbuf[0]);
3694 cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
3696 #define CHECK_RBUFLEN(len) { CHECK_LENGTH(rblen, len); rblen -= len; }
3697 #define CHECK_ACTLEN CHECK_LENGTH(ablen, action->len)
3701 /* [rule N] -- Rule number optional */
3702 if (av[0] && isdigit(**av)) {
3703 rule->rulenum = atoi(*av);
3707 /* [set N] -- set number (0..RESVD_SET), optional */
3708 if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
3709 int set = strtoul(av[1], NULL, 10);
3710 if (set < 0 || set > RESVD_SET)
3711 errx(EX_DATAERR, "illegal set %s", av[1]);
3717 /* [prob D] -- match probability, optional */
3718 if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
3719 match_prob = strtod(av[1], NULL);
3721 if (match_prob <= 0 || match_prob > 1)
3722 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
3726 /* action -- mandatory */
3727 NEED1("missing action");
3728 i = match_token(rule_actions, *av);
3730 action->len = 1; /* default */
3733 case TOK_CHECKSTATE:
3734 have_state = action;
3735 action->opcode = O_CHECK_STATE;
3737 match_token(rule_options, *av) == TOK_COMMENT) {
3738 action->arg1 = pack_object(tstate,
3739 default_state_name, IPFW_TLV_STATE_NAME);
3742 if (*av[0] == ':') {
3743 if (strcmp(*av + 1, "any") == 0)
3745 else if (state_check_name(*av + 1) == 0)
3746 action->arg1 = pack_object(tstate, *av + 1,
3747 IPFW_TLV_STATE_NAME);
3749 errx(EX_DATAERR, "Invalid state name %s",
3754 errx(EX_DATAERR, "Invalid state name %s", *av);
3758 action->opcode = O_ACCEPT;
3762 action->opcode = O_DENY;
3767 action->opcode = O_REJECT;
3768 action->arg1 = ICMP_UNREACH_HOST;
3772 action->opcode = O_REJECT;
3773 action->arg1 = ICMP_REJECT_RST;
3777 action->opcode = O_UNREACH6;
3778 action->arg1 = ICMP6_UNREACH_RST;
3782 action->opcode = O_REJECT;
3783 NEED1("missing reject code");
3784 fill_reject_code(&action->arg1, *av);
3789 action->opcode = O_UNREACH6;
3790 NEED1("missing unreach code");
3791 fill_unreach6_code(&action->arg1, *av);
3796 action->opcode = O_COUNT;
3800 action->opcode = O_NAT;
3801 action->len = F_INSN_SIZE(ipfw_insn_nat);
3803 if (*av != NULL && _substrcmp(*av, "global") == 0) {
3804 action->arg1 = IP_FW_NAT44_GLOBAL;
3810 action->opcode = O_QUEUE;
3813 action->opcode = O_PIPE;
3816 action->opcode = O_SKIPTO;
3819 action->opcode = O_NETGRAPH;
3822 action->opcode = O_NGTEE;
3825 action->opcode = O_DIVERT;
3828 action->opcode = O_TEE;
3831 action->opcode = O_CALLRETURN;
3834 errx(EX_USAGE, "missing argument for %s", *(av - 1));
3835 if (isdigit(**av)) {
3836 action->arg1 = strtoul(*av, NULL, 10);
3837 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
3838 errx(EX_DATAERR, "illegal argument for %s",
3840 } else if (_substrcmp(*av, "tablearg") == 0) {
3841 action->arg1 = IP_FW_TARG;
3842 } else if (i == TOK_DIVERT || i == TOK_TEE) {
3845 s = getservbyname(av[0], "divert");
3847 action->arg1 = ntohs(s->s_port);
3849 errx(EX_DATAERR, "illegal divert/tee port");
3851 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
3857 * Locate the address-port separator (':' or ',').
3858 * Could be one of the following:
3862 * IPv6 w:x:y::z,port
3863 * The ':' can only be used with hostname and IPv4 address.
3864 * XXX-BZ Should we also support [w:x:y::z]:port?
3866 struct sockaddr_storage result;
3867 struct addrinfo *res;
3870 u_short port_number;
3872 NEED1("missing forward address[:port]");
3875 * locate the address-port separator (':' or ',')
3877 s = strchr(*av, ',');
3879 /* Distinguish between IPv4:port and IPv6 cases. */
3880 s = strchr(*av, ':');
3881 if (s && strchr(s+1, ':'))
3882 s = NULL; /* no port */
3887 /* Terminate host portion and set s to start of port. */
3889 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
3892 "illegal forwarding port ``%s''", s);
3893 port_number = (u_short)i;
3896 if (_substrcmp(*av, "tablearg") == 0) {
3898 ((struct sockaddr_in*)&result)->sin_addr.s_addr =
3902 * Resolve the host name or address to a family and a
3903 * network representation of the address.
3905 if (getaddrinfo(*av, NULL, NULL, &res))
3906 errx(EX_DATAERR, NULL);
3907 /* Just use the first host in the answer. */
3908 family = res->ai_family;
3909 memcpy(&result, res->ai_addr, res->ai_addrlen);
3913 if (family == PF_INET) {
3914 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
3916 action->opcode = O_FORWARD_IP;
3917 action->len = F_INSN_SIZE(ipfw_insn_sa);
3921 * In the kernel we assume AF_INET and use only
3922 * sin_port and sin_addr. Remember to set sin_len as
3923 * the routing code seems to use it too.
3925 p->sa.sin_len = sizeof(struct sockaddr_in);
3926 p->sa.sin_family = AF_INET;
3927 p->sa.sin_port = port_number;
3928 p->sa.sin_addr.s_addr =
3929 ((struct sockaddr_in *)&result)->sin_addr.s_addr;
3930 } else if (family == PF_INET6) {
3931 ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
3933 action->opcode = O_FORWARD_IP6;
3934 action->len = F_INSN_SIZE(ipfw_insn_sa6);
3937 p->sa.sin6_len = sizeof(struct sockaddr_in6);
3938 p->sa.sin6_family = AF_INET6;
3939 p->sa.sin6_port = port_number;
3940 p->sa.sin6_flowinfo = 0;
3941 p->sa.sin6_scope_id =
3942 ((struct sockaddr_in6 *)&result)->sin6_scope_id;
3943 bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
3944 &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
3946 errx(EX_DATAERR, "Invalid address family in forward action");
3952 /* pretend it is a 'count' rule followed by the comment */
3953 action->opcode = O_COUNT;
3954 av--; /* go back... */
3960 size_t intsize = sizeof(int);
3962 action->opcode = O_SETFIB;
3963 NEED1("missing fib number");
3964 if (_substrcmp(*av, "tablearg") == 0) {
3965 action->arg1 = IP_FW_TARG;
3967 action->arg1 = strtoul(*av, NULL, 10);
3968 if (sysctlbyname("net.fibs", &numfibs, &intsize,
3970 errx(EX_DATAERR, "fibs not suported.\n");
3971 if (action->arg1 >= numfibs) /* Temporary */
3972 errx(EX_DATAERR, "fib too large.\n");
3973 /* Add high-order bit to fib to make room for tablearg*/
3974 action->arg1 |= 0x8000;
3984 action->opcode = O_SETDSCP;
3985 NEED1("missing DSCP code");
3986 if (_substrcmp(*av, "tablearg") == 0) {
3987 action->arg1 = IP_FW_TARG;
3989 if (isalpha(*av[0])) {
3990 if ((code = match_token(f_ipdscp, *av)) == -1)
3991 errx(EX_DATAERR, "Unknown DSCP code");
3992 action->arg1 = code;
3994 action->arg1 = strtoul(*av, NULL, 10);
3996 * Add high-order bit to DSCP to make room
3999 action->arg1 |= 0x8000;
4006 action->opcode = O_REASS;
4010 fill_cmd(action, O_CALLRETURN, F_NOT, 0);
4013 case TOK_TCPSETMSS: {
4017 idx = pack_object(tstate, "tcp-setmss", IPFW_TLV_EACTION);
4019 errx(EX_DATAERR, "pack_object failed");
4020 fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4021 NEED1("Missing MSS value");
4022 action = next_cmd(action, &ablen);
4025 mss = strtoul(*av, NULL, 10);
4026 if (mss == 0 || mss > UINT16_MAX)
4027 errx(EX_USAGE, "invalid MSS value %s", *av);
4028 fill_cmd(action, O_EXTERNAL_DATA, 0, (uint16_t)mss);
4035 if (match_token(rule_eactions, *av) == -1)
4036 errx(EX_DATAERR, "invalid action %s\n", *av);
4038 * External actions support.
4039 * XXX: we support only syntax with instance name.
4040 * For known external actions (from rule_eactions list)
4041 * we can handle syntax directly. But with `eaction'
4042 * keyword we can use only `eaction <name> <instance>'
4048 NEED1("Missing eaction name");
4049 if (eaction_check_name(*av) != 0)
4050 errx(EX_DATAERR, "Invalid eaction name %s", *av);
4051 idx = pack_object(tstate, *av, IPFW_TLV_EACTION);
4053 errx(EX_DATAERR, "pack_object failed");
4054 fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4056 NEED1("Missing eaction instance name");
4057 action = next_cmd(action, &ablen);
4060 if (eaction_check_name(*av) != 0)
4061 errx(EX_DATAERR, "Invalid eaction instance name %s",
4064 * External action instance object has TLV type depended
4065 * from the external action name object index. Since we
4066 * currently don't know this index, use zero as TLV type.
4068 idx = pack_object(tstate, *av, 0);
4070 errx(EX_DATAERR, "pack_object failed");
4071 fill_cmd(action, O_EXTERNAL_INSTANCE, 0, idx);
4075 action = next_cmd(action, &ablen);
4078 * [altq queuename] -- altq tag, optional
4079 * [log [logamount N]] -- log, optional
4081 * If they exist, it go first in the cmdbuf, but then it is
4082 * skipped in the copy section to the end of the buffer.
4084 while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
4089 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
4094 "log cannot be specified more than once");
4095 have_log = (ipfw_insn *)c;
4096 cmd->len = F_INSN_SIZE(ipfw_insn_log);
4098 cmd->opcode = O_LOG;
4099 if (av[0] && _substrcmp(*av, "logamount") == 0) {
4101 NEED1("logamount requires argument");
4105 "logamount must be positive");
4109 len = sizeof(c->max_log);
4110 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
4111 &c->max_log, &len, NULL, 0) == -1) {
4116 errx(1, "sysctlbyname(\"%s\")",
4117 "net.inet.ip.fw.verbose_limit");
4126 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
4128 NEED1("missing altq queue name");
4131 "altq cannot be specified more than once");
4132 have_altq = (ipfw_insn *)a;
4133 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
4135 cmd->opcode = O_ALTQ;
4136 a->qid = altq_name_to_qid(*av);
4147 errx(EX_USAGE, "tag and untag cannot be "
4148 "specified more than once");
4149 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
4150 rule_action_params);
4152 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
4160 cmd = next_cmd(cmd, &cblen);
4163 if (have_state) { /* must be a check-state, we are done */
4165 match_token(rule_options, *av) == TOK_COMMENT) {
4166 /* check-state has a comment */
4168 fill_comment(cmd, av, cblen);
4169 cmd = next_cmd(cmd, &cblen);
4175 #define OR_START(target) \
4176 if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
4178 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
4181 if ( (av[0])[1] == '\0') { \
4192 strcmp(*av, ")") == 0 || \
4193 strcmp(*av, "}") == 0)) { \
4198 errx(EX_USAGE, "missing \")\"\n"); \
4202 if (av[0] && _substrcmp(*av, "not") == 0) { \
4203 if (cmd->len & F_NOT) \
4204 errx(EX_USAGE, "double \"not\" not allowed\n"); \
4205 cmd->len |= F_NOT; \
4209 #define OR_BLOCK(target) \
4210 if (av[0] && _substrcmp(*av, "or") == 0) { \
4211 if (prev == NULL || open_par == 0) \
4212 errx(EX_DATAERR, "invalid OR block"); \
4213 prev->len |= F_OR; \
4223 * MAC addresses, optional.
4224 * If we have this, we skip the part "proto from src to dst"
4225 * and jump straight to the option parsing.
4228 NEED1("missing protocol");
4229 if (_substrcmp(*av, "MAC") == 0 ||
4230 _substrcmp(*av, "mac") == 0) {
4231 av++; /* the "MAC" keyword */
4232 add_mac(cmd, av); /* exits in case of errors */
4233 cmd = next_cmd(cmd);
4234 av += 2; /* dst-mac and src-mac */
4236 NEED1("missing mac type");
4237 if (add_mactype(cmd, av[0]))
4238 cmd = next_cmd(cmd);
4239 av++; /* any or mac-type */
4245 * protocol, mandatory
4247 OR_START(get_proto);
4249 NEED1("missing protocol");
4250 if (add_proto_compat(cmd, *av, &proto)) {
4252 if (F_LEN(cmd) != 0) {
4254 cmd = next_cmd(cmd, &cblen);
4256 } else if (first_cmd != cmd) {
4257 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
4260 OR_BLOCK(get_proto);
4265 if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
4266 errx(EX_USAGE, "missing ``from''");
4270 * source IP, mandatory
4272 OR_START(source_ip);
4273 NOT_BLOCK; /* optional "not" */
4274 NEED1("missing source address");
4275 if (add_src(cmd, *av, proto, cblen, tstate)) {
4277 if (F_LEN(cmd) != 0) { /* ! any */
4279 cmd = next_cmd(cmd, &cblen);
4282 errx(EX_USAGE, "bad source address %s", *av);
4283 OR_BLOCK(source_ip);
4286 * source ports, optional
4288 NOT_BLOCK; /* optional "not" */
4289 if ( av[0] != NULL ) {
4290 if (_substrcmp(*av, "any") == 0 ||
4291 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4293 if (F_LEN(cmd) != 0)
4294 cmd = next_cmd(cmd, &cblen);
4301 if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
4302 errx(EX_USAGE, "missing ``to''");
4306 * destination, mandatory
4309 NOT_BLOCK; /* optional "not" */
4310 NEED1("missing dst address");
4311 if (add_dst(cmd, *av, proto, cblen, tstate)) {
4313 if (F_LEN(cmd) != 0) { /* ! any */
4315 cmd = next_cmd(cmd, &cblen);
4318 errx( EX_USAGE, "bad destination address %s", *av);
4322 * dest. ports, optional
4324 NOT_BLOCK; /* optional "not" */
4326 if (_substrcmp(*av, "any") == 0 ||
4327 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4329 if (F_LEN(cmd) != 0)
4330 cmd = next_cmd(cmd, &cblen);
4335 if (av[0] && first_cmd == cmd) {
4337 * nothing specified so far, store in the rule to ease
4340 rule->flags |= IPFW_RULE_NOOPT;
4343 while ( av[0] != NULL ) {
4345 ipfw_insn_u32 *cmd32; /* alias for cmd */
4348 cmd32 = (ipfw_insn_u32 *)cmd;
4350 if (*s == '!') { /* alternate syntax for NOT */
4351 if (cmd->len & F_NOT)
4352 errx(EX_USAGE, "double \"not\" not allowed\n");
4356 i = match_token(rule_options, s);
4360 if (cmd->len & F_NOT)
4361 errx(EX_USAGE, "double \"not\" not allowed\n");
4366 if (open_par == 0 || prev == NULL)
4367 errx(EX_USAGE, "invalid \"or\" block\n");
4371 case TOK_STARTBRACE:
4373 errx(EX_USAGE, "+nested \"(\" not allowed\n");
4379 errx(EX_USAGE, "+missing \")\"\n");
4385 fill_cmd(cmd, O_IN, 0, 0);
4389 cmd->len ^= F_NOT; /* toggle F_NOT */
4390 fill_cmd(cmd, O_IN, 0, 0);
4394 fill_cmd(cmd, O_DIVERTED, 0, 3);
4397 case TOK_DIVERTEDLOOPBACK:
4398 fill_cmd(cmd, O_DIVERTED, 0, 1);
4401 case TOK_DIVERTEDOUTPUT:
4402 fill_cmd(cmd, O_DIVERTED, 0, 2);
4406 fill_cmd(cmd, O_FRAG, 0, 0);
4410 fill_cmd(cmd, O_LAYER2, 0, 0);
4416 NEED1("recv, xmit, via require interface name"
4418 fill_iface((ipfw_insn_if *)cmd, av[0], cblen, tstate);
4420 if (F_LEN(cmd) == 0) /* not a valid address */
4423 cmd->opcode = O_XMIT;
4424 else if (i == TOK_RECV)
4425 cmd->opcode = O_RECV;
4426 else if (i == TOK_VIA)
4427 cmd->opcode = O_VIA;
4431 NEED1("icmptypes requires list of types");
4432 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
4436 case TOK_ICMP6TYPES:
4437 NEED1("icmptypes requires list of types");
4438 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
4443 NEED1("ipttl requires TTL");
4444 if (strpbrk(*av, "-,")) {
4445 if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
4446 errx(EX_DATAERR, "invalid ipttl %s", *av);
4448 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
4453 NEED1("ipid requires id");
4454 if (strpbrk(*av, "-,")) {
4455 if (!add_ports(cmd, *av, 0, O_IPID, cblen))
4456 errx(EX_DATAERR, "invalid ipid %s", *av);
4458 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
4463 NEED1("iplen requires length");
4464 if (strpbrk(*av, "-,")) {
4465 if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
4466 errx(EX_DATAERR, "invalid ip len %s", *av);
4468 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
4473 NEED1("ipver requires version");
4474 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
4478 case TOK_IPPRECEDENCE:
4479 NEED1("ipprecedence requires value");
4480 fill_cmd(cmd, O_IPPRECEDENCE, 0,
4481 (strtoul(*av, NULL, 0) & 7) << 5);
4486 NEED1("missing DSCP code");
4487 fill_dscp(cmd, *av, cblen);
4492 NEED1("missing argument for ipoptions");
4493 fill_flags_cmd(cmd, O_IPOPT, f_ipopts, *av);
4498 NEED1("missing argument for iptos");
4499 fill_flags_cmd(cmd, O_IPTOS, f_iptos, *av);
4504 NEED1("uid requires argument");
4510 cmd->opcode = O_UID;
4511 uid = strtoul(*av, &end, 0);
4512 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
4514 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
4515 cmd32->d[0] = pwd->pw_uid;
4516 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4522 NEED1("gid requires argument");
4528 cmd->opcode = O_GID;
4529 gid = strtoul(*av, &end, 0);
4530 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
4532 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
4533 cmd32->d[0] = grp->gr_gid;
4534 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4540 NEED1("jail requires argument");
4545 cmd->opcode = O_JAIL;
4546 jid = (int)strtol(*av, &end, 0);
4547 if (jid < 0 || *end != '\0')
4548 errx(EX_DATAERR, "jail requires prison ID");
4549 cmd32->d[0] = (uint32_t)jid;
4550 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4556 fill_cmd(cmd, O_ESTAB, 0, 0);
4560 fill_cmd(cmd, O_TCPFLAGS, 0,
4561 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
4564 case TOK_TCPDATALEN:
4565 NEED1("tcpdatalen requires length");
4566 if (strpbrk(*av, "-,")) {
4567 if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
4568 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
4570 fill_cmd(cmd, O_TCPDATALEN, 0,
4571 strtoul(*av, NULL, 0));
4576 NEED1("missing argument for tcpoptions");
4577 fill_flags_cmd(cmd, O_TCPOPTS, f_tcpopts, *av);
4583 NEED1("tcpseq/tcpack requires argument");
4584 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
4585 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
4586 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
4591 NEED1("tcpwin requires length");
4592 if (strpbrk(*av, "-,")) {
4593 if (!add_ports(cmd, *av, 0, O_TCPWIN, cblen))
4594 errx(EX_DATAERR, "invalid tcpwin len %s", *av);
4596 fill_cmd(cmd, O_TCPWIN, 0,
4597 strtoul(*av, NULL, 0));
4602 NEED1("missing argument for tcpflags");
4603 cmd->opcode = O_TCPFLAGS;
4604 fill_flags_cmd(cmd, O_TCPFLAGS, f_tcpflags, *av);
4608 case TOK_KEEPSTATE: {
4612 errx(EX_USAGE, "keep-state cannot be part "
4615 errx(EX_USAGE, "only one of keep-state "
4616 "and limit is allowed");
4617 if (*av != NULL && *av[0] == ':') {
4618 if (state_check_name(*av + 1) != 0)
4620 "Invalid state name %s", *av);
4621 uidx = pack_object(tstate, *av + 1,
4622 IPFW_TLV_STATE_NAME);
4625 uidx = pack_object(tstate, default_state_name,
4626 IPFW_TLV_STATE_NAME);
4628 fill_cmd(cmd, O_KEEP_STATE, 0, uidx);
4633 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
4638 "limit cannot be part of an or block");
4640 errx(EX_USAGE, "only one of keep-state and "
4641 "limit is allowed");
4644 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
4646 cmd->opcode = O_LIMIT;
4647 c->limit_mask = c->conn_limit = 0;
4649 while ( av[0] != NULL ) {
4650 if ((val = match_token(limit_masks, *av)) <= 0)
4652 c->limit_mask |= val;
4656 if (c->limit_mask == 0)
4657 errx(EX_USAGE, "limit: missing limit mask");
4659 GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
4660 TOK_LIMIT, rule_options);
4663 if (*av != NULL && *av[0] == ':') {
4664 if (state_check_name(*av + 1) != 0)
4666 "Invalid state name %s", *av);
4667 cmd->arg1 = pack_object(tstate, *av + 1,
4668 IPFW_TLV_STATE_NAME);
4671 cmd->arg1 = pack_object(tstate,
4672 default_state_name, IPFW_TLV_STATE_NAME);
4677 NEED1("missing protocol");
4678 if (add_proto(cmd, *av, &proto)) {
4681 errx(EX_DATAERR, "invalid protocol ``%s''",
4686 NEED1("missing source IP");
4687 if (add_srcip(cmd, *av, cblen, tstate)) {
4693 NEED1("missing destination IP");
4694 if (add_dstip(cmd, *av, cblen, tstate)) {
4700 NEED1("missing source IP6");
4701 if (add_srcip6(cmd, *av, cblen, tstate)) {
4707 NEED1("missing destination IP6");
4708 if (add_dstip6(cmd, *av, cblen, tstate)) {
4714 NEED1("missing source port");
4715 if (_substrcmp(*av, "any") == 0 ||
4716 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4719 errx(EX_DATAERR, "invalid source port %s", *av);
4723 NEED1("missing destination port");
4724 if (_substrcmp(*av, "any") == 0 ||
4725 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4728 errx(EX_DATAERR, "invalid destination port %s",
4733 if (add_mac(cmd, av, cblen))
4738 NEED1("missing mac type");
4739 if (!add_mactype(cmd, *av, cblen))
4740 errx(EX_DATAERR, "invalid mac type %s", *av);
4744 case TOK_VERREVPATH:
4745 fill_cmd(cmd, O_VERREVPATH, 0, 0);
4748 case TOK_VERSRCREACH:
4749 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
4753 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
4757 fill_cmd(cmd, O_IPSEC, 0, 0);
4761 fill_cmd(cmd, O_IP6, 0, 0);
4765 fill_cmd(cmd, O_IP4, 0, 0);
4769 fill_ext6hdr( cmd, *av );
4774 if (proto != IPPROTO_IPV6 )
4775 errx( EX_USAGE, "flow-id filter is active "
4776 "only for ipv6 protocol\n");
4777 fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
4782 fill_comment(cmd, av, cblen);
4787 if (av[0] && strpbrk(*av, "-,")) {
4788 if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
4789 errx(EX_DATAERR, "tagged: invalid tag"
4795 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
4796 TOK_TAGGED, rule_options);
4797 fill_cmd(cmd, O_TAGGED, 0, tag);
4803 NEED1("fib requires fib number");
4804 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
4808 fill_cmd(cmd, O_SOCKARG, 0, 0);
4812 ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
4815 if (!av[0] || !av[1])
4816 errx(EX_USAGE, "format: lookup argument tablenum");
4817 cmd->opcode = O_IP_DST_LOOKUP;
4818 cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
4819 i = match_token(rule_options, *av);
4820 for (j = 0; lookup_key[j] >= 0 ; j++) {
4821 if (i == lookup_key[j])
4824 if (lookup_key[j] <= 0)
4825 errx(EX_USAGE, "format: cannot lookup on %s", *av);
4826 __PAST_END(c->d, 1) = j; // i converted to option
4829 if ((j = pack_table(tstate, *av)) == 0)
4830 errx(EX_DATAERR, "Invalid table name: %s", *av);
4837 NEED1("missing table name");
4838 if (strncmp(*av, "table(", 6) != 0)
4840 "enclose table name into \"table()\"");
4841 fill_table(cmd, *av, O_IP_FLOW_LOOKUP, tstate);
4846 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
4848 if (F_LEN(cmd) > 0) { /* prepare to advance */
4850 cmd = next_cmd(cmd, &cblen);
4856 * Now copy stuff into the rule.
4857 * If we have a keep-state option, the first instruction
4858 * must be a PROBE_STATE (which is generated here).
4859 * If we have a LOG option, it was stored as the first command,
4860 * and now must be moved to the top of the action part.
4862 dst = (ipfw_insn *)rule->cmd;
4865 * First thing to write into the command stream is the match probability.
4867 if (match_prob != 1) { /* 1 means always match */
4868 dst->opcode = O_PROB;
4870 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
4875 * generate O_PROBE_STATE if necessary
4877 if (have_state && have_state->opcode != O_CHECK_STATE) {
4878 fill_cmd(dst, O_PROBE_STATE, 0, have_state->arg1);
4879 dst = next_cmd(dst, &rblen);
4882 /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
4883 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
4887 switch (src->opcode) {
4895 bcopy(src, dst, i * sizeof(uint32_t));
4901 * put back the have_state command as last opcode
4903 if (have_state && have_state->opcode != O_CHECK_STATE) {
4904 i = F_LEN(have_state);
4906 bcopy(have_state, dst, i * sizeof(uint32_t));
4910 * start action section
4912 rule->act_ofs = dst - rule->cmd;
4914 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
4916 i = F_LEN(have_log);
4918 bcopy(have_log, dst, i * sizeof(uint32_t));
4922 i = F_LEN(have_altq);
4924 bcopy(have_altq, dst, i * sizeof(uint32_t));
4928 i = F_LEN(have_tag);
4930 bcopy(have_tag, dst, i * sizeof(uint32_t));
4935 * copy all other actions
4937 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
4940 bcopy(src, dst, i * sizeof(uint32_t));
4944 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
4945 *rbufsize = (char *)dst - (char *)rule;
4949 compare_ntlv(const void *_a, const void *_b)
4951 ipfw_obj_ntlv *a, *b;
4953 a = (ipfw_obj_ntlv *)_a;
4954 b = (ipfw_obj_ntlv *)_b;
4956 if (a->set < b->set)
4958 else if (a->set > b->set)
4961 if (a->idx < b->idx)
4963 else if (a->idx > b->idx)
4966 if (a->head.type < b->head.type)
4968 else if (a->head.type > b->head.type)
4975 * Provide kernel with sorted list of referenced objects
4978 object_sort_ctlv(ipfw_obj_ctlv *ctlv)
4981 qsort(ctlv + 1, ctlv->count, ctlv->objsize, compare_ntlv);
4989 compare_object_kntlv(const void *k, const void *v)
4991 ipfw_obj_ntlv *ntlv;
4992 struct object_kt key;
4994 key = *((struct object_kt *)k);
4995 ntlv = (ipfw_obj_ntlv *)v;
4997 if (key.uidx < ntlv->idx)
4999 else if (key.uidx > ntlv->idx)
5002 if (key.type < ntlv->head.type)
5004 else if (key.type > ntlv->head.type)
5011 * Finds object name in @ctlv by @idx and @type.
5012 * Uses the following facts:
5013 * 1) All TLVs are the same size
5014 * 2) Kernel implementation provides already sorted list.
5016 * Returns table name or NULL.
5019 object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx, uint16_t type)
5021 ipfw_obj_ntlv *ntlv;
5022 struct object_kt key;
5027 ntlv = bsearch(&key, (ctlv + 1), ctlv->count, ctlv->objsize,
5028 compare_object_kntlv);
5031 return (ntlv->name);
5037 table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx)
5040 return (object_search_ctlv(ctlv, idx, IPFW_TLV_TBL_NAME));
5044 * Adds one or more rules to ipfw chain.
5049 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
5050 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ] (*2) (*3)
5055 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
5056 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ]
5059 * Rules in reply are modified to store their actual ruleset number.
5061 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
5062 * according to their idx field and there has to be no duplicates.
5063 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
5064 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
5067 ipfw_add(char *av[])
5069 uint32_t rulebuf[1024];
5070 int rbufsize, default_off, tlen, rlen;
5073 struct ip_fw_rule *rule;
5075 ip_fw3_opheader *op3;
5076 ipfw_obj_ctlv *ctlv, *tstate;
5078 rbufsize = sizeof(rulebuf);
5079 memset(rulebuf, 0, rbufsize);
5080 memset(&ts, 0, sizeof(ts));
5082 /* Optimize case with no tables */
5083 default_off = sizeof(ipfw_obj_ctlv) + sizeof(ip_fw3_opheader);
5084 op3 = (ip_fw3_opheader *)rulebuf;
5085 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5086 rule = (struct ip_fw_rule *)(ctlv + 1);
5087 rbufsize -= default_off;
5089 compile_rule(av, (uint32_t *)rule, &rbufsize, &ts);
5090 /* Align rule size to u64 boundary */
5091 rlen = roundup2(rbufsize, sizeof(uint64_t));
5096 if (ts.count != 0) {
5097 /* Some tables. We have to alloc more data */
5098 tlen = ts.count * sizeof(ipfw_obj_ntlv);
5099 sz = default_off + sizeof(ipfw_obj_ctlv) + tlen + rlen;
5101 if ((tbuf = calloc(1, sz)) == NULL)
5102 err(EX_UNAVAILABLE, "malloc() failed for IP_FW_ADD");
5103 op3 = (ip_fw3_opheader *)tbuf;
5105 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5106 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
5107 ctlv->head.length = sizeof(ipfw_obj_ctlv) + tlen;
5108 ctlv->count = ts.count;
5109 ctlv->objsize = sizeof(ipfw_obj_ntlv);
5110 memcpy(ctlv + 1, ts.idx, tlen);
5111 object_sort_ctlv(ctlv);
5114 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
5115 ctlv->head.type = IPFW_TLV_RULE_LIST;
5116 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5118 memcpy(ctlv + 1, rule, rbufsize);
5120 /* Simply add header */
5121 sz = rlen + default_off;
5122 memset(ctlv, 0, sizeof(*ctlv));
5123 ctlv->head.type = IPFW_TLV_RULE_LIST;
5124 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5128 if (do_get3(IP_FW_XADD, op3, &sz) != 0)
5129 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_XADD");
5132 struct format_opts sfo;
5134 memset(&sfo, 0, sizeof(sfo));
5135 sfo.tstate = tstate;
5136 sfo.set_mask = (uint32_t)(-1);
5137 bp_alloc(&bp, 4096);
5138 show_static_rule(&co, &sfo, &bp, rule, NULL);
5139 printf("%s", bp.buf);
5151 * clear the counters or the log counters.
5152 * optname has the following values:
5153 * 0 (zero both counters and logging)
5154 * 1 (zero logging only)
5157 ipfw_zero(int ac, char *av[], int optname)
5163 char const *name = optname ? "RESETLOG" : "ZERO";
5165 optname = optname ? IP_FW_XRESETLOG : IP_FW_XZERO;
5166 memset(&rt, 0, sizeof(rt));
5171 /* clear all entries */
5172 rt.flags = IPFW_RCFLAG_ALL;
5173 if (do_range_cmd(optname, &rt) < 0)
5174 err(EX_UNAVAILABLE, "setsockopt(IP_FW_X%s)", name);
5176 printf("%s.\n", optname == IP_FW_XZERO ?
5177 "Accounting cleared":"Logging counts reset");
5184 if (isdigit(**av)) {
5185 arg = strtonum(*av, 0, 0xffff, &errstr);
5188 "invalid rule number %s\n", *av);
5189 rt.start_rule = arg;
5191 rt.flags |= IPFW_RCFLAG_RANGE;
5192 if (co.use_set != 0) {
5193 rt.set = co.use_set - 1;
5194 rt.flags |= IPFW_RCFLAG_SET;
5196 if (do_range_cmd(optname, &rt) != 0) {
5197 warn("rule %u: setsockopt(IP_FW_X%s)",
5199 failed = EX_UNAVAILABLE;
5200 } else if (rt.new_set == 0) {
5201 printf("Entry %d not found\n", arg);
5202 failed = EX_UNAVAILABLE;
5203 } else if (!co.do_quiet)
5204 printf("Entry %d %s.\n", arg,
5205 optname == IP_FW_XZERO ?
5206 "cleared" : "logging count reset");
5208 errx(EX_USAGE, "invalid rule number ``%s''", *av);
5212 if (failed != EX_OK)
5217 ipfw_flush(int force)
5221 if (!force && !co.do_quiet) { /* need to ask user */
5224 printf("Are you sure? [yn] ");
5227 c = toupper(getc(stdin));
5228 while (c != '\n' && getc(stdin) != '\n')
5230 return; /* and do not flush */
5231 } while (c != 'Y' && c != 'N');
5233 if (c == 'N') /* user said no */
5240 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
5241 memset(&rt, 0, sizeof(rt));
5242 if (co.use_set != 0) {
5243 rt.set = co.use_set - 1;
5244 rt.flags = IPFW_RCFLAG_SET;
5246 rt.flags = IPFW_RCFLAG_ALL;
5247 if (do_range_cmd(IP_FW_XDEL, &rt) != 0)
5248 err(EX_UNAVAILABLE, "setsockopt(IP_FW_XDEL)");
5250 printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
5253 static struct _s_x intcmds[] = {
5254 { "talist", TOK_TALIST },
5255 { "iflist", TOK_IFLIST },
5256 { "olist", TOK_OLIST },
5257 { "vlist", TOK_VLIST },
5261 static struct _s_x otypes[] = {
5262 { "EACTION", IPFW_TLV_EACTION },
5263 { "DYNSTATE", IPFW_TLV_STATE_NAME },
5268 lookup_eaction_name(ipfw_obj_ntlv *ntlv, int cnt, uint16_t type)
5274 for (i = 0; i < cnt; i++) {
5275 if (ntlv[i].head.type != IPFW_TLV_EACTION)
5277 if (IPFW_TLV_EACTION_NAME(ntlv[i].idx) != type)
5279 name = ntlv[i].name;
5286 ipfw_list_objects(int ac, char *av[])
5288 ipfw_obj_lheader req, *olh;
5289 ipfw_obj_ntlv *ntlv;
5294 memset(&req, 0, sizeof(req));
5296 if (do_get3(IP_FW_DUMP_SRVOBJECTS, &req.opheader, &sz) != 0)
5297 if (errno != ENOMEM)
5301 if ((olh = calloc(1, sz)) == NULL)
5305 if (do_get3(IP_FW_DUMP_SRVOBJECTS, &olh->opheader, &sz) != 0) {
5311 printf("Objects list:\n");
5313 printf("There are no objects\n");
5314 ntlv = (ipfw_obj_ntlv *)(olh + 1);
5315 for (i = 0; i < olh->count; i++) {
5316 name = match_value(otypes, ntlv->head.type);
5318 name = lookup_eaction_name(
5319 (ipfw_obj_ntlv *)(olh + 1), olh->count,
5322 printf(" kidx: %4d\ttype: %10d\tname: %s\n",
5323 ntlv->idx, ntlv->head.type, ntlv->name);
5325 printf(" kidx: %4d\ttype: %10s\tname: %s\n",
5326 ntlv->idx, name, ntlv->name);
5333 ipfw_internal_handler(int ac, char *av[])
5338 NEED1("internal cmd required");
5340 if ((tcmd = match_token(intcmds, *av)) == -1)
5341 errx(EX_USAGE, "invalid internal sub-cmd: %s", *av);
5345 ipfw_list_tifaces();
5348 ipfw_list_ta(ac, av);
5351 ipfw_list_objects(ac, av);
5354 ipfw_list_values(ac, av);
5360 ipfw_get_tracked_ifaces(ipfw_obj_lheader **polh)
5362 ipfw_obj_lheader req, *olh;
5365 memset(&req, 0, sizeof(req));
5368 if (do_get3(IP_FW_XIFLIST, &req.opheader, &sz) != 0) {
5369 if (errno != ENOMEM)
5374 if ((olh = calloc(1, sz)) == NULL)
5378 if (do_get3(IP_FW_XIFLIST, &olh->opheader, &sz) != 0) {
5388 ifinfo_cmp(const void *a, const void *b)
5390 ipfw_iface_info *ia, *ib;
5392 ia = (ipfw_iface_info *)a;
5393 ib = (ipfw_iface_info *)b;
5395 return (stringnum_cmp(ia->ifname, ib->ifname));
5399 * Retrieves table list from kernel,
5400 * optionally sorts it and calls requested function for each table.
5401 * Returns 0 on success.
5406 ipfw_obj_lheader *olh;
5407 ipfw_iface_info *info;
5410 if ((error = ipfw_get_tracked_ifaces(&olh)) != 0)
5411 err(EX_OSERR, "Unable to request ipfw tracked interface list");
5414 qsort(olh + 1, olh->count, olh->objsize, ifinfo_cmp);
5416 info = (ipfw_iface_info *)(olh + 1);
5417 for (i = 0; i < olh->count; i++) {
5418 if (info->flags & IPFW_IFFLAG_RESOLVED)
5419 printf("%s ifindex: %d refcount: %u changes: %u\n",
5420 info->ifname, info->ifindex, info->refcnt,
5423 printf("%s ifindex: unresolved refcount: %u changes: %u\n",
5424 info->ifname, info->refcnt, info->gencnt);
5425 info = (ipfw_iface_info *)((caddr_t)info + olh->objsize);