2 * Copyright (c) 2002-2003 Luigi Rizzo
3 * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
4 * Copyright (c) 1994 Ugen J.S.Antsilevich
6 * Idea and grammar partially left from:
7 * Copyright (c) 1993 Daniel Boulet
9 * Redistribution and use in source forms, with and without modification,
10 * are permitted provided that this entire comment appears intact.
12 * Redistribution in binary form may occur without any restrictions.
13 * Obviously, it would be nice if you gave credit where credit is due
14 * but requiring it would be too onerous.
16 * This software is provided ``AS IS'' without any warranties of any kind.
18 * NEW command line interface for IP firewall facility
23 #include <sys/types.h>
24 #include <sys/param.h>
25 #include <sys/socket.h>
26 #include <sys/sockio.h>
27 #include <sys/sysctl.h>
42 #include <time.h> /* ctime */
43 #include <timeconv.h> /* _long_to_time */
46 #include <stddef.h> /* offsetof */
48 #include <net/ethernet.h>
49 #include <net/if.h> /* only IFNAMSIZ */
50 #include <netinet/in.h>
51 #include <netinet/in_systm.h> /* only n_short, n_long */
52 #include <netinet/ip.h>
53 #include <netinet/ip_icmp.h>
54 #include <netinet/ip_fw.h>
55 #include <netinet/tcp.h>
56 #include <arpa/inet.h>
58 struct cmdline_opts co; /* global options */
64 int show_time; /* show timestamp */
65 uint32_t set_mask; /* enabled sets mask */
66 uint32_t flags; /* request flags */
67 uint32_t first; /* first rule to request */
68 uint32_t last; /* last rule to request */
69 uint32_t dcnt; /* number of dynamic states */
70 ipfw_obj_ctlv *tstate; /* table state data */
73 int resvd_set_number = RESVD_SET;
77 #define CHECK_LENGTH(v, len) do { \
79 errx(EX_DATAERR, "Rule too long"); \
82 * Check if we have enough space in cmd buffer. Note that since
83 * first 8? u32 words are reserved by reserved header, full cmd
84 * buffer can't be used, so we need to protect from buffer overrun
85 * only. At the beginning, cblen is less than actual buffer size by
86 * size of ipfw_insn_u32 instruction + 1 u32 work. This eliminates need
87 * for checking small instructions fitting in given range.
88 * We also (ab)use the fact that ipfw_insn is always the first field
89 * for any custom instruction.
91 #define CHECK_CMDLEN CHECK_LENGTH(cblen, F_LEN((ipfw_insn *)cmd))
93 #define GET_UINT_ARG(arg, min, max, tok, s_x) do { \
95 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
96 if (_substrcmp(*av, "tablearg") == 0) { \
105 _xval = strtol(*av, &end, 10); \
107 if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
108 errx(EX_DATAERR, "%s: invalid argument: %s", \
109 match_value(s_x, tok), *av); \
111 if (errno == ERANGE || _xval < min || _xval > max) \
112 errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
113 match_value(s_x, tok), min, max, *av); \
115 if (_xval == IP_FW_TARG) \
116 errx(EX_DATAERR, "%s: illegal argument value: %s", \
117 match_value(s_x, tok), *av); \
122 static struct _s_x f_tcpflags[] = {
133 static struct _s_x f_tcpopts[] = {
134 { "mss", IP_FW_TCPOPT_MSS },
135 { "maxseg", IP_FW_TCPOPT_MSS },
136 { "window", IP_FW_TCPOPT_WINDOW },
137 { "sack", IP_FW_TCPOPT_SACK },
138 { "ts", IP_FW_TCPOPT_TS },
139 { "timestamp", IP_FW_TCPOPT_TS },
140 { "cc", IP_FW_TCPOPT_CC },
146 * IP options span the range 0 to 255 so we need to remap them
147 * (though in fact only the low 5 bits are significant).
149 static struct _s_x f_ipopts[] = {
150 { "ssrr", IP_FW_IPOPT_SSRR},
151 { "lsrr", IP_FW_IPOPT_LSRR},
152 { "rr", IP_FW_IPOPT_RR},
153 { "ts", IP_FW_IPOPT_TS},
158 static struct _s_x f_iptos[] = {
159 { "lowdelay", IPTOS_LOWDELAY},
160 { "throughput", IPTOS_THROUGHPUT},
161 { "reliability", IPTOS_RELIABILITY},
162 { "mincost", IPTOS_MINCOST},
163 { "congestion", IPTOS_ECN_CE},
164 { "ecntransport", IPTOS_ECN_ECT0},
165 { "ip tos option", 0},
169 struct _s_x f_ipdscp[] = {
170 { "af11", IPTOS_DSCP_AF11 >> 2 }, /* 001010 */
171 { "af12", IPTOS_DSCP_AF12 >> 2 }, /* 001100 */
172 { "af13", IPTOS_DSCP_AF13 >> 2 }, /* 001110 */
173 { "af21", IPTOS_DSCP_AF21 >> 2 }, /* 010010 */
174 { "af22", IPTOS_DSCP_AF22 >> 2 }, /* 010100 */
175 { "af23", IPTOS_DSCP_AF23 >> 2 }, /* 010110 */
176 { "af31", IPTOS_DSCP_AF31 >> 2 }, /* 011010 */
177 { "af32", IPTOS_DSCP_AF32 >> 2 }, /* 011100 */
178 { "af33", IPTOS_DSCP_AF33 >> 2 }, /* 011110 */
179 { "af41", IPTOS_DSCP_AF41 >> 2 }, /* 100010 */
180 { "af42", IPTOS_DSCP_AF42 >> 2 }, /* 100100 */
181 { "af43", IPTOS_DSCP_AF43 >> 2 }, /* 100110 */
182 { "be", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
183 { "ef", IPTOS_DSCP_EF >> 2 }, /* 101110 */
184 { "cs0", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
185 { "cs1", IPTOS_DSCP_CS1 >> 2 }, /* 001000 */
186 { "cs2", IPTOS_DSCP_CS2 >> 2 }, /* 010000 */
187 { "cs3", IPTOS_DSCP_CS3 >> 2 }, /* 011000 */
188 { "cs4", IPTOS_DSCP_CS4 >> 2 }, /* 100000 */
189 { "cs5", IPTOS_DSCP_CS5 >> 2 }, /* 101000 */
190 { "cs6", IPTOS_DSCP_CS6 >> 2 }, /* 110000 */
191 { "cs7", IPTOS_DSCP_CS7 >> 2 }, /* 100000 */
195 static struct _s_x limit_masks[] = {
196 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
197 {"src-addr", DYN_SRC_ADDR},
198 {"src-port", DYN_SRC_PORT},
199 {"dst-addr", DYN_DST_ADDR},
200 {"dst-port", DYN_DST_PORT},
205 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
206 * This is only used in this code.
208 #define IPPROTO_ETHERTYPE 0x1000
209 static struct _s_x ether_types[] = {
211 * Note, we cannot use "-:&/" in the names because they are field
212 * separators in the type specifications. Also, we use s = NULL as
213 * end-delimiter, because a type of 0 can be legal.
226 { "pppoe_disc", 0x8863 },
227 { "pppoe_sess", 0x8864 },
228 { "ipx_8022", 0x00E0 },
229 { "ipx_8023", 0x0000 },
230 { "ipx_ii", 0x8137 },
231 { "ipx_snap", 0x8137 },
237 static struct _s_x rule_eactions[] = {
238 { NULL, 0 } /* terminator */
241 static struct _s_x rule_actions[] = {
242 { "accept", TOK_ACCEPT },
243 { "pass", TOK_ACCEPT },
244 { "allow", TOK_ACCEPT },
245 { "permit", TOK_ACCEPT },
246 { "count", TOK_COUNT },
247 { "pipe", TOK_PIPE },
248 { "queue", TOK_QUEUE },
249 { "divert", TOK_DIVERT },
251 { "netgraph", TOK_NETGRAPH },
252 { "ngtee", TOK_NGTEE },
253 { "fwd", TOK_FORWARD },
254 { "forward", TOK_FORWARD },
255 { "skipto", TOK_SKIPTO },
256 { "deny", TOK_DENY },
257 { "drop", TOK_DENY },
258 { "reject", TOK_REJECT },
259 { "reset6", TOK_RESET6 },
260 { "reset", TOK_RESET },
261 { "unreach6", TOK_UNREACH6 },
262 { "unreach", TOK_UNREACH },
263 { "check-state", TOK_CHECKSTATE },
264 { "//", TOK_COMMENT },
266 { "reass", TOK_REASS },
267 { "setfib", TOK_SETFIB },
268 { "setdscp", TOK_SETDSCP },
269 { "call", TOK_CALL },
270 { "return", TOK_RETURN },
271 { "eaction", TOK_EACTION },
272 { NULL, 0 } /* terminator */
275 static struct _s_x rule_action_params[] = {
276 { "altq", TOK_ALTQ },
279 { "untag", TOK_UNTAG },
280 { NULL, 0 } /* terminator */
284 * The 'lookup' instruction accepts one of the following arguments.
285 * -1 is a terminator for the list.
286 * Arguments are passed as v[1] in O_DST_LOOKUP options.
288 static int lookup_key[] = {
289 TOK_DSTIP, TOK_SRCIP, TOK_DSTPORT, TOK_SRCPORT,
290 TOK_UID, TOK_JAIL, TOK_DSCP, -1 };
292 static struct _s_x rule_options[] = {
293 { "tagged", TOK_TAGGED },
296 { "jail", TOK_JAIL },
298 { "limit", TOK_LIMIT },
299 { "keep-state", TOK_KEEPSTATE },
300 { "bridged", TOK_LAYER2 },
301 { "layer2", TOK_LAYER2 },
303 { "diverted", TOK_DIVERTED },
304 { "diverted-loopback", TOK_DIVERTEDLOOPBACK },
305 { "diverted-output", TOK_DIVERTEDOUTPUT },
306 { "xmit", TOK_XMIT },
307 { "recv", TOK_RECV },
309 { "fragment", TOK_FRAG },
310 { "frag", TOK_FRAG },
312 { "ipoptions", TOK_IPOPTS },
313 { "ipopts", TOK_IPOPTS },
314 { "iplen", TOK_IPLEN },
315 { "ipid", TOK_IPID },
316 { "ipprecedence", TOK_IPPRECEDENCE },
317 { "dscp", TOK_DSCP },
318 { "iptos", TOK_IPTOS },
319 { "ipttl", TOK_IPTTL },
320 { "ipversion", TOK_IPVER },
321 { "ipver", TOK_IPVER },
322 { "estab", TOK_ESTAB },
323 { "established", TOK_ESTAB },
324 { "setup", TOK_SETUP },
325 { "sockarg", TOK_SOCKARG },
326 { "tcpdatalen", TOK_TCPDATALEN },
327 { "tcpflags", TOK_TCPFLAGS },
328 { "tcpflgs", TOK_TCPFLAGS },
329 { "tcpoptions", TOK_TCPOPTS },
330 { "tcpopts", TOK_TCPOPTS },
331 { "tcpseq", TOK_TCPSEQ },
332 { "tcpack", TOK_TCPACK },
333 { "tcpwin", TOK_TCPWIN },
334 { "icmptype", TOK_ICMPTYPES },
335 { "icmptypes", TOK_ICMPTYPES },
336 { "dst-ip", TOK_DSTIP },
337 { "src-ip", TOK_SRCIP },
338 { "dst-port", TOK_DSTPORT },
339 { "src-port", TOK_SRCPORT },
340 { "proto", TOK_PROTO },
343 { "mac-type", TOK_MACTYPE },
344 { "verrevpath", TOK_VERREVPATH },
345 { "versrcreach", TOK_VERSRCREACH },
346 { "antispoof", TOK_ANTISPOOF },
347 { "ipsec", TOK_IPSEC },
348 { "icmp6type", TOK_ICMP6TYPES },
349 { "icmp6types", TOK_ICMP6TYPES },
350 { "ext6hdr", TOK_EXT6HDR},
351 { "flow-id", TOK_FLOWID},
356 { "dst-ipv6", TOK_DSTIP6},
357 { "dst-ip6", TOK_DSTIP6},
358 { "src-ipv6", TOK_SRCIP6},
359 { "src-ip6", TOK_SRCIP6},
360 { "lookup", TOK_LOOKUP},
362 { "//", TOK_COMMENT },
364 { "not", TOK_NOT }, /* pseudo option */
365 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
366 { "or", TOK_OR }, /* pseudo option */
367 { "|", /* escape */ TOK_OR }, /* pseudo option */
368 { "{", TOK_STARTBRACE }, /* pseudo option */
369 { "(", TOK_STARTBRACE }, /* pseudo option */
370 { "}", TOK_ENDBRACE }, /* pseudo option */
371 { ")", TOK_ENDBRACE }, /* pseudo option */
372 { NULL, 0 } /* terminator */
375 void bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg);
376 static int ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
377 ipfw_cfg_lheader **pcfg, size_t *psize);
378 static int ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
379 ipfw_cfg_lheader *cfg, size_t sz, int ac, char **av);
380 static void ipfw_list_tifaces(void);
383 static uint16_t pack_object(struct tidx *tstate, char *name, int otype);
384 static uint16_t pack_table(struct tidx *tstate, char *name);
386 static char *table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx);
387 static void object_sort_ctlv(ipfw_obj_ctlv *ctlv);
388 static char *object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx,
392 * Simple string buffer API.
393 * Used to simplify buffer passing between function and for
394 * transparent overrun handling.
398 * Allocates new buffer of given size @sz.
400 * Returns 0 on success.
403 bp_alloc(struct buf_pr *b, size_t size)
405 memset(b, 0, sizeof(struct buf_pr));
407 if ((b->buf = calloc(1, size)) == NULL)
418 bp_free(struct buf_pr *b)
425 * Flushes buffer so new writer start from beginning.
428 bp_flush(struct buf_pr *b)
437 * Print message specified by @format and args.
438 * Automatically manage buffer space and transparently handle
441 * Returns number of bytes that should have been printed.
444 bprintf(struct buf_pr *b, char *format, ...)
449 va_start(args, format);
451 i = vsnprintf(b->ptr, b->avail, format, args);
454 if (i > b->avail || i < 0) {
455 /* Overflow or print error */
468 * Special values printer for tablearg-aware opcodes.
471 bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg)
475 bprintf(bp, "%s", str);
476 if (arg == IP_FW_TARG)
477 bprintf(bp, "tablearg");
479 bprintf(bp, "%u", arg);
483 * Helper routine to print a possibly unaligned uint64_t on
484 * various platform. If width > 0, print the value with
485 * the desired width, followed by a space;
486 * otherwise, return the required width.
489 pr_u64(struct buf_pr *b, uint64_t *pd, int width)
492 #define U64_FMT "I64"
494 #define U64_FMT "llu"
497 unsigned long long d;
499 bcopy (pd, &u, sizeof(u));
502 bprintf(b, "%*" U64_FMT " ", width, d) :
503 snprintf(NULL, 0, "%" U64_FMT, d) ;
509 safe_calloc(size_t number, size_t size)
511 void *ret = calloc(number, size);
514 err(EX_OSERR, "calloc");
519 safe_realloc(void *ptr, size_t size)
521 void *ret = realloc(ptr, size);
524 err(EX_OSERR, "realloc");
529 * Compare things like interface or table names.
532 stringnum_cmp(const char *a, const char *b)
544 return (strcmp(a, b));
549 * conditionally runs the command.
550 * Selected options or negative -> getsockopt
553 do_cmd(int optname, void *optval, uintptr_t optlen)
560 if (ipfw_socket == -1)
561 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
563 err(EX_UNAVAILABLE, "socket");
565 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
566 optname == IP_FW_ADD || optname == IP_FW3 ||
567 optname == IP_FW_NAT_GET_CONFIG ||
569 optname == IP_FW_NAT_GET_LOG) {
572 i = getsockopt(ipfw_socket, IPPROTO_IP, optname, optval,
573 (socklen_t *)optlen);
575 i = setsockopt(ipfw_socket, IPPROTO_IP, optname, optval, optlen);
581 * do_set3 - pass ipfw control cmd to kernel
582 * @optname: option name
583 * @optval: pointer to option data
584 * @optlen: option length
586 * Assumes op3 header is already embedded.
587 * Calls setsockopt() with IP_FW3 as kernel-visible opcode.
588 * Returns 0 on success or errno otherwise.
591 do_set3(int optname, ip_fw3_opheader *op3, uintptr_t optlen)
597 if (ipfw_socket == -1)
598 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
600 err(EX_UNAVAILABLE, "socket");
602 op3->opcode = optname;
604 return (setsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, optlen));
608 * do_get3 - pass ipfw control cmd to kernel
609 * @optname: option name
610 * @optval: pointer to option data
611 * @optlen: pointer to option length
613 * Assumes op3 header is already embedded.
614 * Calls getsockopt() with IP_FW3 as kernel-visible opcode.
615 * Returns 0 on success or errno otherwise.
618 do_get3(int optname, ip_fw3_opheader *op3, size_t *optlen)
625 if (ipfw_socket == -1)
626 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
628 err(EX_UNAVAILABLE, "socket");
630 op3->opcode = optname;
632 error = getsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3,
633 (socklen_t *)optlen);
639 * match_token takes a table and a string, returns the value associated
640 * with the string (-1 in case of failure).
643 match_token(struct _s_x *table, const char *string)
646 uint i = strlen(string);
648 for (pt = table ; i && pt->s != NULL ; pt++)
649 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
655 * match_token_relaxed takes a table and a string, returns the value associated
656 * with the string for the best match.
659 * value from @table for matched records
660 * -1 for non-matched records
661 * -2 if more than one records match @string.
664 match_token_relaxed(struct _s_x *table, const char *string)
672 for (pt = table ; i != 0 && pt->s != NULL ; pt++) {
673 if (strncmp(pt->s, string, i) != 0)
682 return (c > 0 ? -2: -1);
686 get_token(struct _s_x *table, const char *string, const char *errbase)
690 if ((tcmd = match_token_relaxed(table, string)) < 0)
691 errx(EX_USAGE, "%s %s %s",
692 (tcmd == 0) ? "invalid" : "ambiguous", errbase, string);
698 * match_value takes a table and a value, returns the string associated
699 * with the value (NULL in case of failure).
702 match_value(struct _s_x *p, int value)
704 for (; p->s != NULL; p++)
711 concat_tokens(char *buf, size_t bufsize, struct _s_x *table, char *delimiter)
717 for (sz = 0, pt = table ; pt->s != NULL; pt++) {
718 l = snprintf(buf + sz, bufsize - sz, "%s%s",
719 (sz == 0) ? "" : delimiter, pt->s);
730 * helper function to process a set of flags and set bits in the
734 fill_flags(struct _s_x *flags, char *p, char **e, uint32_t *set,
737 char *q; /* points to the separator */
739 uint32_t *which; /* mask we are working on */
750 val = match_token(flags, p);
756 *which |= (uint32_t)val;
763 print_flags_buffer(char *buf, size_t sz, struct _s_x *list, uint32_t set)
765 char const *comma = "";
768 for (i = 0; list[i].x != 0; i++) {
769 if ((set & list[i].x) == 0)
773 l = snprintf(buf, sz, "%s%s", comma, list[i].s);
783 * _substrcmp takes two strings and returns 1 if they do not match,
784 * and 0 if they match exactly or the first string is a sub-string
785 * of the second. A warning is printed to stderr in the case that the
786 * first string is a sub-string of the second.
788 * This function will be removed in the future through the usual
789 * deprecation process.
792 _substrcmp(const char *str1, const char* str2)
795 if (strncmp(str1, str2, strlen(str1)) != 0)
798 if (strlen(str1) != strlen(str2))
799 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
805 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
806 * and 0 if they match exactly or the second string is a sub-string
807 * of the first. A warning is printed to stderr in the case that the
808 * first string does not match the third.
810 * This function exists to warn about the bizarre construction
811 * strncmp(str, "by", 2) which is used to allow people to use a shortcut
812 * for "bytes". The problem is that in addition to accepting "by",
813 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
814 * other string beginning with "by".
816 * This function will be removed in the future through the usual
817 * deprecation process.
820 _substrcmp2(const char *str1, const char* str2, const char* str3)
823 if (strncmp(str1, str2, strlen(str2)) != 0)
826 if (strcmp(str1, str3) != 0)
827 warnx("DEPRECATED: '%s' matched '%s'",
833 * prints one port, symbolic or numeric
836 print_port(struct buf_pr *bp, int proto, uint16_t port)
839 if (proto == IPPROTO_ETHERTYPE) {
842 if (co.do_resolv && (s = match_value(ether_types, port)) )
843 bprintf(bp, "%s", s);
845 bprintf(bp, "0x%04x", port);
847 struct servent *se = NULL;
849 struct protoent *pe = getprotobynumber(proto);
851 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
854 bprintf(bp, "%s", se->s_name);
856 bprintf(bp, "%d", port);
860 static struct _s_x _port_name[] = {
861 {"dst-port", O_IP_DSTPORT},
862 {"src-port", O_IP_SRCPORT},
866 {"mac-type", O_MAC_TYPE},
867 {"tcpdatalen", O_TCPDATALEN},
868 {"tcpwin", O_TCPWIN},
869 {"tagged", O_TAGGED},
874 * Print the values in a list 16-bit items of the types above.
875 * XXX todo: add support for mask.
878 print_newports(struct buf_pr *bp, ipfw_insn_u16 *cmd, int proto, int opcode)
880 uint16_t *p = cmd->ports;
885 sep = match_value(_port_name, opcode);
888 bprintf(bp, " %s", sep);
891 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
892 bprintf(bp, "%s", sep);
893 print_port(bp, proto, p[0]);
896 print_port(bp, proto, p[1]);
903 * Like strtol, but also translates service names into port numbers
904 * for some protocols.
906 * proto == -1 disables the protocol check;
907 * proto == IPPROTO_ETHERTYPE looks up an internal table
908 * proto == <some value in /etc/protocols> matches the values there.
909 * Returns *end == s in case the parameter is not found.
912 strtoport(char *s, char **end, int base, int proto)
918 *end = s; /* default - not found */
920 return 0; /* not found */
923 return strtol(s, end, base);
926 * find separator. '\\' escapes the next char.
928 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
929 if (*s1 == '\\' && s1[1] != '\0')
932 buf = safe_calloc(s1 - s + 1, 1);
935 * copy into a buffer skipping backslashes
937 for (p = s, i = 0; p != s1 ; p++)
942 if (proto == IPPROTO_ETHERTYPE) {
943 i = match_token(ether_types, buf);
945 if (i != -1) { /* found */
950 struct protoent *pe = NULL;
954 pe = getprotobynumber(proto);
956 se = getservbyname(buf, pe ? pe->p_name : NULL);
960 return ntohs(se->s_port);
963 return 0; /* not found */
967 * Fill the body of the command with the list of port ranges.
970 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
972 uint16_t a, b, *p = cmd->ports;
977 a = strtoport(av, &s, 0, proto);
978 if (s == av) /* empty or invalid argument */
981 CHECK_LENGTH(cblen, i + 2);
984 case '-': /* a range */
986 b = strtoport(av, &s, 0, proto);
987 /* Reject expressions like '1-abc' or '1-2-3'. */
988 if (s == av || (*s != ',' && *s != '\0'))
993 case ',': /* comma separated list */
998 warnx("port list: invalid separator <%c> in <%s>",
1008 if (i + 1 > F_LEN_MASK)
1009 errx(EX_DATAERR, "too many ports/ranges\n");
1010 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
1016 * Fill the body of the command with the list of DiffServ codepoints.
1019 fill_dscp(ipfw_insn *cmd, char *av, int cblen)
1021 uint32_t *low, *high;
1025 cmd->opcode = O_DSCP;
1026 cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
1030 low = (uint32_t *)(cmd + 1);
1043 if ((code = match_token(f_ipdscp, s)) == -1)
1044 errx(EX_DATAERR, "Unknown DSCP code");
1046 code = strtoul(s, NULL, 10);
1047 if (code < 0 || code > 63)
1048 errx(EX_DATAERR, "Invalid DSCP value");
1052 *high |= 1 << (code - 32);
1060 static struct _s_x icmpcodes[] = {
1061 { "net", ICMP_UNREACH_NET },
1062 { "host", ICMP_UNREACH_HOST },
1063 { "protocol", ICMP_UNREACH_PROTOCOL },
1064 { "port", ICMP_UNREACH_PORT },
1065 { "needfrag", ICMP_UNREACH_NEEDFRAG },
1066 { "srcfail", ICMP_UNREACH_SRCFAIL },
1067 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
1068 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
1069 { "isolated", ICMP_UNREACH_ISOLATED },
1070 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
1071 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
1072 { "tosnet", ICMP_UNREACH_TOSNET },
1073 { "toshost", ICMP_UNREACH_TOSHOST },
1074 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
1075 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
1076 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
1081 fill_reject_code(u_short *codep, char *str)
1086 val = strtoul(str, &s, 0);
1087 if (s == str || *s != '\0' || val >= 0x100)
1088 val = match_token(icmpcodes, str);
1090 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
1096 print_reject_code(struct buf_pr *bp, uint16_t code)
1100 if ((s = match_value(icmpcodes, code)) != NULL)
1101 bprintf(bp, "unreach %s", s);
1103 bprintf(bp, "unreach %u", code);
1107 * Returns the number of bits set (from left) in a contiguous bitmask,
1108 * or -1 if the mask is not contiguous.
1109 * XXX this needs a proper fix.
1110 * This effectively works on masks in big-endian (network) format.
1111 * when compiled on little endian architectures.
1113 * First bit is bit 7 of the first byte -- note, for MAC addresses,
1114 * the first bit on the wire is bit 0 of the first byte.
1115 * len is the max length in bits.
1118 contigmask(uint8_t *p, int len)
1122 for (i=0; i<len ; i++)
1123 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
1125 for (n=i+1; n < len; n++)
1126 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
1127 return -1; /* mask not contiguous */
1132 * print flags set/clear in the two bitmasks passed as parameters.
1133 * There is a specialized check for f_tcpflags.
1136 print_flags(struct buf_pr *bp, char const *name, ipfw_insn *cmd,
1139 char const *comma = "";
1141 uint8_t set = cmd->arg1 & 0xff;
1142 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
1144 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
1145 bprintf(bp, " setup");
1149 bprintf(bp, " %s ", name);
1150 for (i=0; list[i].x != 0; i++) {
1151 if (set & list[i].x) {
1153 bprintf(bp, "%s%s", comma, list[i].s);
1156 if (clear & list[i].x) {
1157 clear &= ~list[i].x;
1158 bprintf(bp, "%s!%s", comma, list[i].s);
1166 * Print the ip address contained in a command.
1169 print_ip(struct buf_pr *bp, struct format_opts *fo, ipfw_insn_ip *cmd,
1172 struct hostent *he = NULL;
1174 uint32_t len = F_LEN((ipfw_insn *)cmd);
1175 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
1178 if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
1180 const char *arg = "<invalid>";
1182 if (d < sizeof(lookup_key)/sizeof(lookup_key[0]))
1183 arg = match_value(rule_options, lookup_key[d]);
1184 t = table_search_ctlv(fo->tstate, ((ipfw_insn *)cmd)->arg1);
1185 bprintf(bp, "%s lookup %s %s", cmd->o.len & F_NOT ? " not": "",
1189 bprintf(bp, "%s%s ", cmd->o.len & F_NOT ? " not": "", s);
1191 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
1195 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
1196 cmd->o.opcode == O_IP_DST_LOOKUP) {
1197 t = table_search_ctlv(fo->tstate, ((ipfw_insn *)cmd)->arg1);
1198 bprintf(bp, "table(%s", t);
1199 if (len == F_INSN_SIZE(ipfw_insn_u32))
1200 bprintf(bp, ",%u", *a);
1204 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
1205 uint32_t x, *map = (uint32_t *)&(cmd->mask);
1209 x = cmd->o.arg1 - 1;
1211 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1212 bprintf(bp, "%s/%d", inet_ntoa(cmd->addr),
1213 contigmask((uint8_t *)&x, 32));
1214 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1215 x &= 0xff; /* base */
1217 * Print bits and ranges.
1218 * Locate first bit set (i), then locate first bit unset (j).
1219 * If we have 3+ consecutive bits set, then print them as a
1220 * range, otherwise only print the initial bit and rescan.
1222 for (i=0; i < cmd->o.arg1; i++)
1223 if (map[i/32] & (1<<(i & 31))) {
1224 for (j=i+1; j < cmd->o.arg1; j++)
1225 if (!(map[ j/32] & (1<<(j & 31))))
1227 bprintf(bp, "%c%d", comma, i+x);
1228 if (j>i+2) { /* range has at least 3 elements */
1229 bprintf(bp, "-%d", j-1+x);
1238 * len == 2 indicates a single IP, whereas lists of 1 or more
1239 * addr/mask pairs have len = (2n+1). We convert len to n so we
1240 * use that to count the number of entries.
1242 for (len = len / 2; len > 0; len--, a += 2) {
1243 int mb = /* mask length */
1244 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1245 32 : contigmask((uint8_t *)&(a[1]), 32);
1246 if (mb == 32 && co.do_resolv)
1247 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
1248 if (he != NULL) /* resolved to name */
1249 bprintf(bp, "%s", he->h_name);
1250 else if (mb == 0) /* any */
1252 else { /* numeric IP followed by some kind of mask */
1253 ia = (struct in_addr *)&a[0];
1254 bprintf(bp, "%s", inet_ntoa(*ia));
1256 ia = (struct in_addr *)&a[1];
1257 bprintf(bp, ":%s", inet_ntoa(*ia));
1259 bprintf(bp, "/%d", mb);
1267 * prints a MAC address/mask pair
1270 print_mac(struct buf_pr *bp, uint8_t *addr, uint8_t *mask)
1272 int l = contigmask(mask, 48);
1275 bprintf(bp, " any");
1277 bprintf(bp, " %02x:%02x:%02x:%02x:%02x:%02x",
1278 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1280 bprintf(bp, "&%02x:%02x:%02x:%02x:%02x:%02x",
1281 mask[0], mask[1], mask[2],
1282 mask[3], mask[4], mask[5]);
1284 bprintf(bp, "/%d", l);
1289 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1298 type = strtoul(av, &av, 0);
1300 if (*av != ',' && *av != '\0')
1301 errx(EX_DATAERR, "invalid ICMP type");
1304 errx(EX_DATAERR, "ICMP type out of range");
1306 cmd->d[0] |= 1 << type;
1308 cmd->o.opcode = O_ICMPTYPE;
1309 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1313 print_icmptypes(struct buf_pr *bp, ipfw_insn_u32 *cmd)
1318 bprintf(bp, " icmptypes");
1319 for (i = 0; i < 32; i++) {
1320 if ( (cmd->d[0] & (1 << (i))) == 0)
1322 bprintf(bp, "%c%d", sep, i);
1328 print_dscp(struct buf_pr *bp, ipfw_insn_u32 *cmd)
1335 bprintf(bp, " dscp");
1338 if (*v & (1 << i)) {
1339 if ((code = match_value(f_ipdscp, i)) != NULL)
1340 bprintf(bp, "%c%s", sep, code);
1342 bprintf(bp, "%c%d", sep, i);
1346 if ((++i % 32) == 0)
1352 * show_ipfw() prints the body of an ipfw rule.
1353 * Because the standard rule has at least proto src_ip dst_ip, we use
1354 * a helper function to produce these entries if not provided explicitly.
1355 * The first argument is the list of fields we have, the second is
1356 * the list of fields we want to be printed.
1358 * Special cases if we have provided a MAC header:
1359 * + if the rule does not contain IP addresses/ports, do not print them;
1360 * + if the rule does not contain an IP proto, print "all" instead of "ip";
1362 * Once we have 'have_options', IP header fields are printed as options.
1364 #define HAVE_PROTO 0x0001
1365 #define HAVE_SRCIP 0x0002
1366 #define HAVE_DSTIP 0x0004
1367 #define HAVE_PROTO4 0x0008
1368 #define HAVE_PROTO6 0x0010
1369 #define HAVE_IP 0x0100
1370 #define HAVE_OPTIONS 0x8000
1373 show_prerequisites(struct buf_pr *bp, int *flags, int want, int cmd)
1375 (void)cmd; /* UNUSED */
1376 if (co.comment_only)
1378 if ( (*flags & HAVE_IP) == HAVE_IP)
1379 *flags |= HAVE_OPTIONS;
1381 if ( !(*flags & HAVE_OPTIONS)) {
1382 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) {
1383 if ( (*flags & HAVE_PROTO4))
1384 bprintf(bp, " ip4");
1385 else if ( (*flags & HAVE_PROTO6))
1386 bprintf(bp, " ip6");
1390 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
1391 bprintf(bp, " from any");
1392 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
1393 bprintf(bp, " to any");
1399 show_static_rule(struct cmdline_opts *co, struct format_opts *fo,
1400 struct buf_pr *bp, struct ip_fw_rule *rule, struct ip_fw_bcounter *cntr)
1402 static int twidth = 0;
1404 ipfw_insn *cmd, *has_eaction = NULL, *tagptr = NULL;
1405 const char *comment = NULL; /* ptr to comment if we have one */
1406 int proto = 0; /* default */
1407 int flags = 0; /* prerequisites */
1408 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
1409 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
1410 int or_block = 0; /* we are in an or block */
1413 if ((fo->set_mask & (1 << rule->set)) == 0) {
1418 bprintf(bp, "# DISABLED ");
1420 bprintf(bp, "%05u ", rule->rulenum);
1422 /* Print counters if enabled */
1423 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
1424 pr_u64(bp, &cntr->pcnt, fo->pcwidth);
1425 pr_u64(bp, &cntr->bcnt, fo->bcwidth);
1428 if (co->do_time == 2)
1429 bprintf(bp, "%10u ", cntr->timestamp);
1430 else if (co->do_time == 1) {
1432 time_t t = (time_t)0;
1435 strcpy(timestr, ctime(&t));
1436 *strchr(timestr, '\n') = '\0';
1437 twidth = strlen(timestr);
1439 if (cntr->timestamp > 0) {
1440 t = _long_to_time(cntr->timestamp);
1442 strcpy(timestr, ctime(&t));
1443 *strchr(timestr, '\n') = '\0';
1444 bprintf(bp, "%s ", timestr);
1446 bprintf(bp, "%*s", twidth, " ");
1451 bprintf(bp, "set %d ", rule->set);
1454 * print the optional "match probability"
1456 if (rule->cmd_len > 0) {
1458 if (cmd->opcode == O_PROB) {
1459 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1460 double d = 1.0 * p->d[0];
1462 d = (d / 0x7fffffff);
1463 bprintf(bp, "prob %f ", d);
1468 * first print actions
1470 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1471 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1472 switch(cmd->opcode) {
1474 bprintf(bp, "check-state");
1475 /* avoid printing anything else */
1476 flags = HAVE_PROTO | HAVE_SRCIP |
1477 HAVE_DSTIP | HAVE_IP;
1481 bprintf(bp, "allow");
1485 bprintf(bp, "count");
1489 bprintf(bp, "deny");
1493 if (cmd->arg1 == ICMP_REJECT_RST)
1494 bprintf(bp, "reset");
1495 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1496 bprintf(bp, "reject");
1498 print_reject_code(bp, cmd->arg1);
1502 if (cmd->arg1 == ICMP6_UNREACH_RST)
1503 bprintf(bp, "reset6");
1505 print_unreach6_code(bp, cmd->arg1);
1509 bprint_uint_arg(bp, "skipto ", cmd->arg1);
1513 bprint_uint_arg(bp, "pipe ", cmd->arg1);
1517 bprint_uint_arg(bp, "queue ", cmd->arg1);
1521 bprint_uint_arg(bp, "divert ", cmd->arg1);
1525 bprint_uint_arg(bp, "tee ", cmd->arg1);
1529 bprint_uint_arg(bp, "netgraph ", cmd->arg1);
1533 bprint_uint_arg(bp, "ngtee ", cmd->arg1);
1538 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1540 if (s->sa.sin_addr.s_addr == INADDR_ANY) {
1541 bprintf(bp, "fwd tablearg");
1543 bprintf(bp, "fwd %s",inet_ntoa(s->sa.sin_addr));
1546 bprintf(bp, ",%d", s->sa.sin_port);
1552 char buf[INET6_ADDRSTRLEN + IF_NAMESIZE + 2];
1553 ipfw_insn_sa6 *s = (ipfw_insn_sa6 *)cmd;
1555 bprintf(bp, "fwd ");
1556 if (getnameinfo((const struct sockaddr *)&s->sa,
1557 sizeof(struct sockaddr_in6), buf, sizeof(buf),
1558 NULL, 0, NI_NUMERICHOST) == 0)
1559 bprintf(bp, "%s", buf);
1560 if (s->sa.sin6_port)
1561 bprintf(bp, ",%d", s->sa.sin6_port);
1565 case O_LOG: /* O_LOG is printed last */
1566 logptr = (ipfw_insn_log *)cmd;
1569 case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1570 altqptr = (ipfw_insn_altq *)cmd;
1578 if (cmd->arg1 != IP_FW_NAT44_GLOBAL)
1579 bprint_uint_arg(bp, "nat ", cmd->arg1);
1581 bprintf(bp, "nat global");
1585 if (cmd->arg1 == IP_FW_TARG)
1586 bprint_uint_arg(bp, "setfib ", cmd->arg1);
1588 bprintf(bp, "setfib %u", cmd->arg1 & 0x7FFF);
1591 case O_EXTERNAL_ACTION: {
1595 * The external action can consists of two following
1596 * each other opcodes - O_EXTERNAL_ACTION and
1597 * O_EXTERNAL_INSTANCE. The first contains the ID of
1598 * name of external action. The second contains the ID
1599 * of name of external action instance.
1600 * NOTE: in case when external action has no named
1601 * instances support, the second opcode isn't needed.
1604 ename = object_search_ctlv(fo->tstate, cmd->arg1,
1606 if (match_token(rule_eactions, ename) != -1)
1607 bprintf(bp, "%s", ename);
1609 bprintf(bp, "eaction %s", ename);
1613 case O_EXTERNAL_INSTANCE: {
1616 if (has_eaction == NULL)
1619 * XXX: we need to teach ipfw(9) to rewrite opcodes
1620 * in the user buffer on rule addition. When we add
1621 * the rule, we specify zero TLV type for
1622 * O_EXTERNAL_INSTANCE object. To show correct
1623 * rule after `ipfw add` we need to search instance
1624 * name with zero type. But when we do `ipfw show`
1625 * we calculate TLV type using IPFW_TLV_EACTION_NAME()
1628 ename = object_search_ctlv(fo->tstate, cmd->arg1, 0);
1630 ename = object_search_ctlv(fo->tstate,
1632 IPFW_TLV_EACTION_NAME(has_eaction->arg1));
1633 bprintf(bp, " %s", ename);
1641 if (cmd->arg1 == IP_FW_TARG) {
1642 bprint_uint_arg(bp, "setdscp ", cmd->arg1);
1645 uval = cmd->arg1 & 0x3F;
1646 if ((code = match_value(f_ipdscp, uval)) != NULL)
1647 bprintf(bp, "setdscp %s", code);
1649 bprint_uint_arg(bp, "setdscp ", uval);
1654 bprintf(bp, "reass");
1658 if (cmd->len & F_NOT)
1659 bprintf(bp, "return");
1661 bprint_uint_arg(bp, "call ", cmd->arg1);
1665 bprintf(bp, "** unrecognized action %d len %d ",
1666 cmd->opcode, cmd->len);
1670 if (logptr->max_log > 0)
1671 bprintf(bp, " log logamount %d", logptr->max_log);
1673 bprintf(bp, " log");
1677 print_altq_cmd(bp, altqptr);
1681 if (tagptr->len & F_NOT)
1682 bprint_uint_arg(bp, " untag ", tagptr->arg1);
1684 bprint_uint_arg(bp, " tag ", tagptr->arg1);
1688 * then print the body.
1690 for (l = rule->act_ofs, cmd = rule->cmd;
1691 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1692 if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1694 if (cmd->opcode == O_IP4) {
1695 flags |= HAVE_PROTO4;
1697 } else if (cmd->opcode == O_IP6) {
1698 flags |= HAVE_PROTO6;
1702 if (rule->flags & IPFW_RULE_NOOPT) { /* empty rules before options */
1703 if (!co->do_compact) {
1704 show_prerequisites(bp, &flags, HAVE_PROTO, 0);
1705 bprintf(bp, " from any to any");
1707 flags |= HAVE_IP | HAVE_OPTIONS | HAVE_PROTO |
1708 HAVE_SRCIP | HAVE_DSTIP;
1711 if (co->comment_only)
1714 for (l = rule->act_ofs, cmd = rule->cmd;
1715 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1717 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1719 if (co->comment_only) {
1720 if (cmd->opcode != O_NOP)
1722 bprintf(bp, " // %s\n", (char *)(cmd + 1));
1726 show_prerequisites(bp, &flags, 0, cmd->opcode);
1728 switch(cmd->opcode) {
1730 break; /* done already */
1733 break; /* no need to print anything here */
1736 case O_IP_SRC_LOOKUP:
1740 show_prerequisites(bp, &flags, HAVE_PROTO, 0);
1741 if (!(flags & HAVE_SRCIP))
1742 bprintf(bp, " from");
1743 if ((cmd->len & F_OR) && !or_block)
1745 print_ip(bp, fo, (ipfw_insn_ip *)cmd,
1746 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1747 flags |= HAVE_SRCIP;
1751 case O_IP_DST_LOOKUP:
1755 show_prerequisites(bp, &flags, HAVE_PROTO|HAVE_SRCIP, 0);
1756 if (!(flags & HAVE_DSTIP))
1758 if ((cmd->len & F_OR) && !or_block)
1760 print_ip(bp, fo, (ipfw_insn_ip *)cmd,
1761 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1762 flags |= HAVE_DSTIP;
1766 case O_IP6_SRC_MASK:
1768 show_prerequisites(bp, &flags, HAVE_PROTO, 0);
1769 if (!(flags & HAVE_SRCIP))
1770 bprintf(bp, " from");
1771 if ((cmd->len & F_OR) && !or_block)
1773 print_ip6(bp, (ipfw_insn_ip6 *)cmd,
1774 (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1775 flags |= HAVE_SRCIP | HAVE_PROTO;
1779 case O_IP6_DST_MASK:
1781 show_prerequisites(bp, &flags, HAVE_PROTO|HAVE_SRCIP, 0);
1782 if (!(flags & HAVE_DSTIP))
1784 if ((cmd->len & F_OR) && !or_block)
1786 print_ip6(bp, (ipfw_insn_ip6 *)cmd,
1787 (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1788 flags |= HAVE_DSTIP;
1792 print_flow6id(bp, (ipfw_insn_u32 *) cmd );
1793 flags |= HAVE_OPTIONS;
1797 show_prerequisites(bp, &flags,
1798 HAVE_PROTO | HAVE_SRCIP |
1799 HAVE_DSTIP | HAVE_IP, 0);
1801 if (flags & HAVE_DSTIP)
1803 show_prerequisites(bp, &flags,
1804 HAVE_PROTO | HAVE_SRCIP, 0);
1805 if ((cmd->len & F_OR) && !or_block)
1807 if (cmd->len & F_NOT)
1808 bprintf(bp, " not");
1809 print_newports(bp, (ipfw_insn_u16 *)cmd, proto,
1810 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1814 struct protoent *pe = NULL;
1816 if ((cmd->len & F_OR) && !or_block)
1818 if (cmd->len & F_NOT)
1819 bprintf(bp, " not");
1821 pe = getprotobynumber(cmd->arg1);
1822 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1823 !(flags & HAVE_PROTO))
1824 show_prerequisites(bp, &flags,
1825 HAVE_PROTO | HAVE_IP | HAVE_SRCIP |
1826 HAVE_DSTIP | HAVE_OPTIONS, 0);
1827 if (flags & HAVE_OPTIONS)
1828 bprintf(bp, " proto");
1830 bprintf(bp, " %s", pe->p_name);
1832 bprintf(bp, " %u", cmd->arg1);
1834 flags |= HAVE_PROTO;
1837 default: /*options ... */
1838 if (!(cmd->len & (F_OR|F_NOT)))
1839 if (((cmd->opcode == O_IP6) &&
1840 (flags & HAVE_PROTO6)) ||
1841 ((cmd->opcode == O_IP4) &&
1842 (flags & HAVE_PROTO4)))
1844 show_prerequisites(bp, &flags, HAVE_PROTO | HAVE_SRCIP |
1845 HAVE_DSTIP | HAVE_IP | HAVE_OPTIONS, 0);
1846 if ((cmd->len & F_OR) && !or_block)
1848 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1849 bprintf(bp, " not");
1850 switch(cmd->opcode) {
1852 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1854 bprintf(bp, " MAC");
1855 print_mac(bp, m->addr, m->mask);
1856 print_mac(bp, m->addr + 6, m->mask + 6);
1861 print_newports(bp, (ipfw_insn_u16 *)cmd,
1862 IPPROTO_ETHERTYPE, cmd->opcode);
1867 bprintf(bp, " frag");
1871 bprintf(bp, " fib %u", cmd->arg1 );
1874 bprintf(bp, " sockarg");
1878 bprintf(bp, cmd->len & F_NOT ? " out" : " in");
1882 switch (cmd->arg1) {
1884 bprintf(bp, " diverted");
1887 bprintf(bp, " diverted-loopback");
1890 bprintf(bp, " diverted-output");
1893 bprintf(bp, " diverted-?<%u>", cmd->arg1);
1899 bprintf(bp, " layer2");
1906 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1908 if (cmd->opcode == O_XMIT)
1910 else if (cmd->opcode == O_RECV)
1912 else /* if (cmd->opcode == O_VIA) */
1914 if (cmdif->name[0] == '\0')
1915 bprintf(bp, " %s %s", s,
1916 inet_ntoa(cmdif->p.ip));
1917 else if (cmdif->name[0] == '\1') {
1918 /* interface table */
1919 t = table_search_ctlv(fo->tstate,
1921 bprintf(bp, " %s table(%s)", s, t);
1923 bprintf(bp, " %s %s", s, cmdif->name);
1927 case O_IP_FLOW_LOOKUP:
1931 t = table_search_ctlv(fo->tstate, cmd->arg1);
1932 bprintf(bp, " flow table(%s", t);
1933 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))
1935 ((ipfw_insn_u32 *)cmd)->d[0]);
1940 if (F_LEN(cmd) == 1)
1941 bprintf(bp, " ipid %u", cmd->arg1 );
1943 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1948 if (F_LEN(cmd) == 1)
1949 bprintf(bp, " ipttl %u", cmd->arg1 );
1951 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1956 bprintf(bp, " ipver %u", cmd->arg1 );
1959 case O_IPPRECEDENCE:
1960 bprintf(bp, " ipprecedence %u", cmd->arg1 >> 5);
1964 print_dscp(bp, (ipfw_insn_u32 *)cmd);
1968 if (F_LEN(cmd) == 1)
1969 bprintf(bp, " iplen %u", cmd->arg1 );
1971 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1976 print_flags(bp, "ipoptions", cmd, f_ipopts);
1980 print_flags(bp, "iptos", cmd, f_iptos);
1984 print_icmptypes(bp, (ipfw_insn_u32 *)cmd);
1988 bprintf(bp, " established");
1992 if (F_LEN(cmd) == 1)
1993 bprintf(bp, " tcpdatalen %u", cmd->arg1 );
1995 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
2000 print_flags(bp, "tcpflags", cmd, f_tcpflags);
2004 print_flags(bp, "tcpoptions", cmd, f_tcpopts);
2008 if (F_LEN(cmd) == 1)
2009 bprintf(bp, " tcpwin %u", cmd->arg1);
2011 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
2016 bprintf(bp, " tcpack %d", ntohl(cmd32->d[0]));
2020 bprintf(bp, " tcpseq %d", ntohl(cmd32->d[0]));
2025 struct passwd *pwd = getpwuid(cmd32->d[0]);
2028 bprintf(bp, " uid %s", pwd->pw_name);
2030 bprintf(bp, " uid %u", cmd32->d[0]);
2036 struct group *grp = getgrgid(cmd32->d[0]);
2039 bprintf(bp, " gid %s", grp->gr_name);
2041 bprintf(bp, " gid %u", cmd32->d[0]);
2046 bprintf(bp, " jail %d", cmd32->d[0]);
2050 bprintf(bp, " verrevpath");
2054 bprintf(bp, " versrcreach");
2058 bprintf(bp, " antispoof");
2062 bprintf(bp, " ipsec");
2066 comment = (char *)(cmd + 1);
2070 bprintf(bp, " keep-state");
2074 struct _s_x *p = limit_masks;
2075 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
2076 uint8_t x = c->limit_mask;
2077 char const *comma = " ";
2079 bprintf(bp, " limit");
2080 for (; p->x != 0 ; p++)
2081 if ((x & p->x) == p->x) {
2083 bprintf(bp, "%s%s", comma,p->s);
2086 bprint_uint_arg(bp, " ", c->conn_limit);
2091 bprintf(bp, " ip6");
2095 bprintf(bp, " ip4");
2099 print_icmp6types(bp, (ipfw_insn_u32 *)cmd);
2103 print_ext6hdr(bp, (ipfw_insn *)cmd);
2107 if (F_LEN(cmd) == 1)
2108 bprint_uint_arg(bp, " tagged ",
2111 print_newports(bp, (ipfw_insn_u16 *)cmd,
2116 bprintf(bp, " [opcode %d len %d]",
2117 cmd->opcode, cmd->len);
2120 if (cmd->len & F_OR) {
2123 } else if (or_block) {
2128 show_prerequisites(bp, &flags, HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP
2131 bprintf(bp, " // %s", comment);
2136 show_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2137 struct buf_pr *bp, ipfw_dyn_rule *d)
2139 struct protoent *pe;
2142 char buf[INET6_ADDRSTRLEN];
2144 if (!co->do_expired) {
2145 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
2148 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2149 bprintf(bp, "%05d", rulenum);
2150 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2152 pr_u64(bp, &d->pcnt, fo->pcwidth);
2153 pr_u64(bp, &d->bcnt, fo->bcwidth);
2154 bprintf(bp, "(%ds)", d->expire);
2156 switch (d->dyn_type) {
2157 case O_LIMIT_PARENT:
2158 bprintf(bp, " PARENT %d", d->count);
2161 bprintf(bp, " LIMIT");
2163 case O_KEEP_STATE: /* bidir, no mask */
2164 bprintf(bp, " STATE");
2168 if ((pe = getprotobynumber(d->id.proto)) != NULL)
2169 bprintf(bp, " %s", pe->p_name);
2171 bprintf(bp, " proto %u", d->id.proto);
2173 if (d->id.addr_type == 4) {
2174 a.s_addr = htonl(d->id.src_ip);
2175 bprintf(bp, " %s %d", inet_ntoa(a), d->id.src_port);
2177 a.s_addr = htonl(d->id.dst_ip);
2178 bprintf(bp, " <-> %s %d", inet_ntoa(a), d->id.dst_port);
2179 } else if (d->id.addr_type == 6) {
2180 bprintf(bp, " %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
2181 sizeof(buf)), d->id.src_port);
2182 bprintf(bp, " <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6,
2183 buf, sizeof(buf)), d->id.dst_port);
2185 bprintf(bp, " UNKNOWN <-> UNKNOWN\n");
2189 do_range_cmd(int cmd, ipfw_range_tlv *rt)
2191 ipfw_range_header rh;
2194 memset(&rh, 0, sizeof(rh));
2195 memcpy(&rh.range, rt, sizeof(*rt));
2196 rh.range.head.length = sizeof(*rt);
2197 rh.range.head.type = IPFW_TLV_RANGE;
2200 if (do_get3(cmd, &rh.opheader, &sz) != 0)
2202 /* Save number of matched objects */
2203 rt->new_set = rh.range.new_set;
2208 * This one handles all set-related commands
2209 * ipfw set { show | enable | disable }
2211 * ipfw set move X to Y
2212 * ipfw set move rule X to Y
2215 ipfw_sets_handler(char *av[])
2219 uint8_t cmd, rulenum;
2225 memset(&rt, 0, sizeof(rt));
2228 errx(EX_USAGE, "set needs command");
2229 if (_substrcmp(*av, "show") == 0) {
2230 struct format_opts fo;
2231 ipfw_cfg_lheader *cfg;
2233 memset(&fo, 0, sizeof(fo));
2234 if (ipfw_get_config(&co, &fo, &cfg, &size) != 0)
2235 err(EX_OSERR, "requesting config failed");
2237 for (i = 0, msg = "disable"; i < RESVD_SET; i++)
2238 if ((cfg->set_mask & (1<<i)) == 0) {
2239 printf("%s %d", msg, i);
2242 msg = (cfg->set_mask != (uint32_t)-1) ? " enable" : "enable";
2243 for (i = 0; i < RESVD_SET; i++)
2244 if ((cfg->set_mask & (1<<i)) != 0) {
2245 printf("%s %d", msg, i);
2250 } else if (_substrcmp(*av, "swap") == 0) {
2252 if ( av[0] == NULL || av[1] == NULL )
2253 errx(EX_USAGE, "set swap needs 2 set numbers\n");
2254 rt.set = atoi(av[0]);
2255 rt.new_set = atoi(av[1]);
2256 if (!isdigit(*(av[0])) || rt.set > RESVD_SET)
2257 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2258 if (!isdigit(*(av[1])) || rt.new_set > RESVD_SET)
2259 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2260 i = do_range_cmd(IP_FW_SET_SWAP, &rt);
2261 } else if (_substrcmp(*av, "move") == 0) {
2263 if (av[0] && _substrcmp(*av, "rule") == 0) {
2264 rt.flags = IPFW_RCFLAG_RANGE; /* move rules to new set */
2268 cmd = IP_FW_SET_MOVE; /* Move set to new one */
2269 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
2270 av[3] != NULL || _substrcmp(av[1], "to") != 0)
2271 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2272 rulenum = atoi(av[0]);
2273 rt.new_set = atoi(av[2]);
2274 if (cmd == IP_FW_XMOVE) {
2275 rt.start_rule = rulenum;
2276 rt.end_rule = rulenum;
2279 rt.new_set = atoi(av[2]);
2280 if (!isdigit(*(av[0])) || (cmd == 3 && rt.set > RESVD_SET) ||
2281 (cmd == 2 && rt.start_rule == IPFW_DEFAULT_RULE) )
2282 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2283 if (!isdigit(*(av[2])) || rt.new_set > RESVD_SET)
2284 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2285 i = do_range_cmd(cmd, &rt);
2287 err(EX_OSERR, "failed to move %s",
2288 cmd == IP_FW_SET_MOVE ? "set": "rule");
2289 } else if (_substrcmp(*av, "disable") == 0 ||
2290 _substrcmp(*av, "enable") == 0 ) {
2291 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2294 masks[0] = masks[1] = 0;
2297 if (isdigit(**av)) {
2299 if (i < 0 || i > RESVD_SET)
2301 "invalid set number %d\n", i);
2302 masks[which] |= (1<<i);
2303 } else if (_substrcmp(*av, "disable") == 0)
2305 else if (_substrcmp(*av, "enable") == 0)
2309 "invalid set command %s\n", *av);
2312 if ( (masks[0] & masks[1]) != 0 )
2314 "cannot enable and disable the same set\n");
2317 rt.new_set = masks[1];
2318 i = do_range_cmd(IP_FW_SET_ENABLE, &rt);
2320 warn("set enable/disable: setsockopt(IP_FW_SET_ENABLE)");
2322 errx(EX_USAGE, "invalid set command %s\n", *av);
2326 ipfw_sysctl_handler(char *av[], int which)
2330 if (av[0] == NULL) {
2331 warnx("missing keyword to enable/disable\n");
2332 } else if (_substrcmp(*av, "firewall") == 0) {
2333 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2334 &which, sizeof(which));
2335 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
2336 &which, sizeof(which));
2337 } else if (_substrcmp(*av, "one_pass") == 0) {
2338 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2339 &which, sizeof(which));
2340 } else if (_substrcmp(*av, "debug") == 0) {
2341 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2342 &which, sizeof(which));
2343 } else if (_substrcmp(*av, "verbose") == 0) {
2344 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2345 &which, sizeof(which));
2346 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2347 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2348 &which, sizeof(which));
2350 } else if (_substrcmp(*av, "altq") == 0) {
2351 altq_set_enabled(which);
2354 warnx("unrecognize enable/disable keyword: %s\n", *av);
2358 typedef void state_cb(struct cmdline_opts *co, struct format_opts *fo,
2359 void *arg, void *state);
2362 prepare_format_dyn(struct cmdline_opts *co, struct format_opts *fo,
2363 void *arg, void *_state)
2369 d = (ipfw_dyn_rule *)_state;
2370 /* Count _ALL_ states */
2373 if (fo->show_counters == 0)
2377 /* skip states from another set */
2378 bcopy((char *)&d->rule + sizeof(uint16_t), &set,
2380 if (set != co->use_set - 1)
2384 width = pr_u64(NULL, &d->pcnt, 0);
2385 if (width > fo->pcwidth)
2386 fo->pcwidth = width;
2388 width = pr_u64(NULL, &d->bcnt, 0);
2389 if (width > fo->bcwidth)
2390 fo->bcwidth = width;
2394 foreach_state(struct cmdline_opts *co, struct format_opts *fo,
2395 caddr_t base, size_t sz, state_cb dyn_bc, void *dyn_arg)
2401 ipfw_obj_ctlv *ctlv;
2407 ctlv = (ipfw_obj_ctlv *)base;
2408 switch (ctlv->head.type) {
2409 case IPFW_TLV_DYNSTATE_LIST:
2410 base += sizeof(*ctlv);
2411 sz -= sizeof(*ctlv);
2412 ttype = IPFW_TLV_DYN_ENT;
2421 tlv = (ipfw_obj_tlv *)base;
2422 if (tlv->type != ttype)
2425 fptr(co, fo, farg, tlv + 1);
2427 base += tlv->length;
2435 prepare_format_opts(struct cmdline_opts *co, struct format_opts *fo,
2436 ipfw_obj_tlv *rtlv, int rcnt, caddr_t dynbase, size_t dynsz)
2438 int bcwidth, pcwidth, width;
2440 struct ip_fw_bcounter *cntr;
2441 struct ip_fw_rule *r;
2445 if (fo->show_counters != 0) {
2446 for (n = 0; n < rcnt; n++,
2447 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2448 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2449 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2450 /* skip rules from another set */
2451 if (co->use_set && r->set != co->use_set - 1)
2454 /* packet counter */
2455 width = pr_u64(NULL, &cntr->pcnt, 0);
2456 if (width > pcwidth)
2460 width = pr_u64(NULL, &cntr->bcnt, 0);
2461 if (width > bcwidth)
2465 fo->bcwidth = bcwidth;
2466 fo->pcwidth = pcwidth;
2469 if (co->do_dynamic && dynsz > 0)
2470 foreach_state(co, fo, dynbase, dynsz, prepare_format_dyn, NULL);
2474 list_static_range(struct cmdline_opts *co, struct format_opts *fo,
2475 struct buf_pr *bp, ipfw_obj_tlv *rtlv, int rcnt)
2478 struct ip_fw_rule *r;
2479 struct ip_fw_bcounter *cntr;
2482 for (n = seen = 0; n < rcnt; n++,
2483 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2485 if ((fo->show_counters | fo->show_time) != 0) {
2486 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2487 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2490 r = (struct ip_fw_rule *)(rtlv + 1);
2492 if (r->rulenum > fo->last)
2494 if (co->use_set && r->set != co->use_set - 1)
2496 if (r->rulenum >= fo->first && r->rulenum <= fo->last) {
2497 show_static_rule(co, fo, bp, r, cntr);
2498 printf("%s", bp->buf);
2509 list_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2510 void *_arg, void *_state)
2517 d = (ipfw_dyn_rule *)_state;
2518 bp = (struct buf_pr *)_arg;
2520 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2521 if (rulenum > fo->last)
2524 bcopy((char *)&d->rule + sizeof(uint16_t),
2525 &set, sizeof(uint8_t));
2526 if (set != co->use_set - 1)
2529 if (rulenum >= fo->first) {
2530 show_dyn_state(co, fo, bp, d);
2531 printf("%s\n", bp->buf);
2537 list_dyn_range(struct cmdline_opts *co, struct format_opts *fo,
2538 struct buf_pr *bp, caddr_t base, size_t sz)
2541 sz = foreach_state(co, fo, base, sz, list_dyn_state, bp);
2546 ipfw_list(int ac, char *av[], int show_counters)
2548 ipfw_cfg_lheader *cfg;
2549 struct format_opts sfo;
2558 fprintf(stderr, "Testing only, list disabled\n");
2562 dummynet_list(ac, av, show_counters);
2568 memset(&sfo, 0, sizeof(sfo));
2570 /* Determine rule range to request */
2572 for (lac = ac, lav = av; lac != 0; lac--) {
2573 rnum = strtoul(*lav++, &endptr, 10);
2574 if (sfo.first == 0 || rnum < sfo.first)
2578 rnum = strtoul(endptr + 1, &endptr, 10);
2579 if (sfo.last == 0 || rnum > sfo.last)
2584 /* get configuraion from kernel */
2586 sfo.show_counters = show_counters;
2587 sfo.show_time = co.do_time;
2588 sfo.flags = IPFW_CFG_GET_STATIC;
2589 if (co.do_dynamic != 0)
2590 sfo.flags |= IPFW_CFG_GET_STATES;
2591 if ((sfo.show_counters | sfo.show_time) != 0)
2592 sfo.flags |= IPFW_CFG_GET_COUNTERS;
2593 if (ipfw_get_config(&co, &sfo, &cfg, &sz) != 0)
2594 err(EX_OSERR, "retrieving config failed");
2596 error = ipfw_show_config(&co, &sfo, cfg, sz, ac, av);
2605 ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
2606 ipfw_cfg_lheader *cfg, size_t sz, int ac, char *av[])
2611 int exitval = EX_OK;
2617 ipfw_obj_ctlv *ctlv, *tstate;
2618 ipfw_obj_tlv *rbase;
2621 * Handle tablenames TLV first, if any
2627 readsz = sizeof(*cfg);
2630 fo->set_mask = cfg->set_mask;
2632 ctlv = (ipfw_obj_ctlv *)(cfg + 1);
2634 if (cfg->flags & IPFW_CFG_GET_STATIC) {
2635 /* We've requested static rules */
2636 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2637 object_sort_ctlv(ctlv);
2639 readsz += ctlv->head.length;
2640 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2644 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2645 rbase = (ipfw_obj_tlv *)(ctlv + 1);
2647 readsz += ctlv->head.length;
2648 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2653 if ((cfg->flags & IPFW_CFG_GET_STATES) && (readsz != sz)) {
2654 /* We may have some dynamic states */
2655 dynsz = sz - readsz;
2656 /* Skip empty header */
2657 if (dynsz != sizeof(ipfw_obj_ctlv))
2658 dynbase = (caddr_t)ctlv;
2663 prepare_format_opts(co, fo, rbase, rcnt, dynbase, dynsz);
2664 bp_alloc(&bp, 4096);
2666 /* if no rule numbers were specified, list all rules */
2669 fo->last = IPFW_DEFAULT_RULE;
2670 list_static_range(co, fo, &bp, rbase, rcnt);
2672 if (co->do_dynamic && dynsz > 0) {
2673 printf("## Dynamic rules (%d %zu):\n", fo->dcnt, dynsz);
2674 list_dyn_range(co, fo, &bp, dynbase, dynsz);
2681 /* display specific rules requested on command line */
2682 for (lac = ac, lav = av; lac != 0; lac--) {
2683 /* convert command line rule # */
2684 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2686 fo->last = strtoul(endptr + 1, &endptr, 10);
2689 warnx("invalid rule number: %s", *(lav - 1));
2693 if (list_static_range(co, fo, &bp, rbase, rcnt) == 0) {
2694 /* give precedence to other error(s) */
2695 if (exitval == EX_OK)
2696 exitval = EX_UNAVAILABLE;
2697 if (fo->first == fo->last)
2698 warnx("rule %u does not exist", fo->first);
2700 warnx("no rules in range %u-%u",
2701 fo->first, fo->last);
2705 if (co->do_dynamic && dynsz > 0) {
2706 printf("## Dynamic rules:\n");
2707 for (lac = ac, lav = av; lac != 0; lac--) {
2708 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2710 fo->last = strtoul(endptr+1, &endptr, 10);
2712 /* already warned */
2714 list_dyn_range(co, fo, &bp, dynbase, dynsz);
2724 * Retrieves current ipfw configuration of given type
2725 * and stores its pointer to @pcfg.
2727 * Caller is responsible for freeing @pcfg.
2729 * Returns 0 on success.
2733 ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
2734 ipfw_cfg_lheader **pcfg, size_t *psize)
2736 ipfw_cfg_lheader *cfg;
2741 if (co->test_only != 0) {
2742 fprintf(stderr, "Testing only, list disabled\n");
2746 /* Start with some data size */
2750 for (i = 0; i < 16; i++) {
2753 if ((cfg = calloc(1, sz)) == NULL)
2756 cfg->flags = fo->flags;
2757 cfg->start_rule = fo->first;
2758 cfg->end_rule = fo->last;
2760 if (do_get3(IP_FW_XGET, &cfg->opheader, &sz) != 0) {
2761 if (errno != ENOMEM) {
2766 /* Buffer size is not enough. Try to increase */
2783 lookup_host (char *host, struct in_addr *ipaddr)
2787 if (!inet_aton(host, ipaddr)) {
2788 if ((he = gethostbyname(host)) == NULL)
2790 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2804 ipfw_check_object_name(const char *name)
2809 * Check that name is null-terminated and contains
2810 * valid symbols only. Valid mask is:
2811 * [a-zA-Z0-9\-_\.]{1,63}
2814 if (l == 0 || l >= 64)
2816 for (i = 0; i < l; i++) {
2818 if (isalpha(c) || isdigit(c) || c == '_' ||
2819 c == '-' || c == '.')
2827 eaction_check_name(const char *name)
2830 if (ipfw_check_object_name(name) != 0)
2832 /* Restrict some 'special' names */
2833 if (match_token(rule_actions, name) != -1 &&
2834 match_token(rule_action_params, name) != -1)
2840 pack_object(struct tidx *tstate, char *name, int otype)
2843 ipfw_obj_ntlv *ntlv;
2845 for (i = 0; i < tstate->count; i++) {
2846 if (strcmp(tstate->idx[i].name, name) != 0)
2848 if (tstate->idx[i].set != tstate->set)
2850 if (tstate->idx[i].head.type != otype)
2853 return (tstate->idx[i].idx);
2856 if (tstate->count + 1 > tstate->size) {
2858 tstate->idx = realloc(tstate->idx, tstate->size *
2859 sizeof(ipfw_obj_ntlv));
2860 if (tstate->idx == NULL)
2864 ntlv = &tstate->idx[i];
2865 memset(ntlv, 0, sizeof(ipfw_obj_ntlv));
2866 strlcpy(ntlv->name, name, sizeof(ntlv->name));
2867 ntlv->head.type = otype;
2868 ntlv->head.length = sizeof(ipfw_obj_ntlv);
2869 ntlv->set = tstate->set;
2870 ntlv->idx = ++tstate->counter;
2877 pack_table(struct tidx *tstate, char *name)
2880 if (table_check_name(name) != 0)
2883 return (pack_object(tstate, name, IPFW_TLV_TBL_NAME));
2887 fill_table(struct _ipfw_insn *cmd, char *av, uint8_t opcode,
2888 struct tidx *tstate)
2890 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2894 if ((p = strchr(av + 6, ')')) == NULL)
2895 errx(EX_DATAERR, "forgotten parenthesis: '%s'", av);
2897 p = strchr(av + 6, ',');
2901 if ((uidx = pack_table(tstate, av + 6)) == 0)
2902 errx(EX_DATAERR, "Invalid table name: %s", av + 6);
2904 cmd->opcode = opcode;
2907 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
2908 d[0] = strtoul(p, NULL, 0);
2910 cmd->len |= F_INSN_SIZE(ipfw_insn);
2915 * fills the addr and mask fields in the instruction as appropriate from av.
2916 * Update length as appropriate.
2917 * The following formats are allowed:
2918 * me returns O_IP_*_ME
2919 * 1.2.3.4 single IP address
2920 * 1.2.3.4:5.6.7.8 address:mask
2921 * 1.2.3.4/24 address/mask
2922 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
2923 * We can have multiple comma-separated address/mask entries.
2926 fill_ip(ipfw_insn_ip *cmd, char *av, int cblen, struct tidx *tstate)
2929 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2931 cmd->o.len &= ~F_LEN_MASK; /* zero len */
2933 if (_substrcmp(av, "any") == 0)
2936 if (_substrcmp(av, "me") == 0) {
2937 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2941 if (strncmp(av, "table(", 6) == 0) {
2942 fill_table(&cmd->o, av, O_IP_DST_LOOKUP, tstate);
2948 * After the address we can have '/' or ':' indicating a mask,
2949 * ',' indicating another address follows, '{' indicating a
2950 * set of addresses of unspecified size.
2952 char *t = NULL, *p = strpbrk(av, "/:,{");
2956 CHECK_LENGTH(cblen, F_INSN_SIZE(ipfw_insn) + 2 + len);
2961 if ((t = strpbrk(p, ",{")) != NULL) {
2968 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2969 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2972 if (!inet_aton(p, (struct in_addr *)&d[1]))
2973 errx(EX_DATAERR, "bad netmask ``%s''", p);
2978 d[1] = htonl(0U); /* mask */
2979 else if (masklen > 32)
2980 errx(EX_DATAERR, "bad width ``%s''", p);
2982 d[1] = htonl(~0U << (32 - masklen));
2984 case '{': /* no mask, assume /24 and put back the '{' */
2985 d[1] = htonl(~0U << (32 - 24));
2989 case ',': /* single address plus continuation */
2992 case 0: /* initialization value */
2994 d[1] = htonl(~0U); /* force /32 */
2997 d[0] &= d[1]; /* mask base address with mask */
3000 /* find next separator */
3002 p = strpbrk(p, ",{");
3003 if (p && *p == '{') {
3005 * We have a set of addresses. They are stored as follows:
3006 * arg1 is the set size (powers of 2, 2..256)
3007 * addr is the base address IN HOST FORMAT
3008 * mask.. is an array of arg1 bits (rounded up to
3009 * the next multiple of 32) with bits set
3010 * for each host in the map.
3012 uint32_t *map = (uint32_t *)&cmd->mask;
3014 int i = contigmask((uint8_t *)&(d[1]), 32);
3017 errx(EX_DATAERR, "address set cannot be in a list");
3018 if (i < 24 || i > 31)
3019 errx(EX_DATAERR, "invalid set with mask %d\n", i);
3020 cmd->o.arg1 = 1<<(32-i); /* map length */
3021 d[0] = ntohl(d[0]); /* base addr in host format */
3022 cmd->o.opcode = O_IP_DST_SET; /* default */
3023 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
3024 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
3025 map[i] = 0; /* clear map */
3029 high = low + cmd->o.arg1 - 1;
3031 * Here, i stores the previous value when we specify a range
3032 * of addresses within a mask, e.g. 45-63. i = -1 means we
3033 * have no previous value.
3035 i = -1; /* previous value in a range */
3036 while (isdigit(*av)) {
3038 int a = strtol(av, &s, 0);
3040 if (s == av) { /* no parameter */
3042 errx(EX_DATAERR, "set not closed\n");
3044 errx(EX_DATAERR, "incomplete range %d-", i);
3047 if (a < low || a > high)
3048 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
3051 if (i == -1) /* no previous in range */
3053 else { /* check that range is valid */
3055 errx(EX_DATAERR, "invalid range %d-%d",
3058 errx(EX_DATAERR, "double '-' in range");
3061 map[i/32] |= 1<<(i & 31);
3072 if (av) /* then *av must be a ',' */
3075 /* Check this entry */
3076 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
3078 * 'any' turns the entire list into a NOP.
3079 * 'not any' never matches, so it is removed from the
3080 * list unless it is the only item, in which case we
3083 if (cmd->o.len & F_NOT) { /* "not any" never matches */
3084 if (av == NULL && len == 0) /* only this entry */
3085 errx(EX_DATAERR, "not any never matches");
3087 /* else do nothing and skip this entry */
3090 /* A single IP can be stored in an optimized format */
3091 if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
3092 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
3095 len += 2; /* two words... */
3098 if (len + 1 > F_LEN_MASK)
3099 errx(EX_DATAERR, "address list too long");
3100 cmd->o.len |= len+1;
3104 /* n2mask sets n bits of the mask */
3106 n2mask(struct in6_addr *mask, int n)
3108 static int minimask[9] =
3109 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
3112 memset(mask, 0, sizeof(struct in6_addr));
3113 p = (u_char *) mask;
3114 for (; n > 0; p++, n -= 8) {
3124 fill_flags_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3125 struct _s_x *flags, char *p)
3128 uint32_t set = 0, clear = 0;
3130 if (fill_flags(flags, p, &e, &set, &clear) != 0)
3131 errx(EX_DATAERR, "invalid flag %s", e);
3133 cmd->opcode = opcode;
3134 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
3135 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3140 ipfw_delete(char *av[])
3143 int exitval = EX_OK;
3149 NEED1("missing rule specification");
3150 memset(&rt, 0, sizeof(rt));
3151 if ( *av && _substrcmp(*av, "set") == 0) {
3152 /* Do not allow using the following syntax:
3153 * ipfw set N delete set M
3156 errx(EX_DATAERR, "invalid syntax");
3157 do_set = 1; /* delete set */
3162 while (*av && isdigit(**av)) {
3163 i = strtol(*av, &sep, 10);
3166 j = strtol(sep + 1, NULL, 10);
3169 exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
3171 exitval = EX_UNAVAILABLE;
3172 warn("rule %u not available", i);
3174 } else if (co.do_pipe) {
3175 exitval = ipfw_delete_pipe(co.do_pipe, i);
3179 rt.flags = IPFW_RCFLAG_SET;
3181 rt.start_rule = i & 0xffff;
3182 rt.end_rule = j & 0xffff;
3183 if (rt.start_rule == 0 && rt.end_rule == 0)
3184 rt.flags |= IPFW_RCFLAG_ALL;
3186 rt.flags |= IPFW_RCFLAG_RANGE;
3187 if (co.use_set != 0) {
3188 rt.set = co.use_set - 1;
3189 rt.flags |= IPFW_RCFLAG_SET;
3192 i = do_range_cmd(IP_FW_XDEL, &rt);
3194 exitval = EX_UNAVAILABLE;
3195 warn("rule %u: setsockopt(IP_FW_XDEL)",
3197 } else if (rt.new_set == 0) {
3198 exitval = EX_UNAVAILABLE;
3199 if (rt.start_rule != rt.end_rule)
3200 warnx("no rules rules in %u-%u range",
3201 rt.start_rule, rt.end_rule);
3203 warnx("rule %u not found",
3208 if (exitval != EX_OK)
3214 * fill the interface structure. We do not check the name as we can
3215 * create interfaces dynamically, so checking them at insert time
3216 * makes relatively little sense.
3217 * Interface names containing '*', '?', or '[' are assumed to be shell
3218 * patterns which match interfaces.
3221 fill_iface(ipfw_insn_if *cmd, char *arg, int cblen, struct tidx *tstate)
3226 cmd->name[0] = '\0';
3227 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3231 /* Parse the interface or address */
3232 if (strcmp(arg, "any") == 0)
3233 cmd->o.len = 0; /* effectively ignore this command */
3234 else if (strncmp(arg, "table(", 6) == 0) {
3235 if ((p = strchr(arg + 6, ')')) == NULL)
3236 errx(EX_DATAERR, "forgotten parenthesis: '%s'", arg);
3238 p = strchr(arg + 6, ',');
3241 if ((uidx = pack_table(tstate, arg + 6)) == 0)
3242 errx(EX_DATAERR, "Invalid table name: %s", arg + 6);
3244 cmd->name[0] = '\1'; /* Special value indicating table */
3246 } else if (!isdigit(*arg)) {
3247 strlcpy(cmd->name, arg, sizeof(cmd->name));
3248 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3249 } else if (!inet_aton(arg, &cmd->p.ip))
3250 errx(EX_DATAERR, "bad ip address ``%s''", arg);
3254 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
3258 char *ap, *ptr, *optr;
3259 struct ether_addr *mac;
3260 const char *macset = "0123456789abcdefABCDEF:";
3262 if (strcmp(p, "any") == 0) {
3263 for (i = 0; i < ETHER_ADDR_LEN; i++)
3264 addr[i] = mask[i] = 0;
3268 optr = ptr = strdup(p);
3269 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
3271 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
3272 errx(EX_DATAERR, "Incorrect MAC address");
3273 bcopy(mac, addr, ETHER_ADDR_LEN);
3275 errx(EX_DATAERR, "Incorrect MAC address");
3277 if (ptr != NULL) { /* we have mask? */
3278 if (p[ptr - optr - 1] == '/') { /* mask len */
3279 long ml = strtol(ptr, &ap, 10);
3280 if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
3281 errx(EX_DATAERR, "Incorrect mask length");
3282 for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
3283 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
3286 if (strspn(ptr, macset) != l ||
3287 (mac = ether_aton(ptr)) == NULL)
3288 errx(EX_DATAERR, "Incorrect mask");
3289 bcopy(mac, mask, ETHER_ADDR_LEN);
3291 } else { /* default mask: ff:ff:ff:ff:ff:ff */
3292 for (i = 0; i < ETHER_ADDR_LEN; i++)
3295 for (i = 0; i < ETHER_ADDR_LEN; i++)
3302 * helper function, updates the pointer to cmd with the length
3303 * of the current command, and also cleans up the first word of
3304 * the new command in case it has been clobbered before.
3307 next_cmd(ipfw_insn *cmd, int *len)
3310 CHECK_LENGTH(*len, 0);
3312 bzero(cmd, sizeof(*cmd));
3317 * Takes arguments and copies them into a comment
3320 fill_comment(ipfw_insn *cmd, char **av, int cblen)
3323 char *p = (char *)(cmd + 1);
3325 cmd->opcode = O_NOP;
3326 cmd->len = (cmd->len & (F_NOT | F_OR));
3328 /* Compute length of comment string. */
3329 for (i = 0, l = 0; av[i] != NULL; i++)
3330 l += strlen(av[i]) + 1;
3335 "comment too long (max 80 chars)");
3337 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
3340 for (i = 0; av[i] != NULL; i++) {
3349 * A function to fill simple commands of size 1.
3350 * Existing flags are preserved.
3353 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3355 cmd->opcode = opcode;
3356 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3361 * Fetch and add the MAC address and type, with masks. This generates one or
3362 * two microinstructions, and returns the pointer to the last one.
3365 add_mac(ipfw_insn *cmd, char *av[], int cblen)
3369 if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
3370 errx(EX_DATAERR, "MAC dst src");
3372 cmd->opcode = O_MACADDR2;
3373 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3376 mac = (ipfw_insn_mac *)cmd;
3377 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
3378 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
3379 &(mac->mask[ETHER_ADDR_LEN])); /* src */
3384 add_mactype(ipfw_insn *cmd, char *av, int cblen)
3387 errx(EX_DATAERR, "missing MAC type");
3388 if (strcmp(av, "any") != 0) { /* we have a non-null type */
3389 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
3391 cmd->opcode = O_MAC_TYPE;
3398 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
3400 struct protoent *pe;
3404 proto = strtol(av, &ep, 10);
3405 if (*ep != '\0' || proto <= 0) {
3406 if ((pe = getprotobyname(av)) == NULL)
3408 proto = pe->p_proto;
3411 fill_cmd(cmd, O_PROTO, 0, proto);
3417 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
3419 u_char proto = IPPROTO_IP;
3421 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3422 ; /* do not set O_IP4 nor O_IP6 */
3423 else if (strcmp(av, "ip4") == 0)
3424 /* explicit "just IPv4" rule */
3425 fill_cmd(cmd, O_IP4, 0, 0);
3426 else if (strcmp(av, "ip6") == 0) {
3427 /* explicit "just IPv6" rule */
3428 proto = IPPROTO_IPV6;
3429 fill_cmd(cmd, O_IP6, 0, 0);
3431 return add_proto0(cmd, av, protop);
3438 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
3440 u_char proto = IPPROTO_IP;
3442 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3443 ; /* do not set O_IP4 nor O_IP6 */
3444 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3445 /* explicit "just IPv4" rule */
3446 fill_cmd(cmd, O_IP4, 0, 0);
3447 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3448 /* explicit "just IPv6" rule */
3449 proto = IPPROTO_IPV6;
3450 fill_cmd(cmd, O_IP6, 0, 0);
3452 return add_proto0(cmd, av, protop);
3459 add_srcip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3461 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3462 if (cmd->opcode == O_IP_DST_SET) /* set */
3463 cmd->opcode = O_IP_SRC_SET;
3464 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3465 cmd->opcode = O_IP_SRC_LOOKUP;
3466 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3467 cmd->opcode = O_IP_SRC_ME;
3468 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3469 cmd->opcode = O_IP_SRC;
3470 else /* addr/mask */
3471 cmd->opcode = O_IP_SRC_MASK;
3476 add_dstip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3478 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3479 if (cmd->opcode == O_IP_DST_SET) /* set */
3481 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3483 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3484 cmd->opcode = O_IP_DST_ME;
3485 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3486 cmd->opcode = O_IP_DST;
3487 else /* addr/mask */
3488 cmd->opcode = O_IP_DST_MASK;
3492 static struct _s_x f_reserved_keywords[] = {
3495 { "diverted", TOK_OR },
3496 { "dst-port", TOK_OR },
3497 { "src-port", TOK_OR },
3498 { "established", TOK_OR },
3499 { "keep-state", TOK_OR },
3501 { "icmptypes", TOK_OR },
3509 { NULL, 0 } /* terminator */
3513 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
3516 if (match_token(f_reserved_keywords, av) != -1)
3519 if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
3520 /* XXX todo: check that we have a protocol with ports */
3521 cmd->opcode = opcode;
3528 add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3531 char *host, *ch, buf[INET6_ADDRSTRLEN];
3532 ipfw_insn *ret = NULL;
3535 /* Copy first address in set if needed */
3536 if ((ch = strpbrk(av, "/,")) != NULL) {
3538 strlcpy(buf, av, sizeof(buf));
3539 if (len < sizeof(buf))
3545 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3546 inet_pton(AF_INET6, host, &a) == 1)
3547 ret = add_srcip6(cmd, av, cblen, tstate);
3548 /* XXX: should check for IPv4, not !IPv6 */
3549 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3550 inet_pton(AF_INET6, host, &a) != 1))
3551 ret = add_srcip(cmd, av, cblen, tstate);
3552 if (ret == NULL && strcmp(av, "any") != 0)
3559 add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3562 char *host, *ch, buf[INET6_ADDRSTRLEN];
3563 ipfw_insn *ret = NULL;
3566 /* Copy first address in set if needed */
3567 if ((ch = strpbrk(av, "/,")) != NULL) {
3569 strlcpy(buf, av, sizeof(buf));
3570 if (len < sizeof(buf))
3576 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3577 inet_pton(AF_INET6, host, &a) == 1)
3578 ret = add_dstip6(cmd, av, cblen, tstate);
3579 /* XXX: should check for IPv4, not !IPv6 */
3580 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3581 inet_pton(AF_INET6, host, &a) != 1))
3582 ret = add_dstip(cmd, av, cblen, tstate);
3583 if (ret == NULL && strcmp(av, "any") != 0)
3590 * Parse arguments and assemble the microinstructions which make up a rule.
3591 * Rules are added into the 'rulebuf' and then copied in the correct order
3592 * into the actual rule.
3594 * The syntax for a rule starts with the action, followed by
3595 * optional action parameters, and the various match patterns.
3596 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
3597 * (generated if the rule includes a keep-state option), then the
3598 * various match patterns, log/altq actions, and the actual action.
3602 compile_rule(char *av[], uint32_t *rbuf, int *rbufsize, struct tidx *tstate)
3605 * rules are added into the 'rulebuf' and then copied in
3606 * the correct order into the actual rule.
3607 * Some things that need to go out of order (prob, action etc.)
3610 static uint32_t actbuf[255], cmdbuf[255];
3611 int rblen, ablen, cblen;
3613 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
3614 ipfw_insn *first_cmd; /* first match pattern */
3616 struct ip_fw_rule *rule;
3619 * various flags used to record that we entered some fields.
3621 ipfw_insn *have_state = NULL; /* check-state or keep-state */
3622 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
3627 int open_par = 0; /* open parenthesis ( */
3629 /* proto is here because it is used to fetch ports */
3630 u_char proto = IPPROTO_IP; /* default protocol */
3632 double match_prob = 1; /* match probability, default is always match */
3634 bzero(actbuf, sizeof(actbuf)); /* actions go here */
3635 bzero(cmdbuf, sizeof(cmdbuf));
3636 bzero(rbuf, *rbufsize);
3638 rule = (struct ip_fw_rule *)rbuf;
3639 cmd = (ipfw_insn *)cmdbuf;
3640 action = (ipfw_insn *)actbuf;
3642 rblen = *rbufsize / sizeof(uint32_t);
3643 rblen -= sizeof(struct ip_fw_rule) / sizeof(uint32_t);
3644 ablen = sizeof(actbuf) / sizeof(actbuf[0]);
3645 cblen = sizeof(cmdbuf) / sizeof(cmdbuf[0]);
3646 cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
3648 #define CHECK_RBUFLEN(len) { CHECK_LENGTH(rblen, len); rblen -= len; }
3649 #define CHECK_ACTLEN CHECK_LENGTH(ablen, action->len)
3653 /* [rule N] -- Rule number optional */
3654 if (av[0] && isdigit(**av)) {
3655 rule->rulenum = atoi(*av);
3659 /* [set N] -- set number (0..RESVD_SET), optional */
3660 if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
3661 int set = strtoul(av[1], NULL, 10);
3662 if (set < 0 || set > RESVD_SET)
3663 errx(EX_DATAERR, "illegal set %s", av[1]);
3669 /* [prob D] -- match probability, optional */
3670 if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
3671 match_prob = strtod(av[1], NULL);
3673 if (match_prob <= 0 || match_prob > 1)
3674 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
3678 /* action -- mandatory */
3679 NEED1("missing action");
3680 i = match_token(rule_actions, *av);
3682 action->len = 1; /* default */
3685 case TOK_CHECKSTATE:
3686 have_state = action;
3687 action->opcode = O_CHECK_STATE;
3691 action->opcode = O_ACCEPT;
3695 action->opcode = O_DENY;
3700 action->opcode = O_REJECT;
3701 action->arg1 = ICMP_UNREACH_HOST;
3705 action->opcode = O_REJECT;
3706 action->arg1 = ICMP_REJECT_RST;
3710 action->opcode = O_UNREACH6;
3711 action->arg1 = ICMP6_UNREACH_RST;
3715 action->opcode = O_REJECT;
3716 NEED1("missing reject code");
3717 fill_reject_code(&action->arg1, *av);
3722 action->opcode = O_UNREACH6;
3723 NEED1("missing unreach code");
3724 fill_unreach6_code(&action->arg1, *av);
3729 action->opcode = O_COUNT;
3733 action->opcode = O_NAT;
3734 action->len = F_INSN_SIZE(ipfw_insn_nat);
3736 if (*av != NULL && _substrcmp(*av, "global") == 0) {
3737 action->arg1 = IP_FW_NAT44_GLOBAL;
3743 action->opcode = O_QUEUE;
3746 action->opcode = O_PIPE;
3749 action->opcode = O_SKIPTO;
3752 action->opcode = O_NETGRAPH;
3755 action->opcode = O_NGTEE;
3758 action->opcode = O_DIVERT;
3761 action->opcode = O_TEE;
3764 action->opcode = O_CALLRETURN;
3767 errx(EX_USAGE, "missing argument for %s", *(av - 1));
3768 if (isdigit(**av)) {
3769 action->arg1 = strtoul(*av, NULL, 10);
3770 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
3771 errx(EX_DATAERR, "illegal argument for %s",
3773 } else if (_substrcmp(*av, "tablearg") == 0) {
3774 action->arg1 = IP_FW_TARG;
3775 } else if (i == TOK_DIVERT || i == TOK_TEE) {
3778 s = getservbyname(av[0], "divert");
3780 action->arg1 = ntohs(s->s_port);
3782 errx(EX_DATAERR, "illegal divert/tee port");
3784 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
3790 * Locate the address-port separator (':' or ',').
3791 * Could be one of the following:
3795 * IPv6 w:x:y::z,port
3796 * The ':' can only be used with hostname and IPv4 address.
3797 * XXX-BZ Should we also support [w:x:y::z]:port?
3799 struct sockaddr_storage result;
3800 struct addrinfo *res;
3803 u_short port_number;
3805 NEED1("missing forward address[:port]");
3808 * locate the address-port separator (':' or ',')
3810 s = strchr(*av, ',');
3812 /* Distinguish between IPv4:port and IPv6 cases. */
3813 s = strchr(*av, ':');
3814 if (s && strchr(s+1, ':'))
3815 s = NULL; /* no port */
3820 /* Terminate host portion and set s to start of port. */
3822 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
3825 "illegal forwarding port ``%s''", s);
3826 port_number = (u_short)i;
3829 if (_substrcmp(*av, "tablearg") == 0) {
3831 ((struct sockaddr_in*)&result)->sin_addr.s_addr =
3835 * Resolve the host name or address to a family and a
3836 * network representation of the address.
3838 if (getaddrinfo(*av, NULL, NULL, &res))
3839 errx(EX_DATAERR, NULL);
3840 /* Just use the first host in the answer. */
3841 family = res->ai_family;
3842 memcpy(&result, res->ai_addr, res->ai_addrlen);
3846 if (family == PF_INET) {
3847 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
3849 action->opcode = O_FORWARD_IP;
3850 action->len = F_INSN_SIZE(ipfw_insn_sa);
3854 * In the kernel we assume AF_INET and use only
3855 * sin_port and sin_addr. Remember to set sin_len as
3856 * the routing code seems to use it too.
3858 p->sa.sin_len = sizeof(struct sockaddr_in);
3859 p->sa.sin_family = AF_INET;
3860 p->sa.sin_port = port_number;
3861 p->sa.sin_addr.s_addr =
3862 ((struct sockaddr_in *)&result)->sin_addr.s_addr;
3863 } else if (family == PF_INET6) {
3864 ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
3866 action->opcode = O_FORWARD_IP6;
3867 action->len = F_INSN_SIZE(ipfw_insn_sa6);
3870 p->sa.sin6_len = sizeof(struct sockaddr_in6);
3871 p->sa.sin6_family = AF_INET6;
3872 p->sa.sin6_port = port_number;
3873 p->sa.sin6_flowinfo = 0;
3874 p->sa.sin6_scope_id =
3875 ((struct sockaddr_in6 *)&result)->sin6_scope_id;
3876 bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
3877 &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
3879 errx(EX_DATAERR, "Invalid address family in forward action");
3885 /* pretend it is a 'count' rule followed by the comment */
3886 action->opcode = O_COUNT;
3887 av--; /* go back... */
3893 size_t intsize = sizeof(int);
3895 action->opcode = O_SETFIB;
3896 NEED1("missing fib number");
3897 if (_substrcmp(*av, "tablearg") == 0) {
3898 action->arg1 = IP_FW_TARG;
3900 action->arg1 = strtoul(*av, NULL, 10);
3901 if (sysctlbyname("net.fibs", &numfibs, &intsize,
3903 errx(EX_DATAERR, "fibs not suported.\n");
3904 if (action->arg1 >= numfibs) /* Temporary */
3905 errx(EX_DATAERR, "fib too large.\n");
3906 /* Add high-order bit to fib to make room for tablearg*/
3907 action->arg1 |= 0x8000;
3917 action->opcode = O_SETDSCP;
3918 NEED1("missing DSCP code");
3919 if (_substrcmp(*av, "tablearg") == 0) {
3920 action->arg1 = IP_FW_TARG;
3922 if (isalpha(*av[0])) {
3923 if ((code = match_token(f_ipdscp, *av)) == -1)
3924 errx(EX_DATAERR, "Unknown DSCP code");
3925 action->arg1 = code;
3927 action->arg1 = strtoul(*av, NULL, 10);
3929 * Add high-order bit to DSCP to make room
3932 action->arg1 |= 0x8000;
3939 action->opcode = O_REASS;
3943 fill_cmd(action, O_CALLRETURN, F_NOT, 0);
3948 if (match_token(rule_eactions, *av) == -1)
3949 errx(EX_DATAERR, "invalid action %s\n", *av);
3951 * External actions support.
3952 * XXX: we support only syntax with instance name.
3953 * For known external actions (from rule_eactions list)
3954 * we can handle syntax directly. But with `eaction'
3955 * keyword we can use only `eaction <name> <instance>'
3961 NEED1("Missing eaction name");
3962 if (eaction_check_name(*av) != 0)
3963 errx(EX_DATAERR, "Invalid eaction name %s", *av);
3964 idx = pack_object(tstate, *av, IPFW_TLV_EACTION);
3966 errx(EX_DATAERR, "pack_object failed");
3967 fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
3969 NEED1("Missing eaction instance name");
3970 action = next_cmd(action, &ablen);
3973 if (eaction_check_name(*av) != 0)
3974 errx(EX_DATAERR, "Invalid eaction instance name %s",
3977 * External action instance object has TLV type depended
3978 * from the external action name object index. Since we
3979 * currently don't know this index, use zero as TLV type.
3981 idx = pack_object(tstate, *av, 0);
3983 errx(EX_DATAERR, "pack_object failed");
3984 fill_cmd(action, O_EXTERNAL_INSTANCE, 0, idx);
3988 action = next_cmd(action, &ablen);
3991 * [altq queuename] -- altq tag, optional
3992 * [log [logamount N]] -- log, optional
3994 * If they exist, it go first in the cmdbuf, but then it is
3995 * skipped in the copy section to the end of the buffer.
3997 while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
4002 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
4007 "log cannot be specified more than once");
4008 have_log = (ipfw_insn *)c;
4009 cmd->len = F_INSN_SIZE(ipfw_insn_log);
4011 cmd->opcode = O_LOG;
4012 if (av[0] && _substrcmp(*av, "logamount") == 0) {
4014 NEED1("logamount requires argument");
4018 "logamount must be positive");
4022 len = sizeof(c->max_log);
4023 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
4024 &c->max_log, &len, NULL, 0) == -1) {
4029 errx(1, "sysctlbyname(\"%s\")",
4030 "net.inet.ip.fw.verbose_limit");
4039 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
4041 NEED1("missing altq queue name");
4044 "altq cannot be specified more than once");
4045 have_altq = (ipfw_insn *)a;
4046 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
4048 cmd->opcode = O_ALTQ;
4049 a->qid = altq_name_to_qid(*av);
4060 errx(EX_USAGE, "tag and untag cannot be "
4061 "specified more than once");
4062 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
4063 rule_action_params);
4065 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
4073 cmd = next_cmd(cmd, &cblen);
4076 if (have_state) /* must be a check-state, we are done */
4079 #define OR_START(target) \
4080 if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
4082 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
4085 if ( (av[0])[1] == '\0') { \
4096 strcmp(*av, ")") == 0 || \
4097 strcmp(*av, "}") == 0)) { \
4102 errx(EX_USAGE, "missing \")\"\n"); \
4106 if (av[0] && _substrcmp(*av, "not") == 0) { \
4107 if (cmd->len & F_NOT) \
4108 errx(EX_USAGE, "double \"not\" not allowed\n"); \
4109 cmd->len |= F_NOT; \
4113 #define OR_BLOCK(target) \
4114 if (av[0] && _substrcmp(*av, "or") == 0) { \
4115 if (prev == NULL || open_par == 0) \
4116 errx(EX_DATAERR, "invalid OR block"); \
4117 prev->len |= F_OR; \
4127 * MAC addresses, optional.
4128 * If we have this, we skip the part "proto from src to dst"
4129 * and jump straight to the option parsing.
4132 NEED1("missing protocol");
4133 if (_substrcmp(*av, "MAC") == 0 ||
4134 _substrcmp(*av, "mac") == 0) {
4135 av++; /* the "MAC" keyword */
4136 add_mac(cmd, av); /* exits in case of errors */
4137 cmd = next_cmd(cmd);
4138 av += 2; /* dst-mac and src-mac */
4140 NEED1("missing mac type");
4141 if (add_mactype(cmd, av[0]))
4142 cmd = next_cmd(cmd);
4143 av++; /* any or mac-type */
4149 * protocol, mandatory
4151 OR_START(get_proto);
4153 NEED1("missing protocol");
4154 if (add_proto_compat(cmd, *av, &proto)) {
4156 if (F_LEN(cmd) != 0) {
4158 cmd = next_cmd(cmd, &cblen);
4160 } else if (first_cmd != cmd) {
4161 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
4164 OR_BLOCK(get_proto);
4169 if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
4170 errx(EX_USAGE, "missing ``from''");
4174 * source IP, mandatory
4176 OR_START(source_ip);
4177 NOT_BLOCK; /* optional "not" */
4178 NEED1("missing source address");
4179 if (add_src(cmd, *av, proto, cblen, tstate)) {
4181 if (F_LEN(cmd) != 0) { /* ! any */
4183 cmd = next_cmd(cmd, &cblen);
4186 errx(EX_USAGE, "bad source address %s", *av);
4187 OR_BLOCK(source_ip);
4190 * source ports, optional
4192 NOT_BLOCK; /* optional "not" */
4193 if ( av[0] != NULL ) {
4194 if (_substrcmp(*av, "any") == 0 ||
4195 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4197 if (F_LEN(cmd) != 0)
4198 cmd = next_cmd(cmd, &cblen);
4205 if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
4206 errx(EX_USAGE, "missing ``to''");
4210 * destination, mandatory
4213 NOT_BLOCK; /* optional "not" */
4214 NEED1("missing dst address");
4215 if (add_dst(cmd, *av, proto, cblen, tstate)) {
4217 if (F_LEN(cmd) != 0) { /* ! any */
4219 cmd = next_cmd(cmd, &cblen);
4222 errx( EX_USAGE, "bad destination address %s", *av);
4226 * dest. ports, optional
4228 NOT_BLOCK; /* optional "not" */
4230 if (_substrcmp(*av, "any") == 0 ||
4231 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4233 if (F_LEN(cmd) != 0)
4234 cmd = next_cmd(cmd, &cblen);
4239 if (av[0] && first_cmd == cmd) {
4241 * nothing specified so far, store in the rule to ease
4244 rule->flags |= IPFW_RULE_NOOPT;
4247 while ( av[0] != NULL ) {
4249 ipfw_insn_u32 *cmd32; /* alias for cmd */
4252 cmd32 = (ipfw_insn_u32 *)cmd;
4254 if (*s == '!') { /* alternate syntax for NOT */
4255 if (cmd->len & F_NOT)
4256 errx(EX_USAGE, "double \"not\" not allowed\n");
4260 i = match_token(rule_options, s);
4264 if (cmd->len & F_NOT)
4265 errx(EX_USAGE, "double \"not\" not allowed\n");
4270 if (open_par == 0 || prev == NULL)
4271 errx(EX_USAGE, "invalid \"or\" block\n");
4275 case TOK_STARTBRACE:
4277 errx(EX_USAGE, "+nested \"(\" not allowed\n");
4283 errx(EX_USAGE, "+missing \")\"\n");
4289 fill_cmd(cmd, O_IN, 0, 0);
4293 cmd->len ^= F_NOT; /* toggle F_NOT */
4294 fill_cmd(cmd, O_IN, 0, 0);
4298 fill_cmd(cmd, O_DIVERTED, 0, 3);
4301 case TOK_DIVERTEDLOOPBACK:
4302 fill_cmd(cmd, O_DIVERTED, 0, 1);
4305 case TOK_DIVERTEDOUTPUT:
4306 fill_cmd(cmd, O_DIVERTED, 0, 2);
4310 fill_cmd(cmd, O_FRAG, 0, 0);
4314 fill_cmd(cmd, O_LAYER2, 0, 0);
4320 NEED1("recv, xmit, via require interface name"
4322 fill_iface((ipfw_insn_if *)cmd, av[0], cblen, tstate);
4324 if (F_LEN(cmd) == 0) /* not a valid address */
4327 cmd->opcode = O_XMIT;
4328 else if (i == TOK_RECV)
4329 cmd->opcode = O_RECV;
4330 else if (i == TOK_VIA)
4331 cmd->opcode = O_VIA;
4335 NEED1("icmptypes requires list of types");
4336 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
4340 case TOK_ICMP6TYPES:
4341 NEED1("icmptypes requires list of types");
4342 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
4347 NEED1("ipttl requires TTL");
4348 if (strpbrk(*av, "-,")) {
4349 if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
4350 errx(EX_DATAERR, "invalid ipttl %s", *av);
4352 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
4357 NEED1("ipid requires id");
4358 if (strpbrk(*av, "-,")) {
4359 if (!add_ports(cmd, *av, 0, O_IPID, cblen))
4360 errx(EX_DATAERR, "invalid ipid %s", *av);
4362 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
4367 NEED1("iplen requires length");
4368 if (strpbrk(*av, "-,")) {
4369 if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
4370 errx(EX_DATAERR, "invalid ip len %s", *av);
4372 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
4377 NEED1("ipver requires version");
4378 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
4382 case TOK_IPPRECEDENCE:
4383 NEED1("ipprecedence requires value");
4384 fill_cmd(cmd, O_IPPRECEDENCE, 0,
4385 (strtoul(*av, NULL, 0) & 7) << 5);
4390 NEED1("missing DSCP code");
4391 fill_dscp(cmd, *av, cblen);
4396 NEED1("missing argument for ipoptions");
4397 fill_flags_cmd(cmd, O_IPOPT, f_ipopts, *av);
4402 NEED1("missing argument for iptos");
4403 fill_flags_cmd(cmd, O_IPTOS, f_iptos, *av);
4408 NEED1("uid requires argument");
4414 cmd->opcode = O_UID;
4415 uid = strtoul(*av, &end, 0);
4416 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
4418 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
4419 cmd32->d[0] = pwd->pw_uid;
4420 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4426 NEED1("gid requires argument");
4432 cmd->opcode = O_GID;
4433 gid = strtoul(*av, &end, 0);
4434 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
4436 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
4437 cmd32->d[0] = grp->gr_gid;
4438 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4444 NEED1("jail requires argument");
4449 cmd->opcode = O_JAIL;
4450 jid = (int)strtol(*av, &end, 0);
4451 if (jid < 0 || *end != '\0')
4452 errx(EX_DATAERR, "jail requires prison ID");
4453 cmd32->d[0] = (uint32_t)jid;
4454 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4460 fill_cmd(cmd, O_ESTAB, 0, 0);
4464 fill_cmd(cmd, O_TCPFLAGS, 0,
4465 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
4468 case TOK_TCPDATALEN:
4469 NEED1("tcpdatalen requires length");
4470 if (strpbrk(*av, "-,")) {
4471 if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
4472 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
4474 fill_cmd(cmd, O_TCPDATALEN, 0,
4475 strtoul(*av, NULL, 0));
4480 NEED1("missing argument for tcpoptions");
4481 fill_flags_cmd(cmd, O_TCPOPTS, f_tcpopts, *av);
4487 NEED1("tcpseq/tcpack requires argument");
4488 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
4489 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
4490 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
4495 NEED1("tcpwin requires length");
4496 if (strpbrk(*av, "-,")) {
4497 if (!add_ports(cmd, *av, 0, O_TCPWIN, cblen))
4498 errx(EX_DATAERR, "invalid tcpwin len %s", *av);
4500 fill_cmd(cmd, O_TCPWIN, 0,
4501 strtoul(*av, NULL, 0));
4506 NEED1("missing argument for tcpflags");
4507 cmd->opcode = O_TCPFLAGS;
4508 fill_flags_cmd(cmd, O_TCPFLAGS, f_tcpflags, *av);
4514 errx(EX_USAGE, "keep-state cannot be part "
4517 errx(EX_USAGE, "only one of keep-state "
4518 "and limit is allowed");
4520 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
4524 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
4529 "limit cannot be part of an or block");
4531 errx(EX_USAGE, "only one of keep-state and "
4532 "limit is allowed");
4535 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
4537 cmd->opcode = O_LIMIT;
4538 c->limit_mask = c->conn_limit = 0;
4540 while ( av[0] != NULL ) {
4541 if ((val = match_token(limit_masks, *av)) <= 0)
4543 c->limit_mask |= val;
4547 if (c->limit_mask == 0)
4548 errx(EX_USAGE, "limit: missing limit mask");
4550 GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
4551 TOK_LIMIT, rule_options);
4558 NEED1("missing protocol");
4559 if (add_proto(cmd, *av, &proto)) {
4562 errx(EX_DATAERR, "invalid protocol ``%s''",
4567 NEED1("missing source IP");
4568 if (add_srcip(cmd, *av, cblen, tstate)) {
4574 NEED1("missing destination IP");
4575 if (add_dstip(cmd, *av, cblen, tstate)) {
4581 NEED1("missing source IP6");
4582 if (add_srcip6(cmd, *av, cblen, tstate)) {
4588 NEED1("missing destination IP6");
4589 if (add_dstip6(cmd, *av, cblen, tstate)) {
4595 NEED1("missing source port");
4596 if (_substrcmp(*av, "any") == 0 ||
4597 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4600 errx(EX_DATAERR, "invalid source port %s", *av);
4604 NEED1("missing destination port");
4605 if (_substrcmp(*av, "any") == 0 ||
4606 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4609 errx(EX_DATAERR, "invalid destination port %s",
4614 if (add_mac(cmd, av, cblen))
4619 NEED1("missing mac type");
4620 if (!add_mactype(cmd, *av, cblen))
4621 errx(EX_DATAERR, "invalid mac type %s", *av);
4625 case TOK_VERREVPATH:
4626 fill_cmd(cmd, O_VERREVPATH, 0, 0);
4629 case TOK_VERSRCREACH:
4630 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
4634 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
4638 fill_cmd(cmd, O_IPSEC, 0, 0);
4642 fill_cmd(cmd, O_IP6, 0, 0);
4646 fill_cmd(cmd, O_IP4, 0, 0);
4650 fill_ext6hdr( cmd, *av );
4655 if (proto != IPPROTO_IPV6 )
4656 errx( EX_USAGE, "flow-id filter is active "
4657 "only for ipv6 protocol\n");
4658 fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
4663 fill_comment(cmd, av, cblen);
4668 if (av[0] && strpbrk(*av, "-,")) {
4669 if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
4670 errx(EX_DATAERR, "tagged: invalid tag"
4676 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
4677 TOK_TAGGED, rule_options);
4678 fill_cmd(cmd, O_TAGGED, 0, tag);
4684 NEED1("fib requires fib number");
4685 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
4689 fill_cmd(cmd, O_SOCKARG, 0, 0);
4693 ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
4696 if (!av[0] || !av[1])
4697 errx(EX_USAGE, "format: lookup argument tablenum");
4698 cmd->opcode = O_IP_DST_LOOKUP;
4699 cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
4700 i = match_token(rule_options, *av);
4701 for (j = 0; lookup_key[j] >= 0 ; j++) {
4702 if (i == lookup_key[j])
4705 if (lookup_key[j] <= 0)
4706 errx(EX_USAGE, "format: cannot lookup on %s", *av);
4707 __PAST_END(c->d, 1) = j; // i converted to option
4710 if ((j = pack_table(tstate, *av)) == 0)
4711 errx(EX_DATAERR, "Invalid table name: %s", *av);
4718 NEED1("missing table name");
4719 if (strncmp(*av, "table(", 6) != 0)
4721 "enclose table name into \"table()\"");
4722 fill_table(cmd, *av, O_IP_FLOW_LOOKUP, tstate);
4727 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
4729 if (F_LEN(cmd) > 0) { /* prepare to advance */
4731 cmd = next_cmd(cmd, &cblen);
4737 * Now copy stuff into the rule.
4738 * If we have a keep-state option, the first instruction
4739 * must be a PROBE_STATE (which is generated here).
4740 * If we have a LOG option, it was stored as the first command,
4741 * and now must be moved to the top of the action part.
4743 dst = (ipfw_insn *)rule->cmd;
4746 * First thing to write into the command stream is the match probability.
4748 if (match_prob != 1) { /* 1 means always match */
4749 dst->opcode = O_PROB;
4751 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
4756 * generate O_PROBE_STATE if necessary
4758 if (have_state && have_state->opcode != O_CHECK_STATE) {
4759 fill_cmd(dst, O_PROBE_STATE, 0, 0);
4760 dst = next_cmd(dst, &rblen);
4763 /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
4764 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
4768 switch (src->opcode) {
4776 bcopy(src, dst, i * sizeof(uint32_t));
4782 * put back the have_state command as last opcode
4784 if (have_state && have_state->opcode != O_CHECK_STATE) {
4785 i = F_LEN(have_state);
4787 bcopy(have_state, dst, i * sizeof(uint32_t));
4791 * start action section
4793 rule->act_ofs = dst - rule->cmd;
4795 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
4797 i = F_LEN(have_log);
4799 bcopy(have_log, dst, i * sizeof(uint32_t));
4803 i = F_LEN(have_altq);
4805 bcopy(have_altq, dst, i * sizeof(uint32_t));
4809 i = F_LEN(have_tag);
4811 bcopy(have_tag, dst, i * sizeof(uint32_t));
4816 * copy all other actions
4818 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
4821 bcopy(src, dst, i * sizeof(uint32_t));
4825 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
4826 *rbufsize = (char *)dst - (char *)rule;
4830 compare_ntlv(const void *_a, const void *_b)
4832 ipfw_obj_ntlv *a, *b;
4834 a = (ipfw_obj_ntlv *)_a;
4835 b = (ipfw_obj_ntlv *)_b;
4837 if (a->set < b->set)
4839 else if (a->set > b->set)
4842 if (a->idx < b->idx)
4844 else if (a->idx > b->idx)
4847 if (a->head.type < b->head.type)
4849 else if (a->head.type > b->head.type)
4856 * Provide kernel with sorted list of referenced objects
4859 object_sort_ctlv(ipfw_obj_ctlv *ctlv)
4862 qsort(ctlv + 1, ctlv->count, ctlv->objsize, compare_ntlv);
4870 compare_object_kntlv(const void *k, const void *v)
4872 ipfw_obj_ntlv *ntlv;
4873 struct object_kt key;
4875 key = *((struct object_kt *)k);
4876 ntlv = (ipfw_obj_ntlv *)v;
4878 if (key.uidx < ntlv->idx)
4880 else if (key.uidx > ntlv->idx)
4883 if (key.type < ntlv->head.type)
4885 else if (key.type > ntlv->head.type)
4892 * Finds object name in @ctlv by @idx and @type.
4893 * Uses the following facts:
4894 * 1) All TLVs are the same size
4895 * 2) Kernel implementation provides already sorted list.
4897 * Returns table name or NULL.
4900 object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx, uint16_t type)
4902 ipfw_obj_ntlv *ntlv;
4903 struct object_kt key;
4908 ntlv = bsearch(&key, (ctlv + 1), ctlv->count, ctlv->objsize,
4909 compare_object_kntlv);
4912 return (ntlv->name);
4918 table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx)
4921 return (object_search_ctlv(ctlv, idx, IPFW_TLV_TBL_NAME));
4925 * Adds one or more rules to ipfw chain.
4930 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
4931 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ] (*2) (*3)
4936 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
4937 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ]
4940 * Rules in reply are modified to store their actual ruleset number.
4942 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
4943 * according to their idx field and there has to be no duplicates.
4944 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
4945 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
4948 ipfw_add(char *av[])
4950 uint32_t rulebuf[1024];
4951 int rbufsize, default_off, tlen, rlen;
4954 struct ip_fw_rule *rule;
4956 ip_fw3_opheader *op3;
4957 ipfw_obj_ctlv *ctlv, *tstate;
4959 rbufsize = sizeof(rulebuf);
4960 memset(rulebuf, 0, rbufsize);
4961 memset(&ts, 0, sizeof(ts));
4963 /* Optimize case with no tables */
4964 default_off = sizeof(ipfw_obj_ctlv) + sizeof(ip_fw3_opheader);
4965 op3 = (ip_fw3_opheader *)rulebuf;
4966 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
4967 rule = (struct ip_fw_rule *)(ctlv + 1);
4968 rbufsize -= default_off;
4970 compile_rule(av, (uint32_t *)rule, &rbufsize, &ts);
4971 /* Align rule size to u64 boundary */
4972 rlen = roundup2(rbufsize, sizeof(uint64_t));
4977 if (ts.count != 0) {
4978 /* Some tables. We have to alloc more data */
4979 tlen = ts.count * sizeof(ipfw_obj_ntlv);
4980 sz = default_off + sizeof(ipfw_obj_ctlv) + tlen + rlen;
4982 if ((tbuf = calloc(1, sz)) == NULL)
4983 err(EX_UNAVAILABLE, "malloc() failed for IP_FW_ADD");
4984 op3 = (ip_fw3_opheader *)tbuf;
4986 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
4987 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
4988 ctlv->head.length = sizeof(ipfw_obj_ctlv) + tlen;
4989 ctlv->count = ts.count;
4990 ctlv->objsize = sizeof(ipfw_obj_ntlv);
4991 memcpy(ctlv + 1, ts.idx, tlen);
4992 object_sort_ctlv(ctlv);
4995 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
4996 ctlv->head.type = IPFW_TLV_RULE_LIST;
4997 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
4999 memcpy(ctlv + 1, rule, rbufsize);
5001 /* Simply add header */
5002 sz = rlen + default_off;
5003 memset(ctlv, 0, sizeof(*ctlv));
5004 ctlv->head.type = IPFW_TLV_RULE_LIST;
5005 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5009 if (do_get3(IP_FW_XADD, op3, &sz) != 0)
5010 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_XADD");
5013 struct format_opts sfo;
5015 memset(&sfo, 0, sizeof(sfo));
5016 sfo.tstate = tstate;
5017 sfo.set_mask = (uint32_t)(-1);
5018 bp_alloc(&bp, 4096);
5019 show_static_rule(&co, &sfo, &bp, rule, NULL);
5020 printf("%s", bp.buf);
5032 * clear the counters or the log counters.
5033 * optname has the following values:
5034 * 0 (zero both counters and logging)
5035 * 1 (zero logging only)
5038 ipfw_zero(int ac, char *av[], int optname)
5044 char const *name = optname ? "RESETLOG" : "ZERO";
5046 optname = optname ? IP_FW_XRESETLOG : IP_FW_XZERO;
5047 memset(&rt, 0, sizeof(rt));
5052 /* clear all entries */
5053 rt.flags = IPFW_RCFLAG_ALL;
5054 if (do_range_cmd(optname, &rt) < 0)
5055 err(EX_UNAVAILABLE, "setsockopt(IP_FW_X%s)", name);
5057 printf("%s.\n", optname == IP_FW_XZERO ?
5058 "Accounting cleared":"Logging counts reset");
5065 if (isdigit(**av)) {
5066 arg = strtonum(*av, 0, 0xffff, &errstr);
5069 "invalid rule number %s\n", *av);
5070 rt.start_rule = arg;
5072 rt.flags |= IPFW_RCFLAG_RANGE;
5073 if (co.use_set != 0) {
5074 rt.set = co.use_set - 1;
5075 rt.flags |= IPFW_RCFLAG_SET;
5077 if (do_range_cmd(optname, &rt) != 0) {
5078 warn("rule %u: setsockopt(IP_FW_X%s)",
5080 failed = EX_UNAVAILABLE;
5081 } else if (rt.new_set == 0) {
5082 printf("Entry %d not found\n", arg);
5083 failed = EX_UNAVAILABLE;
5084 } else if (!co.do_quiet)
5085 printf("Entry %d %s.\n", arg,
5086 optname == IP_FW_XZERO ?
5087 "cleared" : "logging count reset");
5089 errx(EX_USAGE, "invalid rule number ``%s''", *av);
5093 if (failed != EX_OK)
5098 ipfw_flush(int force)
5102 if (!force && !co.do_quiet) { /* need to ask user */
5105 printf("Are you sure? [yn] ");
5108 c = toupper(getc(stdin));
5109 while (c != '\n' && getc(stdin) != '\n')
5111 return; /* and do not flush */
5112 } while (c != 'Y' && c != 'N');
5114 if (c == 'N') /* user said no */
5121 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
5122 memset(&rt, 0, sizeof(rt));
5123 if (co.use_set != 0) {
5124 rt.set = co.use_set - 1;
5125 rt.flags = IPFW_RCFLAG_SET;
5127 rt.flags = IPFW_RCFLAG_ALL;
5128 if (do_range_cmd(IP_FW_XDEL, &rt) != 0)
5129 err(EX_UNAVAILABLE, "setsockopt(IP_FW_XDEL)");
5131 printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
5134 static struct _s_x intcmds[] = {
5135 { "talist", TOK_TALIST },
5136 { "iflist", TOK_IFLIST },
5137 { "olist", TOK_OLIST },
5138 { "vlist", TOK_VLIST },
5142 static struct _s_x otypes[] = {
5143 { "EACTION", IPFW_TLV_EACTION },
5148 lookup_eaction_name(ipfw_obj_ntlv *ntlv, int cnt, uint16_t type)
5154 for (i = 0; i < cnt; i++) {
5155 if (ntlv[i].head.type != IPFW_TLV_EACTION)
5157 if (IPFW_TLV_EACTION_NAME(ntlv[i].idx) != type)
5159 name = ntlv[i].name;
5166 ipfw_list_objects(int ac, char *av[])
5168 ipfw_obj_lheader req, *olh;
5169 ipfw_obj_ntlv *ntlv;
5174 memset(&req, 0, sizeof(req));
5176 if (do_get3(IP_FW_DUMP_SRVOBJECTS, &req.opheader, &sz) != 0)
5177 if (errno != ENOMEM)
5181 if ((olh = calloc(1, sz)) == NULL)
5185 if (do_get3(IP_FW_DUMP_SRVOBJECTS, &olh->opheader, &sz) != 0) {
5191 printf("Objects list:\n");
5193 printf("There are no objects\n");
5194 ntlv = (ipfw_obj_ntlv *)(olh + 1);
5195 for (i = 0; i < olh->count; i++) {
5196 name = match_value(otypes, ntlv->head.type);
5198 name = lookup_eaction_name(
5199 (ipfw_obj_ntlv *)(olh + 1), olh->count,
5202 printf(" kidx: %4d\ttype: %10d\tname: %s\n",
5203 ntlv->idx, ntlv->head.type, ntlv->name);
5205 printf(" kidx: %4d\ttype: %10s\tname: %s\n",
5206 ntlv->idx, name, ntlv->name);
5213 ipfw_internal_handler(int ac, char *av[])
5218 NEED1("internal cmd required");
5220 if ((tcmd = match_token(intcmds, *av)) == -1)
5221 errx(EX_USAGE, "invalid internal sub-cmd: %s", *av);
5225 ipfw_list_tifaces();
5228 ipfw_list_ta(ac, av);
5231 ipfw_list_objects(ac, av);
5234 ipfw_list_values(ac, av);
5240 ipfw_get_tracked_ifaces(ipfw_obj_lheader **polh)
5242 ipfw_obj_lheader req, *olh;
5245 memset(&req, 0, sizeof(req));
5248 if (do_get3(IP_FW_XIFLIST, &req.opheader, &sz) != 0) {
5249 if (errno != ENOMEM)
5254 if ((olh = calloc(1, sz)) == NULL)
5258 if (do_get3(IP_FW_XIFLIST, &olh->opheader, &sz) != 0) {
5268 ifinfo_cmp(const void *a, const void *b)
5270 ipfw_iface_info *ia, *ib;
5272 ia = (ipfw_iface_info *)a;
5273 ib = (ipfw_iface_info *)b;
5275 return (stringnum_cmp(ia->ifname, ib->ifname));
5279 * Retrieves table list from kernel,
5280 * optionally sorts it and calls requested function for each table.
5281 * Returns 0 on success.
5286 ipfw_obj_lheader *olh;
5287 ipfw_iface_info *info;
5290 if ((error = ipfw_get_tracked_ifaces(&olh)) != 0)
5291 err(EX_OSERR, "Unable to request ipfw tracked interface list");
5294 qsort(olh + 1, olh->count, olh->objsize, ifinfo_cmp);
5296 info = (ipfw_iface_info *)(olh + 1);
5297 for (i = 0; i < olh->count; i++) {
5298 if (info->flags & IPFW_IFFLAG_RESOLVED)
5299 printf("%s ifindex: %d refcount: %u changes: %u\n",
5300 info->ifname, info->ifindex, info->refcnt,
5303 printf("%s ifindex: unresolved refcount: %u changes: %u\n",
5304 info->ifname, info->refcnt, info->gencnt);
5305 info = (ipfw_iface_info *)((caddr_t)info + olh->objsize);