2 * Copyright (c) 2002-2003 Luigi Rizzo
3 * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
4 * Copyright (c) 1994 Ugen J.S.Antsilevich
6 * Idea and grammar partially left from:
7 * Copyright (c) 1993 Daniel Boulet
9 * Redistribution and use in source forms, with and without modification,
10 * are permitted provided that this entire comment appears intact.
12 * Redistribution in binary form may occur without any restrictions.
13 * Obviously, it would be nice if you gave credit where credit is due
14 * but requiring it would be too onerous.
16 * This software is provided ``AS IS'' without any warranties of any kind.
18 * NEW command line interface for IP firewall facility
23 #include <sys/types.h>
24 #include <sys/param.h>
25 #include <sys/socket.h>
26 #include <sys/sockio.h>
27 #include <sys/sysctl.h>
43 #include <time.h> /* ctime */
44 #include <timeconv.h> /* _long_to_time */
47 #include <stddef.h> /* offsetof */
49 #include <net/ethernet.h>
50 #include <net/if.h> /* only IFNAMSIZ */
51 #include <netinet/in.h>
52 #include <netinet/in_systm.h> /* only n_short, n_long */
53 #include <netinet/ip.h>
54 #include <netinet/ip_icmp.h>
55 #include <netinet/ip_fw.h>
56 #include <netinet/tcp.h>
57 #include <arpa/inet.h>
59 struct cmdline_opts co; /* global options */
65 int show_time; /* show timestamp */
66 uint32_t set_mask; /* enabled sets mask */
67 uint32_t flags; /* request flags */
68 uint32_t first; /* first rule to request */
69 uint32_t last; /* last rule to request */
70 uint32_t dcnt; /* number of dynamic states */
71 ipfw_obj_ctlv *tstate; /* table state data */
74 int resvd_set_number = RESVD_SET;
78 #define CHECK_LENGTH(v, len) do { \
80 errx(EX_DATAERR, "Rule too long"); \
83 * Check if we have enough space in cmd buffer. Note that since
84 * first 8? u32 words are reserved by reserved header, full cmd
85 * buffer can't be used, so we need to protect from buffer overrun
86 * only. At the beginning, cblen is less than actual buffer size by
87 * size of ipfw_insn_u32 instruction + 1 u32 work. This eliminates need
88 * for checking small instructions fitting in given range.
89 * We also (ab)use the fact that ipfw_insn is always the first field
90 * for any custom instruction.
92 #define CHECK_CMDLEN CHECK_LENGTH(cblen, F_LEN((ipfw_insn *)cmd))
94 #define GET_UINT_ARG(arg, min, max, tok, s_x) do { \
96 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
97 if (_substrcmp(*av, "tablearg") == 0) { \
106 _xval = strtol(*av, &end, 10); \
108 if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
109 errx(EX_DATAERR, "%s: invalid argument: %s", \
110 match_value(s_x, tok), *av); \
112 if (errno == ERANGE || _xval < min || _xval > max) \
113 errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
114 match_value(s_x, tok), min, max, *av); \
116 if (_xval == IP_FW_TARG) \
117 errx(EX_DATAERR, "%s: illegal argument value: %s", \
118 match_value(s_x, tok), *av); \
123 static struct _s_x f_tcpflags[] = {
134 static struct _s_x f_tcpopts[] = {
135 { "mss", IP_FW_TCPOPT_MSS },
136 { "maxseg", IP_FW_TCPOPT_MSS },
137 { "window", IP_FW_TCPOPT_WINDOW },
138 { "sack", IP_FW_TCPOPT_SACK },
139 { "ts", IP_FW_TCPOPT_TS },
140 { "timestamp", IP_FW_TCPOPT_TS },
141 { "cc", IP_FW_TCPOPT_CC },
147 * IP options span the range 0 to 255 so we need to remap them
148 * (though in fact only the low 5 bits are significant).
150 static struct _s_x f_ipopts[] = {
151 { "ssrr", IP_FW_IPOPT_SSRR},
152 { "lsrr", IP_FW_IPOPT_LSRR},
153 { "rr", IP_FW_IPOPT_RR},
154 { "ts", IP_FW_IPOPT_TS},
159 static struct _s_x f_iptos[] = {
160 { "lowdelay", IPTOS_LOWDELAY},
161 { "throughput", IPTOS_THROUGHPUT},
162 { "reliability", IPTOS_RELIABILITY},
163 { "mincost", IPTOS_MINCOST},
164 { "congestion", IPTOS_ECN_CE},
165 { "ecntransport", IPTOS_ECN_ECT0},
166 { "ip tos option", 0},
170 struct _s_x f_ipdscp[] = {
171 { "af11", IPTOS_DSCP_AF11 >> 2 }, /* 001010 */
172 { "af12", IPTOS_DSCP_AF12 >> 2 }, /* 001100 */
173 { "af13", IPTOS_DSCP_AF13 >> 2 }, /* 001110 */
174 { "af21", IPTOS_DSCP_AF21 >> 2 }, /* 010010 */
175 { "af22", IPTOS_DSCP_AF22 >> 2 }, /* 010100 */
176 { "af23", IPTOS_DSCP_AF23 >> 2 }, /* 010110 */
177 { "af31", IPTOS_DSCP_AF31 >> 2 }, /* 011010 */
178 { "af32", IPTOS_DSCP_AF32 >> 2 }, /* 011100 */
179 { "af33", IPTOS_DSCP_AF33 >> 2 }, /* 011110 */
180 { "af41", IPTOS_DSCP_AF41 >> 2 }, /* 100010 */
181 { "af42", IPTOS_DSCP_AF42 >> 2 }, /* 100100 */
182 { "af43", IPTOS_DSCP_AF43 >> 2 }, /* 100110 */
183 { "be", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
184 { "ef", IPTOS_DSCP_EF >> 2 }, /* 101110 */
185 { "cs0", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
186 { "cs1", IPTOS_DSCP_CS1 >> 2 }, /* 001000 */
187 { "cs2", IPTOS_DSCP_CS2 >> 2 }, /* 010000 */
188 { "cs3", IPTOS_DSCP_CS3 >> 2 }, /* 011000 */
189 { "cs4", IPTOS_DSCP_CS4 >> 2 }, /* 100000 */
190 { "cs5", IPTOS_DSCP_CS5 >> 2 }, /* 101000 */
191 { "cs6", IPTOS_DSCP_CS6 >> 2 }, /* 110000 */
192 { "cs7", IPTOS_DSCP_CS7 >> 2 }, /* 100000 */
196 static struct _s_x limit_masks[] = {
197 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
198 {"src-addr", DYN_SRC_ADDR},
199 {"src-port", DYN_SRC_PORT},
200 {"dst-addr", DYN_DST_ADDR},
201 {"dst-port", DYN_DST_PORT},
206 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
207 * This is only used in this code.
209 #define IPPROTO_ETHERTYPE 0x1000
210 static struct _s_x ether_types[] = {
212 * Note, we cannot use "-:&/" in the names because they are field
213 * separators in the type specifications. Also, we use s = NULL as
214 * end-delimiter, because a type of 0 can be legal.
227 { "pppoe_disc", 0x8863 },
228 { "pppoe_sess", 0x8864 },
229 { "ipx_8022", 0x00E0 },
230 { "ipx_8023", 0x0000 },
231 { "ipx_ii", 0x8137 },
232 { "ipx_snap", 0x8137 },
238 static struct _s_x rule_eactions[] = {
239 { "nat64lsn", TOK_NAT64LSN },
240 { "nat64stl", TOK_NAT64STL },
241 { "nptv6", TOK_NPTV6 },
242 { "tcp-setmss", TOK_TCPSETMSS },
243 { NULL, 0 } /* terminator */
246 static struct _s_x rule_actions[] = {
247 { "accept", TOK_ACCEPT },
248 { "pass", TOK_ACCEPT },
249 { "allow", TOK_ACCEPT },
250 { "permit", TOK_ACCEPT },
251 { "count", TOK_COUNT },
252 { "pipe", TOK_PIPE },
253 { "queue", TOK_QUEUE },
254 { "divert", TOK_DIVERT },
256 { "netgraph", TOK_NETGRAPH },
257 { "ngtee", TOK_NGTEE },
258 { "fwd", TOK_FORWARD },
259 { "forward", TOK_FORWARD },
260 { "skipto", TOK_SKIPTO },
261 { "deny", TOK_DENY },
262 { "drop", TOK_DENY },
263 { "reject", TOK_REJECT },
264 { "reset6", TOK_RESET6 },
265 { "reset", TOK_RESET },
266 { "unreach6", TOK_UNREACH6 },
267 { "unreach", TOK_UNREACH },
268 { "check-state", TOK_CHECKSTATE },
269 { "//", TOK_COMMENT },
271 { "reass", TOK_REASS },
272 { "setfib", TOK_SETFIB },
273 { "setdscp", TOK_SETDSCP },
274 { "call", TOK_CALL },
275 { "return", TOK_RETURN },
276 { "eaction", TOK_EACTION },
277 { "tcp-setmss", TOK_TCPSETMSS },
278 { NULL, 0 } /* terminator */
281 static struct _s_x rule_action_params[] = {
282 { "altq", TOK_ALTQ },
285 { "untag", TOK_UNTAG },
286 { NULL, 0 } /* terminator */
290 * The 'lookup' instruction accepts one of the following arguments.
291 * -1 is a terminator for the list.
292 * Arguments are passed as v[1] in O_DST_LOOKUP options.
294 static int lookup_key[] = {
295 TOK_DSTIP, TOK_SRCIP, TOK_DSTPORT, TOK_SRCPORT,
296 TOK_UID, TOK_JAIL, TOK_DSCP, -1 };
298 static struct _s_x rule_options[] = {
299 { "tagged", TOK_TAGGED },
302 { "jail", TOK_JAIL },
304 { "limit", TOK_LIMIT },
305 { "keep-state", TOK_KEEPSTATE },
306 { "bridged", TOK_LAYER2 },
307 { "layer2", TOK_LAYER2 },
309 { "diverted", TOK_DIVERTED },
310 { "diverted-loopback", TOK_DIVERTEDLOOPBACK },
311 { "diverted-output", TOK_DIVERTEDOUTPUT },
312 { "xmit", TOK_XMIT },
313 { "recv", TOK_RECV },
315 { "fragment", TOK_FRAG },
316 { "frag", TOK_FRAG },
318 { "ipoptions", TOK_IPOPTS },
319 { "ipopts", TOK_IPOPTS },
320 { "iplen", TOK_IPLEN },
321 { "ipid", TOK_IPID },
322 { "ipprecedence", TOK_IPPRECEDENCE },
323 { "dscp", TOK_DSCP },
324 { "iptos", TOK_IPTOS },
325 { "ipttl", TOK_IPTTL },
326 { "ipversion", TOK_IPVER },
327 { "ipver", TOK_IPVER },
328 { "estab", TOK_ESTAB },
329 { "established", TOK_ESTAB },
330 { "setup", TOK_SETUP },
331 { "sockarg", TOK_SOCKARG },
332 { "tcpdatalen", TOK_TCPDATALEN },
333 { "tcpflags", TOK_TCPFLAGS },
334 { "tcpflgs", TOK_TCPFLAGS },
335 { "tcpoptions", TOK_TCPOPTS },
336 { "tcpopts", TOK_TCPOPTS },
337 { "tcpseq", TOK_TCPSEQ },
338 { "tcpack", TOK_TCPACK },
339 { "tcpwin", TOK_TCPWIN },
340 { "icmptype", TOK_ICMPTYPES },
341 { "icmptypes", TOK_ICMPTYPES },
342 { "dst-ip", TOK_DSTIP },
343 { "src-ip", TOK_SRCIP },
344 { "dst-port", TOK_DSTPORT },
345 { "src-port", TOK_SRCPORT },
346 { "proto", TOK_PROTO },
349 { "mac-type", TOK_MACTYPE },
350 { "verrevpath", TOK_VERREVPATH },
351 { "versrcreach", TOK_VERSRCREACH },
352 { "antispoof", TOK_ANTISPOOF },
353 { "ipsec", TOK_IPSEC },
354 { "icmp6type", TOK_ICMP6TYPES },
355 { "icmp6types", TOK_ICMP6TYPES },
356 { "ext6hdr", TOK_EXT6HDR},
357 { "flow-id", TOK_FLOWID},
362 { "dst-ipv6", TOK_DSTIP6},
363 { "dst-ip6", TOK_DSTIP6},
364 { "src-ipv6", TOK_SRCIP6},
365 { "src-ip6", TOK_SRCIP6},
366 { "lookup", TOK_LOOKUP},
368 { "//", TOK_COMMENT },
370 { "not", TOK_NOT }, /* pseudo option */
371 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
372 { "or", TOK_OR }, /* pseudo option */
373 { "|", /* escape */ TOK_OR }, /* pseudo option */
374 { "{", TOK_STARTBRACE }, /* pseudo option */
375 { "(", TOK_STARTBRACE }, /* pseudo option */
376 { "}", TOK_ENDBRACE }, /* pseudo option */
377 { ")", TOK_ENDBRACE }, /* pseudo option */
378 { NULL, 0 } /* terminator */
381 void bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg);
382 static int ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
383 ipfw_cfg_lheader **pcfg, size_t *psize);
384 static int ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
385 ipfw_cfg_lheader *cfg, size_t sz, int ac, char **av);
386 static void ipfw_list_tifaces(void);
389 static uint16_t pack_object(struct tidx *tstate, char *name, int otype);
390 static uint16_t pack_table(struct tidx *tstate, char *name);
392 static char *table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx);
393 static void object_sort_ctlv(ipfw_obj_ctlv *ctlv);
394 static char *object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx,
398 * Simple string buffer API.
399 * Used to simplify buffer passing between function and for
400 * transparent overrun handling.
404 * Allocates new buffer of given size @sz.
406 * Returns 0 on success.
409 bp_alloc(struct buf_pr *b, size_t size)
411 memset(b, 0, sizeof(struct buf_pr));
413 if ((b->buf = calloc(1, size)) == NULL)
424 bp_free(struct buf_pr *b)
431 * Flushes buffer so new writer start from beginning.
434 bp_flush(struct buf_pr *b)
443 * Print message specified by @format and args.
444 * Automatically manage buffer space and transparently handle
447 * Returns number of bytes that should have been printed.
450 bprintf(struct buf_pr *b, char *format, ...)
455 va_start(args, format);
457 i = vsnprintf(b->ptr, b->avail, format, args);
460 if (i > b->avail || i < 0) {
461 /* Overflow or print error */
474 * Special values printer for tablearg-aware opcodes.
477 bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg)
481 bprintf(bp, "%s", str);
482 if (arg == IP_FW_TARG)
483 bprintf(bp, "tablearg");
485 bprintf(bp, "%u", arg);
489 * Helper routine to print a possibly unaligned uint64_t on
490 * various platform. If width > 0, print the value with
491 * the desired width, followed by a space;
492 * otherwise, return the required width.
495 pr_u64(struct buf_pr *b, uint64_t *pd, int width)
498 #define U64_FMT "I64"
500 #define U64_FMT "llu"
503 unsigned long long d;
505 bcopy (pd, &u, sizeof(u));
508 bprintf(b, "%*" U64_FMT " ", width, d) :
509 snprintf(NULL, 0, "%" U64_FMT, d) ;
515 safe_calloc(size_t number, size_t size)
517 void *ret = calloc(number, size);
520 err(EX_OSERR, "calloc");
525 safe_realloc(void *ptr, size_t size)
527 void *ret = realloc(ptr, size);
530 err(EX_OSERR, "realloc");
535 * Compare things like interface or table names.
538 stringnum_cmp(const char *a, const char *b)
550 return (strcmp(a, b));
555 * conditionally runs the command.
556 * Selected options or negative -> getsockopt
559 do_cmd(int optname, void *optval, uintptr_t optlen)
566 if (ipfw_socket == -1)
567 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
569 err(EX_UNAVAILABLE, "socket");
571 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
572 optname == IP_FW_ADD || optname == IP_FW3 ||
573 optname == IP_FW_NAT_GET_CONFIG ||
575 optname == IP_FW_NAT_GET_LOG) {
578 i = getsockopt(ipfw_socket, IPPROTO_IP, optname, optval,
579 (socklen_t *)optlen);
581 i = setsockopt(ipfw_socket, IPPROTO_IP, optname, optval, optlen);
587 * do_set3 - pass ipfw control cmd to kernel
588 * @optname: option name
589 * @optval: pointer to option data
590 * @optlen: option length
592 * Assumes op3 header is already embedded.
593 * Calls setsockopt() with IP_FW3 as kernel-visible opcode.
594 * Returns 0 on success or errno otherwise.
597 do_set3(int optname, ip_fw3_opheader *op3, size_t optlen)
603 if (ipfw_socket == -1)
604 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
606 err(EX_UNAVAILABLE, "socket");
608 op3->opcode = optname;
610 return (setsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, optlen));
614 * do_get3 - pass ipfw control cmd to kernel
615 * @optname: option name
616 * @optval: pointer to option data
617 * @optlen: pointer to option length
619 * Assumes op3 header is already embedded.
620 * Calls getsockopt() with IP_FW3 as kernel-visible opcode.
621 * Returns 0 on success or errno otherwise.
624 do_get3(int optname, ip_fw3_opheader *op3, size_t *optlen)
632 if (ipfw_socket == -1)
633 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
635 err(EX_UNAVAILABLE, "socket");
637 op3->opcode = optname;
640 error = getsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, &len);
647 * match_token takes a table and a string, returns the value associated
648 * with the string (-1 in case of failure).
651 match_token(struct _s_x *table, const char *string)
654 uint i = strlen(string);
656 for (pt = table ; i && pt->s != NULL ; pt++)
657 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
663 * match_token_relaxed takes a table and a string, returns the value associated
664 * with the string for the best match.
667 * value from @table for matched records
668 * -1 for non-matched records
669 * -2 if more than one records match @string.
672 match_token_relaxed(struct _s_x *table, const char *string)
680 for (pt = table ; i != 0 && pt->s != NULL ; pt++) {
681 if (strncmp(pt->s, string, i) != 0)
690 return (c > 0 ? -2: -1);
694 get_token(struct _s_x *table, const char *string, const char *errbase)
698 if ((tcmd = match_token_relaxed(table, string)) < 0)
699 errx(EX_USAGE, "%s %s %s",
700 (tcmd == 0) ? "invalid" : "ambiguous", errbase, string);
706 * match_value takes a table and a value, returns the string associated
707 * with the value (NULL in case of failure).
710 match_value(struct _s_x *p, int value)
712 for (; p->s != NULL; p++)
719 concat_tokens(char *buf, size_t bufsize, struct _s_x *table, char *delimiter)
725 for (sz = 0, pt = table ; pt->s != NULL; pt++) {
726 l = snprintf(buf + sz, bufsize - sz, "%s%s",
727 (sz == 0) ? "" : delimiter, pt->s);
738 * helper function to process a set of flags and set bits in the
742 fill_flags(struct _s_x *flags, char *p, char **e, uint32_t *set,
745 char *q; /* points to the separator */
747 uint32_t *which; /* mask we are working on */
758 val = match_token(flags, p);
764 *which |= (uint32_t)val;
771 print_flags_buffer(char *buf, size_t sz, struct _s_x *list, uint32_t set)
773 char const *comma = "";
776 for (i = 0; list[i].x != 0; i++) {
777 if ((set & list[i].x) == 0)
781 l = snprintf(buf, sz, "%s%s", comma, list[i].s);
791 * _substrcmp takes two strings and returns 1 if they do not match,
792 * and 0 if they match exactly or the first string is a sub-string
793 * of the second. A warning is printed to stderr in the case that the
794 * first string is a sub-string of the second.
796 * This function will be removed in the future through the usual
797 * deprecation process.
800 _substrcmp(const char *str1, const char* str2)
803 if (strncmp(str1, str2, strlen(str1)) != 0)
806 if (strlen(str1) != strlen(str2))
807 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
813 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
814 * and 0 if they match exactly or the second string is a sub-string
815 * of the first. A warning is printed to stderr in the case that the
816 * first string does not match the third.
818 * This function exists to warn about the bizarre construction
819 * strncmp(str, "by", 2) which is used to allow people to use a shortcut
820 * for "bytes". The problem is that in addition to accepting "by",
821 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
822 * other string beginning with "by".
824 * This function will be removed in the future through the usual
825 * deprecation process.
828 _substrcmp2(const char *str1, const char* str2, const char* str3)
831 if (strncmp(str1, str2, strlen(str2)) != 0)
834 if (strcmp(str1, str3) != 0)
835 warnx("DEPRECATED: '%s' matched '%s'",
841 * prints one port, symbolic or numeric
844 print_port(struct buf_pr *bp, int proto, uint16_t port)
847 if (proto == IPPROTO_ETHERTYPE) {
850 if (co.do_resolv && (s = match_value(ether_types, port)) )
851 bprintf(bp, "%s", s);
853 bprintf(bp, "0x%04x", port);
855 struct servent *se = NULL;
857 struct protoent *pe = getprotobynumber(proto);
859 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
862 bprintf(bp, "%s", se->s_name);
864 bprintf(bp, "%d", port);
868 static struct _s_x _port_name[] = {
869 {"dst-port", O_IP_DSTPORT},
870 {"src-port", O_IP_SRCPORT},
874 {"mac-type", O_MAC_TYPE},
875 {"tcpdatalen", O_TCPDATALEN},
876 {"tcpwin", O_TCPWIN},
877 {"tagged", O_TAGGED},
882 * Print the values in a list 16-bit items of the types above.
883 * XXX todo: add support for mask.
886 print_newports(struct buf_pr *bp, ipfw_insn_u16 *cmd, int proto, int opcode)
888 uint16_t *p = cmd->ports;
893 sep = match_value(_port_name, opcode);
896 bprintf(bp, " %s", sep);
899 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
900 bprintf(bp, "%s", sep);
901 print_port(bp, proto, p[0]);
904 print_port(bp, proto, p[1]);
911 * Like strtol, but also translates service names into port numbers
912 * for some protocols.
914 * proto == -1 disables the protocol check;
915 * proto == IPPROTO_ETHERTYPE looks up an internal table
916 * proto == <some value in /etc/protocols> matches the values there.
917 * Returns *end == s in case the parameter is not found.
920 strtoport(char *s, char **end, int base, int proto)
926 *end = s; /* default - not found */
928 return 0; /* not found */
931 return strtol(s, end, base);
934 * find separator. '\\' escapes the next char.
936 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
937 if (*s1 == '\\' && s1[1] != '\0')
940 buf = safe_calloc(s1 - s + 1, 1);
943 * copy into a buffer skipping backslashes
945 for (p = s, i = 0; p != s1 ; p++)
950 if (proto == IPPROTO_ETHERTYPE) {
951 i = match_token(ether_types, buf);
953 if (i != -1) { /* found */
958 struct protoent *pe = NULL;
962 pe = getprotobynumber(proto);
964 se = getservbyname(buf, pe ? pe->p_name : NULL);
968 return ntohs(se->s_port);
971 return 0; /* not found */
975 * Fill the body of the command with the list of port ranges.
978 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
980 uint16_t a, b, *p = cmd->ports;
985 a = strtoport(av, &s, 0, proto);
986 if (s == av) /* empty or invalid argument */
989 CHECK_LENGTH(cblen, i + 2);
992 case '-': /* a range */
994 b = strtoport(av, &s, 0, proto);
995 /* Reject expressions like '1-abc' or '1-2-3'. */
996 if (s == av || (*s != ',' && *s != '\0'))
1001 case ',': /* comma separated list */
1006 warnx("port list: invalid separator <%c> in <%s>",
1016 if (i + 1 > F_LEN_MASK)
1017 errx(EX_DATAERR, "too many ports/ranges\n");
1018 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
1024 * Fill the body of the command with the list of DiffServ codepoints.
1027 fill_dscp(ipfw_insn *cmd, char *av, int cblen)
1029 uint32_t *low, *high;
1033 cmd->opcode = O_DSCP;
1034 cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
1038 low = (uint32_t *)(cmd + 1);
1051 if ((code = match_token(f_ipdscp, s)) == -1)
1052 errx(EX_DATAERR, "Unknown DSCP code");
1054 code = strtoul(s, NULL, 10);
1055 if (code < 0 || code > 63)
1056 errx(EX_DATAERR, "Invalid DSCP value");
1060 *high |= 1 << (code - 32);
1068 static struct _s_x icmpcodes[] = {
1069 { "net", ICMP_UNREACH_NET },
1070 { "host", ICMP_UNREACH_HOST },
1071 { "protocol", ICMP_UNREACH_PROTOCOL },
1072 { "port", ICMP_UNREACH_PORT },
1073 { "needfrag", ICMP_UNREACH_NEEDFRAG },
1074 { "srcfail", ICMP_UNREACH_SRCFAIL },
1075 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
1076 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
1077 { "isolated", ICMP_UNREACH_ISOLATED },
1078 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
1079 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
1080 { "tosnet", ICMP_UNREACH_TOSNET },
1081 { "toshost", ICMP_UNREACH_TOSHOST },
1082 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
1083 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
1084 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
1089 fill_reject_code(u_short *codep, char *str)
1094 val = strtoul(str, &s, 0);
1095 if (s == str || *s != '\0' || val >= 0x100)
1096 val = match_token(icmpcodes, str);
1098 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
1104 print_reject_code(struct buf_pr *bp, uint16_t code)
1108 if ((s = match_value(icmpcodes, code)) != NULL)
1109 bprintf(bp, "unreach %s", s);
1111 bprintf(bp, "unreach %u", code);
1115 * Returns the number of bits set (from left) in a contiguous bitmask,
1116 * or -1 if the mask is not contiguous.
1117 * XXX this needs a proper fix.
1118 * This effectively works on masks in big-endian (network) format.
1119 * when compiled on little endian architectures.
1121 * First bit is bit 7 of the first byte -- note, for MAC addresses,
1122 * the first bit on the wire is bit 0 of the first byte.
1123 * len is the max length in bits.
1126 contigmask(uint8_t *p, int len)
1130 for (i=0; i<len ; i++)
1131 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
1133 for (n=i+1; n < len; n++)
1134 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
1135 return -1; /* mask not contiguous */
1140 * print flags set/clear in the two bitmasks passed as parameters.
1141 * There is a specialized check for f_tcpflags.
1144 print_flags(struct buf_pr *bp, char const *name, ipfw_insn *cmd,
1147 char const *comma = "";
1149 uint8_t set = cmd->arg1 & 0xff;
1150 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
1152 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
1153 bprintf(bp, " setup");
1157 bprintf(bp, " %s ", name);
1158 for (i=0; list[i].x != 0; i++) {
1159 if (set & list[i].x) {
1161 bprintf(bp, "%s%s", comma, list[i].s);
1164 if (clear & list[i].x) {
1165 clear &= ~list[i].x;
1166 bprintf(bp, "%s!%s", comma, list[i].s);
1174 * Print the ip address contained in a command.
1177 print_ip(struct buf_pr *bp, struct format_opts *fo, ipfw_insn_ip *cmd,
1180 struct hostent *he = NULL;
1182 uint32_t len = F_LEN((ipfw_insn *)cmd);
1183 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
1186 if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
1188 const char *arg = "<invalid>";
1190 if (d < sizeof(lookup_key)/sizeof(lookup_key[0]))
1191 arg = match_value(rule_options, lookup_key[d]);
1192 t = table_search_ctlv(fo->tstate, ((ipfw_insn *)cmd)->arg1);
1193 bprintf(bp, "%s lookup %s %s", cmd->o.len & F_NOT ? " not": "",
1197 bprintf(bp, "%s%s ", cmd->o.len & F_NOT ? " not": "", s);
1199 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
1203 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
1204 cmd->o.opcode == O_IP_DST_LOOKUP) {
1205 t = table_search_ctlv(fo->tstate, ((ipfw_insn *)cmd)->arg1);
1206 bprintf(bp, "table(%s", t);
1207 if (len == F_INSN_SIZE(ipfw_insn_u32))
1208 bprintf(bp, ",%u", *a);
1212 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
1213 uint32_t x, *map = (uint32_t *)&(cmd->mask);
1217 x = cmd->o.arg1 - 1;
1219 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1220 bprintf(bp, "%s/%d", inet_ntoa(cmd->addr),
1221 contigmask((uint8_t *)&x, 32));
1222 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1223 x &= 0xff; /* base */
1225 * Print bits and ranges.
1226 * Locate first bit set (i), then locate first bit unset (j).
1227 * If we have 3+ consecutive bits set, then print them as a
1228 * range, otherwise only print the initial bit and rescan.
1230 for (i=0; i < cmd->o.arg1; i++)
1231 if (map[i/32] & (1<<(i & 31))) {
1232 for (j=i+1; j < cmd->o.arg1; j++)
1233 if (!(map[ j/32] & (1<<(j & 31))))
1235 bprintf(bp, "%c%d", comma, i+x);
1236 if (j>i+2) { /* range has at least 3 elements */
1237 bprintf(bp, "-%d", j-1+x);
1246 * len == 2 indicates a single IP, whereas lists of 1 or more
1247 * addr/mask pairs have len = (2n+1). We convert len to n so we
1248 * use that to count the number of entries.
1250 for (len = len / 2; len > 0; len--, a += 2) {
1251 int mb = /* mask length */
1252 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1253 32 : contigmask((uint8_t *)&(a[1]), 32);
1254 if (mb == 32 && co.do_resolv)
1255 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
1256 if (he != NULL) /* resolved to name */
1257 bprintf(bp, "%s", he->h_name);
1258 else if (mb == 0) /* any */
1260 else { /* numeric IP followed by some kind of mask */
1261 ia = (struct in_addr *)&a[0];
1262 bprintf(bp, "%s", inet_ntoa(*ia));
1264 ia = (struct in_addr *)&a[1];
1265 bprintf(bp, ":%s", inet_ntoa(*ia));
1267 bprintf(bp, "/%d", mb);
1275 * prints a MAC address/mask pair
1278 print_mac(struct buf_pr *bp, uint8_t *addr, uint8_t *mask)
1280 int l = contigmask(mask, 48);
1283 bprintf(bp, " any");
1285 bprintf(bp, " %02x:%02x:%02x:%02x:%02x:%02x",
1286 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1288 bprintf(bp, "&%02x:%02x:%02x:%02x:%02x:%02x",
1289 mask[0], mask[1], mask[2],
1290 mask[3], mask[4], mask[5]);
1292 bprintf(bp, "/%d", l);
1297 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1306 type = strtoul(av, &av, 0);
1308 if (*av != ',' && *av != '\0')
1309 errx(EX_DATAERR, "invalid ICMP type");
1312 errx(EX_DATAERR, "ICMP type out of range");
1314 cmd->d[0] |= 1 << type;
1316 cmd->o.opcode = O_ICMPTYPE;
1317 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1321 print_icmptypes(struct buf_pr *bp, ipfw_insn_u32 *cmd)
1326 bprintf(bp, " icmptypes");
1327 for (i = 0; i < 32; i++) {
1328 if ( (cmd->d[0] & (1 << (i))) == 0)
1330 bprintf(bp, "%c%d", sep, i);
1336 print_dscp(struct buf_pr *bp, ipfw_insn_u32 *cmd)
1343 bprintf(bp, " dscp");
1346 if (*v & (1 << i)) {
1347 if ((code = match_value(f_ipdscp, i)) != NULL)
1348 bprintf(bp, "%c%s", sep, code);
1350 bprintf(bp, "%c%d", sep, i);
1354 if ((++i % 32) == 0)
1360 * show_ipfw() prints the body of an ipfw rule.
1361 * Because the standard rule has at least proto src_ip dst_ip, we use
1362 * a helper function to produce these entries if not provided explicitly.
1363 * The first argument is the list of fields we have, the second is
1364 * the list of fields we want to be printed.
1366 * Special cases if we have provided a MAC header:
1367 * + if the rule does not contain IP addresses/ports, do not print them;
1368 * + if the rule does not contain an IP proto, print "all" instead of "ip";
1370 * Once we have 'have_options', IP header fields are printed as options.
1372 #define HAVE_PROTO 0x0001
1373 #define HAVE_SRCIP 0x0002
1374 #define HAVE_DSTIP 0x0004
1375 #define HAVE_PROTO4 0x0008
1376 #define HAVE_PROTO6 0x0010
1377 #define HAVE_IP 0x0100
1378 #define HAVE_OPTIONS 0x8000
1381 show_prerequisites(struct buf_pr *bp, int *flags, int want, int cmd)
1383 (void)cmd; /* UNUSED */
1384 if (co.comment_only)
1386 if ( (*flags & HAVE_IP) == HAVE_IP)
1387 *flags |= HAVE_OPTIONS;
1389 if ( !(*flags & HAVE_OPTIONS)) {
1390 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) {
1391 if ( (*flags & HAVE_PROTO4))
1392 bprintf(bp, " ip4");
1393 else if ( (*flags & HAVE_PROTO6))
1394 bprintf(bp, " ip6");
1398 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
1399 bprintf(bp, " from any");
1400 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
1401 bprintf(bp, " to any");
1407 show_static_rule(struct cmdline_opts *co, struct format_opts *fo,
1408 struct buf_pr *bp, struct ip_fw_rule *rule, struct ip_fw_bcounter *cntr)
1410 static int twidth = 0;
1412 ipfw_insn *cmd, *has_eaction = NULL, *tagptr = NULL;
1413 const char *comment = NULL; /* ptr to comment if we have one */
1415 int proto = 0; /* default */
1416 int flags = 0; /* prerequisites */
1417 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
1418 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
1419 int or_block = 0; /* we are in an or block */
1422 if ((fo->set_mask & (1 << rule->set)) == 0) {
1427 bprintf(bp, "# DISABLED ");
1429 bprintf(bp, "%05u ", rule->rulenum);
1431 /* Print counters if enabled */
1432 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
1433 pr_u64(bp, &cntr->pcnt, fo->pcwidth);
1434 pr_u64(bp, &cntr->bcnt, fo->bcwidth);
1437 if (co->do_time == 2)
1438 bprintf(bp, "%10u ", cntr->timestamp);
1439 else if (co->do_time == 1) {
1441 time_t t = (time_t)0;
1444 strcpy(timestr, ctime(&t));
1445 *strchr(timestr, '\n') = '\0';
1446 twidth = strlen(timestr);
1448 if (cntr->timestamp > 0) {
1449 t = _long_to_time(cntr->timestamp);
1451 strcpy(timestr, ctime(&t));
1452 *strchr(timestr, '\n') = '\0';
1453 bprintf(bp, "%s ", timestr);
1455 bprintf(bp, "%*s", twidth, " ");
1460 bprintf(bp, "set %d ", rule->set);
1463 * print the optional "match probability"
1465 if (rule->cmd_len > 0) {
1467 if (cmd->opcode == O_PROB) {
1468 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1469 double d = 1.0 * p->d[0];
1471 d = (d / 0x7fffffff);
1472 bprintf(bp, "prob %f ", d);
1477 * first print actions
1479 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1480 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1481 switch(cmd->opcode) {
1483 bprintf(bp, "check-state");
1485 ename = object_search_ctlv(fo->tstate,
1486 cmd->arg1, IPFW_TLV_STATE_NAME);
1489 bprintf(bp, " :%s", ename ? ename: "any");
1490 /* avoid printing anything else */
1491 flags = HAVE_PROTO | HAVE_SRCIP |
1492 HAVE_DSTIP | HAVE_IP;
1496 bprintf(bp, "allow");
1500 bprintf(bp, "count");
1504 bprintf(bp, "deny");
1508 if (cmd->arg1 == ICMP_REJECT_RST)
1509 bprintf(bp, "reset");
1510 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1511 bprintf(bp, "reject");
1513 print_reject_code(bp, cmd->arg1);
1517 if (cmd->arg1 == ICMP6_UNREACH_RST)
1518 bprintf(bp, "reset6");
1520 print_unreach6_code(bp, cmd->arg1);
1524 bprint_uint_arg(bp, "skipto ", cmd->arg1);
1528 bprint_uint_arg(bp, "pipe ", cmd->arg1);
1532 bprint_uint_arg(bp, "queue ", cmd->arg1);
1536 bprint_uint_arg(bp, "divert ", cmd->arg1);
1540 bprint_uint_arg(bp, "tee ", cmd->arg1);
1544 bprint_uint_arg(bp, "netgraph ", cmd->arg1);
1548 bprint_uint_arg(bp, "ngtee ", cmd->arg1);
1553 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1555 if (s->sa.sin_addr.s_addr == INADDR_ANY) {
1556 bprintf(bp, "fwd tablearg");
1558 bprintf(bp, "fwd %s",inet_ntoa(s->sa.sin_addr));
1561 bprintf(bp, ",%d", s->sa.sin_port);
1567 char buf[INET6_ADDRSTRLEN + IF_NAMESIZE + 2];
1568 ipfw_insn_sa6 *s = (ipfw_insn_sa6 *)cmd;
1570 bprintf(bp, "fwd ");
1571 if (getnameinfo((const struct sockaddr *)&s->sa,
1572 sizeof(struct sockaddr_in6), buf, sizeof(buf),
1573 NULL, 0, NI_NUMERICHOST) == 0)
1574 bprintf(bp, "%s", buf);
1575 if (s->sa.sin6_port)
1576 bprintf(bp, ",%d", s->sa.sin6_port);
1580 case O_LOG: /* O_LOG is printed last */
1581 logptr = (ipfw_insn_log *)cmd;
1584 case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1585 altqptr = (ipfw_insn_altq *)cmd;
1593 if (cmd->arg1 != IP_FW_NAT44_GLOBAL)
1594 bprint_uint_arg(bp, "nat ", cmd->arg1);
1596 bprintf(bp, "nat global");
1600 if (cmd->arg1 == IP_FW_TARG)
1601 bprint_uint_arg(bp, "setfib ", cmd->arg1);
1603 bprintf(bp, "setfib %u", cmd->arg1 & 0x7FFF);
1606 case O_EXTERNAL_ACTION: {
1608 * The external action can consists of two following
1609 * each other opcodes - O_EXTERNAL_ACTION and
1610 * O_EXTERNAL_INSTANCE. The first contains the ID of
1611 * name of external action. The second contains the ID
1612 * of name of external action instance.
1613 * NOTE: in case when external action has no named
1614 * instances support, the second opcode isn't needed.
1617 ename = object_search_ctlv(fo->tstate, cmd->arg1,
1619 if (match_token(rule_eactions, ename) != -1)
1620 bprintf(bp, "%s", ename);
1622 bprintf(bp, "eaction %s", ename);
1626 case O_EXTERNAL_INSTANCE: {
1627 if (has_eaction == NULL)
1630 * XXX: we need to teach ipfw(9) to rewrite opcodes
1631 * in the user buffer on rule addition. When we add
1632 * the rule, we specify zero TLV type for
1633 * O_EXTERNAL_INSTANCE object. To show correct
1634 * rule after `ipfw add` we need to search instance
1635 * name with zero type. But when we do `ipfw show`
1636 * we calculate TLV type using IPFW_TLV_EACTION_NAME()
1639 ename = object_search_ctlv(fo->tstate, cmd->arg1, 0);
1641 ename = object_search_ctlv(fo->tstate,
1643 IPFW_TLV_EACTION_NAME(has_eaction->arg1));
1644 bprintf(bp, " %s", ename);
1648 case O_EXTERNAL_DATA: {
1649 if (has_eaction == NULL)
1652 * Currently we support data formatting only for
1653 * external data with datalen u16. For unknown data
1654 * print its size in bytes.
1656 if (cmd->len == F_INSN_SIZE(ipfw_insn))
1657 bprintf(bp, " %u", cmd->arg1);
1659 bprintf(bp, " %ubytes",
1660 cmd->len * sizeof(uint32_t));
1668 if (cmd->arg1 == IP_FW_TARG) {
1669 bprint_uint_arg(bp, "setdscp ", cmd->arg1);
1672 uval = cmd->arg1 & 0x3F;
1673 if ((code = match_value(f_ipdscp, uval)) != NULL)
1674 bprintf(bp, "setdscp %s", code);
1676 bprint_uint_arg(bp, "setdscp ", uval);
1681 bprintf(bp, "reass");
1685 if (cmd->len & F_NOT)
1686 bprintf(bp, "return");
1688 bprint_uint_arg(bp, "call ", cmd->arg1);
1692 bprintf(bp, "** unrecognized action %d len %d ",
1693 cmd->opcode, cmd->len);
1697 if (logptr->max_log > 0)
1698 bprintf(bp, " log logamount %d", logptr->max_log);
1700 bprintf(bp, " log");
1704 print_altq_cmd(bp, altqptr);
1708 if (tagptr->len & F_NOT)
1709 bprint_uint_arg(bp, " untag ", tagptr->arg1);
1711 bprint_uint_arg(bp, " tag ", tagptr->arg1);
1715 * then print the body.
1717 for (l = rule->act_ofs, cmd = rule->cmd;
1718 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1719 if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1721 if (cmd->opcode == O_IP4) {
1722 flags |= HAVE_PROTO4;
1724 } else if (cmd->opcode == O_IP6) {
1725 flags |= HAVE_PROTO6;
1729 if (rule->flags & IPFW_RULE_NOOPT) { /* empty rules before options */
1730 if (!co->do_compact) {
1731 show_prerequisites(bp, &flags, HAVE_PROTO, 0);
1732 bprintf(bp, " from any to any");
1734 flags |= HAVE_IP | HAVE_OPTIONS | HAVE_PROTO |
1735 HAVE_SRCIP | HAVE_DSTIP;
1738 if (co->comment_only)
1741 for (l = rule->act_ofs, cmd = rule->cmd;
1742 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1744 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1746 if (co->comment_only) {
1747 if (cmd->opcode != O_NOP)
1749 bprintf(bp, " // %s\n", (char *)(cmd + 1));
1753 show_prerequisites(bp, &flags, 0, cmd->opcode);
1755 switch(cmd->opcode) {
1757 break; /* done already */
1760 break; /* no need to print anything here */
1763 case O_IP_SRC_LOOKUP:
1767 show_prerequisites(bp, &flags, HAVE_PROTO, 0);
1768 if (!(flags & HAVE_SRCIP))
1769 bprintf(bp, " from");
1770 if ((cmd->len & F_OR) && !or_block)
1772 print_ip(bp, fo, (ipfw_insn_ip *)cmd,
1773 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1774 flags |= HAVE_SRCIP;
1778 case O_IP_DST_LOOKUP:
1782 show_prerequisites(bp, &flags, HAVE_PROTO|HAVE_SRCIP, 0);
1783 if (!(flags & HAVE_DSTIP))
1785 if ((cmd->len & F_OR) && !or_block)
1787 print_ip(bp, fo, (ipfw_insn_ip *)cmd,
1788 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1789 flags |= HAVE_DSTIP;
1793 case O_IP6_SRC_MASK:
1795 show_prerequisites(bp, &flags, HAVE_PROTO, 0);
1796 if (!(flags & HAVE_SRCIP))
1797 bprintf(bp, " from");
1798 if ((cmd->len & F_OR) && !or_block)
1800 print_ip6(bp, (ipfw_insn_ip6 *)cmd,
1801 (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1802 flags |= HAVE_SRCIP | HAVE_PROTO;
1806 case O_IP6_DST_MASK:
1808 show_prerequisites(bp, &flags, HAVE_PROTO|HAVE_SRCIP, 0);
1809 if (!(flags & HAVE_DSTIP))
1811 if ((cmd->len & F_OR) && !or_block)
1813 print_ip6(bp, (ipfw_insn_ip6 *)cmd,
1814 (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1815 flags |= HAVE_DSTIP;
1819 print_flow6id(bp, (ipfw_insn_u32 *) cmd );
1820 flags |= HAVE_OPTIONS;
1824 show_prerequisites(bp, &flags,
1825 HAVE_PROTO | HAVE_SRCIP |
1826 HAVE_DSTIP | HAVE_IP, 0);
1828 if (flags & HAVE_DSTIP)
1830 show_prerequisites(bp, &flags,
1831 HAVE_PROTO | HAVE_SRCIP, 0);
1832 if ((cmd->len & F_OR) && !or_block)
1834 if (cmd->len & F_NOT)
1835 bprintf(bp, " not");
1836 print_newports(bp, (ipfw_insn_u16 *)cmd, proto,
1837 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1841 struct protoent *pe = NULL;
1843 if ((cmd->len & F_OR) && !or_block)
1845 if (cmd->len & F_NOT)
1846 bprintf(bp, " not");
1848 pe = getprotobynumber(cmd->arg1);
1849 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1850 !(flags & HAVE_PROTO))
1851 show_prerequisites(bp, &flags,
1852 HAVE_PROTO | HAVE_IP | HAVE_SRCIP |
1853 HAVE_DSTIP | HAVE_OPTIONS, 0);
1854 if (flags & HAVE_OPTIONS)
1855 bprintf(bp, " proto");
1857 bprintf(bp, " %s", pe->p_name);
1859 bprintf(bp, " %u", cmd->arg1);
1861 flags |= HAVE_PROTO;
1864 default: /*options ... */
1865 if (!(cmd->len & (F_OR|F_NOT)))
1866 if (((cmd->opcode == O_IP6) &&
1867 (flags & HAVE_PROTO6)) ||
1868 ((cmd->opcode == O_IP4) &&
1869 (flags & HAVE_PROTO4)))
1871 show_prerequisites(bp, &flags, HAVE_PROTO | HAVE_SRCIP |
1872 HAVE_DSTIP | HAVE_IP | HAVE_OPTIONS, 0);
1873 if ((cmd->len & F_OR) && !or_block)
1875 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1876 bprintf(bp, " not");
1877 switch(cmd->opcode) {
1879 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1881 bprintf(bp, " MAC");
1882 print_mac(bp, m->addr, m->mask);
1883 print_mac(bp, m->addr + 6, m->mask + 6);
1888 print_newports(bp, (ipfw_insn_u16 *)cmd,
1889 IPPROTO_ETHERTYPE, cmd->opcode);
1894 bprintf(bp, " frag");
1898 bprintf(bp, " fib %u", cmd->arg1 );
1901 bprintf(bp, " sockarg");
1905 bprintf(bp, cmd->len & F_NOT ? " out" : " in");
1909 switch (cmd->arg1) {
1911 bprintf(bp, " diverted");
1914 bprintf(bp, " diverted-loopback");
1917 bprintf(bp, " diverted-output");
1920 bprintf(bp, " diverted-?<%u>", cmd->arg1);
1926 bprintf(bp, " layer2");
1933 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1935 if (cmd->opcode == O_XMIT)
1937 else if (cmd->opcode == O_RECV)
1939 else /* if (cmd->opcode == O_VIA) */
1941 if (cmdif->name[0] == '\0')
1942 bprintf(bp, " %s %s", s,
1943 inet_ntoa(cmdif->p.ip));
1944 else if (cmdif->name[0] == '\1') {
1945 /* interface table */
1946 t = table_search_ctlv(fo->tstate,
1948 bprintf(bp, " %s table(%s)", s, t);
1950 bprintf(bp, " %s %s", s, cmdif->name);
1954 case O_IP_FLOW_LOOKUP:
1958 t = table_search_ctlv(fo->tstate, cmd->arg1);
1959 bprintf(bp, " flow table(%s", t);
1960 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))
1962 ((ipfw_insn_u32 *)cmd)->d[0]);
1967 if (F_LEN(cmd) == 1)
1968 bprintf(bp, " ipid %u", cmd->arg1 );
1970 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1975 if (F_LEN(cmd) == 1)
1976 bprintf(bp, " ipttl %u", cmd->arg1 );
1978 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1983 bprintf(bp, " ipver %u", cmd->arg1 );
1986 case O_IPPRECEDENCE:
1987 bprintf(bp, " ipprecedence %u", cmd->arg1 >> 5);
1991 print_dscp(bp, (ipfw_insn_u32 *)cmd);
1995 if (F_LEN(cmd) == 1)
1996 bprintf(bp, " iplen %u", cmd->arg1 );
1998 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
2003 print_flags(bp, "ipoptions", cmd, f_ipopts);
2007 print_flags(bp, "iptos", cmd, f_iptos);
2011 print_icmptypes(bp, (ipfw_insn_u32 *)cmd);
2015 bprintf(bp, " established");
2019 if (F_LEN(cmd) == 1)
2020 bprintf(bp, " tcpdatalen %u", cmd->arg1 );
2022 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
2027 print_flags(bp, "tcpflags", cmd, f_tcpflags);
2031 print_flags(bp, "tcpoptions", cmd, f_tcpopts);
2035 if (F_LEN(cmd) == 1)
2036 bprintf(bp, " tcpwin %u", cmd->arg1);
2038 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
2043 bprintf(bp, " tcpack %d", ntohl(cmd32->d[0]));
2047 bprintf(bp, " tcpseq %d", ntohl(cmd32->d[0]));
2052 struct passwd *pwd = getpwuid(cmd32->d[0]);
2055 bprintf(bp, " uid %s", pwd->pw_name);
2057 bprintf(bp, " uid %u", cmd32->d[0]);
2063 struct group *grp = getgrgid(cmd32->d[0]);
2066 bprintf(bp, " gid %s", grp->gr_name);
2068 bprintf(bp, " gid %u", cmd32->d[0]);
2073 bprintf(bp, " jail %d", cmd32->d[0]);
2077 bprintf(bp, " verrevpath");
2081 bprintf(bp, " versrcreach");
2085 bprintf(bp, " antispoof");
2089 bprintf(bp, " ipsec");
2093 comment = (char *)(cmd + 1);
2097 bprintf(bp, " keep-state");
2099 object_search_ctlv(fo->tstate, cmd->arg1,
2100 IPFW_TLV_STATE_NAME));
2104 struct _s_x *p = limit_masks;
2105 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
2106 uint8_t x = c->limit_mask;
2107 char const *comma = " ";
2109 bprintf(bp, " limit");
2110 for (; p->x != 0 ; p++)
2111 if ((x & p->x) == p->x) {
2113 bprintf(bp, "%s%s", comma,p->s);
2116 bprint_uint_arg(bp, " ", c->conn_limit);
2118 object_search_ctlv(fo->tstate, cmd->arg1,
2119 IPFW_TLV_STATE_NAME));
2124 bprintf(bp, " ip6");
2128 bprintf(bp, " ip4");
2132 print_icmp6types(bp, (ipfw_insn_u32 *)cmd);
2136 print_ext6hdr(bp, (ipfw_insn *)cmd);
2140 if (F_LEN(cmd) == 1)
2141 bprint_uint_arg(bp, " tagged ",
2144 print_newports(bp, (ipfw_insn_u16 *)cmd,
2149 bprintf(bp, " [opcode %d len %d]",
2150 cmd->opcode, cmd->len);
2153 if (cmd->len & F_OR) {
2156 } else if (or_block) {
2161 show_prerequisites(bp, &flags, HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP
2164 bprintf(bp, " // %s", comment);
2169 show_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2170 struct buf_pr *bp, ipfw_dyn_rule *d)
2172 struct protoent *pe;
2175 char buf[INET6_ADDRSTRLEN];
2177 if (!co->do_expired) {
2178 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
2181 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2182 bprintf(bp, "%05d", rulenum);
2183 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2185 pr_u64(bp, &d->pcnt, fo->pcwidth);
2186 pr_u64(bp, &d->bcnt, fo->bcwidth);
2187 bprintf(bp, "(%ds)", d->expire);
2189 switch (d->dyn_type) {
2190 case O_LIMIT_PARENT:
2191 bprintf(bp, " PARENT %d", d->count);
2194 bprintf(bp, " LIMIT");
2196 case O_KEEP_STATE: /* bidir, no mask */
2197 bprintf(bp, " STATE");
2201 if ((pe = getprotobynumber(d->id.proto)) != NULL)
2202 bprintf(bp, " %s", pe->p_name);
2204 bprintf(bp, " proto %u", d->id.proto);
2206 if (d->id.addr_type == 4) {
2207 a.s_addr = htonl(d->id.src_ip);
2208 bprintf(bp, " %s %d", inet_ntoa(a), d->id.src_port);
2210 a.s_addr = htonl(d->id.dst_ip);
2211 bprintf(bp, " <-> %s %d", inet_ntoa(a), d->id.dst_port);
2212 } else if (d->id.addr_type == 6) {
2213 bprintf(bp, " %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
2214 sizeof(buf)), d->id.src_port);
2215 bprintf(bp, " <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6,
2216 buf, sizeof(buf)), d->id.dst_port);
2218 bprintf(bp, " UNKNOWN <-> UNKNOWN");
2220 bprintf(bp, " :%s", object_search_ctlv(fo->tstate,
2221 d->kidx, IPFW_TLV_STATE_NAME));
2225 do_range_cmd(int cmd, ipfw_range_tlv *rt)
2227 ipfw_range_header rh;
2230 memset(&rh, 0, sizeof(rh));
2231 memcpy(&rh.range, rt, sizeof(*rt));
2232 rh.range.head.length = sizeof(*rt);
2233 rh.range.head.type = IPFW_TLV_RANGE;
2236 if (do_get3(cmd, &rh.opheader, &sz) != 0)
2238 /* Save number of matched objects */
2239 rt->new_set = rh.range.new_set;
2244 * This one handles all set-related commands
2245 * ipfw set { show | enable | disable }
2247 * ipfw set move X to Y
2248 * ipfw set move rule X to Y
2251 ipfw_sets_handler(char *av[])
2262 memset(&rt, 0, sizeof(rt));
2265 errx(EX_USAGE, "set needs command");
2266 if (_substrcmp(*av, "show") == 0) {
2267 struct format_opts fo;
2268 ipfw_cfg_lheader *cfg;
2270 memset(&fo, 0, sizeof(fo));
2271 if (ipfw_get_config(&co, &fo, &cfg, &size) != 0)
2272 err(EX_OSERR, "requesting config failed");
2274 for (i = 0, msg = "disable"; i < RESVD_SET; i++)
2275 if ((cfg->set_mask & (1<<i)) == 0) {
2276 printf("%s %d", msg, i);
2279 msg = (cfg->set_mask != (uint32_t)-1) ? " enable" : "enable";
2280 for (i = 0; i < RESVD_SET; i++)
2281 if ((cfg->set_mask & (1<<i)) != 0) {
2282 printf("%s %d", msg, i);
2287 } else if (_substrcmp(*av, "swap") == 0) {
2289 if ( av[0] == NULL || av[1] == NULL )
2290 errx(EX_USAGE, "set swap needs 2 set numbers\n");
2291 rt.set = atoi(av[0]);
2292 rt.new_set = atoi(av[1]);
2293 if (!isdigit(*(av[0])) || rt.set > RESVD_SET)
2294 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2295 if (!isdigit(*(av[1])) || rt.new_set > RESVD_SET)
2296 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2297 i = do_range_cmd(IP_FW_SET_SWAP, &rt);
2298 } else if (_substrcmp(*av, "move") == 0) {
2300 if (av[0] && _substrcmp(*av, "rule") == 0) {
2301 rt.flags = IPFW_RCFLAG_RANGE; /* move rules to new set */
2305 cmd = IP_FW_SET_MOVE; /* Move set to new one */
2306 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
2307 av[3] != NULL || _substrcmp(av[1], "to") != 0)
2308 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2309 rulenum = atoi(av[0]);
2310 rt.new_set = atoi(av[2]);
2311 if (cmd == IP_FW_XMOVE) {
2312 rt.start_rule = rulenum;
2313 rt.end_rule = rulenum;
2316 rt.new_set = atoi(av[2]);
2317 if (!isdigit(*(av[0])) || (cmd == 3 && rt.set > RESVD_SET) ||
2318 (cmd == 2 && rt.start_rule == IPFW_DEFAULT_RULE) )
2319 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2320 if (!isdigit(*(av[2])) || rt.new_set > RESVD_SET)
2321 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2322 i = do_range_cmd(cmd, &rt);
2324 err(EX_OSERR, "failed to move %s",
2325 cmd == IP_FW_SET_MOVE ? "set": "rule");
2326 } else if (_substrcmp(*av, "disable") == 0 ||
2327 _substrcmp(*av, "enable") == 0 ) {
2328 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2331 masks[0] = masks[1] = 0;
2334 if (isdigit(**av)) {
2336 if (i < 0 || i > RESVD_SET)
2338 "invalid set number %d\n", i);
2339 masks[which] |= (1<<i);
2340 } else if (_substrcmp(*av, "disable") == 0)
2342 else if (_substrcmp(*av, "enable") == 0)
2346 "invalid set command %s\n", *av);
2349 if ( (masks[0] & masks[1]) != 0 )
2351 "cannot enable and disable the same set\n");
2354 rt.new_set = masks[1];
2355 i = do_range_cmd(IP_FW_SET_ENABLE, &rt);
2357 warn("set enable/disable: setsockopt(IP_FW_SET_ENABLE)");
2359 errx(EX_USAGE, "invalid set command %s\n", *av);
2363 ipfw_sysctl_handler(char *av[], int which)
2367 if (av[0] == NULL) {
2368 warnx("missing keyword to enable/disable\n");
2369 } else if (_substrcmp(*av, "firewall") == 0) {
2370 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2371 &which, sizeof(which));
2372 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
2373 &which, sizeof(which));
2374 } else if (_substrcmp(*av, "one_pass") == 0) {
2375 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2376 &which, sizeof(which));
2377 } else if (_substrcmp(*av, "debug") == 0) {
2378 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2379 &which, sizeof(which));
2380 } else if (_substrcmp(*av, "verbose") == 0) {
2381 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2382 &which, sizeof(which));
2383 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2384 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2385 &which, sizeof(which));
2387 } else if (_substrcmp(*av, "altq") == 0) {
2388 altq_set_enabled(which);
2391 warnx("unrecognize enable/disable keyword: %s\n", *av);
2395 typedef void state_cb(struct cmdline_opts *co, struct format_opts *fo,
2396 void *arg, void *state);
2399 prepare_format_dyn(struct cmdline_opts *co, struct format_opts *fo,
2400 void *arg, void *_state)
2406 d = (ipfw_dyn_rule *)_state;
2407 /* Count _ALL_ states */
2410 if (fo->show_counters == 0)
2414 /* skip states from another set */
2415 bcopy((char *)&d->rule + sizeof(uint16_t), &set,
2417 if (set != co->use_set - 1)
2421 width = pr_u64(NULL, &d->pcnt, 0);
2422 if (width > fo->pcwidth)
2423 fo->pcwidth = width;
2425 width = pr_u64(NULL, &d->bcnt, 0);
2426 if (width > fo->bcwidth)
2427 fo->bcwidth = width;
2431 foreach_state(struct cmdline_opts *co, struct format_opts *fo,
2432 caddr_t base, size_t sz, state_cb dyn_bc, void *dyn_arg)
2438 ipfw_obj_ctlv *ctlv;
2444 ctlv = (ipfw_obj_ctlv *)base;
2445 switch (ctlv->head.type) {
2446 case IPFW_TLV_DYNSTATE_LIST:
2447 base += sizeof(*ctlv);
2448 sz -= sizeof(*ctlv);
2449 ttype = IPFW_TLV_DYN_ENT;
2458 tlv = (ipfw_obj_tlv *)base;
2459 if (tlv->type != ttype)
2462 fptr(co, fo, farg, tlv + 1);
2464 base += tlv->length;
2472 prepare_format_opts(struct cmdline_opts *co, struct format_opts *fo,
2473 ipfw_obj_tlv *rtlv, int rcnt, caddr_t dynbase, size_t dynsz)
2475 int bcwidth, pcwidth, width;
2477 struct ip_fw_bcounter *cntr;
2478 struct ip_fw_rule *r;
2482 if (fo->show_counters != 0) {
2483 for (n = 0; n < rcnt; n++,
2484 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2485 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2486 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2487 /* skip rules from another set */
2488 if (co->use_set && r->set != co->use_set - 1)
2491 /* packet counter */
2492 width = pr_u64(NULL, &cntr->pcnt, 0);
2493 if (width > pcwidth)
2497 width = pr_u64(NULL, &cntr->bcnt, 0);
2498 if (width > bcwidth)
2502 fo->bcwidth = bcwidth;
2503 fo->pcwidth = pcwidth;
2506 if (co->do_dynamic && dynsz > 0)
2507 foreach_state(co, fo, dynbase, dynsz, prepare_format_dyn, NULL);
2511 list_static_range(struct cmdline_opts *co, struct format_opts *fo,
2512 struct buf_pr *bp, ipfw_obj_tlv *rtlv, int rcnt)
2515 struct ip_fw_rule *r;
2516 struct ip_fw_bcounter *cntr;
2519 for (n = seen = 0; n < rcnt; n++,
2520 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2522 if ((fo->show_counters | fo->show_time) != 0) {
2523 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2524 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2527 r = (struct ip_fw_rule *)(rtlv + 1);
2529 if (r->rulenum > fo->last)
2531 if (co->use_set && r->set != co->use_set - 1)
2533 if (r->rulenum >= fo->first && r->rulenum <= fo->last) {
2534 show_static_rule(co, fo, bp, r, cntr);
2535 printf("%s", bp->buf);
2546 list_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2547 void *_arg, void *_state)
2554 d = (ipfw_dyn_rule *)_state;
2555 bp = (struct buf_pr *)_arg;
2557 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2558 if (rulenum > fo->last)
2561 bcopy((char *)&d->rule + sizeof(uint16_t),
2562 &set, sizeof(uint8_t));
2563 if (set != co->use_set - 1)
2566 if (rulenum >= fo->first) {
2567 show_dyn_state(co, fo, bp, d);
2568 printf("%s\n", bp->buf);
2574 list_dyn_range(struct cmdline_opts *co, struct format_opts *fo,
2575 struct buf_pr *bp, caddr_t base, size_t sz)
2578 sz = foreach_state(co, fo, base, sz, list_dyn_state, bp);
2583 ipfw_list(int ac, char *av[], int show_counters)
2585 ipfw_cfg_lheader *cfg;
2586 struct format_opts sfo;
2595 fprintf(stderr, "Testing only, list disabled\n");
2599 dummynet_list(ac, av, show_counters);
2605 memset(&sfo, 0, sizeof(sfo));
2607 /* Determine rule range to request */
2609 for (lac = ac, lav = av; lac != 0; lac--) {
2610 rnum = strtoul(*lav++, &endptr, 10);
2611 if (sfo.first == 0 || rnum < sfo.first)
2615 rnum = strtoul(endptr + 1, &endptr, 10);
2616 if (sfo.last == 0 || rnum > sfo.last)
2621 /* get configuraion from kernel */
2623 sfo.show_counters = show_counters;
2624 sfo.show_time = co.do_time;
2625 sfo.flags = IPFW_CFG_GET_STATIC;
2626 if (co.do_dynamic != 0)
2627 sfo.flags |= IPFW_CFG_GET_STATES;
2628 if ((sfo.show_counters | sfo.show_time) != 0)
2629 sfo.flags |= IPFW_CFG_GET_COUNTERS;
2630 if (ipfw_get_config(&co, &sfo, &cfg, &sz) != 0)
2631 err(EX_OSERR, "retrieving config failed");
2633 error = ipfw_show_config(&co, &sfo, cfg, sz, ac, av);
2642 ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
2643 ipfw_cfg_lheader *cfg, size_t sz, int ac, char *av[])
2648 int exitval = EX_OK;
2654 ipfw_obj_ctlv *ctlv, *tstate;
2655 ipfw_obj_tlv *rbase;
2658 * Handle tablenames TLV first, if any
2664 readsz = sizeof(*cfg);
2667 fo->set_mask = cfg->set_mask;
2669 ctlv = (ipfw_obj_ctlv *)(cfg + 1);
2671 if (cfg->flags & IPFW_CFG_GET_STATIC) {
2672 /* We've requested static rules */
2673 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2674 object_sort_ctlv(ctlv);
2676 readsz += ctlv->head.length;
2677 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2681 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2682 rbase = (ipfw_obj_tlv *)(ctlv + 1);
2684 readsz += ctlv->head.length;
2685 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2690 if ((cfg->flags & IPFW_CFG_GET_STATES) && (readsz != sz)) {
2691 /* We may have some dynamic states */
2692 dynsz = sz - readsz;
2693 /* Skip empty header */
2694 if (dynsz != sizeof(ipfw_obj_ctlv))
2695 dynbase = (caddr_t)ctlv;
2700 prepare_format_opts(co, fo, rbase, rcnt, dynbase, dynsz);
2701 bp_alloc(&bp, 4096);
2703 /* if no rule numbers were specified, list all rules */
2706 fo->last = IPFW_DEFAULT_RULE;
2707 list_static_range(co, fo, &bp, rbase, rcnt);
2709 if (co->do_dynamic && dynsz > 0) {
2710 printf("## Dynamic rules (%d %zu):\n", fo->dcnt, dynsz);
2711 list_dyn_range(co, fo, &bp, dynbase, dynsz);
2718 /* display specific rules requested on command line */
2719 for (lac = ac, lav = av; lac != 0; lac--) {
2720 /* convert command line rule # */
2721 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2723 fo->last = strtoul(endptr + 1, &endptr, 10);
2726 warnx("invalid rule number: %s", *(lav - 1));
2730 if (list_static_range(co, fo, &bp, rbase, rcnt) == 0) {
2731 /* give precedence to other error(s) */
2732 if (exitval == EX_OK)
2733 exitval = EX_UNAVAILABLE;
2734 if (fo->first == fo->last)
2735 warnx("rule %u does not exist", fo->first);
2737 warnx("no rules in range %u-%u",
2738 fo->first, fo->last);
2742 if (co->do_dynamic && dynsz > 0) {
2743 printf("## Dynamic rules:\n");
2744 for (lac = ac, lav = av; lac != 0; lac--) {
2745 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2747 fo->last = strtoul(endptr+1, &endptr, 10);
2749 /* already warned */
2751 list_dyn_range(co, fo, &bp, dynbase, dynsz);
2761 * Retrieves current ipfw configuration of given type
2762 * and stores its pointer to @pcfg.
2764 * Caller is responsible for freeing @pcfg.
2766 * Returns 0 on success.
2770 ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
2771 ipfw_cfg_lheader **pcfg, size_t *psize)
2773 ipfw_cfg_lheader *cfg;
2778 if (co->test_only != 0) {
2779 fprintf(stderr, "Testing only, list disabled\n");
2783 /* Start with some data size */
2787 for (i = 0; i < 16; i++) {
2790 if ((cfg = calloc(1, sz)) == NULL)
2793 cfg->flags = fo->flags;
2794 cfg->start_rule = fo->first;
2795 cfg->end_rule = fo->last;
2797 if (do_get3(IP_FW_XGET, &cfg->opheader, &sz) != 0) {
2798 if (errno != ENOMEM) {
2803 /* Buffer size is not enough. Try to increase */
2820 lookup_host (char *host, struct in_addr *ipaddr)
2824 if (!inet_aton(host, ipaddr)) {
2825 if ((he = gethostbyname(host)) == NULL)
2827 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2841 ipfw_check_object_name(const char *name)
2846 * Check that name is null-terminated and contains
2847 * valid symbols only. Valid mask is:
2848 * [a-zA-Z0-9\-_\.]{1,63}
2851 if (l == 0 || l >= 64)
2853 for (i = 0; i < l; i++) {
2855 if (isalpha(c) || isdigit(c) || c == '_' ||
2856 c == '-' || c == '.')
2863 static char *default_state_name = "default";
2865 state_check_name(const char *name)
2868 if (ipfw_check_object_name(name) != 0)
2870 if (strcmp(name, "any") == 0)
2876 eaction_check_name(const char *name)
2879 if (ipfw_check_object_name(name) != 0)
2881 /* Restrict some 'special' names */
2882 if (match_token(rule_actions, name) != -1 &&
2883 match_token(rule_action_params, name) != -1)
2889 pack_object(struct tidx *tstate, char *name, int otype)
2892 ipfw_obj_ntlv *ntlv;
2894 for (i = 0; i < tstate->count; i++) {
2895 if (strcmp(tstate->idx[i].name, name) != 0)
2897 if (tstate->idx[i].set != tstate->set)
2899 if (tstate->idx[i].head.type != otype)
2902 return (tstate->idx[i].idx);
2905 if (tstate->count + 1 > tstate->size) {
2907 tstate->idx = realloc(tstate->idx, tstate->size *
2908 sizeof(ipfw_obj_ntlv));
2909 if (tstate->idx == NULL)
2913 ntlv = &tstate->idx[i];
2914 memset(ntlv, 0, sizeof(ipfw_obj_ntlv));
2915 strlcpy(ntlv->name, name, sizeof(ntlv->name));
2916 ntlv->head.type = otype;
2917 ntlv->head.length = sizeof(ipfw_obj_ntlv);
2918 ntlv->set = tstate->set;
2919 ntlv->idx = ++tstate->counter;
2926 pack_table(struct tidx *tstate, char *name)
2929 if (table_check_name(name) != 0)
2932 return (pack_object(tstate, name, IPFW_TLV_TBL_NAME));
2936 fill_table(struct _ipfw_insn *cmd, char *av, uint8_t opcode,
2937 struct tidx *tstate)
2939 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2943 if ((p = strchr(av + 6, ')')) == NULL)
2944 errx(EX_DATAERR, "forgotten parenthesis: '%s'", av);
2946 p = strchr(av + 6, ',');
2950 if ((uidx = pack_table(tstate, av + 6)) == 0)
2951 errx(EX_DATAERR, "Invalid table name: %s", av + 6);
2953 cmd->opcode = opcode;
2956 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
2957 d[0] = strtoul(p, NULL, 0);
2959 cmd->len |= F_INSN_SIZE(ipfw_insn);
2964 * fills the addr and mask fields in the instruction as appropriate from av.
2965 * Update length as appropriate.
2966 * The following formats are allowed:
2967 * me returns O_IP_*_ME
2968 * 1.2.3.4 single IP address
2969 * 1.2.3.4:5.6.7.8 address:mask
2970 * 1.2.3.4/24 address/mask
2971 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
2972 * We can have multiple comma-separated address/mask entries.
2975 fill_ip(ipfw_insn_ip *cmd, char *av, int cblen, struct tidx *tstate)
2978 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2980 cmd->o.len &= ~F_LEN_MASK; /* zero len */
2982 if (_substrcmp(av, "any") == 0)
2985 if (_substrcmp(av, "me") == 0) {
2986 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2990 if (strncmp(av, "table(", 6) == 0) {
2991 fill_table(&cmd->o, av, O_IP_DST_LOOKUP, tstate);
2997 * After the address we can have '/' or ':' indicating a mask,
2998 * ',' indicating another address follows, '{' indicating a
2999 * set of addresses of unspecified size.
3001 char *t = NULL, *p = strpbrk(av, "/:,{");
3005 CHECK_LENGTH(cblen, F_INSN_SIZE(ipfw_insn) + 2 + len);
3010 if ((t = strpbrk(p, ",{")) != NULL) {
3017 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
3018 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
3021 if (!inet_aton(p, (struct in_addr *)&d[1]))
3022 errx(EX_DATAERR, "bad netmask ``%s''", p);
3027 d[1] = htonl(0U); /* mask */
3028 else if (masklen > 32)
3029 errx(EX_DATAERR, "bad width ``%s''", p);
3031 d[1] = htonl(~0U << (32 - masklen));
3033 case '{': /* no mask, assume /24 and put back the '{' */
3034 d[1] = htonl(~0U << (32 - 24));
3038 case ',': /* single address plus continuation */
3041 case 0: /* initialization value */
3043 d[1] = htonl(~0U); /* force /32 */
3046 d[0] &= d[1]; /* mask base address with mask */
3049 /* find next separator */
3051 p = strpbrk(p, ",{");
3052 if (p && *p == '{') {
3054 * We have a set of addresses. They are stored as follows:
3055 * arg1 is the set size (powers of 2, 2..256)
3056 * addr is the base address IN HOST FORMAT
3057 * mask.. is an array of arg1 bits (rounded up to
3058 * the next multiple of 32) with bits set
3059 * for each host in the map.
3061 uint32_t *map = (uint32_t *)&cmd->mask;
3063 int i = contigmask((uint8_t *)&(d[1]), 32);
3066 errx(EX_DATAERR, "address set cannot be in a list");
3067 if (i < 24 || i > 31)
3068 errx(EX_DATAERR, "invalid set with mask %d\n", i);
3069 cmd->o.arg1 = 1<<(32-i); /* map length */
3070 d[0] = ntohl(d[0]); /* base addr in host format */
3071 cmd->o.opcode = O_IP_DST_SET; /* default */
3072 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
3073 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
3074 map[i] = 0; /* clear map */
3078 high = low + cmd->o.arg1 - 1;
3080 * Here, i stores the previous value when we specify a range
3081 * of addresses within a mask, e.g. 45-63. i = -1 means we
3082 * have no previous value.
3084 i = -1; /* previous value in a range */
3085 while (isdigit(*av)) {
3087 int a = strtol(av, &s, 0);
3089 if (s == av) { /* no parameter */
3091 errx(EX_DATAERR, "set not closed\n");
3093 errx(EX_DATAERR, "incomplete range %d-", i);
3096 if (a < low || a > high)
3097 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
3100 if (i == -1) /* no previous in range */
3102 else { /* check that range is valid */
3104 errx(EX_DATAERR, "invalid range %d-%d",
3107 errx(EX_DATAERR, "double '-' in range");
3110 map[i/32] |= 1<<(i & 31);
3121 if (av) /* then *av must be a ',' */
3124 /* Check this entry */
3125 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
3127 * 'any' turns the entire list into a NOP.
3128 * 'not any' never matches, so it is removed from the
3129 * list unless it is the only item, in which case we
3132 if (cmd->o.len & F_NOT) { /* "not any" never matches */
3133 if (av == NULL && len == 0) /* only this entry */
3134 errx(EX_DATAERR, "not any never matches");
3136 /* else do nothing and skip this entry */
3139 /* A single IP can be stored in an optimized format */
3140 if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
3141 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
3144 len += 2; /* two words... */
3147 if (len + 1 > F_LEN_MASK)
3148 errx(EX_DATAERR, "address list too long");
3149 cmd->o.len |= len+1;
3153 /* n2mask sets n bits of the mask */
3155 n2mask(struct in6_addr *mask, int n)
3157 static int minimask[9] =
3158 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
3161 memset(mask, 0, sizeof(struct in6_addr));
3162 p = (u_char *) mask;
3163 for (; n > 0; p++, n -= 8) {
3173 fill_flags_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3174 struct _s_x *flags, char *p)
3177 uint32_t set = 0, clear = 0;
3179 if (fill_flags(flags, p, &e, &set, &clear) != 0)
3180 errx(EX_DATAERR, "invalid flag %s", e);
3182 cmd->opcode = opcode;
3183 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
3184 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3189 ipfw_delete(char *av[])
3194 int exitval = EX_OK;
3198 NEED1("missing rule specification");
3199 if ( *av && _substrcmp(*av, "set") == 0) {
3200 /* Do not allow using the following syntax:
3201 * ipfw set N delete set M
3204 errx(EX_DATAERR, "invalid syntax");
3205 do_set = 1; /* delete set */
3210 while (*av && isdigit(**av)) {
3211 i = strtol(*av, &sep, 10);
3214 j = strtol(sep + 1, NULL, 10);
3217 exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
3219 exitval = EX_UNAVAILABLE;
3220 warn("rule %u not available", i);
3222 } else if (co.do_pipe) {
3223 exitval = ipfw_delete_pipe(co.do_pipe, i);
3225 memset(&rt, 0, sizeof(rt));
3228 rt.flags = IPFW_RCFLAG_SET;
3230 rt.start_rule = i & 0xffff;
3231 rt.end_rule = j & 0xffff;
3232 if (rt.start_rule == 0 && rt.end_rule == 0)
3233 rt.flags |= IPFW_RCFLAG_ALL;
3235 rt.flags |= IPFW_RCFLAG_RANGE;
3236 if (co.use_set != 0) {
3237 rt.set = co.use_set - 1;
3238 rt.flags |= IPFW_RCFLAG_SET;
3241 i = do_range_cmd(IP_FW_XDEL, &rt);
3243 exitval = EX_UNAVAILABLE;
3244 warn("rule %u: setsockopt(IP_FW_XDEL)",
3246 } else if (rt.new_set == 0 && do_set == 0) {
3247 exitval = EX_UNAVAILABLE;
3248 if (rt.start_rule != rt.end_rule)
3249 warnx("no rules rules in %u-%u range",
3250 rt.start_rule, rt.end_rule);
3252 warnx("rule %u not found",
3257 if (exitval != EX_OK)
3263 * fill the interface structure. We do not check the name as we can
3264 * create interfaces dynamically, so checking them at insert time
3265 * makes relatively little sense.
3266 * Interface names containing '*', '?', or '[' are assumed to be shell
3267 * patterns which match interfaces.
3270 fill_iface(ipfw_insn_if *cmd, char *arg, int cblen, struct tidx *tstate)
3275 cmd->name[0] = '\0';
3276 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3280 /* Parse the interface or address */
3281 if (strcmp(arg, "any") == 0)
3282 cmd->o.len = 0; /* effectively ignore this command */
3283 else if (strncmp(arg, "table(", 6) == 0) {
3284 if ((p = strchr(arg + 6, ')')) == NULL)
3285 errx(EX_DATAERR, "forgotten parenthesis: '%s'", arg);
3287 p = strchr(arg + 6, ',');
3290 if ((uidx = pack_table(tstate, arg + 6)) == 0)
3291 errx(EX_DATAERR, "Invalid table name: %s", arg + 6);
3293 cmd->name[0] = '\1'; /* Special value indicating table */
3295 } else if (!isdigit(*arg)) {
3296 strlcpy(cmd->name, arg, sizeof(cmd->name));
3297 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3298 } else if (!inet_aton(arg, &cmd->p.ip))
3299 errx(EX_DATAERR, "bad ip address ``%s''", arg);
3303 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
3307 char *ap, *ptr, *optr;
3308 struct ether_addr *mac;
3309 const char *macset = "0123456789abcdefABCDEF:";
3311 if (strcmp(p, "any") == 0) {
3312 for (i = 0; i < ETHER_ADDR_LEN; i++)
3313 addr[i] = mask[i] = 0;
3317 optr = ptr = strdup(p);
3318 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
3320 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
3321 errx(EX_DATAERR, "Incorrect MAC address");
3322 bcopy(mac, addr, ETHER_ADDR_LEN);
3324 errx(EX_DATAERR, "Incorrect MAC address");
3326 if (ptr != NULL) { /* we have mask? */
3327 if (p[ptr - optr - 1] == '/') { /* mask len */
3328 long ml = strtol(ptr, &ap, 10);
3329 if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
3330 errx(EX_DATAERR, "Incorrect mask length");
3331 for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
3332 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
3335 if (strspn(ptr, macset) != l ||
3336 (mac = ether_aton(ptr)) == NULL)
3337 errx(EX_DATAERR, "Incorrect mask");
3338 bcopy(mac, mask, ETHER_ADDR_LEN);
3340 } else { /* default mask: ff:ff:ff:ff:ff:ff */
3341 for (i = 0; i < ETHER_ADDR_LEN; i++)
3344 for (i = 0; i < ETHER_ADDR_LEN; i++)
3351 * helper function, updates the pointer to cmd with the length
3352 * of the current command, and also cleans up the first word of
3353 * the new command in case it has been clobbered before.
3356 next_cmd(ipfw_insn *cmd, int *len)
3359 CHECK_LENGTH(*len, 0);
3361 bzero(cmd, sizeof(*cmd));
3366 * Takes arguments and copies them into a comment
3369 fill_comment(ipfw_insn *cmd, char **av, int cblen)
3372 char *p = (char *)(cmd + 1);
3374 cmd->opcode = O_NOP;
3375 cmd->len = (cmd->len & (F_NOT | F_OR));
3377 /* Compute length of comment string. */
3378 for (i = 0, l = 0; av[i] != NULL; i++)
3379 l += strlen(av[i]) + 1;
3384 "comment too long (max 80 chars)");
3386 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
3389 for (i = 0; av[i] != NULL; i++) {
3398 * A function to fill simple commands of size 1.
3399 * Existing flags are preserved.
3402 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3404 cmd->opcode = opcode;
3405 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3410 * Fetch and add the MAC address and type, with masks. This generates one or
3411 * two microinstructions, and returns the pointer to the last one.
3414 add_mac(ipfw_insn *cmd, char *av[], int cblen)
3418 if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
3419 errx(EX_DATAERR, "MAC dst src");
3421 cmd->opcode = O_MACADDR2;
3422 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3425 mac = (ipfw_insn_mac *)cmd;
3426 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
3427 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
3428 &(mac->mask[ETHER_ADDR_LEN])); /* src */
3433 add_mactype(ipfw_insn *cmd, char *av, int cblen)
3436 errx(EX_DATAERR, "missing MAC type");
3437 if (strcmp(av, "any") != 0) { /* we have a non-null type */
3438 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
3440 cmd->opcode = O_MAC_TYPE;
3447 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
3449 struct protoent *pe;
3453 proto = strtol(av, &ep, 10);
3454 if (*ep != '\0' || proto <= 0) {
3455 if ((pe = getprotobyname(av)) == NULL)
3457 proto = pe->p_proto;
3460 fill_cmd(cmd, O_PROTO, 0, proto);
3466 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
3468 u_char proto = IPPROTO_IP;
3470 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3471 ; /* do not set O_IP4 nor O_IP6 */
3472 else if (strcmp(av, "ip4") == 0)
3473 /* explicit "just IPv4" rule */
3474 fill_cmd(cmd, O_IP4, 0, 0);
3475 else if (strcmp(av, "ip6") == 0) {
3476 /* explicit "just IPv6" rule */
3477 proto = IPPROTO_IPV6;
3478 fill_cmd(cmd, O_IP6, 0, 0);
3480 return add_proto0(cmd, av, protop);
3487 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
3489 u_char proto = IPPROTO_IP;
3491 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3492 ; /* do not set O_IP4 nor O_IP6 */
3493 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3494 /* explicit "just IPv4" rule */
3495 fill_cmd(cmd, O_IP4, 0, 0);
3496 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3497 /* explicit "just IPv6" rule */
3498 proto = IPPROTO_IPV6;
3499 fill_cmd(cmd, O_IP6, 0, 0);
3501 return add_proto0(cmd, av, protop);
3508 add_srcip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3510 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3511 if (cmd->opcode == O_IP_DST_SET) /* set */
3512 cmd->opcode = O_IP_SRC_SET;
3513 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3514 cmd->opcode = O_IP_SRC_LOOKUP;
3515 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3516 cmd->opcode = O_IP_SRC_ME;
3517 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3518 cmd->opcode = O_IP_SRC;
3519 else /* addr/mask */
3520 cmd->opcode = O_IP_SRC_MASK;
3525 add_dstip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3527 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3528 if (cmd->opcode == O_IP_DST_SET) /* set */
3530 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3532 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3533 cmd->opcode = O_IP_DST_ME;
3534 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3535 cmd->opcode = O_IP_DST;
3536 else /* addr/mask */
3537 cmd->opcode = O_IP_DST_MASK;
3541 static struct _s_x f_reserved_keywords[] = {
3544 { "diverted", TOK_OR },
3545 { "dst-port", TOK_OR },
3546 { "src-port", TOK_OR },
3547 { "established", TOK_OR },
3548 { "keep-state", TOK_OR },
3550 { "icmptypes", TOK_OR },
3558 { NULL, 0 } /* terminator */
3562 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
3565 if (match_token(f_reserved_keywords, av) != -1)
3568 if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
3569 /* XXX todo: check that we have a protocol with ports */
3570 cmd->opcode = opcode;
3577 add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3580 char *host, *ch, buf[INET6_ADDRSTRLEN];
3581 ipfw_insn *ret = NULL;
3584 /* Copy first address in set if needed */
3585 if ((ch = strpbrk(av, "/,")) != NULL) {
3587 strlcpy(buf, av, sizeof(buf));
3588 if (len < sizeof(buf))
3594 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3595 inet_pton(AF_INET6, host, &a) == 1)
3596 ret = add_srcip6(cmd, av, cblen, tstate);
3597 /* XXX: should check for IPv4, not !IPv6 */
3598 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3599 inet_pton(AF_INET6, host, &a) != 1))
3600 ret = add_srcip(cmd, av, cblen, tstate);
3601 if (ret == NULL && strcmp(av, "any") != 0)
3608 add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3611 char *host, *ch, buf[INET6_ADDRSTRLEN];
3612 ipfw_insn *ret = NULL;
3615 /* Copy first address in set if needed */
3616 if ((ch = strpbrk(av, "/,")) != NULL) {
3618 strlcpy(buf, av, sizeof(buf));
3619 if (len < sizeof(buf))
3625 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3626 inet_pton(AF_INET6, host, &a) == 1)
3627 ret = add_dstip6(cmd, av, cblen, tstate);
3628 /* XXX: should check for IPv4, not !IPv6 */
3629 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3630 inet_pton(AF_INET6, host, &a) != 1))
3631 ret = add_dstip(cmd, av, cblen, tstate);
3632 if (ret == NULL && strcmp(av, "any") != 0)
3639 * Parse arguments and assemble the microinstructions which make up a rule.
3640 * Rules are added into the 'rulebuf' and then copied in the correct order
3641 * into the actual rule.
3643 * The syntax for a rule starts with the action, followed by
3644 * optional action parameters, and the various match patterns.
3645 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
3646 * (generated if the rule includes a keep-state option), then the
3647 * various match patterns, log/altq actions, and the actual action.
3651 compile_rule(char *av[], uint32_t *rbuf, int *rbufsize, struct tidx *tstate)
3654 * rules are added into the 'rulebuf' and then copied in
3655 * the correct order into the actual rule.
3656 * Some things that need to go out of order (prob, action etc.)
3659 static uint32_t actbuf[255], cmdbuf[255];
3660 int rblen, ablen, cblen;
3662 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
3663 ipfw_insn *first_cmd; /* first match pattern */
3665 struct ip_fw_rule *rule;
3668 * various flags used to record that we entered some fields.
3670 ipfw_insn *have_state = NULL; /* check-state or keep-state */
3671 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
3676 int open_par = 0; /* open parenthesis ( */
3678 /* proto is here because it is used to fetch ports */
3679 u_char proto = IPPROTO_IP; /* default protocol */
3681 double match_prob = 1; /* match probability, default is always match */
3683 bzero(actbuf, sizeof(actbuf)); /* actions go here */
3684 bzero(cmdbuf, sizeof(cmdbuf));
3685 bzero(rbuf, *rbufsize);
3687 rule = (struct ip_fw_rule *)rbuf;
3688 cmd = (ipfw_insn *)cmdbuf;
3689 action = (ipfw_insn *)actbuf;
3691 rblen = *rbufsize / sizeof(uint32_t);
3692 rblen -= sizeof(struct ip_fw_rule) / sizeof(uint32_t);
3693 ablen = sizeof(actbuf) / sizeof(actbuf[0]);
3694 cblen = sizeof(cmdbuf) / sizeof(cmdbuf[0]);
3695 cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
3697 #define CHECK_RBUFLEN(len) { CHECK_LENGTH(rblen, len); rblen -= len; }
3698 #define CHECK_ACTLEN CHECK_LENGTH(ablen, action->len)
3702 /* [rule N] -- Rule number optional */
3703 if (av[0] && isdigit(**av)) {
3704 rule->rulenum = atoi(*av);
3708 /* [set N] -- set number (0..RESVD_SET), optional */
3709 if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
3710 int set = strtoul(av[1], NULL, 10);
3711 if (set < 0 || set > RESVD_SET)
3712 errx(EX_DATAERR, "illegal set %s", av[1]);
3718 /* [prob D] -- match probability, optional */
3719 if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
3720 match_prob = strtod(av[1], NULL);
3722 if (match_prob <= 0 || match_prob > 1)
3723 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
3727 /* action -- mandatory */
3728 NEED1("missing action");
3729 i = match_token(rule_actions, *av);
3731 action->len = 1; /* default */
3734 case TOK_CHECKSTATE:
3735 have_state = action;
3736 action->opcode = O_CHECK_STATE;
3738 match_token(rule_options, *av) == TOK_COMMENT) {
3739 action->arg1 = pack_object(tstate,
3740 default_state_name, IPFW_TLV_STATE_NAME);
3743 if (*av[0] == ':') {
3744 if (strcmp(*av + 1, "any") == 0)
3746 else if (state_check_name(*av + 1) == 0)
3747 action->arg1 = pack_object(tstate, *av + 1,
3748 IPFW_TLV_STATE_NAME);
3750 errx(EX_DATAERR, "Invalid state name %s",
3755 errx(EX_DATAERR, "Invalid state name %s", *av);
3759 action->opcode = O_ACCEPT;
3763 action->opcode = O_DENY;
3768 action->opcode = O_REJECT;
3769 action->arg1 = ICMP_UNREACH_HOST;
3773 action->opcode = O_REJECT;
3774 action->arg1 = ICMP_REJECT_RST;
3778 action->opcode = O_UNREACH6;
3779 action->arg1 = ICMP6_UNREACH_RST;
3783 action->opcode = O_REJECT;
3784 NEED1("missing reject code");
3785 fill_reject_code(&action->arg1, *av);
3790 action->opcode = O_UNREACH6;
3791 NEED1("missing unreach code");
3792 fill_unreach6_code(&action->arg1, *av);
3797 action->opcode = O_COUNT;
3801 action->opcode = O_NAT;
3802 action->len = F_INSN_SIZE(ipfw_insn_nat);
3804 if (*av != NULL && _substrcmp(*av, "global") == 0) {
3805 action->arg1 = IP_FW_NAT44_GLOBAL;
3811 action->opcode = O_QUEUE;
3814 action->opcode = O_PIPE;
3817 action->opcode = O_SKIPTO;
3820 action->opcode = O_NETGRAPH;
3823 action->opcode = O_NGTEE;
3826 action->opcode = O_DIVERT;
3829 action->opcode = O_TEE;
3832 action->opcode = O_CALLRETURN;
3835 errx(EX_USAGE, "missing argument for %s", *(av - 1));
3836 if (isdigit(**av)) {
3837 action->arg1 = strtoul(*av, NULL, 10);
3838 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
3839 errx(EX_DATAERR, "illegal argument for %s",
3841 } else if (_substrcmp(*av, "tablearg") == 0) {
3842 action->arg1 = IP_FW_TARG;
3843 } else if (i == TOK_DIVERT || i == TOK_TEE) {
3846 s = getservbyname(av[0], "divert");
3848 action->arg1 = ntohs(s->s_port);
3850 errx(EX_DATAERR, "illegal divert/tee port");
3852 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
3858 * Locate the address-port separator (':' or ',').
3859 * Could be one of the following:
3863 * IPv6 w:x:y::z,port
3864 * The ':' can only be used with hostname and IPv4 address.
3865 * XXX-BZ Should we also support [w:x:y::z]:port?
3867 struct sockaddr_storage result;
3868 struct addrinfo *res;
3871 u_short port_number;
3873 NEED1("missing forward address[:port]");
3876 * locate the address-port separator (':' or ',')
3878 s = strchr(*av, ',');
3880 /* Distinguish between IPv4:port and IPv6 cases. */
3881 s = strchr(*av, ':');
3882 if (s && strchr(s+1, ':'))
3883 s = NULL; /* no port */
3888 /* Terminate host portion and set s to start of port. */
3890 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
3893 "illegal forwarding port ``%s''", s);
3894 port_number = (u_short)i;
3897 if (_substrcmp(*av, "tablearg") == 0) {
3899 ((struct sockaddr_in*)&result)->sin_addr.s_addr =
3903 * Resolve the host name or address to a family and a
3904 * network representation of the address.
3906 if (getaddrinfo(*av, NULL, NULL, &res))
3907 errx(EX_DATAERR, NULL);
3908 /* Just use the first host in the answer. */
3909 family = res->ai_family;
3910 memcpy(&result, res->ai_addr, res->ai_addrlen);
3914 if (family == PF_INET) {
3915 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
3917 action->opcode = O_FORWARD_IP;
3918 action->len = F_INSN_SIZE(ipfw_insn_sa);
3922 * In the kernel we assume AF_INET and use only
3923 * sin_port and sin_addr. Remember to set sin_len as
3924 * the routing code seems to use it too.
3926 p->sa.sin_len = sizeof(struct sockaddr_in);
3927 p->sa.sin_family = AF_INET;
3928 p->sa.sin_port = port_number;
3929 p->sa.sin_addr.s_addr =
3930 ((struct sockaddr_in *)&result)->sin_addr.s_addr;
3931 } else if (family == PF_INET6) {
3932 ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
3934 action->opcode = O_FORWARD_IP6;
3935 action->len = F_INSN_SIZE(ipfw_insn_sa6);
3938 p->sa.sin6_len = sizeof(struct sockaddr_in6);
3939 p->sa.sin6_family = AF_INET6;
3940 p->sa.sin6_port = port_number;
3941 p->sa.sin6_flowinfo = 0;
3942 p->sa.sin6_scope_id =
3943 ((struct sockaddr_in6 *)&result)->sin6_scope_id;
3944 bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
3945 &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
3947 errx(EX_DATAERR, "Invalid address family in forward action");
3953 /* pretend it is a 'count' rule followed by the comment */
3954 action->opcode = O_COUNT;
3955 av--; /* go back... */
3961 size_t intsize = sizeof(int);
3963 action->opcode = O_SETFIB;
3964 NEED1("missing fib number");
3965 if (_substrcmp(*av, "tablearg") == 0) {
3966 action->arg1 = IP_FW_TARG;
3968 action->arg1 = strtoul(*av, NULL, 10);
3969 if (sysctlbyname("net.fibs", &numfibs, &intsize,
3971 errx(EX_DATAERR, "fibs not suported.\n");
3972 if (action->arg1 >= numfibs) /* Temporary */
3973 errx(EX_DATAERR, "fib too large.\n");
3974 /* Add high-order bit to fib to make room for tablearg*/
3975 action->arg1 |= 0x8000;
3985 action->opcode = O_SETDSCP;
3986 NEED1("missing DSCP code");
3987 if (_substrcmp(*av, "tablearg") == 0) {
3988 action->arg1 = IP_FW_TARG;
3990 if (isalpha(*av[0])) {
3991 if ((code = match_token(f_ipdscp, *av)) == -1)
3992 errx(EX_DATAERR, "Unknown DSCP code");
3993 action->arg1 = code;
3995 action->arg1 = strtoul(*av, NULL, 10);
3997 * Add high-order bit to DSCP to make room
4000 action->arg1 |= 0x8000;
4007 action->opcode = O_REASS;
4011 fill_cmd(action, O_CALLRETURN, F_NOT, 0);
4014 case TOK_TCPSETMSS: {
4018 idx = pack_object(tstate, "tcp-setmss", IPFW_TLV_EACTION);
4020 errx(EX_DATAERR, "pack_object failed");
4021 fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4022 NEED1("Missing MSS value");
4023 action = next_cmd(action, &ablen);
4026 mss = strtoul(*av, NULL, 10);
4027 if (mss == 0 || mss > UINT16_MAX)
4028 errx(EX_USAGE, "invalid MSS value %s", *av);
4029 fill_cmd(action, O_EXTERNAL_DATA, 0, (uint16_t)mss);
4036 if (match_token(rule_eactions, *av) == -1)
4037 errx(EX_DATAERR, "invalid action %s\n", *av);
4039 * External actions support.
4040 * XXX: we support only syntax with instance name.
4041 * For known external actions (from rule_eactions list)
4042 * we can handle syntax directly. But with `eaction'
4043 * keyword we can use only `eaction <name> <instance>'
4049 NEED1("Missing eaction name");
4050 if (eaction_check_name(*av) != 0)
4051 errx(EX_DATAERR, "Invalid eaction name %s", *av);
4052 idx = pack_object(tstate, *av, IPFW_TLV_EACTION);
4054 errx(EX_DATAERR, "pack_object failed");
4055 fill_cmd(action, O_EXTERNAL_ACTION, 0, idx);
4057 NEED1("Missing eaction instance name");
4058 action = next_cmd(action, &ablen);
4061 if (eaction_check_name(*av) != 0)
4062 errx(EX_DATAERR, "Invalid eaction instance name %s",
4065 * External action instance object has TLV type depended
4066 * from the external action name object index. Since we
4067 * currently don't know this index, use zero as TLV type.
4069 idx = pack_object(tstate, *av, 0);
4071 errx(EX_DATAERR, "pack_object failed");
4072 fill_cmd(action, O_EXTERNAL_INSTANCE, 0, idx);
4076 action = next_cmd(action, &ablen);
4079 * [altq queuename] -- altq tag, optional
4080 * [log [logamount N]] -- log, optional
4082 * If they exist, it go first in the cmdbuf, but then it is
4083 * skipped in the copy section to the end of the buffer.
4085 while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
4090 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
4095 "log cannot be specified more than once");
4096 have_log = (ipfw_insn *)c;
4097 cmd->len = F_INSN_SIZE(ipfw_insn_log);
4099 cmd->opcode = O_LOG;
4100 if (av[0] && _substrcmp(*av, "logamount") == 0) {
4102 NEED1("logamount requires argument");
4106 "logamount must be positive");
4110 len = sizeof(c->max_log);
4111 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
4112 &c->max_log, &len, NULL, 0) == -1) {
4117 errx(1, "sysctlbyname(\"%s\")",
4118 "net.inet.ip.fw.verbose_limit");
4127 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
4129 NEED1("missing altq queue name");
4132 "altq cannot be specified more than once");
4133 have_altq = (ipfw_insn *)a;
4134 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
4136 cmd->opcode = O_ALTQ;
4137 a->qid = altq_name_to_qid(*av);
4148 errx(EX_USAGE, "tag and untag cannot be "
4149 "specified more than once");
4150 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
4151 rule_action_params);
4153 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
4161 cmd = next_cmd(cmd, &cblen);
4164 if (have_state) { /* must be a check-state, we are done */
4166 match_token(rule_options, *av) == TOK_COMMENT) {
4167 /* check-state has a comment */
4169 fill_comment(cmd, av, cblen);
4170 cmd = next_cmd(cmd, &cblen);
4176 #define OR_START(target) \
4177 if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
4179 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
4182 if ( (av[0])[1] == '\0') { \
4193 strcmp(*av, ")") == 0 || \
4194 strcmp(*av, "}") == 0)) { \
4199 errx(EX_USAGE, "missing \")\"\n"); \
4203 if (av[0] && _substrcmp(*av, "not") == 0) { \
4204 if (cmd->len & F_NOT) \
4205 errx(EX_USAGE, "double \"not\" not allowed\n"); \
4206 cmd->len |= F_NOT; \
4210 #define OR_BLOCK(target) \
4211 if (av[0] && _substrcmp(*av, "or") == 0) { \
4212 if (prev == NULL || open_par == 0) \
4213 errx(EX_DATAERR, "invalid OR block"); \
4214 prev->len |= F_OR; \
4224 * MAC addresses, optional.
4225 * If we have this, we skip the part "proto from src to dst"
4226 * and jump straight to the option parsing.
4229 NEED1("missing protocol");
4230 if (_substrcmp(*av, "MAC") == 0 ||
4231 _substrcmp(*av, "mac") == 0) {
4232 av++; /* the "MAC" keyword */
4233 add_mac(cmd, av); /* exits in case of errors */
4234 cmd = next_cmd(cmd);
4235 av += 2; /* dst-mac and src-mac */
4237 NEED1("missing mac type");
4238 if (add_mactype(cmd, av[0]))
4239 cmd = next_cmd(cmd);
4240 av++; /* any or mac-type */
4246 * protocol, mandatory
4248 OR_START(get_proto);
4250 NEED1("missing protocol");
4251 if (add_proto_compat(cmd, *av, &proto)) {
4253 if (F_LEN(cmd) != 0) {
4255 cmd = next_cmd(cmd, &cblen);
4257 } else if (first_cmd != cmd) {
4258 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
4261 OR_BLOCK(get_proto);
4266 if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
4267 errx(EX_USAGE, "missing ``from''");
4271 * source IP, mandatory
4273 OR_START(source_ip);
4274 NOT_BLOCK; /* optional "not" */
4275 NEED1("missing source address");
4276 if (add_src(cmd, *av, proto, cblen, tstate)) {
4278 if (F_LEN(cmd) != 0) { /* ! any */
4280 cmd = next_cmd(cmd, &cblen);
4283 errx(EX_USAGE, "bad source address %s", *av);
4284 OR_BLOCK(source_ip);
4287 * source ports, optional
4289 NOT_BLOCK; /* optional "not" */
4290 if ( av[0] != NULL ) {
4291 if (_substrcmp(*av, "any") == 0 ||
4292 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4294 if (F_LEN(cmd) != 0)
4295 cmd = next_cmd(cmd, &cblen);
4302 if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
4303 errx(EX_USAGE, "missing ``to''");
4307 * destination, mandatory
4310 NOT_BLOCK; /* optional "not" */
4311 NEED1("missing dst address");
4312 if (add_dst(cmd, *av, proto, cblen, tstate)) {
4314 if (F_LEN(cmd) != 0) { /* ! any */
4316 cmd = next_cmd(cmd, &cblen);
4319 errx( EX_USAGE, "bad destination address %s", *av);
4323 * dest. ports, optional
4325 NOT_BLOCK; /* optional "not" */
4327 if (_substrcmp(*av, "any") == 0 ||
4328 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4330 if (F_LEN(cmd) != 0)
4331 cmd = next_cmd(cmd, &cblen);
4336 if (av[0] && first_cmd == cmd) {
4338 * nothing specified so far, store in the rule to ease
4341 rule->flags |= IPFW_RULE_NOOPT;
4344 while ( av[0] != NULL ) {
4346 ipfw_insn_u32 *cmd32; /* alias for cmd */
4349 cmd32 = (ipfw_insn_u32 *)cmd;
4351 if (*s == '!') { /* alternate syntax for NOT */
4352 if (cmd->len & F_NOT)
4353 errx(EX_USAGE, "double \"not\" not allowed\n");
4357 i = match_token(rule_options, s);
4361 if (cmd->len & F_NOT)
4362 errx(EX_USAGE, "double \"not\" not allowed\n");
4367 if (open_par == 0 || prev == NULL)
4368 errx(EX_USAGE, "invalid \"or\" block\n");
4372 case TOK_STARTBRACE:
4374 errx(EX_USAGE, "+nested \"(\" not allowed\n");
4380 errx(EX_USAGE, "+missing \")\"\n");
4386 fill_cmd(cmd, O_IN, 0, 0);
4390 cmd->len ^= F_NOT; /* toggle F_NOT */
4391 fill_cmd(cmd, O_IN, 0, 0);
4395 fill_cmd(cmd, O_DIVERTED, 0, 3);
4398 case TOK_DIVERTEDLOOPBACK:
4399 fill_cmd(cmd, O_DIVERTED, 0, 1);
4402 case TOK_DIVERTEDOUTPUT:
4403 fill_cmd(cmd, O_DIVERTED, 0, 2);
4407 fill_cmd(cmd, O_FRAG, 0, 0);
4411 fill_cmd(cmd, O_LAYER2, 0, 0);
4417 NEED1("recv, xmit, via require interface name"
4419 fill_iface((ipfw_insn_if *)cmd, av[0], cblen, tstate);
4421 if (F_LEN(cmd) == 0) /* not a valid address */
4424 cmd->opcode = O_XMIT;
4425 else if (i == TOK_RECV)
4426 cmd->opcode = O_RECV;
4427 else if (i == TOK_VIA)
4428 cmd->opcode = O_VIA;
4432 NEED1("icmptypes requires list of types");
4433 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
4437 case TOK_ICMP6TYPES:
4438 NEED1("icmptypes requires list of types");
4439 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
4444 NEED1("ipttl requires TTL");
4445 if (strpbrk(*av, "-,")) {
4446 if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
4447 errx(EX_DATAERR, "invalid ipttl %s", *av);
4449 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
4454 NEED1("ipid requires id");
4455 if (strpbrk(*av, "-,")) {
4456 if (!add_ports(cmd, *av, 0, O_IPID, cblen))
4457 errx(EX_DATAERR, "invalid ipid %s", *av);
4459 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
4464 NEED1("iplen requires length");
4465 if (strpbrk(*av, "-,")) {
4466 if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
4467 errx(EX_DATAERR, "invalid ip len %s", *av);
4469 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
4474 NEED1("ipver requires version");
4475 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
4479 case TOK_IPPRECEDENCE:
4480 NEED1("ipprecedence requires value");
4481 fill_cmd(cmd, O_IPPRECEDENCE, 0,
4482 (strtoul(*av, NULL, 0) & 7) << 5);
4487 NEED1("missing DSCP code");
4488 fill_dscp(cmd, *av, cblen);
4493 NEED1("missing argument for ipoptions");
4494 fill_flags_cmd(cmd, O_IPOPT, f_ipopts, *av);
4499 NEED1("missing argument for iptos");
4500 fill_flags_cmd(cmd, O_IPTOS, f_iptos, *av);
4505 NEED1("uid requires argument");
4511 cmd->opcode = O_UID;
4512 uid = strtoul(*av, &end, 0);
4513 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
4515 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
4516 cmd32->d[0] = pwd->pw_uid;
4517 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4523 NEED1("gid requires argument");
4529 cmd->opcode = O_GID;
4530 gid = strtoul(*av, &end, 0);
4531 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
4533 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
4534 cmd32->d[0] = grp->gr_gid;
4535 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4541 NEED1("jail requires argument");
4546 cmd->opcode = O_JAIL;
4547 jid = (int)strtol(*av, &end, 0);
4548 if (jid < 0 || *end != '\0')
4549 errx(EX_DATAERR, "jail requires prison ID");
4550 cmd32->d[0] = (uint32_t)jid;
4551 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4557 fill_cmd(cmd, O_ESTAB, 0, 0);
4561 fill_cmd(cmd, O_TCPFLAGS, 0,
4562 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
4565 case TOK_TCPDATALEN:
4566 NEED1("tcpdatalen requires length");
4567 if (strpbrk(*av, "-,")) {
4568 if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
4569 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
4571 fill_cmd(cmd, O_TCPDATALEN, 0,
4572 strtoul(*av, NULL, 0));
4577 NEED1("missing argument for tcpoptions");
4578 fill_flags_cmd(cmd, O_TCPOPTS, f_tcpopts, *av);
4584 NEED1("tcpseq/tcpack requires argument");
4585 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
4586 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
4587 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
4592 NEED1("tcpwin requires length");
4593 if (strpbrk(*av, "-,")) {
4594 if (!add_ports(cmd, *av, 0, O_TCPWIN, cblen))
4595 errx(EX_DATAERR, "invalid tcpwin len %s", *av);
4597 fill_cmd(cmd, O_TCPWIN, 0,
4598 strtoul(*av, NULL, 0));
4603 NEED1("missing argument for tcpflags");
4604 cmd->opcode = O_TCPFLAGS;
4605 fill_flags_cmd(cmd, O_TCPFLAGS, f_tcpflags, *av);
4609 case TOK_KEEPSTATE: {
4613 errx(EX_USAGE, "keep-state cannot be part "
4616 errx(EX_USAGE, "only one of keep-state "
4617 "and limit is allowed");
4618 if (*av != NULL && *av[0] == ':') {
4619 if (state_check_name(*av + 1) != 0)
4621 "Invalid state name %s", *av);
4622 uidx = pack_object(tstate, *av + 1,
4623 IPFW_TLV_STATE_NAME);
4626 uidx = pack_object(tstate, default_state_name,
4627 IPFW_TLV_STATE_NAME);
4629 fill_cmd(cmd, O_KEEP_STATE, 0, uidx);
4634 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
4639 "limit cannot be part of an or block");
4641 errx(EX_USAGE, "only one of keep-state and "
4642 "limit is allowed");
4645 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
4647 cmd->opcode = O_LIMIT;
4648 c->limit_mask = c->conn_limit = 0;
4650 while ( av[0] != NULL ) {
4651 if ((val = match_token(limit_masks, *av)) <= 0)
4653 c->limit_mask |= val;
4657 if (c->limit_mask == 0)
4658 errx(EX_USAGE, "limit: missing limit mask");
4660 GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
4661 TOK_LIMIT, rule_options);
4664 if (*av != NULL && *av[0] == ':') {
4665 if (state_check_name(*av + 1) != 0)
4667 "Invalid state name %s", *av);
4668 cmd->arg1 = pack_object(tstate, *av + 1,
4669 IPFW_TLV_STATE_NAME);
4672 cmd->arg1 = pack_object(tstate,
4673 default_state_name, IPFW_TLV_STATE_NAME);
4678 NEED1("missing protocol");
4679 if (add_proto(cmd, *av, &proto)) {
4682 errx(EX_DATAERR, "invalid protocol ``%s''",
4687 NEED1("missing source IP");
4688 if (add_srcip(cmd, *av, cblen, tstate)) {
4694 NEED1("missing destination IP");
4695 if (add_dstip(cmd, *av, cblen, tstate)) {
4701 NEED1("missing source IP6");
4702 if (add_srcip6(cmd, *av, cblen, tstate)) {
4708 NEED1("missing destination IP6");
4709 if (add_dstip6(cmd, *av, cblen, tstate)) {
4715 NEED1("missing source port");
4716 if (_substrcmp(*av, "any") == 0 ||
4717 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4720 errx(EX_DATAERR, "invalid source port %s", *av);
4724 NEED1("missing destination port");
4725 if (_substrcmp(*av, "any") == 0 ||
4726 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4729 errx(EX_DATAERR, "invalid destination port %s",
4734 if (add_mac(cmd, av, cblen))
4739 NEED1("missing mac type");
4740 if (!add_mactype(cmd, *av, cblen))
4741 errx(EX_DATAERR, "invalid mac type %s", *av);
4745 case TOK_VERREVPATH:
4746 fill_cmd(cmd, O_VERREVPATH, 0, 0);
4749 case TOK_VERSRCREACH:
4750 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
4754 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
4758 fill_cmd(cmd, O_IPSEC, 0, 0);
4762 fill_cmd(cmd, O_IP6, 0, 0);
4766 fill_cmd(cmd, O_IP4, 0, 0);
4770 fill_ext6hdr( cmd, *av );
4775 if (proto != IPPROTO_IPV6 )
4776 errx( EX_USAGE, "flow-id filter is active "
4777 "only for ipv6 protocol\n");
4778 fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
4783 fill_comment(cmd, av, cblen);
4788 if (av[0] && strpbrk(*av, "-,")) {
4789 if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
4790 errx(EX_DATAERR, "tagged: invalid tag"
4796 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
4797 TOK_TAGGED, rule_options);
4798 fill_cmd(cmd, O_TAGGED, 0, tag);
4804 NEED1("fib requires fib number");
4805 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
4809 fill_cmd(cmd, O_SOCKARG, 0, 0);
4813 ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
4816 if (!av[0] || !av[1])
4817 errx(EX_USAGE, "format: lookup argument tablenum");
4818 cmd->opcode = O_IP_DST_LOOKUP;
4819 cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
4820 i = match_token(rule_options, *av);
4821 for (j = 0; lookup_key[j] >= 0 ; j++) {
4822 if (i == lookup_key[j])
4825 if (lookup_key[j] <= 0)
4826 errx(EX_USAGE, "format: cannot lookup on %s", *av);
4827 __PAST_END(c->d, 1) = j; // i converted to option
4830 if ((j = pack_table(tstate, *av)) == 0)
4831 errx(EX_DATAERR, "Invalid table name: %s", *av);
4838 NEED1("missing table name");
4839 if (strncmp(*av, "table(", 6) != 0)
4841 "enclose table name into \"table()\"");
4842 fill_table(cmd, *av, O_IP_FLOW_LOOKUP, tstate);
4847 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
4849 if (F_LEN(cmd) > 0) { /* prepare to advance */
4851 cmd = next_cmd(cmd, &cblen);
4857 * Now copy stuff into the rule.
4858 * If we have a keep-state option, the first instruction
4859 * must be a PROBE_STATE (which is generated here).
4860 * If we have a LOG option, it was stored as the first command,
4861 * and now must be moved to the top of the action part.
4863 dst = (ipfw_insn *)rule->cmd;
4866 * First thing to write into the command stream is the match probability.
4868 if (match_prob != 1) { /* 1 means always match */
4869 dst->opcode = O_PROB;
4871 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
4876 * generate O_PROBE_STATE if necessary
4878 if (have_state && have_state->opcode != O_CHECK_STATE) {
4879 fill_cmd(dst, O_PROBE_STATE, 0, have_state->arg1);
4880 dst = next_cmd(dst, &rblen);
4883 /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
4884 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
4888 switch (src->opcode) {
4896 bcopy(src, dst, i * sizeof(uint32_t));
4902 * put back the have_state command as last opcode
4904 if (have_state && have_state->opcode != O_CHECK_STATE) {
4905 i = F_LEN(have_state);
4907 bcopy(have_state, dst, i * sizeof(uint32_t));
4911 * start action section
4913 rule->act_ofs = dst - rule->cmd;
4915 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
4917 i = F_LEN(have_log);
4919 bcopy(have_log, dst, i * sizeof(uint32_t));
4923 i = F_LEN(have_altq);
4925 bcopy(have_altq, dst, i * sizeof(uint32_t));
4929 i = F_LEN(have_tag);
4931 bcopy(have_tag, dst, i * sizeof(uint32_t));
4936 * copy all other actions
4938 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
4941 bcopy(src, dst, i * sizeof(uint32_t));
4945 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
4946 *rbufsize = (char *)dst - (char *)rule;
4950 compare_ntlv(const void *_a, const void *_b)
4952 ipfw_obj_ntlv *a, *b;
4954 a = (ipfw_obj_ntlv *)_a;
4955 b = (ipfw_obj_ntlv *)_b;
4957 if (a->set < b->set)
4959 else if (a->set > b->set)
4962 if (a->idx < b->idx)
4964 else if (a->idx > b->idx)
4967 if (a->head.type < b->head.type)
4969 else if (a->head.type > b->head.type)
4976 * Provide kernel with sorted list of referenced objects
4979 object_sort_ctlv(ipfw_obj_ctlv *ctlv)
4982 qsort(ctlv + 1, ctlv->count, ctlv->objsize, compare_ntlv);
4990 compare_object_kntlv(const void *k, const void *v)
4992 ipfw_obj_ntlv *ntlv;
4993 struct object_kt key;
4995 key = *((struct object_kt *)k);
4996 ntlv = (ipfw_obj_ntlv *)v;
4998 if (key.uidx < ntlv->idx)
5000 else if (key.uidx > ntlv->idx)
5003 if (key.type < ntlv->head.type)
5005 else if (key.type > ntlv->head.type)
5012 * Finds object name in @ctlv by @idx and @type.
5013 * Uses the following facts:
5014 * 1) All TLVs are the same size
5015 * 2) Kernel implementation provides already sorted list.
5017 * Returns table name or NULL.
5020 object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx, uint16_t type)
5022 ipfw_obj_ntlv *ntlv;
5023 struct object_kt key;
5028 ntlv = bsearch(&key, (ctlv + 1), ctlv->count, ctlv->objsize,
5029 compare_object_kntlv);
5032 return (ntlv->name);
5038 table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx)
5041 return (object_search_ctlv(ctlv, idx, IPFW_TLV_TBL_NAME));
5045 * Adds one or more rules to ipfw chain.
5050 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
5051 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ] (*2) (*3)
5056 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
5057 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ]
5060 * Rules in reply are modified to store their actual ruleset number.
5062 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
5063 * according to their idx field and there has to be no duplicates.
5064 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
5065 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
5068 ipfw_add(char *av[])
5070 uint32_t rulebuf[1024];
5071 int rbufsize, default_off, tlen, rlen;
5074 struct ip_fw_rule *rule;
5076 ip_fw3_opheader *op3;
5077 ipfw_obj_ctlv *ctlv, *tstate;
5079 rbufsize = sizeof(rulebuf);
5080 memset(rulebuf, 0, rbufsize);
5081 memset(&ts, 0, sizeof(ts));
5083 /* Optimize case with no tables */
5084 default_off = sizeof(ipfw_obj_ctlv) + sizeof(ip_fw3_opheader);
5085 op3 = (ip_fw3_opheader *)rulebuf;
5086 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5087 rule = (struct ip_fw_rule *)(ctlv + 1);
5088 rbufsize -= default_off;
5090 compile_rule(av, (uint32_t *)rule, &rbufsize, &ts);
5091 /* Align rule size to u64 boundary */
5092 rlen = roundup2(rbufsize, sizeof(uint64_t));
5097 if (ts.count != 0) {
5098 /* Some tables. We have to alloc more data */
5099 tlen = ts.count * sizeof(ipfw_obj_ntlv);
5100 sz = default_off + sizeof(ipfw_obj_ctlv) + tlen + rlen;
5102 if ((tbuf = calloc(1, sz)) == NULL)
5103 err(EX_UNAVAILABLE, "malloc() failed for IP_FW_ADD");
5104 op3 = (ip_fw3_opheader *)tbuf;
5106 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
5107 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
5108 ctlv->head.length = sizeof(ipfw_obj_ctlv) + tlen;
5109 ctlv->count = ts.count;
5110 ctlv->objsize = sizeof(ipfw_obj_ntlv);
5111 memcpy(ctlv + 1, ts.idx, tlen);
5112 object_sort_ctlv(ctlv);
5115 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
5116 ctlv->head.type = IPFW_TLV_RULE_LIST;
5117 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5119 memcpy(ctlv + 1, rule, rbufsize);
5121 /* Simply add header */
5122 sz = rlen + default_off;
5123 memset(ctlv, 0, sizeof(*ctlv));
5124 ctlv->head.type = IPFW_TLV_RULE_LIST;
5125 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
5129 if (do_get3(IP_FW_XADD, op3, &sz) != 0)
5130 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_XADD");
5133 struct format_opts sfo;
5135 memset(&sfo, 0, sizeof(sfo));
5136 sfo.tstate = tstate;
5137 sfo.set_mask = (uint32_t)(-1);
5138 bp_alloc(&bp, 4096);
5139 show_static_rule(&co, &sfo, &bp, rule, NULL);
5140 printf("%s", bp.buf);
5152 * clear the counters or the log counters.
5153 * optname has the following values:
5154 * 0 (zero both counters and logging)
5155 * 1 (zero logging only)
5158 ipfw_zero(int ac, char *av[], int optname)
5162 char const *name = optname ? "RESETLOG" : "ZERO";
5166 optname = optname ? IP_FW_XRESETLOG : IP_FW_XZERO;
5170 /* clear all entries */
5171 memset(&rt, 0, sizeof(rt));
5172 rt.flags = IPFW_RCFLAG_ALL;
5173 if (do_range_cmd(optname, &rt) < 0)
5174 err(EX_UNAVAILABLE, "setsockopt(IP_FW_X%s)", name);
5176 printf("%s.\n", optname == IP_FW_XZERO ?
5177 "Accounting cleared":"Logging counts reset");
5184 if (isdigit(**av)) {
5185 arg = strtonum(*av, 0, 0xffff, &errstr);
5188 "invalid rule number %s\n", *av);
5189 memset(&rt, 0, sizeof(rt));
5190 rt.start_rule = arg;
5192 rt.flags |= IPFW_RCFLAG_RANGE;
5193 if (co.use_set != 0) {
5194 rt.set = co.use_set - 1;
5195 rt.flags |= IPFW_RCFLAG_SET;
5197 if (do_range_cmd(optname, &rt) != 0) {
5198 warn("rule %u: setsockopt(IP_FW_X%s)",
5200 failed = EX_UNAVAILABLE;
5201 } else if (rt.new_set == 0) {
5202 printf("Entry %d not found\n", arg);
5203 failed = EX_UNAVAILABLE;
5204 } else if (!co.do_quiet)
5205 printf("Entry %d %s.\n", arg,
5206 optname == IP_FW_XZERO ?
5207 "cleared" : "logging count reset");
5209 errx(EX_USAGE, "invalid rule number ``%s''", *av);
5213 if (failed != EX_OK)
5218 ipfw_flush(int force)
5222 if (!force && !co.do_quiet) { /* need to ask user */
5225 printf("Are you sure? [yn] ");
5228 c = toupper(getc(stdin));
5229 while (c != '\n' && getc(stdin) != '\n')
5231 return; /* and do not flush */
5232 } while (c != 'Y' && c != 'N');
5234 if (c == 'N') /* user said no */
5241 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
5242 memset(&rt, 0, sizeof(rt));
5243 if (co.use_set != 0) {
5244 rt.set = co.use_set - 1;
5245 rt.flags = IPFW_RCFLAG_SET;
5247 rt.flags = IPFW_RCFLAG_ALL;
5248 if (do_range_cmd(IP_FW_XDEL, &rt) != 0)
5249 err(EX_UNAVAILABLE, "setsockopt(IP_FW_XDEL)");
5251 printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
5254 static struct _s_x intcmds[] = {
5255 { "talist", TOK_TALIST },
5256 { "iflist", TOK_IFLIST },
5257 { "olist", TOK_OLIST },
5258 { "vlist", TOK_VLIST },
5262 static struct _s_x otypes[] = {
5263 { "EACTION", IPFW_TLV_EACTION },
5264 { "DYNSTATE", IPFW_TLV_STATE_NAME },
5269 lookup_eaction_name(ipfw_obj_ntlv *ntlv, int cnt, uint16_t type)
5275 for (i = 0; i < cnt; i++) {
5276 if (ntlv[i].head.type != IPFW_TLV_EACTION)
5278 if (IPFW_TLV_EACTION_NAME(ntlv[i].idx) != type)
5280 name = ntlv[i].name;
5287 ipfw_list_objects(int ac, char *av[])
5289 ipfw_obj_lheader req, *olh;
5290 ipfw_obj_ntlv *ntlv;
5295 memset(&req, 0, sizeof(req));
5297 if (do_get3(IP_FW_DUMP_SRVOBJECTS, &req.opheader, &sz) != 0)
5298 if (errno != ENOMEM)
5302 if ((olh = calloc(1, sz)) == NULL)
5306 if (do_get3(IP_FW_DUMP_SRVOBJECTS, &olh->opheader, &sz) != 0) {
5312 printf("Objects list:\n");
5314 printf("There are no objects\n");
5315 ntlv = (ipfw_obj_ntlv *)(olh + 1);
5316 for (i = 0; i < olh->count; i++) {
5317 name = match_value(otypes, ntlv->head.type);
5319 name = lookup_eaction_name(
5320 (ipfw_obj_ntlv *)(olh + 1), olh->count,
5323 printf(" kidx: %4d\ttype: %10d\tname: %s\n",
5324 ntlv->idx, ntlv->head.type, ntlv->name);
5326 printf(" kidx: %4d\ttype: %10s\tname: %s\n",
5327 ntlv->idx, name, ntlv->name);
5334 ipfw_internal_handler(int ac, char *av[])
5339 NEED1("internal cmd required");
5341 if ((tcmd = match_token(intcmds, *av)) == -1)
5342 errx(EX_USAGE, "invalid internal sub-cmd: %s", *av);
5346 ipfw_list_tifaces();
5349 ipfw_list_ta(ac, av);
5352 ipfw_list_objects(ac, av);
5355 ipfw_list_values(ac, av);
5361 ipfw_get_tracked_ifaces(ipfw_obj_lheader **polh)
5363 ipfw_obj_lheader req, *olh;
5366 memset(&req, 0, sizeof(req));
5369 if (do_get3(IP_FW_XIFLIST, &req.opheader, &sz) != 0) {
5370 if (errno != ENOMEM)
5375 if ((olh = calloc(1, sz)) == NULL)
5379 if (do_get3(IP_FW_XIFLIST, &olh->opheader, &sz) != 0) {
5389 ifinfo_cmp(const void *a, const void *b)
5391 ipfw_iface_info *ia, *ib;
5393 ia = (ipfw_iface_info *)a;
5394 ib = (ipfw_iface_info *)b;
5396 return (stringnum_cmp(ia->ifname, ib->ifname));
5400 * Retrieves table list from kernel,
5401 * optionally sorts it and calls requested function for each table.
5402 * Returns 0 on success.
5407 ipfw_obj_lheader *olh;
5408 ipfw_iface_info *info;
5411 if ((error = ipfw_get_tracked_ifaces(&olh)) != 0)
5412 err(EX_OSERR, "Unable to request ipfw tracked interface list");
5415 qsort(olh + 1, olh->count, olh->objsize, ifinfo_cmp);
5417 info = (ipfw_iface_info *)(olh + 1);
5418 for (i = 0; i < olh->count; i++) {
5419 if (info->flags & IPFW_IFFLAG_RESOLVED)
5420 printf("%s ifindex: %d refcount: %u changes: %u\n",
5421 info->ifname, info->ifindex, info->refcnt,
5424 printf("%s ifindex: unresolved refcount: %u changes: %u\n",
5425 info->ifname, info->refcnt, info->gencnt);
5426 info = (ipfw_iface_info *)((caddr_t)info + olh->objsize);