2 * Copyright (c) 2002-2003 Luigi Rizzo
3 * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
4 * Copyright (c) 1994 Ugen J.S.Antsilevich
6 * Idea and grammar partially left from:
7 * Copyright (c) 1993 Daniel Boulet
9 * Redistribution and use in source forms, with and without modification,
10 * are permitted provided that this entire comment appears intact.
12 * Redistribution in binary form may occur without any restrictions.
13 * Obviously, it would be nice if you gave credit where credit is due
14 * but requiring it would be too onerous.
16 * This software is provided ``AS IS'' without any warranties of any kind.
18 * NEW command line interface for IP firewall facility
23 #include <sys/types.h>
24 #include <sys/param.h>
25 #include <sys/socket.h>
26 #include <sys/sockio.h>
27 #include <sys/sysctl.h>
42 #include <time.h> /* ctime */
43 #include <timeconv.h> /* _long_to_time */
46 #include <stddef.h> /* offsetof */
48 #include <net/ethernet.h>
49 #include <net/if.h> /* only IFNAMSIZ */
50 #include <netinet/in.h>
51 #include <netinet/in_systm.h> /* only n_short, n_long */
52 #include <netinet/ip.h>
53 #include <netinet/ip_icmp.h>
54 #include <netinet/ip_fw.h>
55 #include <netinet/tcp.h>
56 #include <arpa/inet.h>
58 struct cmdline_opts co; /* global options */
64 int show_time; /* show timestamp */
65 uint32_t set_mask; /* enabled sets mask */
66 uint32_t flags; /* request flags */
67 uint32_t first; /* first rule to request */
68 uint32_t last; /* last rule to request */
69 uint32_t dcnt; /* number of dynamic states */
70 ipfw_obj_ctlv *tstate; /* table state data */
73 int resvd_set_number = RESVD_SET;
77 #define CHECK_LENGTH(v, len) do { \
79 errx(EX_DATAERR, "Rule too long"); \
82 * Check if we have enough space in cmd buffer. Note that since
83 * first 8? u32 words are reserved by reserved header, full cmd
84 * buffer can't be used, so we need to protect from buffer overrun
85 * only. At the beginnig, cblen is less than actual buffer size by
86 * size of ipfw_insn_u32 instruction + 1 u32 work. This eliminates need
87 * for checking small instructions fitting in given range.
88 * We also (ab)use the fact that ipfw_insn is always the first field
89 * for any custom instruction.
91 #define CHECK_CMDLEN CHECK_LENGTH(cblen, F_LEN((ipfw_insn *)cmd))
93 #define GET_UINT_ARG(arg, min, max, tok, s_x) do { \
95 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
96 if (_substrcmp(*av, "tablearg") == 0) { \
105 _xval = strtol(*av, &end, 10); \
107 if (!isdigit(**av) || *end != '\0' || (_xval == 0 && errno == EINVAL)) \
108 errx(EX_DATAERR, "%s: invalid argument: %s", \
109 match_value(s_x, tok), *av); \
111 if (errno == ERANGE || _xval < min || _xval > max) \
112 errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
113 match_value(s_x, tok), min, max, *av); \
115 if (_xval == IP_FW_TARG) \
116 errx(EX_DATAERR, "%s: illegal argument value: %s", \
117 match_value(s_x, tok), *av); \
122 static struct _s_x f_tcpflags[] = {
133 static struct _s_x f_tcpopts[] = {
134 { "mss", IP_FW_TCPOPT_MSS },
135 { "maxseg", IP_FW_TCPOPT_MSS },
136 { "window", IP_FW_TCPOPT_WINDOW },
137 { "sack", IP_FW_TCPOPT_SACK },
138 { "ts", IP_FW_TCPOPT_TS },
139 { "timestamp", IP_FW_TCPOPT_TS },
140 { "cc", IP_FW_TCPOPT_CC },
146 * IP options span the range 0 to 255 so we need to remap them
147 * (though in fact only the low 5 bits are significant).
149 static struct _s_x f_ipopts[] = {
150 { "ssrr", IP_FW_IPOPT_SSRR},
151 { "lsrr", IP_FW_IPOPT_LSRR},
152 { "rr", IP_FW_IPOPT_RR},
153 { "ts", IP_FW_IPOPT_TS},
158 static struct _s_x f_iptos[] = {
159 { "lowdelay", IPTOS_LOWDELAY},
160 { "throughput", IPTOS_THROUGHPUT},
161 { "reliability", IPTOS_RELIABILITY},
162 { "mincost", IPTOS_MINCOST},
163 { "congestion", IPTOS_ECN_CE},
164 { "ecntransport", IPTOS_ECN_ECT0},
165 { "ip tos option", 0},
169 struct _s_x f_ipdscp[] = {
170 { "af11", IPTOS_DSCP_AF11 >> 2 }, /* 001010 */
171 { "af12", IPTOS_DSCP_AF12 >> 2 }, /* 001100 */
172 { "af13", IPTOS_DSCP_AF13 >> 2 }, /* 001110 */
173 { "af21", IPTOS_DSCP_AF21 >> 2 }, /* 010010 */
174 { "af22", IPTOS_DSCP_AF22 >> 2 }, /* 010100 */
175 { "af23", IPTOS_DSCP_AF23 >> 2 }, /* 010110 */
176 { "af31", IPTOS_DSCP_AF31 >> 2 }, /* 011010 */
177 { "af32", IPTOS_DSCP_AF32 >> 2 }, /* 011100 */
178 { "af33", IPTOS_DSCP_AF33 >> 2 }, /* 011110 */
179 { "af41", IPTOS_DSCP_AF41 >> 2 }, /* 100010 */
180 { "af42", IPTOS_DSCP_AF42 >> 2 }, /* 100100 */
181 { "af43", IPTOS_DSCP_AF43 >> 2 }, /* 100110 */
182 { "be", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
183 { "ef", IPTOS_DSCP_EF >> 2 }, /* 101110 */
184 { "cs0", IPTOS_DSCP_CS0 >> 2 }, /* 000000 */
185 { "cs1", IPTOS_DSCP_CS1 >> 2 }, /* 001000 */
186 { "cs2", IPTOS_DSCP_CS2 >> 2 }, /* 010000 */
187 { "cs3", IPTOS_DSCP_CS3 >> 2 }, /* 011000 */
188 { "cs4", IPTOS_DSCP_CS4 >> 2 }, /* 100000 */
189 { "cs5", IPTOS_DSCP_CS5 >> 2 }, /* 101000 */
190 { "cs6", IPTOS_DSCP_CS6 >> 2 }, /* 110000 */
191 { "cs7", IPTOS_DSCP_CS7 >> 2 }, /* 100000 */
195 static struct _s_x limit_masks[] = {
196 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
197 {"src-addr", DYN_SRC_ADDR},
198 {"src-port", DYN_SRC_PORT},
199 {"dst-addr", DYN_DST_ADDR},
200 {"dst-port", DYN_DST_PORT},
205 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
206 * This is only used in this code.
208 #define IPPROTO_ETHERTYPE 0x1000
209 static struct _s_x ether_types[] = {
211 * Note, we cannot use "-:&/" in the names because they are field
212 * separators in the type specifications. Also, we use s = NULL as
213 * end-delimiter, because a type of 0 can be legal.
226 { "pppoe_disc", 0x8863 },
227 { "pppoe_sess", 0x8864 },
228 { "ipx_8022", 0x00E0 },
229 { "ipx_8023", 0x0000 },
230 { "ipx_ii", 0x8137 },
231 { "ipx_snap", 0x8137 },
238 static struct _s_x rule_actions[] = {
239 { "accept", TOK_ACCEPT },
240 { "pass", TOK_ACCEPT },
241 { "allow", TOK_ACCEPT },
242 { "permit", TOK_ACCEPT },
243 { "count", TOK_COUNT },
244 { "pipe", TOK_PIPE },
245 { "queue", TOK_QUEUE },
246 { "divert", TOK_DIVERT },
248 { "netgraph", TOK_NETGRAPH },
249 { "ngtee", TOK_NGTEE },
250 { "fwd", TOK_FORWARD },
251 { "forward", TOK_FORWARD },
252 { "skipto", TOK_SKIPTO },
253 { "deny", TOK_DENY },
254 { "drop", TOK_DENY },
255 { "reject", TOK_REJECT },
256 { "reset6", TOK_RESET6 },
257 { "reset", TOK_RESET },
258 { "unreach6", TOK_UNREACH6 },
259 { "unreach", TOK_UNREACH },
260 { "check-state", TOK_CHECKSTATE },
261 { "//", TOK_COMMENT },
263 { "reass", TOK_REASS },
264 { "setfib", TOK_SETFIB },
265 { "setdscp", TOK_SETDSCP },
266 { "call", TOK_CALL },
267 { "return", TOK_RETURN },
268 { NULL, 0 } /* terminator */
271 static struct _s_x rule_action_params[] = {
272 { "altq", TOK_ALTQ },
275 { "untag", TOK_UNTAG },
276 { NULL, 0 } /* terminator */
280 * The 'lookup' instruction accepts one of the following arguments.
281 * -1 is a terminator for the list.
282 * Arguments are passed as v[1] in O_DST_LOOKUP options.
284 static int lookup_key[] = {
285 TOK_DSTIP, TOK_SRCIP, TOK_DSTPORT, TOK_SRCPORT,
286 TOK_UID, TOK_JAIL, TOK_DSCP, -1 };
288 static struct _s_x rule_options[] = {
289 { "tagged", TOK_TAGGED },
292 { "jail", TOK_JAIL },
294 { "limit", TOK_LIMIT },
295 { "keep-state", TOK_KEEPSTATE },
296 { "bridged", TOK_LAYER2 },
297 { "layer2", TOK_LAYER2 },
299 { "diverted", TOK_DIVERTED },
300 { "diverted-loopback", TOK_DIVERTEDLOOPBACK },
301 { "diverted-output", TOK_DIVERTEDOUTPUT },
302 { "xmit", TOK_XMIT },
303 { "recv", TOK_RECV },
305 { "fragment", TOK_FRAG },
306 { "frag", TOK_FRAG },
308 { "ipoptions", TOK_IPOPTS },
309 { "ipopts", TOK_IPOPTS },
310 { "iplen", TOK_IPLEN },
311 { "ipid", TOK_IPID },
312 { "ipprecedence", TOK_IPPRECEDENCE },
313 { "dscp", TOK_DSCP },
314 { "iptos", TOK_IPTOS },
315 { "ipttl", TOK_IPTTL },
316 { "ipversion", TOK_IPVER },
317 { "ipver", TOK_IPVER },
318 { "estab", TOK_ESTAB },
319 { "established", TOK_ESTAB },
320 { "setup", TOK_SETUP },
321 { "sockarg", TOK_SOCKARG },
322 { "tcpdatalen", TOK_TCPDATALEN },
323 { "tcpflags", TOK_TCPFLAGS },
324 { "tcpflgs", TOK_TCPFLAGS },
325 { "tcpoptions", TOK_TCPOPTS },
326 { "tcpopts", TOK_TCPOPTS },
327 { "tcpseq", TOK_TCPSEQ },
328 { "tcpack", TOK_TCPACK },
329 { "tcpwin", TOK_TCPWIN },
330 { "icmptype", TOK_ICMPTYPES },
331 { "icmptypes", TOK_ICMPTYPES },
332 { "dst-ip", TOK_DSTIP },
333 { "src-ip", TOK_SRCIP },
334 { "dst-port", TOK_DSTPORT },
335 { "src-port", TOK_SRCPORT },
336 { "proto", TOK_PROTO },
339 { "mac-type", TOK_MACTYPE },
340 { "verrevpath", TOK_VERREVPATH },
341 { "versrcreach", TOK_VERSRCREACH },
342 { "antispoof", TOK_ANTISPOOF },
343 { "ipsec", TOK_IPSEC },
344 { "icmp6type", TOK_ICMP6TYPES },
345 { "icmp6types", TOK_ICMP6TYPES },
346 { "ext6hdr", TOK_EXT6HDR},
347 { "flow-id", TOK_FLOWID},
352 { "dst-ipv6", TOK_DSTIP6},
353 { "dst-ip6", TOK_DSTIP6},
354 { "src-ipv6", TOK_SRCIP6},
355 { "src-ip6", TOK_SRCIP6},
356 { "lookup", TOK_LOOKUP},
358 { "//", TOK_COMMENT },
360 { "not", TOK_NOT }, /* pseudo option */
361 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
362 { "or", TOK_OR }, /* pseudo option */
363 { "|", /* escape */ TOK_OR }, /* pseudo option */
364 { "{", TOK_STARTBRACE }, /* pseudo option */
365 { "(", TOK_STARTBRACE }, /* pseudo option */
366 { "}", TOK_ENDBRACE }, /* pseudo option */
367 { ")", TOK_ENDBRACE }, /* pseudo option */
368 { NULL, 0 } /* terminator */
371 void bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg);
372 static int ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
373 ipfw_cfg_lheader **pcfg, size_t *psize);
374 static int ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
375 ipfw_cfg_lheader *cfg, size_t sz, int ac, char **av);
376 static void ipfw_list_tifaces(void);
379 static uint16_t pack_object(struct tidx *tstate, char *name, int otype);
380 static uint16_t pack_table(struct tidx *tstate, char *name);
382 static char *table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx);
383 static void object_sort_ctlv(ipfw_obj_ctlv *ctlv);
386 * Simple string buffer API.
387 * Used to simplify buffer passing between function and for
388 * transparent overrun handling.
392 * Allocates new buffer of given size @sz.
394 * Returns 0 on success.
397 bp_alloc(struct buf_pr *b, size_t size)
399 memset(b, 0, sizeof(struct buf_pr));
401 if ((b->buf = calloc(1, size)) == NULL)
412 bp_free(struct buf_pr *b)
419 * Flushes buffer so new writer start from beginning.
422 bp_flush(struct buf_pr *b)
430 * Print message specified by @format and args.
431 * Automatically manage buffer space and transparently handle
434 * Returns number of bytes that should have been printed.
437 bprintf(struct buf_pr *b, char *format, ...)
442 va_start(args, format);
444 i = vsnprintf(b->ptr, b->avail, format, args);
447 if (i > b->avail || i < 0) {
448 /* Overflow or print error */
461 * Special values printer for tablearg-aware opcodes.
464 bprint_uint_arg(struct buf_pr *bp, const char *str, uint32_t arg)
468 bprintf(bp, "%s", str);
469 if (arg == IP_FW_TARG)
470 bprintf(bp, "tablearg");
472 bprintf(bp, "%u", arg);
476 * Helper routine to print a possibly unaligned uint64_t on
477 * various platform. If width > 0, print the value with
478 * the desired width, followed by a space;
479 * otherwise, return the required width.
482 pr_u64(struct buf_pr *b, uint64_t *pd, int width)
485 #define U64_FMT "I64"
487 #define U64_FMT "llu"
490 unsigned long long d;
492 bcopy (pd, &u, sizeof(u));
495 bprintf(b, "%*" U64_FMT " ", width, d) :
496 snprintf(NULL, 0, "%" U64_FMT, d) ;
502 safe_calloc(size_t number, size_t size)
504 void *ret = calloc(number, size);
507 err(EX_OSERR, "calloc");
512 safe_realloc(void *ptr, size_t size)
514 void *ret = realloc(ptr, size);
517 err(EX_OSERR, "realloc");
522 * Compare things like interface or table names.
525 stringnum_cmp(const char *a, const char *b)
537 return (strcmp(a, b));
542 * conditionally runs the command.
543 * Selected options or negative -> getsockopt
546 do_cmd(int optname, void *optval, uintptr_t optlen)
553 if (ipfw_socket == -1)
554 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
556 err(EX_UNAVAILABLE, "socket");
558 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
559 optname == IP_FW_ADD || optname == IP_FW3 ||
560 optname == IP_FW_NAT_GET_CONFIG ||
562 optname == IP_FW_NAT_GET_LOG) {
565 i = getsockopt(ipfw_socket, IPPROTO_IP, optname, optval,
566 (socklen_t *)optlen);
568 i = setsockopt(ipfw_socket, IPPROTO_IP, optname, optval, optlen);
574 * do_set3 - pass ipfw control cmd to kernel
575 * @optname: option name
576 * @optval: pointer to option data
577 * @optlen: option length
579 * Assumes op3 header is already embedded.
580 * Calls setsockopt() with IP_FW3 as kernel-visible opcode.
581 * Returns 0 on success or errno otherwise.
584 do_set3(int optname, ip_fw3_opheader *op3, uintptr_t optlen)
590 if (ipfw_socket == -1)
591 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
593 err(EX_UNAVAILABLE, "socket");
595 op3->opcode = optname;
597 return (setsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3, optlen));
601 * do_get3 - pass ipfw control cmd to kernel
602 * @optname: option name
603 * @optval: pointer to option data
604 * @optlen: pointer to option length
606 * Assumes op3 header is already embedded.
607 * Calls getsockopt() with IP_FW3 as kernel-visible opcode.
608 * Returns 0 on success or errno otherwise.
611 do_get3(int optname, ip_fw3_opheader *op3, size_t *optlen)
618 if (ipfw_socket == -1)
619 ipfw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
621 err(EX_UNAVAILABLE, "socket");
623 op3->opcode = optname;
625 error = getsockopt(ipfw_socket, IPPROTO_IP, IP_FW3, op3,
626 (socklen_t *)optlen);
632 * match_token takes a table and a string, returns the value associated
633 * with the string (-1 in case of failure).
636 match_token(struct _s_x *table, char *string)
639 uint i = strlen(string);
641 for (pt = table ; i && pt->s != NULL ; pt++)
642 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
648 * match_token takes a table and a string, returns the value associated
649 * with the string for the best match.
652 * value from @table for matched records
653 * -1 for non-matched records
654 * -2 if more than one records match @string.
657 match_token_relaxed(struct _s_x *table, char *string)
665 for (pt = table ; i != 0 && pt->s != NULL ; pt++) {
666 if (strncmp(pt->s, string, i) != 0)
675 return (c > 0 ? -2: -1);
679 * match_value takes a table and a value, returns the string associated
680 * with the value (NULL in case of failure).
683 match_value(struct _s_x *p, int value)
685 for (; p->s != NULL; p++)
692 concat_tokens(char *buf, size_t bufsize, struct _s_x *table, char *delimiter)
698 for (sz = 0, pt = table ; pt->s != NULL; pt++) {
699 l = snprintf(buf + sz, bufsize - sz, "%s%s",
700 (sz == 0) ? "" : delimiter, pt->s);
711 * helper function to process a set of flags and set bits in the
715 fill_flags(struct _s_x *flags, char *p, char **e, uint32_t *set,
718 char *q; /* points to the separator */
720 uint32_t *which; /* mask we are working on */
731 val = match_token(flags, p);
737 *which |= (uint32_t)val;
744 print_flags_buffer(char *buf, size_t sz, struct _s_x *list, uint32_t set)
746 char const *comma = "";
749 for (i = 0; list[i].x != 0; i++) {
750 if ((set & list[i].x) == 0)
754 l = snprintf(buf, sz, "%s%s", comma, list[i].s);
764 * _substrcmp takes two strings and returns 1 if they do not match,
765 * and 0 if they match exactly or the first string is a sub-string
766 * of the second. A warning is printed to stderr in the case that the
767 * first string is a sub-string of the second.
769 * This function will be removed in the future through the usual
770 * deprecation process.
773 _substrcmp(const char *str1, const char* str2)
776 if (strncmp(str1, str2, strlen(str1)) != 0)
779 if (strlen(str1) != strlen(str2))
780 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
786 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
787 * and 0 if they match exactly or the second string is a sub-string
788 * of the first. A warning is printed to stderr in the case that the
789 * first string does not match the third.
791 * This function exists to warn about the bizarre construction
792 * strncmp(str, "by", 2) which is used to allow people to use a shortcut
793 * for "bytes". The problem is that in addition to accepting "by",
794 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
795 * other string beginning with "by".
797 * This function will be removed in the future through the usual
798 * deprecation process.
801 _substrcmp2(const char *str1, const char* str2, const char* str3)
804 if (strncmp(str1, str2, strlen(str2)) != 0)
807 if (strcmp(str1, str3) != 0)
808 warnx("DEPRECATED: '%s' matched '%s'",
814 * prints one port, symbolic or numeric
817 print_port(struct buf_pr *bp, int proto, uint16_t port)
820 if (proto == IPPROTO_ETHERTYPE) {
823 if (co.do_resolv && (s = match_value(ether_types, port)) )
824 bprintf(bp, "%s", s);
826 bprintf(bp, "0x%04x", port);
828 struct servent *se = NULL;
830 struct protoent *pe = getprotobynumber(proto);
832 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
835 bprintf(bp, "%s", se->s_name);
837 bprintf(bp, "%d", port);
841 static struct _s_x _port_name[] = {
842 {"dst-port", O_IP_DSTPORT},
843 {"src-port", O_IP_SRCPORT},
847 {"mac-type", O_MAC_TYPE},
848 {"tcpdatalen", O_TCPDATALEN},
849 {"tcpwin", O_TCPWIN},
850 {"tagged", O_TAGGED},
855 * Print the values in a list 16-bit items of the types above.
856 * XXX todo: add support for mask.
859 print_newports(struct buf_pr *bp, ipfw_insn_u16 *cmd, int proto, int opcode)
861 uint16_t *p = cmd->ports;
866 sep = match_value(_port_name, opcode);
869 bprintf(bp, " %s", sep);
872 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
873 bprintf(bp, "%s", sep);
874 print_port(bp, proto, p[0]);
877 print_port(bp, proto, p[1]);
884 * Like strtol, but also translates service names into port numbers
885 * for some protocols.
887 * proto == -1 disables the protocol check;
888 * proto == IPPROTO_ETHERTYPE looks up an internal table
889 * proto == <some value in /etc/protocols> matches the values there.
890 * Returns *end == s in case the parameter is not found.
893 strtoport(char *s, char **end, int base, int proto)
899 *end = s; /* default - not found */
901 return 0; /* not found */
904 return strtol(s, end, base);
907 * find separator. '\\' escapes the next char.
909 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
910 if (*s1 == '\\' && s1[1] != '\0')
913 buf = safe_calloc(s1 - s + 1, 1);
916 * copy into a buffer skipping backslashes
918 for (p = s, i = 0; p != s1 ; p++)
923 if (proto == IPPROTO_ETHERTYPE) {
924 i = match_token(ether_types, buf);
926 if (i != -1) { /* found */
931 struct protoent *pe = NULL;
935 pe = getprotobynumber(proto);
937 se = getservbyname(buf, pe ? pe->p_name : NULL);
941 return ntohs(se->s_port);
944 return 0; /* not found */
948 * Fill the body of the command with the list of port ranges.
951 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto, int cblen)
953 uint16_t a, b, *p = cmd->ports;
958 a = strtoport(av, &s, 0, proto);
959 if (s == av) /* empty or invalid argument */
962 CHECK_LENGTH(cblen, i + 2);
965 case '-': /* a range */
967 b = strtoport(av, &s, 0, proto);
968 /* Reject expressions like '1-abc' or '1-2-3'. */
969 if (s == av || (*s != ',' && *s != '\0'))
974 case ',': /* comma separated list */
979 warnx("port list: invalid separator <%c> in <%s>",
989 if (i + 1 > F_LEN_MASK)
990 errx(EX_DATAERR, "too many ports/ranges\n");
991 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
997 * Fill the body of the command with the list of DiffServ codepoints.
1000 fill_dscp(ipfw_insn *cmd, char *av, int cblen)
1002 uint32_t *low, *high;
1006 cmd->opcode = O_DSCP;
1007 cmd->len |= F_INSN_SIZE(ipfw_insn_u32) + 1;
1011 low = (uint32_t *)(cmd + 1);
1024 if ((code = match_token(f_ipdscp, s)) == -1)
1025 errx(EX_DATAERR, "Unknown DSCP code");
1027 code = strtoul(s, NULL, 10);
1028 if (code < 0 || code > 63)
1029 errx(EX_DATAERR, "Invalid DSCP value");
1033 *high |= 1 << (code - 32);
1041 static struct _s_x icmpcodes[] = {
1042 { "net", ICMP_UNREACH_NET },
1043 { "host", ICMP_UNREACH_HOST },
1044 { "protocol", ICMP_UNREACH_PROTOCOL },
1045 { "port", ICMP_UNREACH_PORT },
1046 { "needfrag", ICMP_UNREACH_NEEDFRAG },
1047 { "srcfail", ICMP_UNREACH_SRCFAIL },
1048 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
1049 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
1050 { "isolated", ICMP_UNREACH_ISOLATED },
1051 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
1052 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
1053 { "tosnet", ICMP_UNREACH_TOSNET },
1054 { "toshost", ICMP_UNREACH_TOSHOST },
1055 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
1056 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
1057 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
1062 fill_reject_code(u_short *codep, char *str)
1067 val = strtoul(str, &s, 0);
1068 if (s == str || *s != '\0' || val >= 0x100)
1069 val = match_token(icmpcodes, str);
1071 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
1077 print_reject_code(struct buf_pr *bp, uint16_t code)
1081 if ((s = match_value(icmpcodes, code)) != NULL)
1082 bprintf(bp, "unreach %s", s);
1084 bprintf(bp, "unreach %u", code);
1088 * Returns the number of bits set (from left) in a contiguous bitmask,
1089 * or -1 if the mask is not contiguous.
1090 * XXX this needs a proper fix.
1091 * This effectively works on masks in big-endian (network) format.
1092 * when compiled on little endian architectures.
1094 * First bit is bit 7 of the first byte -- note, for MAC addresses,
1095 * the first bit on the wire is bit 0 of the first byte.
1096 * len is the max length in bits.
1099 contigmask(uint8_t *p, int len)
1103 for (i=0; i<len ; i++)
1104 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
1106 for (n=i+1; n < len; n++)
1107 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
1108 return -1; /* mask not contiguous */
1113 * print flags set/clear in the two bitmasks passed as parameters.
1114 * There is a specialized check for f_tcpflags.
1117 print_flags(struct buf_pr *bp, char const *name, ipfw_insn *cmd,
1120 char const *comma = "";
1122 uint8_t set = cmd->arg1 & 0xff;
1123 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
1125 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
1126 bprintf(bp, " setup");
1130 bprintf(bp, " %s ", name);
1131 for (i=0; list[i].x != 0; i++) {
1132 if (set & list[i].x) {
1134 bprintf(bp, "%s%s", comma, list[i].s);
1137 if (clear & list[i].x) {
1138 clear &= ~list[i].x;
1139 bprintf(bp, "%s!%s", comma, list[i].s);
1147 * Print the ip address contained in a command.
1150 print_ip(struct buf_pr *bp, struct format_opts *fo, ipfw_insn_ip *cmd,
1153 struct hostent *he = NULL;
1155 uint32_t len = F_LEN((ipfw_insn *)cmd);
1156 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
1159 if (cmd->o.opcode == O_IP_DST_LOOKUP && len > F_INSN_SIZE(ipfw_insn_u32)) {
1161 const char *arg = "<invalid>";
1163 if (d < sizeof(lookup_key)/sizeof(lookup_key[0]))
1164 arg = match_value(rule_options, lookup_key[d]);
1165 t = table_search_ctlv(fo->tstate, ((ipfw_insn *)cmd)->arg1);
1166 bprintf(bp, "%s lookup %s %s", cmd->o.len & F_NOT ? " not": "",
1170 bprintf(bp, "%s%s ", cmd->o.len & F_NOT ? " not": "", s);
1172 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
1176 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
1177 cmd->o.opcode == O_IP_DST_LOOKUP) {
1178 t = table_search_ctlv(fo->tstate, ((ipfw_insn *)cmd)->arg1);
1179 bprintf(bp, "table(%s", t);
1180 if (len == F_INSN_SIZE(ipfw_insn_u32))
1181 bprintf(bp, ",%u", *a);
1185 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
1186 uint32_t x, *map = (uint32_t *)&(cmd->mask);
1190 x = cmd->o.arg1 - 1;
1192 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1193 bprintf(bp, "%s/%d", inet_ntoa(cmd->addr),
1194 contigmask((uint8_t *)&x, 32));
1195 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1196 x &= 0xff; /* base */
1198 * Print bits and ranges.
1199 * Locate first bit set (i), then locate first bit unset (j).
1200 * If we have 3+ consecutive bits set, then print them as a
1201 * range, otherwise only print the initial bit and rescan.
1203 for (i=0; i < cmd->o.arg1; i++)
1204 if (map[i/32] & (1<<(i & 31))) {
1205 for (j=i+1; j < cmd->o.arg1; j++)
1206 if (!(map[ j/32] & (1<<(j & 31))))
1208 bprintf(bp, "%c%d", comma, i+x);
1209 if (j>i+2) { /* range has at least 3 elements */
1210 bprintf(bp, "-%d", j-1+x);
1219 * len == 2 indicates a single IP, whereas lists of 1 or more
1220 * addr/mask pairs have len = (2n+1). We convert len to n so we
1221 * use that to count the number of entries.
1223 for (len = len / 2; len > 0; len--, a += 2) {
1224 int mb = /* mask length */
1225 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1226 32 : contigmask((uint8_t *)&(a[1]), 32);
1227 if (mb == 32 && co.do_resolv)
1228 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
1229 if (he != NULL) /* resolved to name */
1230 bprintf(bp, "%s", he->h_name);
1231 else if (mb == 0) /* any */
1233 else { /* numeric IP followed by some kind of mask */
1234 ia = (struct in_addr *)&a[0];
1235 bprintf(bp, "%s", inet_ntoa(*ia));
1237 ia = (struct in_addr *)&a[1];
1238 bprintf(bp, ":%s", inet_ntoa(*ia));
1240 bprintf(bp, "/%d", mb);
1248 * prints a MAC address/mask pair
1251 print_mac(struct buf_pr *bp, uint8_t *addr, uint8_t *mask)
1253 int l = contigmask(mask, 48);
1256 bprintf(bp, " any");
1258 bprintf(bp, " %02x:%02x:%02x:%02x:%02x:%02x",
1259 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1261 bprintf(bp, "&%02x:%02x:%02x:%02x:%02x:%02x",
1262 mask[0], mask[1], mask[2],
1263 mask[3], mask[4], mask[5]);
1265 bprintf(bp, "/%d", l);
1270 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1279 type = strtoul(av, &av, 0);
1281 if (*av != ',' && *av != '\0')
1282 errx(EX_DATAERR, "invalid ICMP type");
1285 errx(EX_DATAERR, "ICMP type out of range");
1287 cmd->d[0] |= 1 << type;
1289 cmd->o.opcode = O_ICMPTYPE;
1290 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1294 print_icmptypes(struct buf_pr *bp, ipfw_insn_u32 *cmd)
1299 bprintf(bp, " icmptypes");
1300 for (i = 0; i < 32; i++) {
1301 if ( (cmd->d[0] & (1 << (i))) == 0)
1303 bprintf(bp, "%c%d", sep, i);
1309 print_dscp(struct buf_pr *bp, ipfw_insn_u32 *cmd)
1316 bprintf(bp, " dscp");
1319 if (*v & (1 << i)) {
1320 if ((code = match_value(f_ipdscp, i)) != NULL)
1321 bprintf(bp, "%c%s", sep, code);
1323 bprintf(bp, "%c%d", sep, i);
1327 if ((++i % 32) == 0)
1333 * show_ipfw() prints the body of an ipfw rule.
1334 * Because the standard rule has at least proto src_ip dst_ip, we use
1335 * a helper function to produce these entries if not provided explicitly.
1336 * The first argument is the list of fields we have, the second is
1337 * the list of fields we want to be printed.
1339 * Special cases if we have provided a MAC header:
1340 * + if the rule does not contain IP addresses/ports, do not print them;
1341 * + if the rule does not contain an IP proto, print "all" instead of "ip";
1343 * Once we have 'have_options', IP header fields are printed as options.
1345 #define HAVE_PROTO 0x0001
1346 #define HAVE_SRCIP 0x0002
1347 #define HAVE_DSTIP 0x0004
1348 #define HAVE_PROTO4 0x0008
1349 #define HAVE_PROTO6 0x0010
1350 #define HAVE_IP 0x0100
1351 #define HAVE_OPTIONS 0x8000
1354 show_prerequisites(struct buf_pr *bp, int *flags, int want, int cmd)
1356 (void)cmd; /* UNUSED */
1357 if (co.comment_only)
1359 if ( (*flags & HAVE_IP) == HAVE_IP)
1360 *flags |= HAVE_OPTIONS;
1362 if ( !(*flags & HAVE_OPTIONS)) {
1363 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) {
1364 if ( (*flags & HAVE_PROTO4))
1365 bprintf(bp, " ip4");
1366 else if ( (*flags & HAVE_PROTO6))
1367 bprintf(bp, " ip6");
1371 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
1372 bprintf(bp, " from any");
1373 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
1374 bprintf(bp, " to any");
1380 show_static_rule(struct cmdline_opts *co, struct format_opts *fo,
1381 struct buf_pr *bp, struct ip_fw_rule *rule, struct ip_fw_bcounter *cntr)
1383 static int twidth = 0;
1385 ipfw_insn *cmd, *tagptr = NULL;
1386 const char *comment = NULL; /* ptr to comment if we have one */
1387 int proto = 0; /* default */
1388 int flags = 0; /* prerequisites */
1389 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
1390 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
1391 int or_block = 0; /* we are in an or block */
1394 if ((fo->set_mask & (1 << rule->set)) == 0) {
1399 bprintf(bp, "# DISABLED ");
1401 bprintf(bp, "%05u ", rule->rulenum);
1403 /* Print counters if enabled */
1404 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
1405 pr_u64(bp, &cntr->pcnt, fo->pcwidth);
1406 pr_u64(bp, &cntr->bcnt, fo->bcwidth);
1409 if (co->do_time == 2)
1410 bprintf(bp, "%10u ", cntr->timestamp);
1411 else if (co->do_time == 1) {
1413 time_t t = (time_t)0;
1416 strcpy(timestr, ctime(&t));
1417 *strchr(timestr, '\n') = '\0';
1418 twidth = strlen(timestr);
1420 if (cntr->timestamp > 0) {
1421 t = _long_to_time(cntr->timestamp);
1423 strcpy(timestr, ctime(&t));
1424 *strchr(timestr, '\n') = '\0';
1425 bprintf(bp, "%s ", timestr);
1427 bprintf(bp, "%*s", twidth, " ");
1432 bprintf(bp, "set %d ", rule->set);
1435 * print the optional "match probability"
1437 if (rule->cmd_len > 0) {
1439 if (cmd->opcode == O_PROB) {
1440 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1441 double d = 1.0 * p->d[0];
1443 d = (d / 0x7fffffff);
1444 bprintf(bp, "prob %f ", d);
1449 * first print actions
1451 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1452 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1453 switch(cmd->opcode) {
1455 bprintf(bp, "check-state");
1456 /* avoid printing anything else */
1457 flags = HAVE_PROTO | HAVE_SRCIP |
1458 HAVE_DSTIP | HAVE_IP;
1462 bprintf(bp, "allow");
1466 bprintf(bp, "count");
1470 bprintf(bp, "deny");
1474 if (cmd->arg1 == ICMP_REJECT_RST)
1475 bprintf(bp, "reset");
1476 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1477 bprintf(bp, "reject");
1479 print_reject_code(bp, cmd->arg1);
1483 if (cmd->arg1 == ICMP6_UNREACH_RST)
1484 bprintf(bp, "reset6");
1486 print_unreach6_code(cmd->arg1);
1490 bprint_uint_arg(bp, "skipto ", cmd->arg1);
1494 bprint_uint_arg(bp, "pipe ", cmd->arg1);
1498 bprint_uint_arg(bp, "queue ", cmd->arg1);
1502 bprint_uint_arg(bp, "divert ", cmd->arg1);
1506 bprint_uint_arg(bp, "tee ", cmd->arg1);
1510 bprint_uint_arg(bp, "netgraph ", cmd->arg1);
1514 bprint_uint_arg(bp, "ngtee ", cmd->arg1);
1519 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1521 if (s->sa.sin_addr.s_addr == INADDR_ANY) {
1522 bprintf(bp, "fwd tablearg");
1524 bprintf(bp, "fwd %s",inet_ntoa(s->sa.sin_addr));
1527 bprintf(bp, ",%d", s->sa.sin_port);
1533 char buf[INET6_ADDRSTRLEN + IF_NAMESIZE + 2];
1534 ipfw_insn_sa6 *s = (ipfw_insn_sa6 *)cmd;
1536 bprintf(bp, "fwd ");
1537 if (getnameinfo((const struct sockaddr *)&s->sa,
1538 sizeof(struct sockaddr_in6), buf, sizeof(buf),
1539 NULL, 0, NI_NUMERICHOST) == 0)
1540 bprintf(bp, "%s", buf);
1541 if (s->sa.sin6_port)
1542 bprintf(bp, ",%d", s->sa.sin6_port);
1546 case O_LOG: /* O_LOG is printed last */
1547 logptr = (ipfw_insn_log *)cmd;
1550 case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1551 altqptr = (ipfw_insn_altq *)cmd;
1560 bprint_uint_arg(bp, "nat ", cmd->arg1);
1562 bprintf(bp, "nat global");
1566 bprint_uint_arg(bp, "setfib ", cmd->arg1 & 0x7FFF);
1573 if (cmd->arg1 == IP_FW_TARG) {
1574 bprint_uint_arg(bp, "setdscp ", cmd->arg1);
1577 uval = cmd->arg1 & 0x3F;
1578 if ((code = match_value(f_ipdscp, uval)) != NULL)
1579 bprintf(bp, "setdscp %s", code);
1581 bprint_uint_arg(bp, "setdscp ", uval);
1586 bprintf(bp, "reass");
1590 if (cmd->len & F_NOT)
1591 bprintf(bp, "return");
1593 bprint_uint_arg(bp, "call ", cmd->arg1);
1597 bprintf(bp, "** unrecognized action %d len %d ",
1598 cmd->opcode, cmd->len);
1602 if (logptr->max_log > 0)
1603 bprintf(bp, " log logamount %d", logptr->max_log);
1605 bprintf(bp, " log");
1609 print_altq_cmd(bp, altqptr);
1613 if (tagptr->len & F_NOT)
1614 bprint_uint_arg(bp, " untag ", tagptr->arg1);
1616 bprint_uint_arg(bp, " tag ", tagptr->arg1);
1620 * then print the body.
1622 for (l = rule->act_ofs, cmd = rule->cmd;
1623 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1624 if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1626 if (cmd->opcode == O_IP4) {
1627 flags |= HAVE_PROTO4;
1629 } else if (cmd->opcode == O_IP6) {
1630 flags |= HAVE_PROTO6;
1634 if (rule->flags & IPFW_RULE_NOOPT) { /* empty rules before options */
1635 if (!co->do_compact) {
1636 show_prerequisites(bp, &flags, HAVE_PROTO, 0);
1637 bprintf(bp, " from any to any");
1639 flags |= HAVE_IP | HAVE_OPTIONS | HAVE_PROTO |
1640 HAVE_SRCIP | HAVE_DSTIP;
1643 if (co->comment_only)
1646 for (l = rule->act_ofs, cmd = rule->cmd;
1647 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1649 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1651 if (co->comment_only) {
1652 if (cmd->opcode != O_NOP)
1654 bprintf(bp, " // %s\n", (char *)(cmd + 1));
1658 show_prerequisites(bp, &flags, 0, cmd->opcode);
1660 switch(cmd->opcode) {
1662 break; /* done already */
1665 break; /* no need to print anything here */
1668 case O_IP_SRC_LOOKUP:
1672 show_prerequisites(bp, &flags, HAVE_PROTO, 0);
1673 if (!(flags & HAVE_SRCIP))
1674 bprintf(bp, " from");
1675 if ((cmd->len & F_OR) && !or_block)
1677 print_ip(bp, fo, (ipfw_insn_ip *)cmd,
1678 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1679 flags |= HAVE_SRCIP;
1683 case O_IP_DST_LOOKUP:
1687 show_prerequisites(bp, &flags, HAVE_PROTO|HAVE_SRCIP, 0);
1688 if (!(flags & HAVE_DSTIP))
1690 if ((cmd->len & F_OR) && !or_block)
1692 print_ip(bp, fo, (ipfw_insn_ip *)cmd,
1693 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1694 flags |= HAVE_DSTIP;
1698 case O_IP6_SRC_MASK:
1700 show_prerequisites(bp, &flags, HAVE_PROTO, 0);
1701 if (!(flags & HAVE_SRCIP))
1702 bprintf(bp, " from");
1703 if ((cmd->len & F_OR) && !or_block)
1705 print_ip6(bp, (ipfw_insn_ip6 *)cmd,
1706 (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1707 flags |= HAVE_SRCIP | HAVE_PROTO;
1711 case O_IP6_DST_MASK:
1713 show_prerequisites(bp, &flags, HAVE_PROTO|HAVE_SRCIP, 0);
1714 if (!(flags & HAVE_DSTIP))
1716 if ((cmd->len & F_OR) && !or_block)
1718 print_ip6(bp, (ipfw_insn_ip6 *)cmd,
1719 (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1720 flags |= HAVE_DSTIP;
1724 print_flow6id(bp, (ipfw_insn_u32 *) cmd );
1725 flags |= HAVE_OPTIONS;
1729 show_prerequisites(bp, &flags,
1730 HAVE_PROTO | HAVE_SRCIP |
1731 HAVE_DSTIP | HAVE_IP, 0);
1733 if (flags & HAVE_DSTIP)
1735 show_prerequisites(bp, &flags,
1736 HAVE_PROTO | HAVE_SRCIP, 0);
1737 if ((cmd->len & F_OR) && !or_block)
1739 if (cmd->len & F_NOT)
1740 bprintf(bp, " not");
1741 print_newports(bp, (ipfw_insn_u16 *)cmd, proto,
1742 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1746 struct protoent *pe = NULL;
1748 if ((cmd->len & F_OR) && !or_block)
1750 if (cmd->len & F_NOT)
1751 bprintf(bp, " not");
1753 pe = getprotobynumber(cmd->arg1);
1754 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1755 !(flags & HAVE_PROTO))
1756 show_prerequisites(bp, &flags,
1757 HAVE_PROTO | HAVE_IP | HAVE_SRCIP |
1758 HAVE_DSTIP | HAVE_OPTIONS, 0);
1759 if (flags & HAVE_OPTIONS)
1760 bprintf(bp, " proto");
1762 bprintf(bp, " %s", pe->p_name);
1764 bprintf(bp, " %u", cmd->arg1);
1766 flags |= HAVE_PROTO;
1769 default: /*options ... */
1770 if (!(cmd->len & (F_OR|F_NOT)))
1771 if (((cmd->opcode == O_IP6) &&
1772 (flags & HAVE_PROTO6)) ||
1773 ((cmd->opcode == O_IP4) &&
1774 (flags & HAVE_PROTO4)))
1776 show_prerequisites(bp, &flags, HAVE_PROTO | HAVE_SRCIP |
1777 HAVE_DSTIP | HAVE_IP | HAVE_OPTIONS, 0);
1778 if ((cmd->len & F_OR) && !or_block)
1780 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1781 bprintf(bp, " not");
1782 switch(cmd->opcode) {
1784 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1786 bprintf(bp, " MAC");
1787 print_mac(bp, m->addr, m->mask);
1788 print_mac(bp, m->addr + 6, m->mask + 6);
1793 print_newports(bp, (ipfw_insn_u16 *)cmd,
1794 IPPROTO_ETHERTYPE, cmd->opcode);
1799 bprintf(bp, " frag");
1803 bprintf(bp, " fib %u", cmd->arg1 );
1806 bprintf(bp, " sockarg");
1810 bprintf(bp, cmd->len & F_NOT ? " out" : " in");
1814 switch (cmd->arg1) {
1816 bprintf(bp, " diverted");
1819 bprintf(bp, " diverted-loopback");
1822 bprintf(bp, " diverted-output");
1825 bprintf(bp, " diverted-?<%u>", cmd->arg1);
1831 bprintf(bp, " layer2");
1838 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1840 if (cmd->opcode == O_XMIT)
1842 else if (cmd->opcode == O_RECV)
1844 else /* if (cmd->opcode == O_VIA) */
1846 if (cmdif->name[0] == '\0')
1847 bprintf(bp, " %s %s", s,
1848 inet_ntoa(cmdif->p.ip));
1849 else if (cmdif->name[0] == '\1') {
1850 /* interface table */
1851 t = table_search_ctlv(fo->tstate,
1853 bprintf(bp, " %s table(%s)", s, t);
1855 bprintf(bp, " %s %s", s, cmdif->name);
1859 case O_IP_FLOW_LOOKUP:
1863 t = table_search_ctlv(fo->tstate, cmd->arg1);
1864 bprintf(bp, " flow table(%s", t);
1865 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32))
1867 ((ipfw_insn_u32 *)cmd)->d[0]);
1872 if (F_LEN(cmd) == 1)
1873 bprintf(bp, " ipid %u", cmd->arg1 );
1875 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1880 if (F_LEN(cmd) == 1)
1881 bprintf(bp, " ipttl %u", cmd->arg1 );
1883 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1888 bprintf(bp, " ipver %u", cmd->arg1 );
1891 case O_IPPRECEDENCE:
1892 bprintf(bp, " ipprecedence %u", cmd->arg1 >> 5);
1896 print_dscp(bp, (ipfw_insn_u32 *)cmd);
1900 if (F_LEN(cmd) == 1)
1901 bprintf(bp, " iplen %u", cmd->arg1 );
1903 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1908 print_flags(bp, "ipoptions", cmd, f_ipopts);
1912 print_flags(bp, "iptos", cmd, f_iptos);
1916 print_icmptypes(bp, (ipfw_insn_u32 *)cmd);
1920 bprintf(bp, " established");
1924 if (F_LEN(cmd) == 1)
1925 bprintf(bp, " tcpdatalen %u", cmd->arg1 );
1927 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1932 print_flags(bp, "tcpflags", cmd, f_tcpflags);
1936 print_flags(bp, "tcpoptions", cmd, f_tcpopts);
1940 if (F_LEN(cmd) == 1)
1941 bprintf(bp, " tcpwin %u", cmd->arg1);
1943 print_newports(bp, (ipfw_insn_u16 *)cmd, 0,
1948 bprintf(bp, " tcpack %d", ntohl(cmd32->d[0]));
1952 bprintf(bp, " tcpseq %d", ntohl(cmd32->d[0]));
1957 struct passwd *pwd = getpwuid(cmd32->d[0]);
1960 bprintf(bp, " uid %s", pwd->pw_name);
1962 bprintf(bp, " uid %u", cmd32->d[0]);
1968 struct group *grp = getgrgid(cmd32->d[0]);
1971 bprintf(bp, " gid %s", grp->gr_name);
1973 bprintf(bp, " gid %u", cmd32->d[0]);
1978 bprintf(bp, " jail %d", cmd32->d[0]);
1982 bprintf(bp, " verrevpath");
1986 bprintf(bp, " versrcreach");
1990 bprintf(bp, " antispoof");
1994 bprintf(bp, " ipsec");
1998 comment = (char *)(cmd + 1);
2002 bprintf(bp, " keep-state");
2006 struct _s_x *p = limit_masks;
2007 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
2008 uint8_t x = c->limit_mask;
2009 char const *comma = " ";
2011 bprintf(bp, " limit");
2012 for (; p->x != 0 ; p++)
2013 if ((x & p->x) == p->x) {
2015 bprintf(bp, "%s%s", comma,p->s);
2018 bprint_uint_arg(bp, " ", c->conn_limit);
2023 bprintf(bp, " ip6");
2027 bprintf(bp, " ip4");
2031 print_icmp6types(bp, (ipfw_insn_u32 *)cmd);
2035 print_ext6hdr(bp, (ipfw_insn *)cmd);
2039 if (F_LEN(cmd) == 1)
2040 bprint_uint_arg(bp, " tagged ",
2043 print_newports(bp, (ipfw_insn_u16 *)cmd,
2048 bprintf(bp, " [opcode %d len %d]",
2049 cmd->opcode, cmd->len);
2052 if (cmd->len & F_OR) {
2055 } else if (or_block) {
2060 show_prerequisites(bp, &flags, HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP
2063 bprintf(bp, " // %s", comment);
2068 show_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2069 struct buf_pr *bp, ipfw_dyn_rule *d)
2071 struct protoent *pe;
2074 char buf[INET6_ADDRSTRLEN];
2076 if (!co->do_expired) {
2077 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
2080 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2081 bprintf(bp, "%05d", rulenum);
2082 if (fo->pcwidth > 0 || fo->bcwidth > 0) {
2084 pr_u64(bp, &d->pcnt, fo->pcwidth);
2085 pr_u64(bp, &d->bcnt, fo->bcwidth);
2086 bprintf(bp, "(%ds)", d->expire);
2088 switch (d->dyn_type) {
2089 case O_LIMIT_PARENT:
2090 bprintf(bp, " PARENT %d", d->count);
2093 bprintf(bp, " LIMIT");
2095 case O_KEEP_STATE: /* bidir, no mask */
2096 bprintf(bp, " STATE");
2100 if ((pe = getprotobynumber(d->id.proto)) != NULL)
2101 bprintf(bp, " %s", pe->p_name);
2103 bprintf(bp, " proto %u", d->id.proto);
2105 if (d->id.addr_type == 4) {
2106 a.s_addr = htonl(d->id.src_ip);
2107 bprintf(bp, " %s %d", inet_ntoa(a), d->id.src_port);
2109 a.s_addr = htonl(d->id.dst_ip);
2110 bprintf(bp, " <-> %s %d", inet_ntoa(a), d->id.dst_port);
2111 } else if (d->id.addr_type == 6) {
2112 bprintf(bp, " %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
2113 sizeof(buf)), d->id.src_port);
2114 bprintf(bp, " <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6,
2115 buf, sizeof(buf)), d->id.dst_port);
2117 bprintf(bp, " UNKNOWN <-> UNKNOWN\n");
2121 do_range_cmd(int cmd, ipfw_range_tlv *rt)
2123 ipfw_range_header rh;
2126 memset(&rh, 0, sizeof(rh));
2127 memcpy(&rh.range, rt, sizeof(*rt));
2128 rh.range.head.length = sizeof(*rt);
2129 rh.range.head.type = IPFW_TLV_RANGE;
2132 if (do_get3(cmd, &rh.opheader, &sz) != 0)
2134 /* Save number of matched objects */
2135 rt->new_set = rh.range.new_set;
2140 * This one handles all set-related commands
2141 * ipfw set { show | enable | disable }
2143 * ipfw set move X to Y
2144 * ipfw set move rule X to Y
2147 ipfw_sets_handler(char *av[])
2151 uint8_t cmd, rulenum;
2157 memset(&rt, 0, sizeof(rt));
2160 errx(EX_USAGE, "set needs command");
2161 if (_substrcmp(*av, "show") == 0) {
2162 struct format_opts fo;
2163 ipfw_cfg_lheader *cfg;
2165 memset(&fo, 0, sizeof(fo));
2166 if (ipfw_get_config(&co, &fo, &cfg, &size) != 0)
2167 err(EX_OSERR, "requesting config failed");
2169 for (i = 0, msg = "disable"; i < RESVD_SET; i++)
2170 if ((cfg->set_mask & (1<<i)) == 0) {
2171 printf("%s %d", msg, i);
2174 msg = (cfg->set_mask != (uint32_t)-1) ? " enable" : "enable";
2175 for (i = 0; i < RESVD_SET; i++)
2176 if ((cfg->set_mask & (1<<i)) != 0) {
2177 printf("%s %d", msg, i);
2182 } else if (_substrcmp(*av, "swap") == 0) {
2184 if ( av[0] == NULL || av[1] == NULL )
2185 errx(EX_USAGE, "set swap needs 2 set numbers\n");
2186 rt.set = atoi(av[0]);
2187 rt.new_set = atoi(av[1]);
2188 if (!isdigit(*(av[0])) || rt.set > RESVD_SET)
2189 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2190 if (!isdigit(*(av[1])) || rt.new_set > RESVD_SET)
2191 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2192 i = do_range_cmd(IP_FW_SET_SWAP, &rt);
2193 } else if (_substrcmp(*av, "move") == 0) {
2195 if (av[0] && _substrcmp(*av, "rule") == 0) {
2196 rt.flags = IPFW_RCFLAG_RANGE; /* move rules to new set */
2200 cmd = IP_FW_SET_MOVE; /* Move set to new one */
2201 if (av[0] == NULL || av[1] == NULL || av[2] == NULL ||
2202 av[3] != NULL || _substrcmp(av[1], "to") != 0)
2203 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2204 rulenum = atoi(av[0]);
2205 rt.new_set = atoi(av[2]);
2206 if (cmd == IP_FW_XMOVE) {
2207 rt.start_rule = rulenum;
2208 rt.end_rule = rulenum;
2211 rt.new_set = atoi(av[2]);
2212 if (!isdigit(*(av[0])) || (cmd == 3 && rt.set > RESVD_SET) ||
2213 (cmd == 2 && rt.start_rule == IPFW_DEFAULT_RULE) )
2214 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2215 if (!isdigit(*(av[2])) || rt.new_set > RESVD_SET)
2216 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2217 i = do_range_cmd(cmd, &rt);
2218 } else if (_substrcmp(*av, "disable") == 0 ||
2219 _substrcmp(*av, "enable") == 0 ) {
2220 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2223 masks[0] = masks[1] = 0;
2226 if (isdigit(**av)) {
2228 if (i < 0 || i > RESVD_SET)
2230 "invalid set number %d\n", i);
2231 masks[which] |= (1<<i);
2232 } else if (_substrcmp(*av, "disable") == 0)
2234 else if (_substrcmp(*av, "enable") == 0)
2238 "invalid set command %s\n", *av);
2241 if ( (masks[0] & masks[1]) != 0 )
2243 "cannot enable and disable the same set\n");
2246 rt.new_set = masks[1];
2247 i = do_range_cmd(IP_FW_SET_ENABLE, &rt);
2249 warn("set enable/disable: setsockopt(IP_FW_SET_ENABLE)");
2251 errx(EX_USAGE, "invalid set command %s\n", *av);
2255 ipfw_sysctl_handler(char *av[], int which)
2259 if (av[0] == NULL) {
2260 warnx("missing keyword to enable/disable\n");
2261 } else if (_substrcmp(*av, "firewall") == 0) {
2262 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2263 &which, sizeof(which));
2264 sysctlbyname("net.inet6.ip6.fw.enable", NULL, 0,
2265 &which, sizeof(which));
2266 } else if (_substrcmp(*av, "one_pass") == 0) {
2267 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2268 &which, sizeof(which));
2269 } else if (_substrcmp(*av, "debug") == 0) {
2270 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2271 &which, sizeof(which));
2272 } else if (_substrcmp(*av, "verbose") == 0) {
2273 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2274 &which, sizeof(which));
2275 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2276 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2277 &which, sizeof(which));
2279 } else if (_substrcmp(*av, "altq") == 0) {
2280 altq_set_enabled(which);
2283 warnx("unrecognize enable/disable keyword: %s\n", *av);
2287 typedef void state_cb(struct cmdline_opts *co, struct format_opts *fo,
2288 void *arg, void *state);
2291 prepare_format_dyn(struct cmdline_opts *co, struct format_opts *fo,
2292 void *arg, void *_state)
2298 d = (ipfw_dyn_rule *)_state;
2299 /* Count _ALL_ states */
2302 if (fo->show_counters == 0)
2306 /* skip states from another set */
2307 bcopy((char *)&d->rule + sizeof(uint16_t), &set,
2309 if (set != co->use_set - 1)
2313 width = pr_u64(NULL, &d->pcnt, 0);
2314 if (width > fo->pcwidth)
2315 fo->pcwidth = width;
2317 width = pr_u64(NULL, &d->bcnt, 0);
2318 if (width > fo->bcwidth)
2319 fo->bcwidth = width;
2323 foreach_state(struct cmdline_opts *co, struct format_opts *fo,
2324 caddr_t base, size_t sz, state_cb dyn_bc, void *dyn_arg)
2330 ipfw_obj_ctlv *ctlv;
2336 ctlv = (ipfw_obj_ctlv *)base;
2337 switch (ctlv->head.type) {
2338 case IPFW_TLV_DYNSTATE_LIST:
2339 base += sizeof(*ctlv);
2340 sz -= sizeof(*ctlv);
2341 ttype = IPFW_TLV_DYN_ENT;
2350 tlv = (ipfw_obj_tlv *)base;
2351 if (tlv->type != ttype)
2354 fptr(co, fo, farg, tlv + 1);
2356 base += tlv->length;
2364 prepare_format_opts(struct cmdline_opts *co, struct format_opts *fo,
2365 ipfw_obj_tlv *rtlv, int rcnt, caddr_t dynbase, size_t dynsz)
2367 int bcwidth, pcwidth, width;
2369 struct ip_fw_bcounter *cntr;
2370 struct ip_fw_rule *r;
2374 if (fo->show_counters != 0) {
2375 for (n = 0; n < rcnt; n++,
2376 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2377 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2378 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2379 /* skip rules from another set */
2380 if (co->use_set && r->set != co->use_set - 1)
2383 /* packet counter */
2384 width = pr_u64(NULL, &cntr->pcnt, 0);
2385 if (width > pcwidth)
2389 width = pr_u64(NULL, &cntr->bcnt, 0);
2390 if (width > bcwidth)
2394 fo->bcwidth = bcwidth;
2395 fo->pcwidth = pcwidth;
2398 if (co->do_dynamic && dynsz > 0)
2399 foreach_state(co, fo, dynbase, dynsz, prepare_format_dyn, NULL);
2403 list_static_range(struct cmdline_opts *co, struct format_opts *fo,
2404 struct buf_pr *bp, ipfw_obj_tlv *rtlv, int rcnt)
2407 struct ip_fw_rule *r;
2408 struct ip_fw_bcounter *cntr;
2411 for (n = seen = 0; n < rcnt; n++,
2412 rtlv = (ipfw_obj_tlv *)((caddr_t)rtlv + rtlv->length)) {
2414 if ((fo->show_counters | fo->show_time) != 0) {
2415 cntr = (struct ip_fw_bcounter *)(rtlv + 1);
2416 r = (struct ip_fw_rule *)((caddr_t)cntr + cntr->size);
2419 r = (struct ip_fw_rule *)(rtlv + 1);
2421 if (r->rulenum > fo->last)
2423 if (co->use_set && r->set != co->use_set - 1)
2425 if (r->rulenum >= fo->first && r->rulenum <= fo->last) {
2426 show_static_rule(co, fo, bp, r, cntr);
2427 printf("%s", bp->buf);
2438 list_dyn_state(struct cmdline_opts *co, struct format_opts *fo,
2439 void *_arg, void *_state)
2446 d = (ipfw_dyn_rule *)_state;
2447 bp = (struct buf_pr *)_arg;
2449 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2450 if (rulenum > fo->last)
2453 bcopy((char *)&d->rule + sizeof(uint16_t),
2454 &set, sizeof(uint8_t));
2455 if (set != co->use_set - 1)
2458 if (rulenum >= fo->first) {
2459 show_dyn_state(co, fo, bp, d);
2460 printf("%s\n", bp->buf);
2466 list_dyn_range(struct cmdline_opts *co, struct format_opts *fo,
2467 struct buf_pr *bp, caddr_t base, size_t sz)
2470 sz = foreach_state(co, fo, base, sz, list_dyn_state, bp);
2475 ipfw_list(int ac, char *av[], int show_counters)
2477 ipfw_cfg_lheader *cfg;
2478 struct format_opts sfo;
2487 fprintf(stderr, "Testing only, list disabled\n");
2491 dummynet_list(ac, av, show_counters);
2497 memset(&sfo, 0, sizeof(sfo));
2499 /* Determine rule range to request */
2501 for (lac = ac, lav = av; lac != 0; lac--) {
2502 rnum = strtoul(*lav++, &endptr, 10);
2503 if (sfo.first == 0 || rnum < sfo.first)
2507 rnum = strtoul(endptr + 1, &endptr, 10);
2508 if (sfo.last == 0 || rnum > sfo.last)
2513 /* get configuraion from kernel */
2515 sfo.show_counters = show_counters;
2516 sfo.show_time = co.do_time;
2517 sfo.flags = IPFW_CFG_GET_STATIC;
2518 if (co.do_dynamic != 0)
2519 sfo.flags |= IPFW_CFG_GET_STATES;
2520 if ((sfo.show_counters | sfo.show_time) != 0)
2521 sfo.flags |= IPFW_CFG_GET_COUNTERS;
2522 if (ipfw_get_config(&co, &sfo, &cfg, &sz) != 0)
2523 err(EX_OSERR, "retrieving config failed");
2525 error = ipfw_show_config(&co, &sfo, cfg, sz, ac, av);
2534 ipfw_show_config(struct cmdline_opts *co, struct format_opts *fo,
2535 ipfw_cfg_lheader *cfg, size_t sz, int ac, char *av[])
2540 int exitval = EX_OK;
2546 ipfw_obj_ctlv *ctlv, *tstate;
2547 ipfw_obj_tlv *rbase;
2550 * Handle tablenames TLV first, if any
2556 readsz = sizeof(*cfg);
2559 fo->set_mask = cfg->set_mask;
2561 ctlv = (ipfw_obj_ctlv *)(cfg + 1);
2563 if (cfg->flags & IPFW_CFG_GET_STATIC) {
2564 /* We've requested static rules */
2565 if (ctlv->head.type == IPFW_TLV_TBLNAME_LIST) {
2566 object_sort_ctlv(ctlv);
2568 readsz += ctlv->head.length;
2569 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2573 if (ctlv->head.type == IPFW_TLV_RULE_LIST) {
2574 rbase = (ipfw_obj_tlv *)(ctlv + 1);
2576 readsz += ctlv->head.length;
2577 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv +
2582 if ((cfg->flags & IPFW_CFG_GET_STATES) && (readsz != sz)) {
2583 /* We may have some dynamic states */
2584 dynsz = sz - readsz;
2585 /* Skip empty header */
2586 if (dynsz != sizeof(ipfw_obj_ctlv))
2587 dynbase = (caddr_t)ctlv;
2592 prepare_format_opts(co, fo, rbase, rcnt, dynbase, dynsz);
2593 bp_alloc(&bp, 4096);
2595 /* if no rule numbers were specified, list all rules */
2598 fo->last = IPFW_DEFAULT_RULE;
2599 list_static_range(co, fo, &bp, rbase, rcnt);
2601 if (co->do_dynamic && dynsz > 0) {
2602 printf("## Dynamic rules (%d %zu):\n", fo->dcnt, dynsz);
2603 list_dyn_range(co, fo, &bp, dynbase, dynsz);
2610 /* display specific rules requested on command line */
2611 for (lac = ac, lav = av; lac != 0; lac--) {
2612 /* convert command line rule # */
2613 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2615 fo->last = strtoul(endptr + 1, &endptr, 10);
2618 warnx("invalid rule number: %s", *(lav - 1));
2622 if (list_static_range(co, fo, &bp, rbase, rcnt) == 0) {
2623 /* give precedence to other error(s) */
2624 if (exitval == EX_OK)
2625 exitval = EX_UNAVAILABLE;
2626 if (fo->first == fo->last)
2627 warnx("rule %u does not exist", fo->first);
2629 warnx("no rules in range %u-%u",
2630 fo->first, fo->last);
2634 if (co->do_dynamic && dynsz > 0) {
2635 printf("## Dynamic rules:\n");
2636 for (lac = ac, lav = av; lac != 0; lac--) {
2637 fo->last = fo->first = strtoul(*lav++, &endptr, 10);
2639 fo->last = strtoul(endptr+1, &endptr, 10);
2641 /* already warned */
2643 list_dyn_range(co, fo, &bp, dynbase, dynsz);
2653 * Retrieves current ipfw configuration of given type
2654 * and stores its pointer to @pcfg.
2656 * Caller is responsible for freeing @pcfg.
2658 * Returns 0 on success.
2662 ipfw_get_config(struct cmdline_opts *co, struct format_opts *fo,
2663 ipfw_cfg_lheader **pcfg, size_t *psize)
2665 ipfw_cfg_lheader *cfg;
2670 if (co->test_only != 0) {
2671 fprintf(stderr, "Testing only, list disabled\n");
2675 /* Start with some data size */
2679 for (i = 0; i < 16; i++) {
2682 if ((cfg = calloc(1, sz)) == NULL)
2685 cfg->flags = fo->flags;
2686 cfg->start_rule = fo->first;
2687 cfg->end_rule = fo->last;
2689 if (do_get3(IP_FW_XGET, &cfg->opheader, &sz) != 0) {
2690 if (errno != ENOMEM) {
2695 /* Buffer size is not enough. Try to increase */
2712 lookup_host (char *host, struct in_addr *ipaddr)
2716 if (!inet_aton(host, ipaddr)) {
2717 if ((he = gethostbyname(host)) == NULL)
2719 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2733 pack_object(struct tidx *tstate, char *name, int otype)
2736 ipfw_obj_ntlv *ntlv;
2738 for (i = 0; i < tstate->count; i++) {
2739 if (strcmp(tstate->idx[i].name, name) != 0)
2741 if (tstate->idx[i].set != tstate->set)
2743 if (tstate->idx[i].head.type != otype)
2746 return (tstate->idx[i].idx);
2749 if (tstate->count + 1 > tstate->size) {
2751 tstate->idx = realloc(tstate->idx, tstate->size *
2752 sizeof(ipfw_obj_ntlv));
2753 if (tstate->idx == NULL)
2757 ntlv = &tstate->idx[i];
2758 memset(ntlv, 0, sizeof(ipfw_obj_ntlv));
2759 strlcpy(ntlv->name, name, sizeof(ntlv->name));
2760 ntlv->head.type = otype;
2761 ntlv->head.length = sizeof(ipfw_obj_ntlv);
2762 ntlv->set = tstate->set;
2763 ntlv->idx = ++tstate->counter;
2770 pack_table(struct tidx *tstate, char *name)
2773 if (table_check_name(name) != 0)
2776 return (pack_object(tstate, name, IPFW_TLV_TBL_NAME));
2780 fill_table(ipfw_insn *cmd, char *av, uint8_t opcode, struct tidx *tstate)
2782 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2786 if ((p = strchr(av + 6, ')')) == NULL)
2787 errx(EX_DATAERR, "forgotten parenthesis: '%s'", av);
2789 p = strchr(av + 6, ',');
2793 if ((uidx = pack_table(tstate, av + 6)) == 0)
2794 errx(EX_DATAERR, "Invalid table name: %s", av + 6);
2796 cmd->opcode = opcode;
2799 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
2800 d[0] = strtoul(p, NULL, 0);
2802 cmd->len |= F_INSN_SIZE(ipfw_insn);
2807 * fills the addr and mask fields in the instruction as appropriate from av.
2808 * Update length as appropriate.
2809 * The following formats are allowed:
2810 * me returns O_IP_*_ME
2811 * 1.2.3.4 single IP address
2812 * 1.2.3.4:5.6.7.8 address:mask
2813 * 1.2.3.4/24 address/mask
2814 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
2815 * We can have multiple comma-separated address/mask entries.
2818 fill_ip(ipfw_insn_ip *cmd, char *av, int cblen, struct tidx *tstate)
2821 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2823 cmd->o.len &= ~F_LEN_MASK; /* zero len */
2825 if (_substrcmp(av, "any") == 0)
2828 if (_substrcmp(av, "me") == 0) {
2829 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2833 if (strncmp(av, "table(", 6) == 0) {
2834 fill_table(&cmd->o, av, O_IP_DST_LOOKUP, tstate);
2840 * After the address we can have '/' or ':' indicating a mask,
2841 * ',' indicating another address follows, '{' indicating a
2842 * set of addresses of unspecified size.
2844 char *t = NULL, *p = strpbrk(av, "/:,{");
2848 CHECK_LENGTH(cblen, F_INSN_SIZE(ipfw_insn) + 2 + len);
2853 if ((t = strpbrk(p, ",{")) != NULL) {
2860 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2861 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2864 if (!inet_aton(p, (struct in_addr *)&d[1]))
2865 errx(EX_DATAERR, "bad netmask ``%s''", p);
2870 d[1] = htonl(0U); /* mask */
2871 else if (masklen > 32)
2872 errx(EX_DATAERR, "bad width ``%s''", p);
2874 d[1] = htonl(~0U << (32 - masklen));
2876 case '{': /* no mask, assume /24 and put back the '{' */
2877 d[1] = htonl(~0U << (32 - 24));
2881 case ',': /* single address plus continuation */
2884 case 0: /* initialization value */
2886 d[1] = htonl(~0U); /* force /32 */
2889 d[0] &= d[1]; /* mask base address with mask */
2892 /* find next separator */
2894 p = strpbrk(p, ",{");
2895 if (p && *p == '{') {
2897 * We have a set of addresses. They are stored as follows:
2898 * arg1 is the set size (powers of 2, 2..256)
2899 * addr is the base address IN HOST FORMAT
2900 * mask.. is an array of arg1 bits (rounded up to
2901 * the next multiple of 32) with bits set
2902 * for each host in the map.
2904 uint32_t *map = (uint32_t *)&cmd->mask;
2906 int i = contigmask((uint8_t *)&(d[1]), 32);
2909 errx(EX_DATAERR, "address set cannot be in a list");
2910 if (i < 24 || i > 31)
2911 errx(EX_DATAERR, "invalid set with mask %d\n", i);
2912 cmd->o.arg1 = 1<<(32-i); /* map length */
2913 d[0] = ntohl(d[0]); /* base addr in host format */
2914 cmd->o.opcode = O_IP_DST_SET; /* default */
2915 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2916 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2917 map[i] = 0; /* clear map */
2921 high = low + cmd->o.arg1 - 1;
2923 * Here, i stores the previous value when we specify a range
2924 * of addresses within a mask, e.g. 45-63. i = -1 means we
2925 * have no previous value.
2927 i = -1; /* previous value in a range */
2928 while (isdigit(*av)) {
2930 int a = strtol(av, &s, 0);
2932 if (s == av) { /* no parameter */
2934 errx(EX_DATAERR, "set not closed\n");
2936 errx(EX_DATAERR, "incomplete range %d-", i);
2939 if (a < low || a > high)
2940 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
2943 if (i == -1) /* no previous in range */
2945 else { /* check that range is valid */
2947 errx(EX_DATAERR, "invalid range %d-%d",
2950 errx(EX_DATAERR, "double '-' in range");
2953 map[i/32] |= 1<<(i & 31);
2964 if (av) /* then *av must be a ',' */
2967 /* Check this entry */
2968 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2970 * 'any' turns the entire list into a NOP.
2971 * 'not any' never matches, so it is removed from the
2972 * list unless it is the only item, in which case we
2975 if (cmd->o.len & F_NOT) { /* "not any" never matches */
2976 if (av == NULL && len == 0) /* only this entry */
2977 errx(EX_DATAERR, "not any never matches");
2979 /* else do nothing and skip this entry */
2982 /* A single IP can be stored in an optimized format */
2983 if (d[1] == (uint32_t)~0 && av == NULL && len == 0) {
2984 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2987 len += 2; /* two words... */
2990 if (len + 1 > F_LEN_MASK)
2991 errx(EX_DATAERR, "address list too long");
2992 cmd->o.len |= len+1;
2996 /* n2mask sets n bits of the mask */
2998 n2mask(struct in6_addr *mask, int n)
3000 static int minimask[9] =
3001 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
3004 memset(mask, 0, sizeof(struct in6_addr));
3005 p = (u_char *) mask;
3006 for (; n > 0; p++, n -= 8) {
3016 fill_flags_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3017 struct _s_x *flags, char *p)
3020 uint32_t set = 0, clear = 0;
3022 if (fill_flags(flags, p, &e, &set, &clear) != 0)
3023 errx(EX_DATAERR, "invalid flag %s", e);
3025 cmd->opcode = opcode;
3026 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
3027 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3032 ipfw_delete(char *av[])
3035 int exitval = EX_OK;
3041 NEED1("missing rule specification");
3042 memset(&rt, 0, sizeof(rt));
3043 if ( *av && _substrcmp(*av, "set") == 0) {
3044 /* Do not allow using the following syntax:
3045 * ipfw set N delete set M
3048 errx(EX_DATAERR, "invalid syntax");
3049 do_set = 1; /* delete set */
3054 while (*av && isdigit(**av)) {
3055 i = strtol(*av, &sep, 10);
3058 j = strtol(sep + 1, NULL, 10);
3061 exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
3063 exitval = EX_UNAVAILABLE;
3064 warn("rule %u not available", i);
3066 } else if (co.do_pipe) {
3067 exitval = ipfw_delete_pipe(co.do_pipe, i);
3071 rt.flags = IPFW_RCFLAG_SET;
3073 rt.start_rule = i & 0xffff;
3074 rt.end_rule = j & 0xffff;
3075 if (rt.start_rule == 0 && rt.end_rule == 0)
3076 rt.flags |= IPFW_RCFLAG_ALL;
3078 rt.flags |= IPFW_RCFLAG_RANGE;
3079 if (co.use_set != 0) {
3080 rt.set = co.use_set - 1;
3081 rt.flags |= IPFW_RCFLAG_SET;
3084 i = do_range_cmd(IP_FW_XDEL, &rt);
3086 exitval = EX_UNAVAILABLE;
3087 warn("rule %u: setsockopt(IP_FW_XDEL)",
3089 } else if (rt.new_set == 0) {
3090 exitval = EX_UNAVAILABLE;
3091 if (rt.start_rule != rt.end_rule)
3092 warnx("no rules rules in %u-%u range",
3093 rt.start_rule, rt.end_rule);
3095 warnx("rule %u not found",
3100 if (exitval != EX_OK)
3106 * fill the interface structure. We do not check the name as we can
3107 * create interfaces dynamically, so checking them at insert time
3108 * makes relatively little sense.
3109 * Interface names containing '*', '?', or '[' are assumed to be shell
3110 * patterns which match interfaces.
3113 fill_iface(ipfw_insn_if *cmd, char *arg, int cblen, struct tidx *tstate)
3118 cmd->name[0] = '\0';
3119 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3123 /* Parse the interface or address */
3124 if (strcmp(arg, "any") == 0)
3125 cmd->o.len = 0; /* effectively ignore this command */
3126 else if (strncmp(arg, "table(", 6) == 0) {
3127 if ((p = strchr(arg + 6, ')')) == NULL)
3128 errx(EX_DATAERR, "forgotten parenthesis: '%s'", arg);
3130 p = strchr(arg + 6, ',');
3133 if ((uidx = pack_table(tstate, arg + 6)) == 0)
3134 errx(EX_DATAERR, "Invalid table name: %s", arg + 6);
3136 cmd->name[0] = '\1'; /* Special value indicating table */
3138 } else if (!isdigit(*arg)) {
3139 strlcpy(cmd->name, arg, sizeof(cmd->name));
3140 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3141 } else if (!inet_aton(arg, &cmd->p.ip))
3142 errx(EX_DATAERR, "bad ip address ``%s''", arg);
3146 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
3150 char *ap, *ptr, *optr;
3151 struct ether_addr *mac;
3152 const char *macset = "0123456789abcdefABCDEF:";
3154 if (strcmp(p, "any") == 0) {
3155 for (i = 0; i < ETHER_ADDR_LEN; i++)
3156 addr[i] = mask[i] = 0;
3160 optr = ptr = strdup(p);
3161 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
3163 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
3164 errx(EX_DATAERR, "Incorrect MAC address");
3165 bcopy(mac, addr, ETHER_ADDR_LEN);
3167 errx(EX_DATAERR, "Incorrect MAC address");
3169 if (ptr != NULL) { /* we have mask? */
3170 if (p[ptr - optr - 1] == '/') { /* mask len */
3171 long ml = strtol(ptr, &ap, 10);
3172 if (*ap != 0 || ml > ETHER_ADDR_LEN * 8 || ml < 0)
3173 errx(EX_DATAERR, "Incorrect mask length");
3174 for (i = 0; ml > 0 && i < ETHER_ADDR_LEN; ml -= 8, i++)
3175 mask[i] = (ml >= 8) ? 0xff: (~0) << (8 - ml);
3178 if (strspn(ptr, macset) != l ||
3179 (mac = ether_aton(ptr)) == NULL)
3180 errx(EX_DATAERR, "Incorrect mask");
3181 bcopy(mac, mask, ETHER_ADDR_LEN);
3183 } else { /* default mask: ff:ff:ff:ff:ff:ff */
3184 for (i = 0; i < ETHER_ADDR_LEN; i++)
3187 for (i = 0; i < ETHER_ADDR_LEN; i++)
3194 * helper function, updates the pointer to cmd with the length
3195 * of the current command, and also cleans up the first word of
3196 * the new command in case it has been clobbered before.
3199 next_cmd(ipfw_insn *cmd, int *len)
3202 CHECK_LENGTH(*len, 0);
3204 bzero(cmd, sizeof(*cmd));
3209 * Takes arguments and copies them into a comment
3212 fill_comment(ipfw_insn *cmd, char **av, int cblen)
3215 char *p = (char *)(cmd + 1);
3217 cmd->opcode = O_NOP;
3218 cmd->len = (cmd->len & (F_NOT | F_OR));
3220 /* Compute length of comment string. */
3221 for (i = 0, l = 0; av[i] != NULL; i++)
3222 l += strlen(av[i]) + 1;
3227 "comment too long (max 80 chars)");
3229 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
3232 for (i = 0; av[i] != NULL; i++) {
3241 * A function to fill simple commands of size 1.
3242 * Existing flags are preserved.
3245 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
3247 cmd->opcode = opcode;
3248 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
3253 * Fetch and add the MAC address and type, with masks. This generates one or
3254 * two microinstructions, and returns the pointer to the last one.
3257 add_mac(ipfw_insn *cmd, char *av[], int cblen)
3261 if ( ( av[0] == NULL ) || ( av[1] == NULL ) )
3262 errx(EX_DATAERR, "MAC dst src");
3264 cmd->opcode = O_MACADDR2;
3265 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
3268 mac = (ipfw_insn_mac *)cmd;
3269 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
3270 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
3271 &(mac->mask[ETHER_ADDR_LEN])); /* src */
3276 add_mactype(ipfw_insn *cmd, char *av, int cblen)
3279 errx(EX_DATAERR, "missing MAC type");
3280 if (strcmp(av, "any") != 0) { /* we have a non-null type */
3281 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE,
3283 cmd->opcode = O_MAC_TYPE;
3290 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
3292 struct protoent *pe;
3296 proto = strtol(av, &ep, 10);
3297 if (*ep != '\0' || proto <= 0) {
3298 if ((pe = getprotobyname(av)) == NULL)
3300 proto = pe->p_proto;
3303 fill_cmd(cmd, O_PROTO, 0, proto);
3309 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
3311 u_char proto = IPPROTO_IP;
3313 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3314 ; /* do not set O_IP4 nor O_IP6 */
3315 else if (strcmp(av, "ip4") == 0)
3316 /* explicit "just IPv4" rule */
3317 fill_cmd(cmd, O_IP4, 0, 0);
3318 else if (strcmp(av, "ip6") == 0) {
3319 /* explicit "just IPv6" rule */
3320 proto = IPPROTO_IPV6;
3321 fill_cmd(cmd, O_IP6, 0, 0);
3323 return add_proto0(cmd, av, protop);
3330 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
3332 u_char proto = IPPROTO_IP;
3334 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
3335 ; /* do not set O_IP4 nor O_IP6 */
3336 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
3337 /* explicit "just IPv4" rule */
3338 fill_cmd(cmd, O_IP4, 0, 0);
3339 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
3340 /* explicit "just IPv6" rule */
3341 proto = IPPROTO_IPV6;
3342 fill_cmd(cmd, O_IP6, 0, 0);
3344 return add_proto0(cmd, av, protop);
3351 add_srcip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3353 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3354 if (cmd->opcode == O_IP_DST_SET) /* set */
3355 cmd->opcode = O_IP_SRC_SET;
3356 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3357 cmd->opcode = O_IP_SRC_LOOKUP;
3358 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3359 cmd->opcode = O_IP_SRC_ME;
3360 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3361 cmd->opcode = O_IP_SRC;
3362 else /* addr/mask */
3363 cmd->opcode = O_IP_SRC_MASK;
3368 add_dstip(ipfw_insn *cmd, char *av, int cblen, struct tidx *tstate)
3370 fill_ip((ipfw_insn_ip *)cmd, av, cblen, tstate);
3371 if (cmd->opcode == O_IP_DST_SET) /* set */
3373 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
3375 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
3376 cmd->opcode = O_IP_DST_ME;
3377 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
3378 cmd->opcode = O_IP_DST;
3379 else /* addr/mask */
3380 cmd->opcode = O_IP_DST_MASK;
3384 static struct _s_x f_reserved_keywords[] = {
3387 { "diverted", TOK_OR },
3388 { "dst-port", TOK_OR },
3389 { "src-port", TOK_OR },
3390 { "established", TOK_OR },
3391 { "keep-state", TOK_OR },
3393 { "icmptypes", TOK_OR },
3401 { NULL, 0 } /* terminator */
3405 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode, int cblen)
3408 if (match_token(f_reserved_keywords, av) != -1)
3411 if (fill_newports((ipfw_insn_u16 *)cmd, av, proto, cblen)) {
3412 /* XXX todo: check that we have a protocol with ports */
3413 cmd->opcode = opcode;
3420 add_src(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3423 char *host, *ch, buf[INET6_ADDRSTRLEN];
3424 ipfw_insn *ret = NULL;
3427 /* Copy first address in set if needed */
3428 if ((ch = strpbrk(av, "/,")) != NULL) {
3430 strlcpy(buf, av, sizeof(buf));
3431 if (len < sizeof(buf))
3437 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3438 inet_pton(AF_INET6, host, &a) == 1)
3439 ret = add_srcip6(cmd, av, cblen);
3440 /* XXX: should check for IPv4, not !IPv6 */
3441 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3442 inet_pton(AF_INET6, host, &a) != 1))
3443 ret = add_srcip(cmd, av, cblen, tstate);
3444 if (ret == NULL && strcmp(av, "any") != 0)
3451 add_dst(ipfw_insn *cmd, char *av, u_char proto, int cblen, struct tidx *tstate)
3454 char *host, *ch, buf[INET6_ADDRSTRLEN];
3455 ipfw_insn *ret = NULL;
3458 /* Copy first address in set if needed */
3459 if ((ch = strpbrk(av, "/,")) != NULL) {
3461 strlcpy(buf, av, sizeof(buf));
3462 if (len < sizeof(buf))
3468 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
3469 inet_pton(AF_INET6, host, &a) == 1)
3470 ret = add_dstip6(cmd, av, cblen);
3471 /* XXX: should check for IPv4, not !IPv6 */
3472 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
3473 inet_pton(AF_INET6, host, &a) != 1))
3474 ret = add_dstip(cmd, av, cblen, tstate);
3475 if (ret == NULL && strcmp(av, "any") != 0)
3482 * Parse arguments and assemble the microinstructions which make up a rule.
3483 * Rules are added into the 'rulebuf' and then copied in the correct order
3484 * into the actual rule.
3486 * The syntax for a rule starts with the action, followed by
3487 * optional action parameters, and the various match patterns.
3488 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
3489 * (generated if the rule includes a keep-state option), then the
3490 * various match patterns, log/altq actions, and the actual action.
3494 compile_rule(char *av[], uint32_t *rbuf, int *rbufsize, struct tidx *tstate)
3497 * rules are added into the 'rulebuf' and then copied in
3498 * the correct order into the actual rule.
3499 * Some things that need to go out of order (prob, action etc.)
3502 static uint32_t actbuf[255], cmdbuf[255];
3503 int rblen, ablen, cblen;
3505 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
3506 ipfw_insn *first_cmd; /* first match pattern */
3508 struct ip_fw_rule *rule;
3511 * various flags used to record that we entered some fields.
3513 ipfw_insn *have_state = NULL; /* check-state or keep-state */
3514 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
3519 int open_par = 0; /* open parenthesis ( */
3521 /* proto is here because it is used to fetch ports */
3522 u_char proto = IPPROTO_IP; /* default protocol */
3524 double match_prob = 1; /* match probability, default is always match */
3526 bzero(actbuf, sizeof(actbuf)); /* actions go here */
3527 bzero(cmdbuf, sizeof(cmdbuf));
3528 bzero(rbuf, *rbufsize);
3530 rule = (struct ip_fw_rule *)rbuf;
3531 cmd = (ipfw_insn *)cmdbuf;
3532 action = (ipfw_insn *)actbuf;
3534 rblen = *rbufsize / sizeof(uint32_t);
3535 rblen -= sizeof(struct ip_fw_rule) / sizeof(uint32_t);
3536 ablen = sizeof(actbuf) / sizeof(actbuf[0]);
3537 cblen = sizeof(cmdbuf) / sizeof(cmdbuf[0]);
3538 cblen -= F_INSN_SIZE(ipfw_insn_u32) + 1;
3540 #define CHECK_RBUFLEN(len) { CHECK_LENGTH(rblen, len); rblen -= len; }
3541 #define CHECK_ACTLEN CHECK_LENGTH(ablen, action->len)
3545 /* [rule N] -- Rule number optional */
3546 if (av[0] && isdigit(**av)) {
3547 rule->rulenum = atoi(*av);
3551 /* [set N] -- set number (0..RESVD_SET), optional */
3552 if (av[0] && av[1] && _substrcmp(*av, "set") == 0) {
3553 int set = strtoul(av[1], NULL, 10);
3554 if (set < 0 || set > RESVD_SET)
3555 errx(EX_DATAERR, "illegal set %s", av[1]);
3561 /* [prob D] -- match probability, optional */
3562 if (av[0] && av[1] && _substrcmp(*av, "prob") == 0) {
3563 match_prob = strtod(av[1], NULL);
3565 if (match_prob <= 0 || match_prob > 1)
3566 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
3570 /* action -- mandatory */
3571 NEED1("missing action");
3572 i = match_token(rule_actions, *av);
3574 action->len = 1; /* default */
3577 case TOK_CHECKSTATE:
3578 have_state = action;
3579 action->opcode = O_CHECK_STATE;
3583 action->opcode = O_ACCEPT;
3587 action->opcode = O_DENY;
3592 action->opcode = O_REJECT;
3593 action->arg1 = ICMP_UNREACH_HOST;
3597 action->opcode = O_REJECT;
3598 action->arg1 = ICMP_REJECT_RST;
3602 action->opcode = O_UNREACH6;
3603 action->arg1 = ICMP6_UNREACH_RST;
3607 action->opcode = O_REJECT;
3608 NEED1("missing reject code");
3609 fill_reject_code(&action->arg1, *av);
3614 action->opcode = O_UNREACH6;
3615 NEED1("missing unreach code");
3616 fill_unreach6_code(&action->arg1, *av);
3621 action->opcode = O_COUNT;
3625 action->opcode = O_NAT;
3626 action->len = F_INSN_SIZE(ipfw_insn_nat);
3628 if (*av != NULL && _substrcmp(*av, "global") == 0) {
3635 action->opcode = O_QUEUE;
3638 action->opcode = O_PIPE;
3641 action->opcode = O_SKIPTO;
3644 action->opcode = O_NETGRAPH;
3647 action->opcode = O_NGTEE;
3650 action->opcode = O_DIVERT;
3653 action->opcode = O_TEE;
3656 action->opcode = O_CALLRETURN;
3659 errx(EX_USAGE, "missing argument for %s", *(av - 1));
3660 if (isdigit(**av)) {
3661 action->arg1 = strtoul(*av, NULL, 10);
3662 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
3663 errx(EX_DATAERR, "illegal argument for %s",
3665 } else if (_substrcmp(*av, "tablearg") == 0) {
3666 action->arg1 = IP_FW_TARG;
3667 } else if (i == TOK_DIVERT || i == TOK_TEE) {
3670 s = getservbyname(av[0], "divert");
3672 action->arg1 = ntohs(s->s_port);
3674 errx(EX_DATAERR, "illegal divert/tee port");
3676 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
3682 * Locate the address-port separator (':' or ',').
3683 * Could be one of the following:
3687 * IPv6 w:x:y::z,port
3688 * The ':' can only be used with hostname and IPv4 address.
3689 * XXX-BZ Should we also support [w:x:y::z]:port?
3691 struct sockaddr_storage result;
3692 struct addrinfo *res;
3695 u_short port_number;
3697 NEED1("missing forward address[:port]");
3700 * locate the address-port separator (':' or ',')
3702 s = strchr(*av, ',');
3704 /* Distinguish between IPv4:port and IPv6 cases. */
3705 s = strchr(*av, ':');
3706 if (s && strchr(s+1, ':'))
3707 s = NULL; /* no port */
3712 /* Terminate host portion and set s to start of port. */
3714 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
3717 "illegal forwarding port ``%s''", s);
3718 port_number = (u_short)i;
3721 if (_substrcmp(*av, "tablearg") == 0) {
3723 ((struct sockaddr_in*)&result)->sin_addr.s_addr =
3727 * Resolve the host name or address to a family and a
3728 * network representation of the address.
3730 if (getaddrinfo(*av, NULL, NULL, &res))
3731 errx(EX_DATAERR, NULL);
3732 /* Just use the first host in the answer. */
3733 family = res->ai_family;
3734 memcpy(&result, res->ai_addr, res->ai_addrlen);
3738 if (family == PF_INET) {
3739 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
3741 action->opcode = O_FORWARD_IP;
3742 action->len = F_INSN_SIZE(ipfw_insn_sa);
3746 * In the kernel we assume AF_INET and use only
3747 * sin_port and sin_addr. Remember to set sin_len as
3748 * the routing code seems to use it too.
3750 p->sa.sin_len = sizeof(struct sockaddr_in);
3751 p->sa.sin_family = AF_INET;
3752 p->sa.sin_port = port_number;
3753 p->sa.sin_addr.s_addr =
3754 ((struct sockaddr_in *)&result)->sin_addr.s_addr;
3755 } else if (family == PF_INET6) {
3756 ipfw_insn_sa6 *p = (ipfw_insn_sa6 *)action;
3758 action->opcode = O_FORWARD_IP6;
3759 action->len = F_INSN_SIZE(ipfw_insn_sa6);
3762 p->sa.sin6_len = sizeof(struct sockaddr_in6);
3763 p->sa.sin6_family = AF_INET6;
3764 p->sa.sin6_port = port_number;
3765 p->sa.sin6_flowinfo = 0;
3766 p->sa.sin6_scope_id =
3767 ((struct sockaddr_in6 *)&result)->sin6_scope_id;
3768 bcopy(&((struct sockaddr_in6*)&result)->sin6_addr,
3769 &p->sa.sin6_addr, sizeof(p->sa.sin6_addr));
3771 errx(EX_DATAERR, "Invalid address family in forward action");
3777 /* pretend it is a 'count' rule followed by the comment */
3778 action->opcode = O_COUNT;
3779 av--; /* go back... */
3785 size_t intsize = sizeof(int);
3787 action->opcode = O_SETFIB;
3788 NEED1("missing fib number");
3789 if (_substrcmp(*av, "tablearg") == 0) {
3790 action->arg1 = IP_FW_TARG;
3792 action->arg1 = strtoul(*av, NULL, 10);
3793 if (sysctlbyname("net.fibs", &numfibs, &intsize,
3795 errx(EX_DATAERR, "fibs not suported.\n");
3796 if (action->arg1 >= numfibs) /* Temporary */
3797 errx(EX_DATAERR, "fib too large.\n");
3798 /* Add high-order bit to fib to make room for tablearg*/
3799 action->arg1 |= 0x8000;
3809 action->opcode = O_SETDSCP;
3810 NEED1("missing DSCP code");
3811 if (_substrcmp(*av, "tablearg") == 0) {
3812 action->arg1 = IP_FW_TARG;
3813 } else if (isalpha(*av[0])) {
3814 if ((code = match_token(f_ipdscp, *av)) == -1)
3815 errx(EX_DATAERR, "Unknown DSCP code");
3816 action->arg1 = code;
3818 action->arg1 = strtoul(*av, NULL, 10);
3819 /* Add high-order bit to DSCP to make room for tablearg */
3820 if (action->arg1 != IP_FW_TARG)
3821 action->arg1 |= 0x8000;
3827 action->opcode = O_REASS;
3831 fill_cmd(action, O_CALLRETURN, F_NOT, 0);
3835 errx(EX_DATAERR, "invalid action %s\n", av[-1]);
3837 action = next_cmd(action, &ablen);
3840 * [altq queuename] -- altq tag, optional
3841 * [log [logamount N]] -- log, optional
3843 * If they exist, it go first in the cmdbuf, but then it is
3844 * skipped in the copy section to the end of the buffer.
3846 while (av[0] != NULL && (i = match_token(rule_action_params, *av)) != -1) {
3851 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
3856 "log cannot be specified more than once");
3857 have_log = (ipfw_insn *)c;
3858 cmd->len = F_INSN_SIZE(ipfw_insn_log);
3860 cmd->opcode = O_LOG;
3861 if (av[0] && _substrcmp(*av, "logamount") == 0) {
3863 NEED1("logamount requires argument");
3867 "logamount must be positive");
3871 len = sizeof(c->max_log);
3872 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
3873 &c->max_log, &len, NULL, 0) == -1) {
3878 errx(1, "sysctlbyname(\"%s\")",
3879 "net.inet.ip.fw.verbose_limit");
3888 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
3890 NEED1("missing altq queue name");
3893 "altq cannot be specified more than once");
3894 have_altq = (ipfw_insn *)a;
3895 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
3897 cmd->opcode = O_ALTQ;
3898 a->qid = altq_name_to_qid(*av);
3909 errx(EX_USAGE, "tag and untag cannot be "
3910 "specified more than once");
3911 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX, i,
3912 rule_action_params);
3914 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
3922 cmd = next_cmd(cmd, &cblen);
3925 if (have_state) /* must be a check-state, we are done */
3928 #define OR_START(target) \
3929 if (av[0] && (*av[0] == '(' || *av[0] == '{')) { \
3931 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
3934 if ( (av[0])[1] == '\0') { \
3945 strcmp(*av, ")") == 0 || \
3946 strcmp(*av, "}") == 0)) { \
3951 errx(EX_USAGE, "missing \")\"\n"); \
3955 if (av[0] && _substrcmp(*av, "not") == 0) { \
3956 if (cmd->len & F_NOT) \
3957 errx(EX_USAGE, "double \"not\" not allowed\n"); \
3958 cmd->len |= F_NOT; \
3962 #define OR_BLOCK(target) \
3963 if (av[0] && _substrcmp(*av, "or") == 0) { \
3964 if (prev == NULL || open_par == 0) \
3965 errx(EX_DATAERR, "invalid OR block"); \
3966 prev->len |= F_OR; \
3976 * MAC addresses, optional.
3977 * If we have this, we skip the part "proto from src to dst"
3978 * and jump straight to the option parsing.
3981 NEED1("missing protocol");
3982 if (_substrcmp(*av, "MAC") == 0 ||
3983 _substrcmp(*av, "mac") == 0) {
3984 av++; /* the "MAC" keyword */
3985 add_mac(cmd, av); /* exits in case of errors */
3986 cmd = next_cmd(cmd);
3987 av += 2; /* dst-mac and src-mac */
3989 NEED1("missing mac type");
3990 if (add_mactype(cmd, av[0]))
3991 cmd = next_cmd(cmd);
3992 av++; /* any or mac-type */
3998 * protocol, mandatory
4000 OR_START(get_proto);
4002 NEED1("missing protocol");
4003 if (add_proto_compat(cmd, *av, &proto)) {
4005 if (F_LEN(cmd) != 0) {
4007 cmd = next_cmd(cmd, &cblen);
4009 } else if (first_cmd != cmd) {
4010 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
4013 OR_BLOCK(get_proto);
4018 if ((av[0] == NULL) || _substrcmp(*av, "from") != 0)
4019 errx(EX_USAGE, "missing ``from''");
4023 * source IP, mandatory
4025 OR_START(source_ip);
4026 NOT_BLOCK; /* optional "not" */
4027 NEED1("missing source address");
4028 if (add_src(cmd, *av, proto, cblen, tstate)) {
4030 if (F_LEN(cmd) != 0) { /* ! any */
4032 cmd = next_cmd(cmd, &cblen);
4035 errx(EX_USAGE, "bad source address %s", *av);
4036 OR_BLOCK(source_ip);
4039 * source ports, optional
4041 NOT_BLOCK; /* optional "not" */
4042 if ( av[0] != NULL ) {
4043 if (_substrcmp(*av, "any") == 0 ||
4044 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4046 if (F_LEN(cmd) != 0)
4047 cmd = next_cmd(cmd, &cblen);
4054 if ( (av[0] == NULL) || _substrcmp(*av, "to") != 0 )
4055 errx(EX_USAGE, "missing ``to''");
4059 * destination, mandatory
4062 NOT_BLOCK; /* optional "not" */
4063 NEED1("missing dst address");
4064 if (add_dst(cmd, *av, proto, cblen, tstate)) {
4066 if (F_LEN(cmd) != 0) { /* ! any */
4068 cmd = next_cmd(cmd, &cblen);
4071 errx( EX_USAGE, "bad destination address %s", *av);
4075 * dest. ports, optional
4077 NOT_BLOCK; /* optional "not" */
4079 if (_substrcmp(*av, "any") == 0 ||
4080 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4082 if (F_LEN(cmd) != 0)
4083 cmd = next_cmd(cmd, &cblen);
4088 if (av[0] && first_cmd == cmd) {
4090 * nothing specified so far, store in the rule to ease
4093 rule->flags |= IPFW_RULE_NOOPT;
4096 while ( av[0] != NULL ) {
4098 ipfw_insn_u32 *cmd32; /* alias for cmd */
4101 cmd32 = (ipfw_insn_u32 *)cmd;
4103 if (*s == '!') { /* alternate syntax for NOT */
4104 if (cmd->len & F_NOT)
4105 errx(EX_USAGE, "double \"not\" not allowed\n");
4109 i = match_token(rule_options, s);
4113 if (cmd->len & F_NOT)
4114 errx(EX_USAGE, "double \"not\" not allowed\n");
4119 if (open_par == 0 || prev == NULL)
4120 errx(EX_USAGE, "invalid \"or\" block\n");
4124 case TOK_STARTBRACE:
4126 errx(EX_USAGE, "+nested \"(\" not allowed\n");
4132 errx(EX_USAGE, "+missing \")\"\n");
4138 fill_cmd(cmd, O_IN, 0, 0);
4142 cmd->len ^= F_NOT; /* toggle F_NOT */
4143 fill_cmd(cmd, O_IN, 0, 0);
4147 fill_cmd(cmd, O_DIVERTED, 0, 3);
4150 case TOK_DIVERTEDLOOPBACK:
4151 fill_cmd(cmd, O_DIVERTED, 0, 1);
4154 case TOK_DIVERTEDOUTPUT:
4155 fill_cmd(cmd, O_DIVERTED, 0, 2);
4159 fill_cmd(cmd, O_FRAG, 0, 0);
4163 fill_cmd(cmd, O_LAYER2, 0, 0);
4169 NEED1("recv, xmit, via require interface name"
4171 fill_iface((ipfw_insn_if *)cmd, av[0], cblen, tstate);
4173 if (F_LEN(cmd) == 0) /* not a valid address */
4176 cmd->opcode = O_XMIT;
4177 else if (i == TOK_RECV)
4178 cmd->opcode = O_RECV;
4179 else if (i == TOK_VIA)
4180 cmd->opcode = O_VIA;
4184 NEED1("icmptypes requires list of types");
4185 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
4189 case TOK_ICMP6TYPES:
4190 NEED1("icmptypes requires list of types");
4191 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av, cblen);
4196 NEED1("ipttl requires TTL");
4197 if (strpbrk(*av, "-,")) {
4198 if (!add_ports(cmd, *av, 0, O_IPTTL, cblen))
4199 errx(EX_DATAERR, "invalid ipttl %s", *av);
4201 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
4206 NEED1("ipid requires id");
4207 if (strpbrk(*av, "-,")) {
4208 if (!add_ports(cmd, *av, 0, O_IPID, cblen))
4209 errx(EX_DATAERR, "invalid ipid %s", *av);
4211 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
4216 NEED1("iplen requires length");
4217 if (strpbrk(*av, "-,")) {
4218 if (!add_ports(cmd, *av, 0, O_IPLEN, cblen))
4219 errx(EX_DATAERR, "invalid ip len %s", *av);
4221 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
4226 NEED1("ipver requires version");
4227 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
4231 case TOK_IPPRECEDENCE:
4232 NEED1("ipprecedence requires value");
4233 fill_cmd(cmd, O_IPPRECEDENCE, 0,
4234 (strtoul(*av, NULL, 0) & 7) << 5);
4239 NEED1("missing DSCP code");
4240 fill_dscp(cmd, *av, cblen);
4245 NEED1("missing argument for ipoptions");
4246 fill_flags_cmd(cmd, O_IPOPT, f_ipopts, *av);
4251 NEED1("missing argument for iptos");
4252 fill_flags_cmd(cmd, O_IPTOS, f_iptos, *av);
4257 NEED1("uid requires argument");
4263 cmd->opcode = O_UID;
4264 uid = strtoul(*av, &end, 0);
4265 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
4267 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
4268 cmd32->d[0] = pwd->pw_uid;
4269 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4275 NEED1("gid requires argument");
4281 cmd->opcode = O_GID;
4282 gid = strtoul(*av, &end, 0);
4283 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
4285 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
4286 cmd32->d[0] = grp->gr_gid;
4287 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4293 NEED1("jail requires argument");
4298 cmd->opcode = O_JAIL;
4299 jid = (int)strtol(*av, &end, 0);
4300 if (jid < 0 || *end != '\0')
4301 errx(EX_DATAERR, "jail requires prison ID");
4302 cmd32->d[0] = (uint32_t)jid;
4303 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
4309 fill_cmd(cmd, O_ESTAB, 0, 0);
4313 fill_cmd(cmd, O_TCPFLAGS, 0,
4314 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
4317 case TOK_TCPDATALEN:
4318 NEED1("tcpdatalen requires length");
4319 if (strpbrk(*av, "-,")) {
4320 if (!add_ports(cmd, *av, 0, O_TCPDATALEN, cblen))
4321 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
4323 fill_cmd(cmd, O_TCPDATALEN, 0,
4324 strtoul(*av, NULL, 0));
4329 NEED1("missing argument for tcpoptions");
4330 fill_flags_cmd(cmd, O_TCPOPTS, f_tcpopts, *av);
4336 NEED1("tcpseq/tcpack requires argument");
4337 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
4338 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
4339 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
4344 NEED1("tcpwin requires length");
4345 if (strpbrk(*av, "-,")) {
4346 if (!add_ports(cmd, *av, 0, O_TCPWIN, cblen))
4347 errx(EX_DATAERR, "invalid tcpwin len %s", *av);
4349 fill_cmd(cmd, O_TCPWIN, 0,
4350 strtoul(*av, NULL, 0));
4355 NEED1("missing argument for tcpflags");
4356 cmd->opcode = O_TCPFLAGS;
4357 fill_flags_cmd(cmd, O_TCPFLAGS, f_tcpflags, *av);
4363 errx(EX_USAGE, "keep-state cannot be part "
4366 errx(EX_USAGE, "only one of keep-state "
4367 "and limit is allowed");
4369 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
4373 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
4378 "limit cannot be part of an or block");
4380 errx(EX_USAGE, "only one of keep-state and "
4381 "limit is allowed");
4384 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
4386 cmd->opcode = O_LIMIT;
4387 c->limit_mask = c->conn_limit = 0;
4389 while ( av[0] != NULL ) {
4390 if ((val = match_token(limit_masks, *av)) <= 0)
4392 c->limit_mask |= val;
4396 if (c->limit_mask == 0)
4397 errx(EX_USAGE, "limit: missing limit mask");
4399 GET_UINT_ARG(c->conn_limit, IPFW_ARG_MIN, IPFW_ARG_MAX,
4400 TOK_LIMIT, rule_options);
4407 NEED1("missing protocol");
4408 if (add_proto(cmd, *av, &proto)) {
4411 errx(EX_DATAERR, "invalid protocol ``%s''",
4416 NEED1("missing source IP");
4417 if (add_srcip(cmd, *av, cblen, tstate)) {
4423 NEED1("missing destination IP");
4424 if (add_dstip(cmd, *av, cblen, tstate)) {
4430 NEED1("missing source IP6");
4431 if (add_srcip6(cmd, *av, cblen)) {
4437 NEED1("missing destination IP6");
4438 if (add_dstip6(cmd, *av, cblen)) {
4444 NEED1("missing source port");
4445 if (_substrcmp(*av, "any") == 0 ||
4446 add_ports(cmd, *av, proto, O_IP_SRCPORT, cblen)) {
4449 errx(EX_DATAERR, "invalid source port %s", *av);
4453 NEED1("missing destination port");
4454 if (_substrcmp(*av, "any") == 0 ||
4455 add_ports(cmd, *av, proto, O_IP_DSTPORT, cblen)) {
4458 errx(EX_DATAERR, "invalid destination port %s",
4463 if (add_mac(cmd, av, cblen))
4468 NEED1("missing mac type");
4469 if (!add_mactype(cmd, *av, cblen))
4470 errx(EX_DATAERR, "invalid mac type %s", *av);
4474 case TOK_VERREVPATH:
4475 fill_cmd(cmd, O_VERREVPATH, 0, 0);
4478 case TOK_VERSRCREACH:
4479 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
4483 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
4487 fill_cmd(cmd, O_IPSEC, 0, 0);
4491 fill_cmd(cmd, O_IP6, 0, 0);
4495 fill_cmd(cmd, O_IP4, 0, 0);
4499 fill_ext6hdr( cmd, *av );
4504 if (proto != IPPROTO_IPV6 )
4505 errx( EX_USAGE, "flow-id filter is active "
4506 "only for ipv6 protocol\n");
4507 fill_flow6( (ipfw_insn_u32 *) cmd, *av, cblen);
4512 fill_comment(cmd, av, cblen);
4517 if (av[0] && strpbrk(*av, "-,")) {
4518 if (!add_ports(cmd, *av, 0, O_TAGGED, cblen))
4519 errx(EX_DATAERR, "tagged: invalid tag"
4525 GET_UINT_ARG(tag, IPFW_ARG_MIN, IPFW_ARG_MAX,
4526 TOK_TAGGED, rule_options);
4527 fill_cmd(cmd, O_TAGGED, 0, tag);
4533 NEED1("fib requires fib number");
4534 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
4538 fill_cmd(cmd, O_SOCKARG, 0, 0);
4542 ipfw_insn_u32 *c = (ipfw_insn_u32 *)cmd;
4545 if (!av[0] || !av[1])
4546 errx(EX_USAGE, "format: lookup argument tablenum");
4547 cmd->opcode = O_IP_DST_LOOKUP;
4548 cmd->len |= F_INSN_SIZE(ipfw_insn) + 2;
4549 i = match_token(rule_options, *av);
4550 for (j = 0; lookup_key[j] >= 0 ; j++) {
4551 if (i == lookup_key[j])
4554 if (lookup_key[j] <= 0)
4555 errx(EX_USAGE, "format: cannot lookup on %s", *av);
4556 __PAST_END(c->d, 1) = j; // i converted to option
4559 if ((j = pack_table(tstate, *av)) == 0)
4560 errx(EX_DATAERR, "Invalid table name: %s", *av);
4567 NEED1("missing table name");
4568 if (strncmp(*av, "table(", 6) != 0)
4570 "enclose table name into \"table()\"");
4571 fill_table(cmd, *av, O_IP_FLOW_LOOKUP, tstate);
4576 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
4578 if (F_LEN(cmd) > 0) { /* prepare to advance */
4580 cmd = next_cmd(cmd, &cblen);
4586 * Now copy stuff into the rule.
4587 * If we have a keep-state option, the first instruction
4588 * must be a PROBE_STATE (which is generated here).
4589 * If we have a LOG option, it was stored as the first command,
4590 * and now must be moved to the top of the action part.
4592 dst = (ipfw_insn *)rule->cmd;
4595 * First thing to write into the command stream is the match probability.
4597 if (match_prob != 1) { /* 1 means always match */
4598 dst->opcode = O_PROB;
4600 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
4605 * generate O_PROBE_STATE if necessary
4607 if (have_state && have_state->opcode != O_CHECK_STATE) {
4608 fill_cmd(dst, O_PROBE_STATE, 0, 0);
4609 dst = next_cmd(dst, &rblen);
4612 /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
4613 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
4617 switch (src->opcode) {
4625 bcopy(src, dst, i * sizeof(uint32_t));
4631 * put back the have_state command as last opcode
4633 if (have_state && have_state->opcode != O_CHECK_STATE) {
4634 i = F_LEN(have_state);
4636 bcopy(have_state, dst, i * sizeof(uint32_t));
4640 * start action section
4642 rule->act_ofs = dst - rule->cmd;
4644 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
4646 i = F_LEN(have_log);
4648 bcopy(have_log, dst, i * sizeof(uint32_t));
4652 i = F_LEN(have_altq);
4654 bcopy(have_altq, dst, i * sizeof(uint32_t));
4658 i = F_LEN(have_tag);
4660 bcopy(have_tag, dst, i * sizeof(uint32_t));
4665 * copy all other actions
4667 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
4670 bcopy(src, dst, i * sizeof(uint32_t));
4674 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
4675 *rbufsize = (char *)dst - (char *)rule;
4679 compare_ntlv(const void *_a, const void *_b)
4681 ipfw_obj_ntlv *a, *b;
4683 a = (ipfw_obj_ntlv *)_a;
4684 b = (ipfw_obj_ntlv *)_b;
4686 if (a->set < b->set)
4688 else if (a->set > b->set)
4691 if (a->idx < b->idx)
4693 else if (a->idx > b->idx)
4696 if (a->head.type < b->head.type)
4698 else if (a->head.type > b->head.type)
4705 * Provide kernel with sorted list of referenced objects
4708 object_sort_ctlv(ipfw_obj_ctlv *ctlv)
4711 qsort(ctlv + 1, ctlv->count, ctlv->objsize, compare_ntlv);
4719 compare_object_kntlv(const void *k, const void *v)
4721 ipfw_obj_ntlv *ntlv;
4722 struct object_kt key;
4724 key = *((struct object_kt *)k);
4725 ntlv = (ipfw_obj_ntlv *)v;
4727 if (key.uidx < ntlv->idx)
4729 else if (key.uidx > ntlv->idx)
4732 if (key.type < ntlv->head.type)
4734 else if (key.type > ntlv->head.type)
4741 * Finds object name in @ctlv by @idx and @type.
4742 * Uses the following facts:
4743 * 1) All TLVs are the same size
4744 * 2) Kernel implementation provides already sorted list.
4746 * Returns table name or NULL.
4749 object_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx, uint16_t type)
4751 ipfw_obj_ntlv *ntlv;
4752 struct object_kt key;
4757 ntlv = bsearch(&key, (ctlv + 1), ctlv->count, ctlv->objsize,
4758 compare_object_kntlv);
4761 return (ntlv->name);
4767 table_search_ctlv(ipfw_obj_ctlv *ctlv, uint16_t idx)
4770 return (object_search_ctlv(ctlv, idx, IPFW_TLV_TBL_NAME));
4774 * Adds one or more rules to ipfw chain.
4779 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional *1)
4780 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ] (*2) (*3)
4785 * [ ipfw_obj_ctlv(IPFW_TLV_TBL_LIST) ipfw_obj_ntlv x N ] (optional)
4786 * [ ipfw_obj_ctlv(IPFW_TLV_RULE_LIST) [ ip_fw_rule ip_fw_insn ] x N ]
4789 * Rules in reply are modified to store their actual ruleset number.
4791 * (*1) TLVs inside IPFW_TLV_TBL_LIST needs to be sorted ascending
4792 * accoring to their idx field and there has to be no duplicates.
4793 * (*2) Numbered rules inside IPFW_TLV_RULE_LIST needs to be sorted ascending.
4794 * (*3) Each ip_fw structure needs to be aligned to u64 boundary.
4797 ipfw_add(char *av[])
4799 uint32_t rulebuf[1024];
4800 int rbufsize, default_off, tlen, rlen;
4803 struct ip_fw_rule *rule;
4805 ip_fw3_opheader *op3;
4806 ipfw_obj_ctlv *ctlv, *tstate;
4808 rbufsize = sizeof(rulebuf);
4809 memset(rulebuf, 0, rbufsize);
4810 memset(&ts, 0, sizeof(ts));
4812 /* Optimize case with no tables */
4813 default_off = sizeof(ipfw_obj_ctlv) + sizeof(ip_fw3_opheader);
4814 op3 = (ip_fw3_opheader *)rulebuf;
4815 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
4816 rule = (struct ip_fw_rule *)(ctlv + 1);
4817 rbufsize -= default_off;
4819 compile_rule(av, (uint32_t *)rule, &rbufsize, &ts);
4820 /* Align rule size to u64 boundary */
4821 rlen = roundup2(rbufsize, sizeof(uint64_t));
4826 if (ts.count != 0) {
4827 /* Some tables. We have to alloc more data */
4828 tlen = ts.count * sizeof(ipfw_obj_ntlv);
4829 sz = default_off + sizeof(ipfw_obj_ctlv) + tlen + rlen;
4831 if ((tbuf = calloc(1, sz)) == NULL)
4832 err(EX_UNAVAILABLE, "malloc() failed for IP_FW_ADD");
4833 op3 = (ip_fw3_opheader *)tbuf;
4835 ctlv = (ipfw_obj_ctlv *)(op3 + 1);
4836 ctlv->head.type = IPFW_TLV_TBLNAME_LIST;
4837 ctlv->head.length = sizeof(ipfw_obj_ctlv) + tlen;
4838 ctlv->count = ts.count;
4839 ctlv->objsize = sizeof(ipfw_obj_ntlv);
4840 memcpy(ctlv + 1, ts.idx, tlen);
4841 object_sort_ctlv(ctlv);
4844 ctlv = (ipfw_obj_ctlv *)((caddr_t)ctlv + ctlv->head.length);
4845 ctlv->head.type = IPFW_TLV_RULE_LIST;
4846 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
4848 memcpy(ctlv + 1, rule, rbufsize);
4850 /* Simply add header */
4851 sz = rlen + default_off;
4852 memset(ctlv, 0, sizeof(*ctlv));
4853 ctlv->head.type = IPFW_TLV_RULE_LIST;
4854 ctlv->head.length = sizeof(ipfw_obj_ctlv) + rlen;
4858 if (do_get3(IP_FW_XADD, op3, &sz) != 0)
4859 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_XADD");
4862 struct format_opts sfo;
4864 memset(&sfo, 0, sizeof(sfo));
4865 sfo.tstate = tstate;
4866 sfo.set_mask = (uint32_t)(-1);
4867 bp_alloc(&bp, 4096);
4868 show_static_rule(&co, &sfo, &bp, rule, NULL);
4869 printf("%s", bp.buf);
4881 * clear the counters or the log counters.
4882 * optname has the following values:
4883 * 0 (zero both counters and logging)
4884 * 1 (zero logging only)
4887 ipfw_zero(int ac, char *av[], int optname)
4893 char const *name = optname ? "RESETLOG" : "ZERO";
4895 optname = optname ? IP_FW_XRESETLOG : IP_FW_XZERO;
4896 memset(&rt, 0, sizeof(rt));
4901 /* clear all entries */
4902 rt.flags = IPFW_RCFLAG_ALL;
4903 if (do_range_cmd(optname, &rt) < 0)
4904 err(EX_UNAVAILABLE, "setsockopt(IP_FW_X%s)", name);
4906 printf("%s.\n", optname == IP_FW_XZERO ?
4907 "Accounting cleared":"Logging counts reset");
4914 if (isdigit(**av)) {
4915 arg = strtonum(*av, 0, 0xffff, &errstr);
4918 "invalid rule number %s\n", *av);
4919 rt.start_rule = arg;
4921 rt.flags |= IPFW_RCFLAG_RANGE;
4922 if (co.use_set != 0) {
4923 rt.set = co.use_set - 1;
4924 rt.flags |= IPFW_RCFLAG_SET;
4926 if (do_range_cmd(optname, &rt) != 0) {
4927 warn("rule %u: setsockopt(IP_FW_X%s)",
4929 failed = EX_UNAVAILABLE;
4930 } else if (rt.new_set == 0) {
4931 printf("Entry %d not found\n", arg);
4932 failed = EX_UNAVAILABLE;
4933 } else if (!co.do_quiet)
4934 printf("Entry %d %s.\n", arg,
4935 optname == IP_FW_XZERO ?
4936 "cleared" : "logging count reset");
4938 errx(EX_USAGE, "invalid rule number ``%s''", *av);
4942 if (failed != EX_OK)
4947 ipfw_flush(int force)
4951 if (!force && !co.do_quiet) { /* need to ask user */
4954 printf("Are you sure? [yn] ");
4957 c = toupper(getc(stdin));
4958 while (c != '\n' && getc(stdin) != '\n')
4960 return; /* and do not flush */
4961 } while (c != 'Y' && c != 'N');
4963 if (c == 'N') /* user said no */
4970 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
4971 memset(&rt, 0, sizeof(rt));
4972 if (co.use_set != 0) {
4973 rt.set = co.use_set - 1;
4974 rt.flags = IPFW_RCFLAG_SET;
4976 rt.flags = IPFW_RCFLAG_ALL;
4977 if (do_range_cmd(IP_FW_XDEL, &rt) != 0)
4978 err(EX_UNAVAILABLE, "setsockopt(IP_FW_XDEL)");
4980 printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
4983 static struct _s_x intcmds[] = {
4984 { "talist", TOK_TALIST },
4985 { "iflist", TOK_IFLIST },
4986 { "vlist", TOK_VLIST },
4991 ipfw_internal_handler(int ac, char *av[])
4996 NEED1("internal cmd required");
4998 if ((tcmd = match_token(intcmds, *av)) == -1)
4999 errx(EX_USAGE, "invalid internal sub-cmd: %s", *av);
5003 ipfw_list_tifaces();
5006 ipfw_list_ta(ac, av);
5009 ipfw_list_values(ac, av);
5015 ipfw_get_tracked_ifaces(ipfw_obj_lheader **polh)
5017 ipfw_obj_lheader req, *olh;
5020 memset(&req, 0, sizeof(req));
5023 if (do_get3(IP_FW_XIFLIST, &req.opheader, &sz) != 0) {
5024 if (errno != ENOMEM)
5029 if ((olh = calloc(1, sz)) == NULL)
5033 if (do_get3(IP_FW_XIFLIST, &olh->opheader, &sz) != 0) {
5043 ifinfo_cmp(const void *a, const void *b)
5045 ipfw_iface_info *ia, *ib;
5047 ia = (ipfw_iface_info *)a;
5048 ib = (ipfw_iface_info *)b;
5050 return (stringnum_cmp(ia->ifname, ib->ifname));
5054 * Retrieves table list from kernel,
5055 * optionally sorts it and calls requested function for each table.
5056 * Returns 0 on success.
5061 ipfw_obj_lheader *olh;
5062 ipfw_iface_info *info;
5065 if ((error = ipfw_get_tracked_ifaces(&olh)) != 0)
5066 err(EX_OSERR, "Unable to request ipfw tracked interface list");
5069 qsort(olh + 1, olh->count, olh->objsize, ifinfo_cmp);
5071 info = (ipfw_iface_info *)(olh + 1);
5072 for (i = 0; i < olh->count; i++) {
5073 if (info->flags & IPFW_IFFLAG_RESOLVED)
5074 printf("%s ifindex: %d refcount: %u changes: %u\n",
5075 info->ifname, info->ifindex, info->refcnt,
5078 printf("%s ifindex: unresolved refcount: %u changes: %u\n",
5079 info->ifname, info->refcnt, info->gencnt);
5080 info = (ipfw_iface_info *)((caddr_t)info + olh->objsize);