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/param.h>
25 #include <sys/socket.h>
26 #include <sys/sockio.h>
27 #include <sys/sysctl.h>
30 #include <sys/queue.h>
44 #include <timeconv.h> /* XXX do we need this ? */
50 #define IPFW_INTERNAL /* Access to protected structures in ip_fw.h. */
52 #include <net/ethernet.h>
54 #include <net/if_dl.h>
55 #include <net/pfvar.h>
56 #include <net/route.h> /* def. of struct route */
57 #include <netinet/in.h>
58 #include <netinet/in_systm.h>
59 #include <netinet/ip.h>
60 #include <netinet/ip_icmp.h>
61 #include <netinet/icmp6.h>
62 #include <netinet/ip_fw.h>
63 #include <netinet/ip_dummynet.h>
64 #include <netinet/tcp.h>
65 #include <arpa/inet.h>
69 do_value_as_ip, /* show table value as IP */
70 do_resolv, /* Would try to resolve all */
71 do_time, /* Show time stamps */
72 do_quiet, /* Be quiet in add and flush */
73 do_pipe, /* this cmd refers to a pipe */
74 do_nat, /* Nat configuration. */
75 do_sort, /* field to sort results (0 = no) */
76 do_dynamic, /* display dynamic rules */
77 do_expired, /* display expired dynamic rules */
78 do_compact, /* show rules in compact mode */
79 do_force, /* do not ask for confirmation */
80 use_set, /* work with specified set number */
81 show_sets, /* display rule sets */
82 test_only, /* only check syntax */
83 comment_only, /* only print action and comment */
86 #define IP_MASK_ALL 0xffffffff
88 * the following macro returns an error message if we run out of
91 #define NEED1(msg) {if (!ac) errx(EX_USAGE, msg);}
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) { \
97 arg = IP_FW_TABLEARG; \
105 val = strtol(*av, &end, 10); \
107 if (!isdigit(**av) || *end != '\0' || (val == 0 && errno == EINVAL)) \
108 errx(EX_DATAERR, "%s: invalid argument: %s", \
109 match_value(s_x, tok), *av); \
111 if (errno == ERANGE || val < min || val > 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 (val == IP_FW_TABLEARG) \
116 errx(EX_DATAERR, "%s: illegal argument value: %s", \
117 match_value(s_x, tok), *av); \
122 #define PRINT_UINT_ARG(str, arg) do { \
125 if (arg == IP_FW_TABLEARG) \
126 printf("tablearg"); \
128 printf("%u", (uint32_t)arg); \
132 * _s_x is a structure that stores a string <-> token pairs, used in
133 * various places in the parser. Entries are stored in arrays,
134 * with an entry with s=NULL as terminator.
135 * The search routines are match_token() and match_value().
136 * Often, an element with x=0 contains an error string.
144 static struct _s_x f_tcpflags[] = {
155 static struct _s_x f_tcpopts[] = {
156 { "mss", IP_FW_TCPOPT_MSS },
157 { "maxseg", IP_FW_TCPOPT_MSS },
158 { "window", IP_FW_TCPOPT_WINDOW },
159 { "sack", IP_FW_TCPOPT_SACK },
160 { "ts", IP_FW_TCPOPT_TS },
161 { "timestamp", IP_FW_TCPOPT_TS },
162 { "cc", IP_FW_TCPOPT_CC },
168 * IP options span the range 0 to 255 so we need to remap them
169 * (though in fact only the low 5 bits are significant).
171 static struct _s_x f_ipopts[] = {
172 { "ssrr", IP_FW_IPOPT_SSRR},
173 { "lsrr", IP_FW_IPOPT_LSRR},
174 { "rr", IP_FW_IPOPT_RR},
175 { "ts", IP_FW_IPOPT_TS},
180 static struct _s_x f_iptos[] = {
181 { "lowdelay", IPTOS_LOWDELAY},
182 { "throughput", IPTOS_THROUGHPUT},
183 { "reliability", IPTOS_RELIABILITY},
184 { "mincost", IPTOS_MINCOST},
185 { "congestion", IPTOS_ECN_CE},
186 { "ecntransport", IPTOS_ECN_ECT0},
187 { "ip tos option", 0},
191 static struct _s_x limit_masks[] = {
192 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
193 {"src-addr", DYN_SRC_ADDR},
194 {"src-port", DYN_SRC_PORT},
195 {"dst-addr", DYN_DST_ADDR},
196 {"dst-port", DYN_DST_PORT},
201 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
202 * This is only used in this code.
204 #define IPPROTO_ETHERTYPE 0x1000
205 static struct _s_x ether_types[] = {
207 * Note, we cannot use "-:&/" in the names because they are field
208 * separators in the type specifications. Also, we use s = NULL as
209 * end-delimiter, because a type of 0 can be legal.
222 { "pppoe_disc", 0x8863 },
223 { "pppoe_sess", 0x8864 },
224 { "ipx_8022", 0x00E0 },
225 { "ipx_8023", 0x0000 },
226 { "ipx_ii", 0x8137 },
227 { "ipx_snap", 0x8137 },
233 static void show_usage(void);
275 TOK_DIVERTEDLOOPBACK,
349 struct _s_x dummynet_params[] = {
351 { "noerror", TOK_NOERROR },
352 { "buckets", TOK_BUCKETS },
353 { "dst-ip", TOK_DSTIP },
354 { "src-ip", TOK_SRCIP },
355 { "dst-port", TOK_DSTPORT },
356 { "src-port", TOK_SRCPORT },
357 { "proto", TOK_PROTO },
358 { "weight", TOK_WEIGHT },
360 { "mask", TOK_MASK },
361 { "droptail", TOK_DROPTAIL },
363 { "gred", TOK_GRED },
365 { "bandwidth", TOK_BW },
366 { "delay", TOK_DELAY },
367 { "pipe", TOK_PIPE },
368 { "queue", TOK_QUEUE },
369 { "flow-id", TOK_FLOWID},
370 { "dst-ipv6", TOK_DSTIP6},
371 { "dst-ip6", TOK_DSTIP6},
372 { "src-ipv6", TOK_SRCIP6},
373 { "src-ip6", TOK_SRCIP6},
374 { "dummynet-params", TOK_NULL },
375 { NULL, 0 } /* terminator */
378 struct _s_x nat_params[] = {
382 { "deny_in", TOK_DENY_INC },
383 { "same_ports", TOK_SAME_PORTS },
384 { "unreg_only", TOK_UNREG_ONLY },
385 { "reset", TOK_RESET_ADDR },
386 { "reverse", TOK_ALIAS_REV },
387 { "proxy_only", TOK_PROXY_ONLY },
388 { "redirect_addr", TOK_REDIR_ADDR },
389 { "redirect_port", TOK_REDIR_PORT },
390 { "redirect_proto", TOK_REDIR_PROTO },
391 { NULL, 0 } /* terminator */
394 struct _s_x rule_actions[] = {
395 { "accept", TOK_ACCEPT },
396 { "pass", TOK_ACCEPT },
397 { "allow", TOK_ACCEPT },
398 { "permit", TOK_ACCEPT },
399 { "count", TOK_COUNT },
400 { "pipe", TOK_PIPE },
401 { "queue", TOK_QUEUE },
402 { "divert", TOK_DIVERT },
404 { "netgraph", TOK_NETGRAPH },
405 { "ngtee", TOK_NGTEE },
406 { "fwd", TOK_FORWARD },
407 { "forward", TOK_FORWARD },
408 { "skipto", TOK_SKIPTO },
409 { "deny", TOK_DENY },
410 { "drop", TOK_DENY },
411 { "reject", TOK_REJECT },
412 { "reset6", TOK_RESET6 },
413 { "reset", TOK_RESET },
414 { "unreach6", TOK_UNREACH6 },
415 { "unreach", TOK_UNREACH },
416 { "check-state", TOK_CHECKSTATE },
417 { "//", TOK_COMMENT },
419 { "setfib", TOK_SETFIB },
420 { NULL, 0 } /* terminator */
423 struct _s_x rule_action_params[] = {
424 { "altq", TOK_ALTQ },
427 { "untag", TOK_UNTAG },
428 { NULL, 0 } /* terminator */
431 struct _s_x rule_options[] = {
432 { "tagged", TOK_TAGGED },
435 { "jail", TOK_JAIL },
437 { "limit", TOK_LIMIT },
438 { "keep-state", TOK_KEEPSTATE },
439 { "bridged", TOK_LAYER2 },
440 { "layer2", TOK_LAYER2 },
442 { "diverted", TOK_DIVERTED },
443 { "diverted-loopback", TOK_DIVERTEDLOOPBACK },
444 { "diverted-output", TOK_DIVERTEDOUTPUT },
445 { "xmit", TOK_XMIT },
446 { "recv", TOK_RECV },
448 { "fragment", TOK_FRAG },
449 { "frag", TOK_FRAG },
451 { "ipoptions", TOK_IPOPTS },
452 { "ipopts", TOK_IPOPTS },
453 { "iplen", TOK_IPLEN },
454 { "ipid", TOK_IPID },
455 { "ipprecedence", TOK_IPPRECEDENCE },
456 { "iptos", TOK_IPTOS },
457 { "ipttl", TOK_IPTTL },
458 { "ipversion", TOK_IPVER },
459 { "ipver", TOK_IPVER },
460 { "estab", TOK_ESTAB },
461 { "established", TOK_ESTAB },
462 { "setup", TOK_SETUP },
463 { "tcpdatalen", TOK_TCPDATALEN },
464 { "tcpflags", TOK_TCPFLAGS },
465 { "tcpflgs", TOK_TCPFLAGS },
466 { "tcpoptions", TOK_TCPOPTS },
467 { "tcpopts", TOK_TCPOPTS },
468 { "tcpseq", TOK_TCPSEQ },
469 { "tcpack", TOK_TCPACK },
470 { "tcpwin", TOK_TCPWIN },
471 { "icmptype", TOK_ICMPTYPES },
472 { "icmptypes", TOK_ICMPTYPES },
473 { "dst-ip", TOK_DSTIP },
474 { "src-ip", TOK_SRCIP },
475 { "dst-port", TOK_DSTPORT },
476 { "src-port", TOK_SRCPORT },
477 { "proto", TOK_PROTO },
480 { "mac-type", TOK_MACTYPE },
481 { "verrevpath", TOK_VERREVPATH },
482 { "versrcreach", TOK_VERSRCREACH },
483 { "antispoof", TOK_ANTISPOOF },
484 { "ipsec", TOK_IPSEC },
485 { "icmp6type", TOK_ICMP6TYPES },
486 { "icmp6types", TOK_ICMP6TYPES },
487 { "ext6hdr", TOK_EXT6HDR},
488 { "flow-id", TOK_FLOWID},
493 { "dst-ipv6", TOK_DSTIP6},
494 { "dst-ip6", TOK_DSTIP6},
495 { "src-ipv6", TOK_SRCIP6},
496 { "src-ip6", TOK_SRCIP6},
497 { "//", TOK_COMMENT },
499 { "not", TOK_NOT }, /* pseudo option */
500 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
501 { "or", TOK_OR }, /* pseudo option */
502 { "|", /* escape */ TOK_OR }, /* pseudo option */
503 { "{", TOK_STARTBRACE }, /* pseudo option */
504 { "(", TOK_STARTBRACE }, /* pseudo option */
505 { "}", TOK_ENDBRACE }, /* pseudo option */
506 { ")", TOK_ENDBRACE }, /* pseudo option */
507 { NULL, 0 } /* terminator */
510 #define TABLEARG "tablearg"
512 static __inline uint64_t
513 align_uint64(uint64_t *pll) {
516 bcopy (pll, &ret, sizeof(ret));
521 * conditionally runs the command.
524 do_cmd(int optname, void *optval, uintptr_t optlen)
526 static int s = -1; /* the socket */
533 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
535 err(EX_UNAVAILABLE, "socket");
537 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
538 optname == IP_FW_ADD || optname == IP_FW_TABLE_LIST ||
539 optname == IP_FW_TABLE_GETSIZE ||
540 optname == IP_FW_NAT_GET_CONFIG ||
541 optname == IP_FW_NAT_GET_LOG)
542 i = getsockopt(s, IPPROTO_IP, optname, optval,
543 (socklen_t *)optlen);
545 i = setsockopt(s, IPPROTO_IP, optname, optval, optlen);
550 * match_token takes a table and a string, returns the value associated
551 * with the string (-1 in case of failure).
554 match_token(struct _s_x *table, char *string)
557 uint i = strlen(string);
559 for (pt = table ; i && pt->s != NULL ; pt++)
560 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
566 * match_value takes a table and a value, returns the string associated
567 * with the value (NULL in case of failure).
570 match_value(struct _s_x *p, int value)
572 for (; p->s != NULL; p++)
579 * _substrcmp takes two strings and returns 1 if they do not match,
580 * and 0 if they match exactly or the first string is a sub-string
581 * of the second. A warning is printed to stderr in the case that the
582 * first string is a sub-string of the second.
584 * This function will be removed in the future through the usual
585 * deprecation process.
588 _substrcmp(const char *str1, const char* str2)
591 if (strncmp(str1, str2, strlen(str1)) != 0)
594 if (strlen(str1) != strlen(str2))
595 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
601 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
602 * and 0 if they match exactly or the second string is a sub-string
603 * of the first. A warning is printed to stderr in the case that the
604 * first string does not match the third.
606 * This function exists to warn about the bizzare construction
607 * strncmp(str, "by", 2) which is used to allow people to use a shotcut
608 * for "bytes". The problem is that in addition to accepting "by",
609 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
610 * other string beginning with "by".
612 * This function will be removed in the future through the usual
613 * deprecation process.
616 _substrcmp2(const char *str1, const char* str2, const char* str3)
619 if (strncmp(str1, str2, strlen(str2)) != 0)
622 if (strcmp(str1, str3) != 0)
623 warnx("DEPRECATED: '%s' matched '%s'",
629 * prints one port, symbolic or numeric
632 print_port(int proto, uint16_t port)
635 if (proto == IPPROTO_ETHERTYPE) {
638 if (do_resolv && (s = match_value(ether_types, port)) )
641 printf("0x%04x", port);
643 struct servent *se = NULL;
645 struct protoent *pe = getprotobynumber(proto);
647 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
650 printf("%s", se->s_name);
656 struct _s_x _port_name[] = {
657 {"dst-port", O_IP_DSTPORT},
658 {"src-port", O_IP_SRCPORT},
662 {"mac-type", O_MAC_TYPE},
663 {"tcpdatalen", O_TCPDATALEN},
664 {"tagged", O_TAGGED},
669 * Print the values in a list 16-bit items of the types above.
670 * XXX todo: add support for mask.
673 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode)
675 uint16_t *p = cmd->ports;
680 sep = match_value(_port_name, opcode);
686 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
688 print_port(proto, p[0]);
691 print_port(proto, p[1]);
698 * Like strtol, but also translates service names into port numbers
699 * for some protocols.
701 * proto == -1 disables the protocol check;
702 * proto == IPPROTO_ETHERTYPE looks up an internal table
703 * proto == <some value in /etc/protocols> matches the values there.
704 * Returns *end == s in case the parameter is not found.
707 strtoport(char *s, char **end, int base, int proto)
713 *end = s; /* default - not found */
715 return 0; /* not found */
718 return strtol(s, end, base);
721 * find separator. '\\' escapes the next char.
723 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
724 if (*s1 == '\\' && s1[1] != '\0')
727 buf = malloc(s1 - s + 1);
732 * copy into a buffer skipping backslashes
734 for (p = s, i = 0; p != s1 ; p++)
739 if (proto == IPPROTO_ETHERTYPE) {
740 i = match_token(ether_types, buf);
742 if (i != -1) { /* found */
747 struct protoent *pe = NULL;
751 pe = getprotobynumber(proto);
753 se = getservbyname(buf, pe ? pe->p_name : NULL);
757 return ntohs(se->s_port);
760 return 0; /* not found */
764 * Map between current altq queue id numbers and names.
766 static int altq_fetched = 0;
767 static TAILQ_HEAD(, pf_altq) altq_entries =
768 TAILQ_HEAD_INITIALIZER(altq_entries);
771 altq_set_enabled(int enabled)
775 pffd = open("/dev/pf", O_RDWR);
778 "altq support opening pf(4) control device");
780 if (ioctl(pffd, DIOCSTARTALTQ) != 0 && errno != EEXIST)
781 err(EX_UNAVAILABLE, "enabling altq");
783 if (ioctl(pffd, DIOCSTOPALTQ) != 0 && errno != ENOENT)
784 err(EX_UNAVAILABLE, "disabling altq");
792 struct pfioc_altq pfioc;
793 struct pf_altq *altq;
799 pffd = open("/dev/pf", O_RDONLY);
801 warn("altq support opening pf(4) control device");
804 bzero(&pfioc, sizeof(pfioc));
805 if (ioctl(pffd, DIOCGETALTQS, &pfioc) != 0) {
806 warn("altq support getting queue list");
811 for (pfioc.nr = 0; pfioc.nr < mnr; pfioc.nr++) {
812 if (ioctl(pffd, DIOCGETALTQ, &pfioc) != 0) {
815 warn("altq support getting queue list");
819 if (pfioc.altq.qid == 0)
821 altq = malloc(sizeof(*altq));
823 err(EX_OSERR, "malloc");
825 TAILQ_INSERT_TAIL(&altq_entries, altq, entries);
831 altq_name_to_qid(const char *name)
833 struct pf_altq *altq;
836 TAILQ_FOREACH(altq, &altq_entries, entries)
837 if (strcmp(name, altq->qname) == 0)
840 errx(EX_DATAERR, "altq has no queue named `%s'", name);
845 altq_qid_to_name(u_int32_t qid)
847 struct pf_altq *altq;
850 TAILQ_FOREACH(altq, &altq_entries, entries)
851 if (qid == altq->qid)
859 fill_altq_qid(u_int32_t *qid, const char *av)
861 *qid = altq_name_to_qid(av);
865 * Fill the body of the command with the list of port ranges.
868 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto)
870 uint16_t a, b, *p = cmd->ports;
875 a = strtoport(av, &s, 0, proto);
876 if (s == av) /* empty or invalid argument */
880 case '-': /* a range */
882 b = strtoport(av, &s, 0, proto);
883 /* Reject expressions like '1-abc' or '1-2-3'. */
884 if (s == av || (*s != ',' && *s != '\0'))
889 case ',': /* comma separated list */
894 warnx("port list: invalid separator <%c> in <%s>",
904 if (i + 1 > F_LEN_MASK)
905 errx(EX_DATAERR, "too many ports/ranges\n");
906 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
911 static struct _s_x icmpcodes[] = {
912 { "net", ICMP_UNREACH_NET },
913 { "host", ICMP_UNREACH_HOST },
914 { "protocol", ICMP_UNREACH_PROTOCOL },
915 { "port", ICMP_UNREACH_PORT },
916 { "needfrag", ICMP_UNREACH_NEEDFRAG },
917 { "srcfail", ICMP_UNREACH_SRCFAIL },
918 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
919 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
920 { "isolated", ICMP_UNREACH_ISOLATED },
921 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
922 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
923 { "tosnet", ICMP_UNREACH_TOSNET },
924 { "toshost", ICMP_UNREACH_TOSHOST },
925 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
926 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
927 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
932 fill_reject_code(u_short *codep, char *str)
937 val = strtoul(str, &s, 0);
938 if (s == str || *s != '\0' || val >= 0x100)
939 val = match_token(icmpcodes, str);
941 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
947 print_reject_code(uint16_t code)
949 char const *s = match_value(icmpcodes, code);
952 printf("unreach %s", s);
954 printf("unreach %u", code);
957 static struct _s_x icmp6codes[] = {
958 { "no-route", ICMP6_DST_UNREACH_NOROUTE },
959 { "admin-prohib", ICMP6_DST_UNREACH_ADMIN },
960 { "address", ICMP6_DST_UNREACH_ADDR },
961 { "port", ICMP6_DST_UNREACH_NOPORT },
966 fill_unreach6_code(u_short *codep, char *str)
971 val = strtoul(str, &s, 0);
972 if (s == str || *s != '\0' || val >= 0x100)
973 val = match_token(icmp6codes, str);
975 errx(EX_DATAERR, "unknown ICMPv6 unreachable code ``%s''", str);
981 print_unreach6_code(uint16_t code)
983 char const *s = match_value(icmp6codes, code);
986 printf("unreach6 %s", s);
988 printf("unreach6 %u", code);
992 * Returns the number of bits set (from left) in a contiguous bitmask,
993 * or -1 if the mask is not contiguous.
994 * XXX this needs a proper fix.
995 * This effectively works on masks in big-endian (network) format.
996 * when compiled on little endian architectures.
998 * First bit is bit 7 of the first byte -- note, for MAC addresses,
999 * the first bit on the wire is bit 0 of the first byte.
1000 * len is the max length in bits.
1003 contigmask(uint8_t *p, int len)
1007 for (i=0; i<len ; i++)
1008 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
1010 for (n=i+1; n < len; n++)
1011 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
1012 return -1; /* mask not contiguous */
1017 * print flags set/clear in the two bitmasks passed as parameters.
1018 * There is a specialized check for f_tcpflags.
1021 print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list)
1023 char const *comma = "";
1025 uint8_t set = cmd->arg1 & 0xff;
1026 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
1028 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
1033 printf(" %s ", name);
1034 for (i=0; list[i].x != 0; i++) {
1035 if (set & list[i].x) {
1037 printf("%s%s", comma, list[i].s);
1040 if (clear & list[i].x) {
1041 clear &= ~list[i].x;
1042 printf("%s!%s", comma, list[i].s);
1049 * Print the ip address contained in a command.
1052 print_ip(ipfw_insn_ip *cmd, char const *s)
1054 struct hostent *he = NULL;
1055 int len = F_LEN((ipfw_insn *)cmd);
1056 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
1058 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
1060 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
1064 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
1065 cmd->o.opcode == O_IP_DST_LOOKUP) {
1066 printf("table(%u", ((ipfw_insn *)cmd)->arg1);
1067 if (len == F_INSN_SIZE(ipfw_insn_u32))
1072 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
1073 uint32_t x, *map = (uint32_t *)&(cmd->mask);
1077 x = cmd->o.arg1 - 1;
1079 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1080 printf("%s/%d", inet_ntoa(cmd->addr),
1081 contigmask((uint8_t *)&x, 32));
1082 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1083 x &= 0xff; /* base */
1085 * Print bits and ranges.
1086 * Locate first bit set (i), then locate first bit unset (j).
1087 * If we have 3+ consecutive bits set, then print them as a
1088 * range, otherwise only print the initial bit and rescan.
1090 for (i=0; i < cmd->o.arg1; i++)
1091 if (map[i/32] & (1<<(i & 31))) {
1092 for (j=i+1; j < cmd->o.arg1; j++)
1093 if (!(map[ j/32] & (1<<(j & 31))))
1095 printf("%c%d", comma, i+x);
1096 if (j>i+2) { /* range has at least 3 elements */
1097 printf("-%d", j-1+x);
1106 * len == 2 indicates a single IP, whereas lists of 1 or more
1107 * addr/mask pairs have len = (2n+1). We convert len to n so we
1108 * use that to count the number of entries.
1110 for (len = len / 2; len > 0; len--, a += 2) {
1111 int mb = /* mask length */
1112 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1113 32 : contigmask((uint8_t *)&(a[1]), 32);
1114 if (mb == 32 && do_resolv)
1115 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
1116 if (he != NULL) /* resolved to name */
1117 printf("%s", he->h_name);
1118 else if (mb == 0) /* any */
1120 else { /* numeric IP followed by some kind of mask */
1121 printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) );
1123 printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) );
1133 * prints a MAC address/mask pair
1136 print_mac(uint8_t *addr, uint8_t *mask)
1138 int l = contigmask(mask, 48);
1143 printf(" %02x:%02x:%02x:%02x:%02x:%02x",
1144 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1146 printf("&%02x:%02x:%02x:%02x:%02x:%02x",
1147 mask[0], mask[1], mask[2],
1148 mask[3], mask[4], mask[5]);
1155 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1164 type = strtoul(av, &av, 0);
1166 if (*av != ',' && *av != '\0')
1167 errx(EX_DATAERR, "invalid ICMP type");
1170 errx(EX_DATAERR, "ICMP type out of range");
1172 cmd->d[0] |= 1 << type;
1174 cmd->o.opcode = O_ICMPTYPE;
1175 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1179 print_icmptypes(ipfw_insn_u32 *cmd)
1184 printf(" icmptypes");
1185 for (i = 0; i < 32; i++) {
1186 if ( (cmd->d[0] & (1 << (i))) == 0)
1188 printf("%c%d", sep, i);
1194 * Print the ip address contained in a command.
1197 print_ip6(ipfw_insn_ip6 *cmd, char const *s)
1199 struct hostent *he = NULL;
1200 int len = F_LEN((ipfw_insn *) cmd) - 1;
1201 struct in6_addr *a = &(cmd->addr6);
1204 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
1206 if (cmd->o.opcode == O_IP6_SRC_ME || cmd->o.opcode == O_IP6_DST_ME) {
1210 if (cmd->o.opcode == O_IP6) {
1216 * len == 4 indicates a single IP, whereas lists of 1 or more
1217 * addr/mask pairs have len = (2n+1). We convert len to n so we
1218 * use that to count the number of entries.
1221 for (len = len / 4; len > 0; len -= 2, a += 2) {
1222 int mb = /* mask length */
1223 (cmd->o.opcode == O_IP6_SRC || cmd->o.opcode == O_IP6_DST) ?
1224 128 : contigmask((uint8_t *)&(a[1]), 128);
1226 if (mb == 128 && do_resolv)
1227 he = gethostbyaddr((char *)a, sizeof(*a), AF_INET6);
1228 if (he != NULL) /* resolved to name */
1229 printf("%s", he->h_name);
1230 else if (mb == 0) /* any */
1232 else { /* numeric IP followed by some kind of mask */
1233 if (inet_ntop(AF_INET6, a, trad, sizeof( trad ) ) == NULL)
1234 printf("Error ntop in print_ip6\n");
1235 printf("%s", trad );
1236 if (mb < 0) /* XXX not really legal... */
1238 inet_ntop(AF_INET6, &a[1], trad, sizeof(trad)));
1248 fill_icmp6types(ipfw_insn_icmp6 *cmd, char *av)
1252 bzero(cmd, sizeof(*cmd));
1256 type = strtoul(av, &av, 0);
1257 if (*av != ',' && *av != '\0')
1258 errx(EX_DATAERR, "invalid ICMP6 type");
1260 * XXX: shouldn't this be 0xFF? I can't see any reason why
1261 * we shouldn't be able to filter all possiable values
1262 * regardless of the ability of the rest of the kernel to do
1263 * anything useful with them.
1265 if (type > ICMP6_MAXTYPE)
1266 errx(EX_DATAERR, "ICMP6 type out of range");
1267 cmd->d[type / 32] |= ( 1 << (type % 32));
1269 cmd->o.opcode = O_ICMP6TYPE;
1270 cmd->o.len |= F_INSN_SIZE(ipfw_insn_icmp6);
1275 print_icmp6types(ipfw_insn_u32 *cmd)
1280 printf(" ip6 icmp6types");
1281 for (i = 0; i < 7; i++)
1282 for (j=0; j < 32; ++j) {
1283 if ( (cmd->d[i] & (1 << (j))) == 0)
1285 printf("%c%d", sep, (i*32 + j));
1291 print_flow6id( ipfw_insn_u32 *cmd)
1293 uint16_t i, limit = cmd->o.arg1;
1296 printf(" flow-id ");
1297 for( i=0; i < limit; ++i) {
1300 printf("%d%c", cmd->d[i], sep);
1304 /* structure and define for the extension header in ipv6 */
1305 static struct _s_x ext6hdrcodes[] = {
1306 { "frag", EXT_FRAGMENT },
1307 { "hopopt", EXT_HOPOPTS },
1308 { "route", EXT_ROUTING },
1309 { "dstopt", EXT_DSTOPTS },
1312 { "rthdr0", EXT_RTHDR0 },
1313 { "rthdr2", EXT_RTHDR2 },
1317 /* fills command for the extension header filtering */
1319 fill_ext6hdr( ipfw_insn *cmd, char *av)
1327 av = strsep( &s, ",") ;
1328 tok = match_token(ext6hdrcodes, av);
1331 cmd->arg1 |= EXT_FRAGMENT;
1335 cmd->arg1 |= EXT_HOPOPTS;
1339 cmd->arg1 |= EXT_ROUTING;
1343 cmd->arg1 |= EXT_DSTOPTS;
1347 cmd->arg1 |= EXT_AH;
1351 cmd->arg1 |= EXT_ESP;
1355 cmd->arg1 |= EXT_RTHDR0;
1359 cmd->arg1 |= EXT_RTHDR2;
1363 errx( EX_DATAERR, "invalid option for ipv6 exten header" );
1367 if (cmd->arg1 == 0 )
1369 cmd->opcode = O_EXT_HDR;
1370 cmd->len |= F_INSN_SIZE( ipfw_insn );
1375 print_ext6hdr( ipfw_insn *cmd )
1379 printf(" extension header:");
1380 if (cmd->arg1 & EXT_FRAGMENT ) {
1381 printf("%cfragmentation", sep);
1384 if (cmd->arg1 & EXT_HOPOPTS ) {
1385 printf("%chop options", sep);
1388 if (cmd->arg1 & EXT_ROUTING ) {
1389 printf("%crouting options", sep);
1392 if (cmd->arg1 & EXT_RTHDR0 ) {
1393 printf("%crthdr0", sep);
1396 if (cmd->arg1 & EXT_RTHDR2 ) {
1397 printf("%crthdr2", sep);
1400 if (cmd->arg1 & EXT_DSTOPTS ) {
1401 printf("%cdestination options", sep);
1404 if (cmd->arg1 & EXT_AH ) {
1405 printf("%cauthentication header", sep);
1408 if (cmd->arg1 & EXT_ESP ) {
1409 printf("%cencapsulated security payload", sep);
1414 * show_ipfw() prints the body of an ipfw rule.
1415 * Because the standard rule has at least proto src_ip dst_ip, we use
1416 * a helper function to produce these entries if not provided explicitly.
1417 * The first argument is the list of fields we have, the second is
1418 * the list of fields we want to be printed.
1420 * Special cases if we have provided a MAC header:
1421 * + if the rule does not contain IP addresses/ports, do not print them;
1422 * + if the rule does not contain an IP proto, print "all" instead of "ip";
1424 * Once we have 'have_options', IP header fields are printed as options.
1426 #define HAVE_PROTO 0x0001
1427 #define HAVE_SRCIP 0x0002
1428 #define HAVE_DSTIP 0x0004
1429 #define HAVE_PROTO4 0x0008
1430 #define HAVE_PROTO6 0x0010
1431 #define HAVE_OPTIONS 0x8000
1433 #define HAVE_IP (HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP)
1435 show_prerequisites(int *flags, int want, int cmd)
1439 if ( (*flags & HAVE_IP) == HAVE_IP)
1440 *flags |= HAVE_OPTIONS;
1442 if ( !(*flags & HAVE_OPTIONS)) {
1443 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO))
1444 if ( (*flags & HAVE_PROTO4))
1446 else if ( (*flags & HAVE_PROTO6))
1451 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
1452 printf(" from any");
1453 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
1460 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth)
1462 static int twidth = 0;
1464 ipfw_insn *cmd, *tagptr = NULL;
1465 char *comment = NULL; /* ptr to comment if we have one */
1466 int proto = 0; /* default */
1467 int flags = 0; /* prerequisites */
1468 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
1469 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
1470 int or_block = 0; /* we are in an or block */
1471 uint32_t set_disable;
1473 bcopy(&rule->next_rule, &set_disable, sizeof(set_disable));
1475 if (set_disable & (1 << rule->set)) { /* disabled */
1479 printf("# DISABLED ");
1481 printf("%05u ", rule->rulenum);
1483 if (pcwidth>0 || bcwidth>0)
1484 printf("%*llu %*llu ", pcwidth, align_uint64(&rule->pcnt),
1485 bcwidth, align_uint64(&rule->bcnt));
1488 printf("%10u ", rule->timestamp);
1489 else if (do_time == 1) {
1491 time_t t = (time_t)0;
1494 strcpy(timestr, ctime(&t));
1495 *strchr(timestr, '\n') = '\0';
1496 twidth = strlen(timestr);
1498 if (rule->timestamp) {
1499 t = _long_to_time(rule->timestamp);
1501 strcpy(timestr, ctime(&t));
1502 *strchr(timestr, '\n') = '\0';
1503 printf("%s ", timestr);
1505 printf("%*s", twidth, " ");
1510 printf("set %d ", rule->set);
1513 * print the optional "match probability"
1515 if (rule->cmd_len > 0) {
1517 if (cmd->opcode == O_PROB) {
1518 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1519 double d = 1.0 * p->d[0];
1521 d = (d / 0x7fffffff);
1522 printf("prob %f ", d);
1527 * first print actions
1529 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1530 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1531 switch(cmd->opcode) {
1533 printf("check-state");
1534 flags = HAVE_IP; /* avoid printing anything else */
1550 if (cmd->arg1 == ICMP_REJECT_RST)
1552 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1555 print_reject_code(cmd->arg1);
1559 if (cmd->arg1 == ICMP6_UNREACH_RST)
1562 print_unreach6_code(cmd->arg1);
1566 PRINT_UINT_ARG("skipto ", cmd->arg1);
1570 PRINT_UINT_ARG("pipe ", cmd->arg1);
1574 PRINT_UINT_ARG("queue ", cmd->arg1);
1578 PRINT_UINT_ARG("divert ", cmd->arg1);
1582 PRINT_UINT_ARG("tee ", cmd->arg1);
1586 PRINT_UINT_ARG("netgraph ", cmd->arg1);
1590 PRINT_UINT_ARG("ngtee ", cmd->arg1);
1595 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1597 if (s->sa.sin_addr.s_addr == INADDR_ANY) {
1598 printf("fwd tablearg");
1600 printf("fwd %s", inet_ntoa(s->sa.sin_addr));
1603 printf(",%d", s->sa.sin_port);
1607 case O_LOG: /* O_LOG is printed last */
1608 logptr = (ipfw_insn_log *)cmd;
1611 case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1612 altqptr = (ipfw_insn_altq *)cmd;
1620 PRINT_UINT_ARG("nat ", cmd->arg1);
1624 PRINT_UINT_ARG("setfib ", cmd->arg1);
1628 printf("** unrecognized action %d len %d ",
1629 cmd->opcode, cmd->len);
1633 if (logptr->max_log > 0)
1634 printf(" log logamount %d", logptr->max_log);
1641 qname = altq_qid_to_name(altqptr->qid);
1643 printf(" altq ?<%u>", altqptr->qid);
1645 printf(" altq %s", qname);
1648 if (tagptr->len & F_NOT)
1649 PRINT_UINT_ARG(" untag ", tagptr->arg1);
1651 PRINT_UINT_ARG(" tag ", tagptr->arg1);
1655 * then print the body.
1657 for (l = rule->act_ofs, cmd = rule->cmd ;
1658 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1659 if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1661 if (cmd->opcode == O_IP4) {
1662 flags |= HAVE_PROTO4;
1664 } else if (cmd->opcode == O_IP6) {
1665 flags |= HAVE_PROTO6;
1669 if (rule->_pad & 1) { /* empty rules before options */
1671 show_prerequisites(&flags, HAVE_PROTO, 0);
1672 printf(" from any to any");
1674 flags |= HAVE_IP | HAVE_OPTIONS;
1680 for (l = rule->act_ofs, cmd = rule->cmd ;
1681 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1683 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1686 if (cmd->opcode != O_NOP)
1688 printf(" // %s\n", (char *)(cmd + 1));
1692 show_prerequisites(&flags, 0, cmd->opcode);
1694 switch(cmd->opcode) {
1696 break; /* done already */
1699 break; /* no need to print anything here */
1702 case O_IP_SRC_LOOKUP:
1706 show_prerequisites(&flags, HAVE_PROTO, 0);
1707 if (!(flags & HAVE_SRCIP))
1709 if ((cmd->len & F_OR) && !or_block)
1711 print_ip((ipfw_insn_ip *)cmd,
1712 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1713 flags |= HAVE_SRCIP;
1717 case O_IP_DST_LOOKUP:
1721 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1722 if (!(flags & HAVE_DSTIP))
1724 if ((cmd->len & F_OR) && !or_block)
1726 print_ip((ipfw_insn_ip *)cmd,
1727 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1728 flags |= HAVE_DSTIP;
1732 case O_IP6_SRC_MASK:
1734 show_prerequisites(&flags, HAVE_PROTO, 0);
1735 if (!(flags & HAVE_SRCIP))
1737 if ((cmd->len & F_OR) && !or_block)
1739 print_ip6((ipfw_insn_ip6 *)cmd,
1740 (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1741 flags |= HAVE_SRCIP | HAVE_PROTO;
1745 case O_IP6_DST_MASK:
1747 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1748 if (!(flags & HAVE_DSTIP))
1750 if ((cmd->len & F_OR) && !or_block)
1752 print_ip6((ipfw_insn_ip6 *)cmd,
1753 (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1754 flags |= HAVE_DSTIP;
1758 print_flow6id( (ipfw_insn_u32 *) cmd );
1759 flags |= HAVE_OPTIONS;
1763 show_prerequisites(&flags, HAVE_IP, 0);
1765 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1766 if ((cmd->len & F_OR) && !or_block)
1768 if (cmd->len & F_NOT)
1770 print_newports((ipfw_insn_u16 *)cmd, proto,
1771 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1775 struct protoent *pe = NULL;
1777 if ((cmd->len & F_OR) && !or_block)
1779 if (cmd->len & F_NOT)
1782 pe = getprotobynumber(cmd->arg1);
1783 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1784 !(flags & HAVE_PROTO))
1785 show_prerequisites(&flags,
1786 HAVE_IP | HAVE_OPTIONS, 0);
1787 if (flags & HAVE_OPTIONS)
1790 printf(" %s", pe->p_name);
1792 printf(" %u", cmd->arg1);
1794 flags |= HAVE_PROTO;
1797 default: /*options ... */
1798 if (!(cmd->len & (F_OR|F_NOT)))
1799 if (((cmd->opcode == O_IP6) &&
1800 (flags & HAVE_PROTO6)) ||
1801 ((cmd->opcode == O_IP4) &&
1802 (flags & HAVE_PROTO4)))
1804 show_prerequisites(&flags, HAVE_IP | HAVE_OPTIONS, 0);
1805 if ((cmd->len & F_OR) && !or_block)
1807 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1809 switch(cmd->opcode) {
1811 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1814 print_mac(m->addr, m->mask);
1815 print_mac(m->addr + 6, m->mask + 6);
1820 print_newports((ipfw_insn_u16 *)cmd,
1821 IPPROTO_ETHERTYPE, cmd->opcode);
1830 printf(" fib %u", cmd->arg1 );
1834 printf(cmd->len & F_NOT ? " out" : " in");
1838 switch (cmd->arg1) {
1840 printf(" diverted");
1843 printf(" diverted-loopback");
1846 printf(" diverted-output");
1849 printf(" diverted-?<%u>", cmd->arg1);
1862 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1864 if (cmd->opcode == O_XMIT)
1866 else if (cmd->opcode == O_RECV)
1868 else /* if (cmd->opcode == O_VIA) */
1870 if (cmdif->name[0] == '\0')
1872 inet_ntoa(cmdif->p.ip));
1874 printf(" %s %s", s, cmdif->name);
1879 if (F_LEN(cmd) == 1)
1880 printf(" ipid %u", cmd->arg1 );
1882 print_newports((ipfw_insn_u16 *)cmd, 0,
1887 if (F_LEN(cmd) == 1)
1888 printf(" ipttl %u", cmd->arg1 );
1890 print_newports((ipfw_insn_u16 *)cmd, 0,
1895 printf(" ipver %u", cmd->arg1 );
1898 case O_IPPRECEDENCE:
1899 printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1903 if (F_LEN(cmd) == 1)
1904 printf(" iplen %u", cmd->arg1 );
1906 print_newports((ipfw_insn_u16 *)cmd, 0,
1911 print_flags("ipoptions", cmd, f_ipopts);
1915 print_flags("iptos", cmd, f_iptos);
1919 print_icmptypes((ipfw_insn_u32 *)cmd);
1923 printf(" established");
1927 if (F_LEN(cmd) == 1)
1928 printf(" tcpdatalen %u", cmd->arg1 );
1930 print_newports((ipfw_insn_u16 *)cmd, 0,
1935 print_flags("tcpflags", cmd, f_tcpflags);
1939 print_flags("tcpoptions", cmd, f_tcpopts);
1943 printf(" tcpwin %d", ntohs(cmd->arg1));
1947 printf(" tcpack %d", ntohl(cmd32->d[0]));
1951 printf(" tcpseq %d", ntohl(cmd32->d[0]));
1956 struct passwd *pwd = getpwuid(cmd32->d[0]);
1959 printf(" uid %s", pwd->pw_name);
1961 printf(" uid %u", cmd32->d[0]);
1967 struct group *grp = getgrgid(cmd32->d[0]);
1970 printf(" gid %s", grp->gr_name);
1972 printf(" gid %u", cmd32->d[0]);
1977 printf(" jail %d", cmd32->d[0]);
1981 printf(" verrevpath");
1985 printf(" versrcreach");
1989 printf(" antispoof");
1997 comment = (char *)(cmd + 1);
2001 printf(" keep-state");
2005 struct _s_x *p = limit_masks;
2006 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
2007 uint8_t x = c->limit_mask;
2008 char const *comma = " ";
2011 for (; p->x != 0 ; p++)
2012 if ((x & p->x) == p->x) {
2014 printf("%s%s", comma, p->s);
2017 PRINT_UINT_ARG(" ", c->conn_limit);
2030 print_icmp6types((ipfw_insn_u32 *)cmd);
2034 print_ext6hdr( (ipfw_insn *) cmd );
2038 if (F_LEN(cmd) == 1)
2039 PRINT_UINT_ARG(" tagged ", cmd->arg1);
2041 print_newports((ipfw_insn_u16 *)cmd, 0,
2046 printf(" [opcode %d len %d]",
2047 cmd->opcode, cmd->len);
2050 if (cmd->len & F_OR) {
2053 } else if (or_block) {
2058 show_prerequisites(&flags, HAVE_IP, 0);
2060 printf(" // %s", comment);
2065 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth)
2067 struct protoent *pe;
2070 char buf[INET6_ADDRSTRLEN];
2073 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
2076 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2077 printf("%05d", rulenum);
2078 if (pcwidth>0 || bcwidth>0)
2079 printf(" %*llu %*llu (%ds)", pcwidth,
2080 align_uint64(&d->pcnt), bcwidth,
2081 align_uint64(&d->bcnt), d->expire);
2082 switch (d->dyn_type) {
2083 case O_LIMIT_PARENT:
2084 printf(" PARENT %d", d->count);
2089 case O_KEEP_STATE: /* bidir, no mask */
2094 if ((pe = getprotobynumber(d->id.proto)) != NULL)
2095 printf(" %s", pe->p_name);
2097 printf(" proto %u", d->id.proto);
2099 if (d->id.addr_type == 4) {
2100 a.s_addr = htonl(d->id.src_ip);
2101 printf(" %s %d", inet_ntoa(a), d->id.src_port);
2103 a.s_addr = htonl(d->id.dst_ip);
2104 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
2105 } else if (d->id.addr_type == 6) {
2106 printf(" %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
2107 sizeof(buf)), d->id.src_port);
2108 printf(" <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6, buf,
2109 sizeof(buf)), d->id.dst_port);
2111 printf(" UNKNOWN <-> UNKNOWN\n");
2117 sort_q(const void *pa, const void *pb)
2119 int rev = (do_sort < 0);
2120 int field = rev ? -do_sort : do_sort;
2122 const struct dn_flow_queue *a = pa;
2123 const struct dn_flow_queue *b = pb;
2127 res = a->len - b->len;
2130 res = a->len_bytes - b->len_bytes;
2133 case 3: /* tot pkts */
2134 res = a->tot_pkts - b->tot_pkts;
2137 case 4: /* tot bytes */
2138 res = a->tot_bytes - b->tot_bytes;
2145 return (int)(rev ? res : -res);
2149 list_queues(struct dn_flow_set *fs, struct dn_flow_queue *q)
2152 int index_printed, indexes = 0;
2154 struct protoent *pe;
2156 if (fs->rq_elements == 0)
2160 heapsort(q, fs->rq_elements, sizeof *q, sort_q);
2162 /* Print IPv4 flows */
2164 for (l = 0; l < fs->rq_elements; l++) {
2167 /* XXX: Should check for IPv4 flows */
2168 if (IS_IP6_FLOW_ID(&(q[l].id)))
2171 if (!index_printed) {
2173 if (indexes > 0) /* currently a no-op */
2177 "mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
2178 fs->flow_mask.proto,
2179 fs->flow_mask.src_ip, fs->flow_mask.src_port,
2180 fs->flow_mask.dst_ip, fs->flow_mask.dst_port);
2182 printf("BKT Prot ___Source IP/port____ "
2183 "____Dest. IP/port____ "
2184 "Tot_pkt/bytes Pkt/Byte Drp\n");
2187 printf("%3d ", q[l].hash_slot);
2188 pe = getprotobynumber(q[l].id.proto);
2190 printf("%-4s ", pe->p_name);
2192 printf("%4u ", q[l].id.proto);
2193 ina.s_addr = htonl(q[l].id.src_ip);
2194 printf("%15s/%-5d ",
2195 inet_ntoa(ina), q[l].id.src_port);
2196 ina.s_addr = htonl(q[l].id.dst_ip);
2197 printf("%15s/%-5d ",
2198 inet_ntoa(ina), q[l].id.dst_port);
2199 printf("%4qu %8qu %2u %4u %3u\n",
2200 q[l].tot_pkts, q[l].tot_bytes,
2201 q[l].len, q[l].len_bytes, q[l].drops);
2203 printf(" S %20qd F %20qd\n",
2207 /* Print IPv6 flows */
2209 for (l = 0; l < fs->rq_elements; l++) {
2210 if (!IS_IP6_FLOW_ID(&(q[l].id)))
2213 if (!index_printed) {
2218 printf("\n mask: proto: 0x%02x, flow_id: 0x%08x, ",
2219 fs->flow_mask.proto, fs->flow_mask.flow_id6);
2220 inet_ntop(AF_INET6, &(fs->flow_mask.src_ip6),
2221 buff, sizeof(buff));
2222 printf("%s/0x%04x -> ", buff, fs->flow_mask.src_port);
2223 inet_ntop( AF_INET6, &(fs->flow_mask.dst_ip6),
2224 buff, sizeof(buff) );
2225 printf("%s/0x%04x\n", buff, fs->flow_mask.dst_port);
2227 printf("BKT ___Prot___ _flow-id_ "
2228 "______________Source IPv6/port_______________ "
2229 "_______________Dest. IPv6/port_______________ "
2230 "Tot_pkt/bytes Pkt/Byte Drp\n");
2232 printf("%3d ", q[l].hash_slot);
2233 pe = getprotobynumber(q[l].id.proto);
2235 printf("%9s ", pe->p_name);
2237 printf("%9u ", q[l].id.proto);
2238 printf("%7d %39s/%-5d ", q[l].id.flow_id6,
2239 inet_ntop(AF_INET6, &(q[l].id.src_ip6), buff, sizeof(buff)),
2241 printf(" %39s/%-5d ",
2242 inet_ntop(AF_INET6, &(q[l].id.dst_ip6), buff, sizeof(buff)),
2244 printf(" %4qu %8qu %2u %4u %3u\n",
2245 q[l].tot_pkts, q[l].tot_bytes,
2246 q[l].len, q[l].len_bytes, q[l].drops);
2248 printf(" S %20qd F %20qd\n", q[l].S, q[l].F);
2253 print_flowset_parms(struct dn_flow_set *fs, char *prefix)
2258 char red[90]; /* Display RED parameters */
2261 if (fs->flags_fs & DN_QSIZE_IS_BYTES) {
2263 sprintf(qs, "%d KB", l / 1024);
2265 sprintf(qs, "%d B", l);
2267 sprintf(qs, "%3d sl.", l);
2269 sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff));
2272 if (fs->flags_fs & DN_IS_RED) /* RED parameters */
2274 "\n\t %cRED w_q %f min_th %d max_th %d max_p %f",
2275 (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ',
2276 1.0 * fs->w_q / (double)(1 << SCALE_RED),
2277 SCALE_VAL(fs->min_th),
2278 SCALE_VAL(fs->max_th),
2279 1.0 * fs->max_p / (double)(1 << SCALE_RED));
2281 sprintf(red, "droptail");
2283 printf("%s %s%s %d queues (%d buckets) %s\n",
2284 prefix, qs, plr, fs->rq_elements, fs->rq_size, red);
2288 list_pipes(void *data, uint nbytes, int ac, char *av[])
2292 struct dn_pipe *p = (struct dn_pipe *) data;
2293 struct dn_flow_set *fs;
2294 struct dn_flow_queue *q;
2298 rulenum = strtoul(*av++, NULL, 10);
2301 for (; nbytes >= sizeof *p; p = (struct dn_pipe *)next) {
2302 double b = p->bandwidth;
2306 if (SLIST_NEXT(p, next) != (struct dn_pipe *)DN_IS_PIPE)
2307 break; /* done with pipes, now queues */
2310 * compute length, as pipe have variable size
2312 l = sizeof(*p) + p->fs.rq_elements * sizeof(*q);
2313 next = (char *)p + l;
2316 if ((rulenum != 0 && rulenum != p->pipe_nr) || do_pipe == 2)
2320 * Print rate (or clocking interface)
2322 if (p->if_name[0] != '\0')
2323 sprintf(buf, "%s", p->if_name);
2325 sprintf(buf, "unlimited");
2326 else if (b >= 1000000)
2327 sprintf(buf, "%7.3f Mbit/s", b/1000000);
2329 sprintf(buf, "%7.3f Kbit/s", b/1000);
2331 sprintf(buf, "%7.3f bit/s ", b);
2333 sprintf(prefix, "%05d: %s %4d ms ",
2334 p->pipe_nr, buf, p->delay);
2335 print_flowset_parms(&(p->fs), prefix);
2337 printf(" V %20qd\n", p->V >> MY_M);
2339 q = (struct dn_flow_queue *)(p+1);
2340 list_queues(&(p->fs), q);
2342 for (fs = next; nbytes >= sizeof *fs; fs = next) {
2345 if (SLIST_NEXT(fs, next) != (struct dn_flow_set *)DN_IS_QUEUE)
2347 l = sizeof(*fs) + fs->rq_elements * sizeof(*q);
2348 next = (char *)fs + l;
2351 if (rulenum != 0 && ((rulenum != fs->fs_nr && do_pipe == 2) ||
2352 (rulenum != fs->parent_nr && do_pipe == 1))) {
2356 q = (struct dn_flow_queue *)(fs+1);
2357 sprintf(prefix, "q%05d: weight %d pipe %d ",
2358 fs->fs_nr, fs->weight, fs->parent_nr);
2359 print_flowset_parms(fs, prefix);
2365 * This one handles all set-related commands
2366 * ipfw set { show | enable | disable }
2368 * ipfw set move X to Y
2369 * ipfw set move rule X to Y
2372 sets_handler(int ac, char *av[])
2374 uint32_t set_disable, masks[2];
2377 uint8_t cmd, new_set;
2383 errx(EX_USAGE, "set needs command");
2384 if (_substrcmp(*av, "show") == 0) {
2388 nbytes = sizeof(struct ip_fw);
2389 if ((data = calloc(1, nbytes)) == NULL)
2390 err(EX_OSERR, "calloc");
2391 if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0)
2392 err(EX_OSERR, "getsockopt(IP_FW_GET)");
2393 bcopy(&((struct ip_fw *)data)->next_rule,
2394 &set_disable, sizeof(set_disable));
2396 for (i = 0, msg = "disable" ; i < RESVD_SET; i++)
2397 if ((set_disable & (1<<i))) {
2398 printf("%s %d", msg, i);
2401 msg = (set_disable) ? " enable" : "enable";
2402 for (i = 0; i < RESVD_SET; i++)
2403 if (!(set_disable & (1<<i))) {
2404 printf("%s %d", msg, i);
2408 } else if (_substrcmp(*av, "swap") == 0) {
2411 errx(EX_USAGE, "set swap needs 2 set numbers\n");
2412 rulenum = atoi(av[0]);
2413 new_set = atoi(av[1]);
2414 if (!isdigit(*(av[0])) || rulenum > RESVD_SET)
2415 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2416 if (!isdigit(*(av[1])) || new_set > RESVD_SET)
2417 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2418 masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
2419 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
2420 } else if (_substrcmp(*av, "move") == 0) {
2422 if (ac && _substrcmp(*av, "rule") == 0) {
2427 if (ac != 3 || _substrcmp(av[1], "to") != 0)
2428 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2429 rulenum = atoi(av[0]);
2430 new_set = atoi(av[2]);
2431 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) ||
2432 (cmd == 2 && rulenum == IPFW_DEFAULT_RULE) )
2433 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2434 if (!isdigit(*(av[2])) || new_set > RESVD_SET)
2435 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2436 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
2437 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
2438 } else if (_substrcmp(*av, "disable") == 0 ||
2439 _substrcmp(*av, "enable") == 0 ) {
2440 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2443 masks[0] = masks[1] = 0;
2446 if (isdigit(**av)) {
2448 if (i < 0 || i > RESVD_SET)
2450 "invalid set number %d\n", i);
2451 masks[which] |= (1<<i);
2452 } else if (_substrcmp(*av, "disable") == 0)
2454 else if (_substrcmp(*av, "enable") == 0)
2458 "invalid set command %s\n", *av);
2461 if ( (masks[0] & masks[1]) != 0 )
2463 "cannot enable and disable the same set\n");
2465 i = do_cmd(IP_FW_DEL, masks, sizeof(masks));
2467 warn("set enable/disable: setsockopt(IP_FW_DEL)");
2469 errx(EX_USAGE, "invalid set command %s\n", *av);
2473 sysctl_handler(int ac, char *av[], int which)
2479 warnx("missing keyword to enable/disable\n");
2480 } else if (_substrcmp(*av, "firewall") == 0) {
2481 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2482 &which, sizeof(which));
2483 } else if (_substrcmp(*av, "one_pass") == 0) {
2484 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2485 &which, sizeof(which));
2486 } else if (_substrcmp(*av, "debug") == 0) {
2487 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2488 &which, sizeof(which));
2489 } else if (_substrcmp(*av, "verbose") == 0) {
2490 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2491 &which, sizeof(which));
2492 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2493 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2494 &which, sizeof(which));
2495 } else if (_substrcmp(*av, "altq") == 0) {
2496 altq_set_enabled(which);
2498 warnx("unrecognize enable/disable keyword: %s\n", *av);
2503 list(int ac, char *av[], int show_counters)
2506 ipfw_dyn_rule *dynrules, *d;
2508 #define NEXT(r) ((struct ip_fw *)((char *)r + RULESIZE(r)))
2511 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
2512 int exitval = EX_OK;
2520 const int ocmd = do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
2521 int nalloc = 1024; /* start somewhere... */
2526 fprintf(stderr, "Testing only, list disabled\n");
2533 /* get rules or pipes from kernel, resizing array as necessary */
2536 while (nbytes >= nalloc) {
2537 nalloc = nalloc * 2 + 200;
2539 if ((data = realloc(data, nbytes)) == NULL)
2540 err(EX_OSERR, "realloc");
2541 if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0)
2542 err(EX_OSERR, "getsockopt(IP_%s_GET)",
2543 do_pipe ? "DUMMYNET" : "FW");
2547 list_pipes(data, nbytes, ac, av);
2552 * Count static rules. They have variable size so we
2553 * need to scan the list to count them.
2555 for (nstat = 1, r = data, lim = (char *)data + nbytes;
2556 r->rulenum < IPFW_DEFAULT_RULE && (char *)r < lim;
2557 ++nstat, r = NEXT(r) )
2561 * Count dynamic rules. This is easier as they have
2565 dynrules = (ipfw_dyn_rule *)r ;
2566 n = (char *)r - (char *)data;
2567 ndyn = (nbytes - n) / sizeof *dynrules;
2569 /* if showing stats, figure out column widths ahead of time */
2570 bcwidth = pcwidth = 0;
2571 if (show_counters) {
2572 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
2573 /* skip rules from another set */
2574 if (use_set && r->set != use_set - 1)
2577 /* packet counter */
2578 width = snprintf(NULL, 0, "%llu",
2579 align_uint64(&r->pcnt));
2580 if (width > pcwidth)
2584 width = snprintf(NULL, 0, "%llu",
2585 align_uint64(&r->bcnt));
2586 if (width > bcwidth)
2590 if (do_dynamic && ndyn) {
2591 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2593 /* skip rules from another set */
2594 bcopy((char *)&d->rule + sizeof(uint16_t),
2595 &set, sizeof(uint8_t));
2596 if (set != use_set - 1)
2599 width = snprintf(NULL, 0, "%llu",
2600 align_uint64(&d->pcnt));
2601 if (width > pcwidth)
2604 width = snprintf(NULL, 0, "%llu",
2605 align_uint64(&d->bcnt));
2606 if (width > bcwidth)
2610 /* if no rule numbers were specified, list all rules */
2612 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
2613 if (use_set && r->set != use_set - 1)
2615 show_ipfw(r, pcwidth, bcwidth);
2618 if (do_dynamic && ndyn) {
2619 printf("## Dynamic rules (%d):\n", ndyn);
2620 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2622 bcopy((char *)&d->rule + sizeof(uint16_t),
2623 &set, sizeof(uint8_t));
2624 if (set != use_set - 1)
2627 show_dyn_ipfw(d, pcwidth, bcwidth);
2633 /* display specific rules requested on command line */
2635 for (lac = ac, lav = av; lac != 0; lac--) {
2636 /* convert command line rule # */
2637 last = rnum = strtoul(*lav++, &endptr, 10);
2639 last = strtoul(endptr+1, &endptr, 10);
2642 warnx("invalid rule number: %s", *(lav - 1));
2645 for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) {
2646 if (r->rulenum > last)
2648 if (use_set && r->set != use_set - 1)
2650 if (r->rulenum >= rnum && r->rulenum <= last) {
2651 show_ipfw(r, pcwidth, bcwidth);
2656 /* give precedence to other error(s) */
2657 if (exitval == EX_OK)
2658 exitval = EX_UNAVAILABLE;
2659 warnx("rule %lu does not exist", rnum);
2663 if (do_dynamic && ndyn) {
2664 printf("## Dynamic rules:\n");
2665 for (lac = ac, lav = av; lac != 0; lac--) {
2666 last = rnum = strtoul(*lav++, &endptr, 10);
2668 last = strtoul(endptr+1, &endptr, 10);
2670 /* already warned */
2672 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2675 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2679 bcopy((char *)&d->rule + sizeof(uint16_t),
2680 &set, sizeof(uint8_t));
2681 if (set != use_set - 1)
2684 if (r->rulenum >= rnum && r->rulenum <= last)
2685 show_dyn_ipfw(d, pcwidth, bcwidth);
2695 if (exitval != EX_OK)
2703 fprintf(stderr, "usage: ipfw [options]\n"
2704 "do \"ipfw -h\" or see ipfw manpage for details\n"
2713 "ipfw syntax summary (but please do read the ipfw(8) manpage):\n"
2714 "ipfw [-abcdefhnNqStTv] <command> where <command> is one of:\n"
2715 "add [num] [set N] [prob x] RULE-BODY\n"
2716 "{pipe|queue} N config PIPE-BODY\n"
2717 "[pipe|queue] {zero|delete|show} [N{,N}]\n"
2718 "nat N config {ip IPADDR|if IFNAME|log|deny_in|same_ports|unreg_only|reset|\n"
2719 " reverse|proxy_only|redirect_addr linkspec|\n"
2720 " redirect_port linkspec|redirect_proto linkspec}\n"
2721 "set [disable N... enable N...] | move [rule] X to Y | swap X Y | show\n"
2722 "set N {show|list|zero|resetlog|delete} [N{,N}] | flush\n"
2723 "table N {add ip[/bits] [value] | delete ip[/bits] | flush | list}\n"
2724 "table all {flush | list}\n"
2726 "RULE-BODY: check-state [PARAMS] | ACTION [PARAMS] ADDR [OPTION_LIST]\n"
2727 "ACTION: check-state | allow | count | deny | unreach{,6} CODE |\n"
2728 " skipto N | {divert|tee} PORT | forward ADDR |\n"
2729 " pipe N | queue N | nat N | setfib FIB\n"
2730 "PARAMS: [log [logamount LOGLIMIT]] [altq QUEUE_NAME]\n"
2731 "ADDR: [ MAC dst src ether_type ] \n"
2732 " [ ip from IPADDR [ PORT ] to IPADDR [ PORTLIST ] ]\n"
2733 " [ ipv6|ip6 from IP6ADDR [ PORT ] to IP6ADDR [ PORTLIST ] ]\n"
2734 "IPADDR: [not] { any | me | ip/bits{x,y,z} | table(t[,v]) | IPLIST }\n"
2735 "IP6ADDR: [not] { any | me | me6 | ip6/bits | IP6LIST }\n"
2736 "IP6LIST: { ip6 | ip6/bits }[,IP6LIST]\n"
2737 "IPLIST: { ip | ip/bits | ip:mask }[,IPLIST]\n"
2738 "OPTION_LIST: OPTION [OPTION_LIST]\n"
2739 "OPTION: bridged | diverted | diverted-loopback | diverted-output |\n"
2740 " {dst-ip|src-ip} IPADDR | {dst-ip6|src-ip6|dst-ipv6|src-ipv6} IP6ADDR |\n"
2741 " {dst-port|src-port} LIST |\n"
2742 " estab | frag | {gid|uid} N | icmptypes LIST | in | out | ipid LIST |\n"
2743 " iplen LIST | ipoptions SPEC | ipprecedence | ipsec | iptos SPEC |\n"
2744 " ipttl LIST | ipversion VER | keep-state | layer2 | limit ... |\n"
2745 " icmp6types LIST | ext6hdr LIST | flow-id N[,N] | fib FIB |\n"
2746 " mac ... | mac-type LIST | proto LIST | {recv|xmit|via} {IF|IPADDR} |\n"
2747 " setup | {tcpack|tcpseq|tcpwin} NN | tcpflags SPEC | tcpoptions SPEC |\n"
2748 " tcpdatalen LIST | verrevpath | versrcreach | antispoof\n"
2755 lookup_host (char *host, struct in_addr *ipaddr)
2759 if (!inet_aton(host, ipaddr)) {
2760 if ((he = gethostbyname(host)) == NULL)
2762 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2768 * fills the addr and mask fields in the instruction as appropriate from av.
2769 * Update length as appropriate.
2770 * The following formats are allowed:
2771 * me returns O_IP_*_ME
2772 * 1.2.3.4 single IP address
2773 * 1.2.3.4:5.6.7.8 address:mask
2774 * 1.2.3.4/24 address/mask
2775 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
2776 * We can have multiple comma-separated address/mask entries.
2779 fill_ip(ipfw_insn_ip *cmd, char *av)
2782 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2784 cmd->o.len &= ~F_LEN_MASK; /* zero len */
2786 if (_substrcmp(av, "any") == 0)
2789 if (_substrcmp(av, "me") == 0) {
2790 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2794 if (strncmp(av, "table(", 6) == 0) {
2795 char *p = strchr(av + 6, ',');
2799 cmd->o.opcode = O_IP_DST_LOOKUP;
2800 cmd->o.arg1 = strtoul(av + 6, NULL, 0);
2802 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2803 d[0] = strtoul(p, NULL, 0);
2805 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2811 * After the address we can have '/' or ':' indicating a mask,
2812 * ',' indicating another address follows, '{' indicating a
2813 * set of addresses of unspecified size.
2815 char *t = NULL, *p = strpbrk(av, "/:,{");
2822 if ((t = strpbrk(p, ",{")) != NULL) {
2829 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2830 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2833 if (!inet_aton(p, (struct in_addr *)&d[1]))
2834 errx(EX_DATAERR, "bad netmask ``%s''", p);
2839 d[1] = htonl(0); /* mask */
2840 else if (masklen > 32)
2841 errx(EX_DATAERR, "bad width ``%s''", p);
2843 d[1] = htonl(~0 << (32 - masklen));
2845 case '{': /* no mask, assume /24 and put back the '{' */
2846 d[1] = htonl(~0 << (32 - 24));
2850 case ',': /* single address plus continuation */
2853 case 0: /* initialization value */
2855 d[1] = htonl(~0); /* force /32 */
2858 d[0] &= d[1]; /* mask base address with mask */
2861 /* find next separator */
2863 p = strpbrk(p, ",{");
2864 if (p && *p == '{') {
2866 * We have a set of addresses. They are stored as follows:
2867 * arg1 is the set size (powers of 2, 2..256)
2868 * addr is the base address IN HOST FORMAT
2869 * mask.. is an array of arg1 bits (rounded up to
2870 * the next multiple of 32) with bits set
2871 * for each host in the map.
2873 uint32_t *map = (uint32_t *)&cmd->mask;
2875 int i = contigmask((uint8_t *)&(d[1]), 32);
2878 errx(EX_DATAERR, "address set cannot be in a list");
2879 if (i < 24 || i > 31)
2880 errx(EX_DATAERR, "invalid set with mask %d\n", i);
2881 cmd->o.arg1 = 1<<(32-i); /* map length */
2882 d[0] = ntohl(d[0]); /* base addr in host format */
2883 cmd->o.opcode = O_IP_DST_SET; /* default */
2884 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2885 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2886 map[i] = 0; /* clear map */
2890 high = low + cmd->o.arg1 - 1;
2892 * Here, i stores the previous value when we specify a range
2893 * of addresses within a mask, e.g. 45-63. i = -1 means we
2894 * have no previous value.
2896 i = -1; /* previous value in a range */
2897 while (isdigit(*av)) {
2899 int a = strtol(av, &s, 0);
2901 if (s == av) { /* no parameter */
2903 errx(EX_DATAERR, "set not closed\n");
2905 errx(EX_DATAERR, "incomplete range %d-", i);
2908 if (a < low || a > high)
2909 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
2912 if (i == -1) /* no previous in range */
2914 else { /* check that range is valid */
2916 errx(EX_DATAERR, "invalid range %d-%d",
2919 errx(EX_DATAERR, "double '-' in range");
2922 map[i/32] |= 1<<(i & 31);
2933 if (av) /* then *av must be a ',' */
2936 /* Check this entry */
2937 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2939 * 'any' turns the entire list into a NOP.
2940 * 'not any' never matches, so it is removed from the
2941 * list unless it is the only item, in which case we
2944 if (cmd->o.len & F_NOT) { /* "not any" never matches */
2945 if (av == NULL && len == 0) /* only this entry */
2946 errx(EX_DATAERR, "not any never matches");
2948 /* else do nothing and skip this entry */
2951 /* A single IP can be stored in an optimized format */
2952 if (d[1] == IP_MASK_ALL && av == NULL && len == 0) {
2953 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2956 len += 2; /* two words... */
2959 if (len + 1 > F_LEN_MASK)
2960 errx(EX_DATAERR, "address list too long");
2961 cmd->o.len |= len+1;
2965 /* Try to find ipv6 address by hostname */
2967 lookup_host6 (char *host, struct in6_addr *ip6addr)
2971 if (!inet_pton(AF_INET6, host, ip6addr)) {
2972 if ((he = gethostbyname2(host, AF_INET6)) == NULL)
2974 memcpy(ip6addr, he->h_addr_list[0], sizeof( struct in6_addr));
2980 /* n2mask sets n bits of the mask */
2982 n2mask(struct in6_addr *mask, int n)
2984 static int minimask[9] =
2985 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
2988 memset(mask, 0, sizeof(struct in6_addr));
2989 p = (u_char *) mask;
2990 for (; n > 0; p++, n -= 8) {
3001 * fill the addr and mask fields in the instruction as appropriate from av.
3002 * Update length as appropriate.
3003 * The following formats are allowed:
3004 * any matches any IP6. Actually returns an empty instruction.
3005 * me returns O_IP6_*_ME
3007 * 03f1::234:123:0342 single IP6 addres
3008 * 03f1::234:123:0342/24 address/mask
3009 * 03f1::234:123:0342/24,03f1::234:123:0343/ List of address
3011 * Set of address (as in ipv6) not supported because ipv6 address
3012 * are typically random past the initial prefix.
3013 * Return 1 on success, 0 on failure.
3016 fill_ip6(ipfw_insn_ip6 *cmd, char *av)
3019 struct in6_addr *d = &(cmd->addr6);
3021 * Needed for multiple address.
3022 * Note d[1] points to struct in6_add r mask6 of cmd
3025 cmd->o.len &= ~F_LEN_MASK; /* zero len */
3027 if (strcmp(av, "any") == 0)
3031 if (strcmp(av, "me") == 0) { /* Set the data for "me" opt*/
3032 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
3036 if (strcmp(av, "me6") == 0) { /* Set the data for "me" opt*/
3037 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
3044 * After the address we can have '/' indicating a mask,
3045 * or ',' indicating another address follows.
3052 if ((p = strpbrk(av, "/,")) ) {
3053 md = *p; /* save the separator */
3054 *p = '\0'; /* terminate address string */
3055 p++; /* and skip past it */
3057 /* now p points to NULL, mask or next entry */
3059 /* lookup stores address in *d as a side effect */
3060 if (lookup_host6(av, d) != 0) {
3061 /* XXX: failed. Free memory and go */
3062 errx(EX_DATAERR, "bad address \"%s\"", av);
3064 /* next, look at the mask, if any */
3065 masklen = (md == '/') ? atoi(p) : 128;
3066 if (masklen > 128 || masklen < 0)
3067 errx(EX_DATAERR, "bad width \"%s\''", p);
3069 n2mask(&d[1], masklen);
3071 APPLY_MASK(d, &d[1]) /* mask base address with mask */
3073 /* find next separator */
3075 if (md == '/') { /* find separator past the mask */
3076 p = strpbrk(p, ",");
3082 /* Check this entry */
3085 * 'any' turns the entire list into a NOP.
3086 * 'not any' never matches, so it is removed from the
3087 * list unless it is the only item, in which case we
3090 if (cmd->o.len & F_NOT && av == NULL && len == 0)
3091 errx(EX_DATAERR, "not any never matches");
3096 * A single IP can be stored alone
3098 if (masklen == 128 && av == NULL && len == 0) {
3099 len = F_INSN_SIZE(struct in6_addr);
3103 /* Update length and pointer to arguments */
3104 len += F_INSN_SIZE(struct in6_addr)*2;
3109 * Total length of the command, remember that 1 is the size of
3112 if (len + 1 > F_LEN_MASK)
3113 errx(EX_DATAERR, "address list too long");
3114 cmd->o.len |= len+1;
3120 * fills command for ipv6 flow-id filtering
3121 * note that the 20 bit flow number is stored in a array of u_int32_t
3122 * it's supported lists of flow-id, so in the o.arg1 we store how many
3123 * additional flow-id we want to filter, the basic is 1
3126 fill_flow6( ipfw_insn_u32 *cmd, char *av )
3128 u_int32_t type; /* Current flow number */
3129 u_int16_t nflow = 0; /* Current flow index */
3131 cmd->d[0] = 0; /* Initializing the base number*/
3134 av = strsep( &s, ",") ;
3135 type = strtoul(av, &av, 0);
3136 if (*av != ',' && *av != '\0')
3137 errx(EX_DATAERR, "invalid ipv6 flow number %s", av);
3139 errx(EX_DATAERR, "flow number out of range %s", av);
3140 cmd->d[nflow] |= type;
3144 cmd->o.opcode = O_FLOW6ID;
3145 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + nflow;
3146 cmd->o.arg1 = nflow;
3149 errx(EX_DATAERR, "invalid ipv6 flow number %s", av);
3154 add_srcip6(ipfw_insn *cmd, char *av)
3157 fill_ip6((ipfw_insn_ip6 *)cmd, av);
3158 if (F_LEN(cmd) == 0) /* any */
3160 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) { /* "me" */
3161 cmd->opcode = O_IP6_SRC_ME;
3162 } else if (F_LEN(cmd) ==
3163 (F_INSN_SIZE(struct in6_addr) + F_INSN_SIZE(ipfw_insn))) {
3164 /* single IP, no mask*/
3165 cmd->opcode = O_IP6_SRC;
3166 } else { /* addr/mask opt */
3167 cmd->opcode = O_IP6_SRC_MASK;
3173 add_dstip6(ipfw_insn *cmd, char *av)
3176 fill_ip6((ipfw_insn_ip6 *)cmd, av);
3177 if (F_LEN(cmd) == 0) /* any */
3179 if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) { /* "me" */
3180 cmd->opcode = O_IP6_DST_ME;
3181 } else if (F_LEN(cmd) ==
3182 (F_INSN_SIZE(struct in6_addr) + F_INSN_SIZE(ipfw_insn))) {
3183 /* single IP, no mask*/
3184 cmd->opcode = O_IP6_DST;
3185 } else { /* addr/mask opt */
3186 cmd->opcode = O_IP6_DST_MASK;
3193 * helper function to process a set of flags and set bits in the
3194 * appropriate masks.
3197 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3198 struct _s_x *flags, char *p)
3200 uint8_t set=0, clear=0;
3203 char *q; /* points to the separator */
3205 uint8_t *which; /* mask we are working on */
3215 val = match_token(flags, p);
3217 errx(EX_DATAERR, "invalid flag %s", p);
3218 *which |= (uint8_t)val;
3221 cmd->opcode = opcode;
3222 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
3223 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3228 delete(int ac, char *av[])
3233 int exitval = EX_OK;
3236 memset(&p, 0, sizeof p);
3239 NEED1("missing rule specification");
3240 if (ac > 0 && _substrcmp(*av, "set") == 0) {
3241 /* Do not allow using the following syntax:
3242 * ipfw set N delete set M
3245 errx(EX_DATAERR, "invalid syntax");
3246 do_set = 1; /* delete set */
3251 while (ac && isdigit(**av)) {
3252 i = atoi(*av); av++; ac--;
3254 exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
3256 exitval = EX_UNAVAILABLE;
3257 warn("rule %u not available", i);
3259 } else if (do_pipe) {
3264 i = do_cmd(IP_DUMMYNET_DEL, &p, sizeof p);
3267 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)",
3268 do_pipe == 1 ? p.pipe_nr : p.fs.fs_nr);
3272 rulenum = (i & 0xffff) | (5 << 24) |
3273 ((use_set - 1) << 16);
3275 rulenum = (i & 0xffff) | (do_set << 24);
3276 i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum);
3278 exitval = EX_UNAVAILABLE;
3279 warn("rule %u: setsockopt(IP_FW_DEL)",
3284 if (exitval != EX_OK)
3290 * fill the interface structure. We do not check the name as we can
3291 * create interfaces dynamically, so checking them at insert time
3292 * makes relatively little sense.
3293 * Interface names containing '*', '?', or '[' are assumed to be shell
3294 * patterns which match interfaces.
3297 fill_iface(ipfw_insn_if *cmd, char *arg)
3299 cmd->name[0] = '\0';
3300 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3302 /* Parse the interface or address */
3303 if (strcmp(arg, "any") == 0)
3304 cmd->o.len = 0; /* effectively ignore this command */
3305 else if (!isdigit(*arg)) {
3306 strlcpy(cmd->name, arg, sizeof(cmd->name));
3307 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3308 } else if (!inet_aton(arg, &cmd->p.ip))
3309 errx(EX_DATAERR, "bad ip address ``%s''", arg);
3313 * Search for interface with name "ifn", and fill n accordingly:
3315 * n->ip ip address of interface "ifn"
3316 * n->if_name copy of interface name "ifn"
3319 set_addr_dynamic(const char *ifn, struct cfg_nat *n)
3323 char *buf, *lim, *next;
3324 struct if_msghdr *ifm;
3325 struct ifa_msghdr *ifam;
3326 struct sockaddr_dl *sdl;
3327 struct sockaddr_in *sin;
3334 mib[4] = NET_RT_IFLIST;
3337 * Get interface data.
3339 if (sysctl(mib, 6, NULL, &needed, NULL, 0) == -1)
3340 err(1, "iflist-sysctl-estimate");
3341 if ((buf = malloc(needed)) == NULL)
3342 errx(1, "malloc failed");
3343 if (sysctl(mib, 6, buf, &needed, NULL, 0) == -1)
3344 err(1, "iflist-sysctl-get");
3347 * Loop through interfaces until one with
3348 * given name is found. This is done to
3349 * find correct interface index for routing
3350 * message processing.
3354 while (next < lim) {
3355 ifm = (struct if_msghdr *)next;
3356 next += ifm->ifm_msglen;
3357 if (ifm->ifm_version != RTM_VERSION) {
3359 warnx("routing message version %d "
3360 "not understood", ifm->ifm_version);
3363 if (ifm->ifm_type == RTM_IFINFO) {
3364 sdl = (struct sockaddr_dl *)(ifm + 1);
3365 if (strlen(ifn) == sdl->sdl_nlen &&
3366 strncmp(ifn, sdl->sdl_data, sdl->sdl_nlen) == 0) {
3367 ifIndex = ifm->ifm_index;
3368 ifMTU = ifm->ifm_data.ifi_mtu;
3374 errx(1, "unknown interface name %s", ifn);
3376 * Get interface address.
3379 while (next < lim) {
3380 ifam = (struct ifa_msghdr *)next;
3381 next += ifam->ifam_msglen;
3382 if (ifam->ifam_version != RTM_VERSION) {
3384 warnx("routing message version %d "
3385 "not understood", ifam->ifam_version);
3388 if (ifam->ifam_type != RTM_NEWADDR)
3390 if (ifam->ifam_addrs & RTA_IFA) {
3392 char *cp = (char *)(ifam + 1);
3394 for (i = 1; i < RTA_IFA; i <<= 1) {
3395 if (ifam->ifam_addrs & i)
3396 cp += SA_SIZE((struct sockaddr *)cp);
3398 if (((struct sockaddr *)cp)->sa_family == AF_INET) {
3399 sin = (struct sockaddr_in *)cp;
3405 errx(1, "%s: cannot get interface address", ifn);
3407 n->ip = sin->sin_addr;
3408 strncpy(n->if_name, ifn, IF_NAMESIZE);
3414 * XXX - The following functions, macros and definitions come from natd.c:
3415 * it would be better to move them outside natd.c, in a file
3416 * (redirect_support.[ch]?) shared by ipfw and natd, but for now i can live
3421 * Definition of a port range, and macros to deal with values.
3422 * FORMAT: HI 16-bits == first port in range, 0 == all ports.
3423 * LO 16-bits == number of ports in range
3424 * NOTES: - Port values are not stored in network byte order.
3427 #define port_range u_long
3429 #define GETLOPORT(x) ((x) >> 0x10)
3430 #define GETNUMPORTS(x) ((x) & 0x0000ffff)
3431 #define GETHIPORT(x) (GETLOPORT((x)) + GETNUMPORTS((x)))
3433 /* Set y to be the low-port value in port_range variable x. */
3434 #define SETLOPORT(x,y) ((x) = ((x) & 0x0000ffff) | ((y) << 0x10))
3436 /* Set y to be the number of ports in port_range variable x. */
3437 #define SETNUMPORTS(x,y) ((x) = ((x) & 0xffff0000) | (y))
3440 StrToAddr (const char* str, struct in_addr* addr)
3444 if (inet_aton (str, addr))
3447 hp = gethostbyname (str);
3449 errx (1, "unknown host %s", str);
3451 memcpy (addr, hp->h_addr, sizeof (struct in_addr));
3455 StrToPortRange (const char* str, const char* proto, port_range *portRange)
3463 /* First see if this is a service, return corresponding port if so. */
3464 sp = getservbyname (str,proto);
3466 SETLOPORT(*portRange, ntohs(sp->s_port));
3467 SETNUMPORTS(*portRange, 1);
3471 /* Not a service, see if it's a single port or port range. */
3472 sep = strchr (str, '-');
3474 SETLOPORT(*portRange, strtol(str, &end, 10));
3477 SETNUMPORTS(*portRange, 1);
3481 /* Error in port range field. */
3482 errx (EX_DATAERR, "%s/%s: unknown service", str, proto);
3485 /* Port range, get the values and sanity check. */
3486 sscanf (str, "%hu-%hu", &loPort, &hiPort);
3487 SETLOPORT(*portRange, loPort);
3488 SETNUMPORTS(*portRange, 0); /* Error by default */
3489 if (loPort <= hiPort)
3490 SETNUMPORTS(*portRange, hiPort - loPort + 1);
3492 if (GETNUMPORTS(*portRange) == 0)
3493 errx (EX_DATAERR, "invalid port range %s", str);
3499 StrToProto (const char* str)
3501 if (!strcmp (str, "tcp"))
3504 if (!strcmp (str, "udp"))
3507 errx (EX_DATAERR, "unknown protocol %s. Expected tcp or udp", str);
3511 StrToAddrAndPortRange (const char* str, struct in_addr* addr, char* proto,
3512 port_range *portRange)
3516 ptr = strchr (str, ':');
3518 errx (EX_DATAERR, "%s is missing port number", str);
3523 StrToAddr (str, addr);
3524 return StrToPortRange (ptr, proto, portRange);
3527 /* End of stuff taken from natd.c. */
3529 #define INC_ARGCV() do { \
3537 * The next 3 functions add support for the addr, port and proto redirect and
3538 * their logic is loosely based on SetupAddressRedirect(), SetupPortRedirect()
3539 * and SetupProtoRedirect() from natd.c.
3541 * Every setup_* function fills at least one redirect entry
3542 * (struct cfg_redir) and zero or more server pool entry (struct cfg_spool)
3545 * The format of data in buf is:
3548 * cfg_nat cfg_redir cfg_spool ...... cfg_spool
3550 * ------------------------------------- ------------
3551 * | | .....X ... | | | | .....
3552 * ------------------------------------- ...... ------------
3554 * spool_cnt n=0 ...... n=(X-1)
3556 * len points to the amount of available space in buf
3557 * space counts the memory consumed by every function
3559 * XXX - Every function get all the argv params so it
3560 * has to check, in optional parameters, that the next
3561 * args is a valid option for the redir entry and not
3562 * another token. Only redir_port and redir_proto are
3567 setup_redir_addr(char *spool_buf, int len,
3568 int *_ac, char ***_av)
3570 char **av, *sep; /* Token separator. */
3571 /* Temporary buffer used to hold server pool ip's. */
3572 char tmp_spool_buf[NAT_BUF_LEN];
3573 int ac, space, lsnat;
3574 struct cfg_redir *r;
3575 struct cfg_spool *tmp;
3581 if (len >= SOF_REDIR) {
3582 r = (struct cfg_redir *)spool_buf;
3583 /* Skip cfg_redir at beginning of buf. */
3584 spool_buf = &spool_buf[SOF_REDIR];
3589 r->mode = REDIR_ADDR;
3590 /* Extract local address. */
3592 errx(EX_DATAERR, "redirect_addr: missing local address");
3593 sep = strchr(*av, ',');
3594 if (sep) { /* LSNAT redirection syntax. */
3595 r->laddr.s_addr = INADDR_NONE;
3596 /* Preserve av, copy spool servers to tmp_spool_buf. */
3597 strncpy(tmp_spool_buf, *av, strlen(*av)+1);
3600 StrToAddr(*av, &r->laddr);
3603 /* Extract public address. */
3605 errx(EX_DATAERR, "redirect_addr: missing public address");
3606 StrToAddr(*av, &r->paddr);
3609 /* Setup LSNAT server pool. */
3611 sep = strtok(tmp_spool_buf, ",");
3612 while (sep != NULL) {
3613 tmp = (struct cfg_spool *)spool_buf;
3614 if (len < SOF_SPOOL)
3618 StrToAddr(sep, &tmp->addr);
3621 /* Point to the next possible cfg_spool. */
3622 spool_buf = &spool_buf[SOF_SPOOL];
3623 sep = strtok(NULL, ",");
3628 errx(EX_DATAERR, "redirect_addr: buf is too small\n");
3632 setup_redir_port(char *spool_buf, int len,
3633 int *_ac, char ***_av)
3635 char **av, *sep, *protoName;
3636 char tmp_spool_buf[NAT_BUF_LEN];
3637 int ac, space, lsnat;
3638 struct cfg_redir *r;
3639 struct cfg_spool *tmp;
3640 u_short numLocalPorts;
3641 port_range portRange;
3649 if (len >= SOF_REDIR) {
3650 r = (struct cfg_redir *)spool_buf;
3651 /* Skip cfg_redir at beginning of buf. */
3652 spool_buf = &spool_buf[SOF_REDIR];
3657 r->mode = REDIR_PORT;
3662 errx (EX_DATAERR, "redirect_port: missing protocol");
3663 r->proto = StrToProto(*av);
3668 * Extract local address.
3671 errx (EX_DATAERR, "redirect_port: missing local address");
3673 sep = strchr(*av, ',');
3674 /* LSNAT redirection syntax. */
3676 r->laddr.s_addr = INADDR_NONE;
3679 /* Preserve av, copy spool servers to tmp_spool_buf. */
3680 strncpy(tmp_spool_buf, *av, strlen(*av)+1);
3683 if (StrToAddrAndPortRange (*av, &r->laddr, protoName,
3685 errx(EX_DATAERR, "redirect_port:"
3686 "invalid local port range");
3688 r->lport = GETLOPORT(portRange);
3689 numLocalPorts = GETNUMPORTS(portRange);
3694 * Extract public port and optionally address.
3697 errx (EX_DATAERR, "redirect_port: missing public port");
3699 sep = strchr (*av, ':');
3701 if (StrToAddrAndPortRange (*av, &r->paddr, protoName,
3703 errx(EX_DATAERR, "redirect_port:"
3704 "invalid public port range");
3706 r->paddr.s_addr = INADDR_ANY;
3707 if (StrToPortRange (*av, protoName, &portRange) != 0)
3708 errx(EX_DATAERR, "redirect_port:"
3709 "invalid public port range");
3712 r->pport = GETLOPORT(portRange);
3713 r->pport_cnt = GETNUMPORTS(portRange);
3717 * Extract remote address and optionally port.
3720 * NB: isalpha(**av) => we've to check that next parameter is really an
3721 * option for this redirect entry, else stop here processing arg[cv].
3723 if (ac != 0 && !isalpha(**av)) {
3724 sep = strchr (*av, ':');
3726 if (StrToAddrAndPortRange (*av, &r->raddr, protoName,
3728 errx(EX_DATAERR, "redirect_port:"
3729 "invalid remote port range");
3731 SETLOPORT(portRange, 0);
3732 SETNUMPORTS(portRange, 1);
3733 StrToAddr (*av, &r->raddr);
3737 SETLOPORT(portRange, 0);
3738 SETNUMPORTS(portRange, 1);
3739 r->raddr.s_addr = INADDR_ANY;
3741 r->rport = GETLOPORT(portRange);
3742 r->rport_cnt = GETNUMPORTS(portRange);
3745 * Make sure port ranges match up, then add the redirect ports.
3747 if (numLocalPorts != r->pport_cnt)
3748 errx(EX_DATAERR, "redirect_port:"
3749 "port ranges must be equal in size");
3751 /* Remote port range is allowed to be '0' which means all ports. */
3752 if (r->rport_cnt != numLocalPorts &&
3753 (r->rport_cnt != 1 || r->rport != 0))
3754 errx(EX_DATAERR, "redirect_port: remote port must"
3755 "be 0 or equal to local port range in size");
3758 * Setup LSNAT server pool.
3761 sep = strtok(tmp_spool_buf, ",");
3762 while (sep != NULL) {
3763 tmp = (struct cfg_spool *)spool_buf;
3764 if (len < SOF_SPOOL)
3768 if (StrToAddrAndPortRange(sep, &tmp->addr, protoName,
3770 errx(EX_DATAERR, "redirect_port:"
3771 "invalid local port range");
3772 if (GETNUMPORTS(portRange) != 1)
3773 errx(EX_DATAERR, "redirect_port: local port"
3774 "must be single in this context");
3775 tmp->port = GETLOPORT(portRange);
3777 /* Point to the next possible cfg_spool. */
3778 spool_buf = &spool_buf[SOF_SPOOL];
3779 sep = strtok(NULL, ",");
3784 errx(EX_DATAERR, "redirect_port: buf is too small\n");
3788 setup_redir_proto(char *spool_buf, int len,
3789 int *_ac, char ***_av)
3793 struct protoent *protoent;
3794 struct cfg_redir *r;
3798 if (len >= SOF_REDIR) {
3799 r = (struct cfg_redir *)spool_buf;
3800 /* Skip cfg_redir at beginning of buf. */
3801 spool_buf = &spool_buf[SOF_REDIR];
3806 r->mode = REDIR_PROTO;
3811 errx(EX_DATAERR, "redirect_proto: missing protocol");
3813 protoent = getprotobyname(*av);
3814 if (protoent == NULL)
3815 errx(EX_DATAERR, "redirect_proto: unknown protocol %s", *av);
3817 r->proto = protoent->p_proto;
3822 * Extract local address.
3825 errx(EX_DATAERR, "redirect_proto: missing local address");
3827 StrToAddr(*av, &r->laddr);
3832 * Extract optional public address.
3835 r->paddr.s_addr = INADDR_ANY;
3836 r->raddr.s_addr = INADDR_ANY;
3838 /* see above in setup_redir_port() */
3839 if (!isalpha(**av)) {
3840 StrToAddr(*av, &r->paddr);
3844 * Extract optional remote address.
3846 /* see above in setup_redir_port() */
3847 if (ac!=0 && !isalpha(**av)) {
3848 StrToAddr(*av, &r->raddr);
3855 errx(EX_DATAERR, "redirect_proto: buf is too small\n");
3859 show_nat(int ac, char **av);
3862 print_nat_config(char *buf) {
3864 int i, cnt, flag, off;
3865 struct cfg_redir *t;
3866 struct cfg_spool *s;
3869 n = (struct cfg_nat *)buf;
3872 printf("ipfw nat %u config", n->id);
3873 if (strlen(n->if_name) != 0)
3874 printf(" if %s", n->if_name);
3875 else if (n->ip.s_addr != 0)
3876 printf(" ip %s", inet_ntoa(n->ip));
3877 while (n->mode != 0) {
3878 if (n->mode & PKT_ALIAS_LOG) {
3880 n->mode &= ~PKT_ALIAS_LOG;
3881 } else if (n->mode & PKT_ALIAS_DENY_INCOMING) {
3883 n->mode &= ~PKT_ALIAS_DENY_INCOMING;
3884 } else if (n->mode & PKT_ALIAS_SAME_PORTS) {
3885 printf(" same_ports");
3886 n->mode &= ~PKT_ALIAS_SAME_PORTS;
3887 } else if (n->mode & PKT_ALIAS_UNREGISTERED_ONLY) {
3888 printf(" unreg_only");
3889 n->mode &= ~PKT_ALIAS_UNREGISTERED_ONLY;
3890 } else if (n->mode & PKT_ALIAS_RESET_ON_ADDR_CHANGE) {
3892 n->mode &= ~PKT_ALIAS_RESET_ON_ADDR_CHANGE;
3893 } else if (n->mode & PKT_ALIAS_REVERSE) {
3895 n->mode &= ~PKT_ALIAS_REVERSE;
3896 } else if (n->mode & PKT_ALIAS_PROXY_ONLY) {
3897 printf(" proxy_only");
3898 n->mode &= ~PKT_ALIAS_PROXY_ONLY;
3901 /* Print all the redirect's data configuration. */
3902 for (cnt = 0; cnt < n->redir_cnt; cnt++) {
3903 t = (struct cfg_redir *)&buf[off];
3907 printf(" redirect_addr");
3908 if (t->spool_cnt == 0)
3909 printf(" %s", inet_ntoa(t->laddr));
3911 for (i = 0; i < t->spool_cnt; i++) {
3912 s = (struct cfg_spool *)&buf[off];
3917 printf("%s", inet_ntoa(s->addr));
3920 printf(" %s", inet_ntoa(t->paddr));
3923 p = getprotobynumber(t->proto);
3924 printf(" redirect_port %s ", p->p_name);
3925 if (!t->spool_cnt) {
3926 printf("%s:%u", inet_ntoa(t->laddr), t->lport);
3927 if (t->pport_cnt > 1)
3928 printf("-%u", t->lport +
3931 for (i=0; i < t->spool_cnt; i++) {
3932 s = (struct cfg_spool *)&buf[off];
3935 printf("%s:%u", inet_ntoa(s->addr),
3941 if (t->paddr.s_addr)
3942 printf("%s:", inet_ntoa(t->paddr));
3943 printf("%u", t->pport);
3944 if (!t->spool_cnt && t->pport_cnt > 1)
3945 printf("-%u", t->pport + t->pport_cnt - 1);
3947 if (t->raddr.s_addr) {
3948 printf(" %s", inet_ntoa(t->raddr));
3950 printf(":%u", t->rport);
3951 if (!t->spool_cnt && t->rport_cnt > 1)
3952 printf("-%u", t->rport +
3958 p = getprotobynumber(t->proto);
3959 printf(" redirect_proto %s %s", p->p_name,
3960 inet_ntoa(t->laddr));
3961 if (t->paddr.s_addr != 0) {
3962 printf(" %s", inet_ntoa(t->paddr));
3963 if (t->raddr.s_addr)
3964 printf(" %s", inet_ntoa(t->raddr));
3968 errx(EX_DATAERR, "unknown redir mode");
3976 config_nat(int ac, char **av)
3978 struct cfg_nat *n; /* Nat instance configuration. */
3979 int i, len, off, tok;
3980 char *id, buf[NAT_BUF_LEN]; /* Buffer for serialized data. */
3983 /* Offset in buf: save space for n at the beginning. */
3985 memset(buf, 0, sizeof(buf));
3986 n = (struct cfg_nat *)buf;
3990 if (ac && isdigit(**av)) {
3996 errx(EX_DATAERR, "missing nat id");
3998 errx(EX_DATAERR, "missing option");
4001 tok = match_token(nat_params, *av);
4006 errx(EX_DATAERR, "missing option");
4007 if (!inet_aton(av[0], &(n->ip)))
4008 errx(EX_DATAERR, "bad ip address ``%s''",
4014 errx(EX_DATAERR, "missing option");
4015 set_addr_dynamic(av[0], n);
4019 n->mode |= PKT_ALIAS_LOG;
4022 n->mode |= PKT_ALIAS_DENY_INCOMING;
4024 case TOK_SAME_PORTS:
4025 n->mode |= PKT_ALIAS_SAME_PORTS;
4027 case TOK_UNREG_ONLY:
4028 n->mode |= PKT_ALIAS_UNREGISTERED_ONLY;
4030 case TOK_RESET_ADDR:
4031 n->mode |= PKT_ALIAS_RESET_ON_ADDR_CHANGE;
4034 n->mode |= PKT_ALIAS_REVERSE;
4036 case TOK_PROXY_ONLY:
4037 n->mode |= PKT_ALIAS_PROXY_ONLY;
4040 * All the setup_redir_* functions work directly in the final
4041 * buffer, see above for details.
4043 case TOK_REDIR_ADDR:
4044 case TOK_REDIR_PORT:
4045 case TOK_REDIR_PROTO:
4047 case TOK_REDIR_ADDR:
4048 i = setup_redir_addr(&buf[off], len, &ac, &av);
4050 case TOK_REDIR_PORT:
4051 i = setup_redir_port(&buf[off], len, &ac, &av);
4053 case TOK_REDIR_PROTO:
4054 i = setup_redir_proto(&buf[off], len, &ac, &av);
4062 errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]);
4066 i = do_cmd(IP_FW_NAT_CFG, buf, off);
4068 err(1, "setsockopt(%s)", "IP_FW_NAT_CFG");
4071 /* After every modification, we show the resultant rule. */
4073 char *_av[] = {"show", "config", id};
4079 config_pipe(int ac, char **av)
4086 memset(&p, 0, sizeof p);
4090 if (ac && isdigit(**av)) {
4091 i = atoi(*av); av++; ac--;
4099 int tok = match_token(dummynet_params, *av);
4104 p.fs.flags_fs |= DN_NOERROR;
4108 NEED1("plr needs argument 0..1\n");
4109 d = strtod(av[0], NULL);
4114 p.fs.plr = (int)(d*0x7fffffff);
4119 NEED1("queue needs queue size\n");
4121 p.fs.qsize = strtoul(av[0], &end, 0);
4122 if (*end == 'K' || *end == 'k') {
4123 p.fs.flags_fs |= DN_QSIZE_IS_BYTES;
4125 } else if (*end == 'B' ||
4126 _substrcmp2(end, "by", "bytes") == 0) {
4127 p.fs.flags_fs |= DN_QSIZE_IS_BYTES;
4133 NEED1("buckets needs argument\n");
4134 p.fs.rq_size = strtoul(av[0], NULL, 0);
4139 NEED1("mask needs mask specifier\n");
4141 * per-flow queue, mask is dst_ip, dst_port,
4142 * src_ip, src_port, proto measured in bits
4146 bzero(&p.fs.flow_mask, sizeof(p.fs.flow_mask));
4150 uint32_t *p32 = NULL;
4151 uint16_t *p16 = NULL;
4152 uint32_t *p20 = NULL;
4153 struct in6_addr *pa6 = NULL;
4156 tok = match_token(dummynet_params, *av);
4161 * special case, all bits significant
4163 p.fs.flow_mask.dst_ip = ~0;
4164 p.fs.flow_mask.src_ip = ~0;
4165 p.fs.flow_mask.dst_port = ~0;
4166 p.fs.flow_mask.src_port = ~0;
4167 p.fs.flow_mask.proto = ~0;
4168 n2mask(&(p.fs.flow_mask.dst_ip6), 128);
4169 n2mask(&(p.fs.flow_mask.src_ip6), 128);
4170 p.fs.flow_mask.flow_id6 = ~0;
4171 p.fs.flags_fs |= DN_HAVE_FLOW_MASK;
4175 p32 = &p.fs.flow_mask.dst_ip;
4179 p32 = &p.fs.flow_mask.src_ip;
4183 pa6 = &(p.fs.flow_mask.dst_ip6);
4187 pa6 = &(p.fs.flow_mask.src_ip6);
4191 p20 = &p.fs.flow_mask.flow_id6;
4195 p16 = &p.fs.flow_mask.dst_port;
4199 p16 = &p.fs.flow_mask.src_port;
4206 ac++; av--; /* backtrack */
4210 errx(EX_USAGE, "mask: value missing");
4211 if (*av[0] == '/') {
4212 a = strtoul(av[0]+1, &end, 0);
4214 a = (a == 32) ? ~0 : (1 << a) - 1;
4216 a = strtoul(av[0], &end, 0);
4219 else if (p16 != NULL) {
4222 "port mask must be 16 bit");
4224 } else if (p20 != NULL) {
4227 "flow_id mask must be 20 bit");
4229 } else if (pa6 != NULL) {
4230 if (a < 0 || a > 128)
4232 "in6addr invalid mask len");
4238 "proto mask must be 8 bit");
4239 p.fs.flow_mask.proto = (uint8_t)a;
4242 p.fs.flags_fs |= DN_HAVE_FLOW_MASK;
4244 } /* end while, config masks */
4250 NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
4251 p.fs.flags_fs |= DN_IS_RED;
4252 if (tok == TOK_GRED)
4253 p.fs.flags_fs |= DN_IS_GENTLE_RED;
4255 * the format for parameters is w_q/min_th/max_th/max_p
4257 if ((end = strsep(&av[0], "/"))) {
4258 double w_q = strtod(end, NULL);
4259 if (w_q > 1 || w_q <= 0)
4260 errx(EX_DATAERR, "0 < w_q <= 1");
4261 p.fs.w_q = (int) (w_q * (1 << SCALE_RED));
4263 if ((end = strsep(&av[0], "/"))) {
4264 p.fs.min_th = strtoul(end, &end, 0);
4265 if (*end == 'K' || *end == 'k')
4266 p.fs.min_th *= 1024;
4268 if ((end = strsep(&av[0], "/"))) {
4269 p.fs.max_th = strtoul(end, &end, 0);
4270 if (*end == 'K' || *end == 'k')
4271 p.fs.max_th *= 1024;
4273 if ((end = strsep(&av[0], "/"))) {
4274 double max_p = strtod(end, NULL);
4275 if (max_p > 1 || max_p <= 0)
4276 errx(EX_DATAERR, "0 < max_p <= 1");
4277 p.fs.max_p = (int)(max_p * (1 << SCALE_RED));
4283 p.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
4287 NEED1("bw needs bandwidth or interface\n");
4289 errx(EX_DATAERR, "bandwidth only valid for pipes");
4291 * set clocking interface or bandwidth value
4293 if (av[0][0] >= 'a' && av[0][0] <= 'z') {
4294 int l = sizeof(p.if_name)-1;
4295 /* interface name */
4296 strncpy(p.if_name, av[0], l);
4297 p.if_name[l] = '\0';
4300 p.if_name[0] = '\0';
4301 p.bandwidth = strtoul(av[0], &end, 0);
4302 if (*end == 'K' || *end == 'k') {
4304 p.bandwidth *= 1000;
4305 } else if (*end == 'M') {
4307 p.bandwidth *= 1000000;
4310 _substrcmp2(end, "Bi", "Bit/s") != 0) ||
4311 _substrcmp2(end, "by", "bytes") == 0)
4313 if (p.bandwidth < 0)
4314 errx(EX_DATAERR, "bandwidth too large");
4321 errx(EX_DATAERR, "delay only valid for pipes");
4322 NEED1("delay needs argument 0..10000ms\n");
4323 p.delay = strtoul(av[0], NULL, 0);
4329 errx(EX_DATAERR,"weight only valid for queues");
4330 NEED1("weight needs argument 0..100\n");
4331 p.fs.weight = strtoul(av[0], &end, 0);
4337 errx(EX_DATAERR,"pipe only valid for queues");
4338 NEED1("pipe needs pipe_number\n");
4339 p.fs.parent_nr = strtoul(av[0], &end, 0);
4344 errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]);
4349 errx(EX_DATAERR, "pipe_nr must be > 0");
4350 if (p.delay > 10000)
4351 errx(EX_DATAERR, "delay must be < 10000");
4352 } else { /* do_pipe == 2, queue */
4353 if (p.fs.parent_nr == 0)
4354 errx(EX_DATAERR, "pipe must be > 0");
4355 if (p.fs.weight >100)
4356 errx(EX_DATAERR, "weight must be <= 100");
4358 if (p.fs.flags_fs & DN_QSIZE_IS_BYTES) {
4362 len = sizeof(limit);
4363 if (sysctlbyname("net.inet.ip.dummynet.pipe_byte_limit",
4364 &limit, &len, NULL, 0) == -1)
4366 if (p.fs.qsize > limit)
4367 errx(EX_DATAERR, "queue size must be < %ldB", limit);
4372 len = sizeof(limit);
4373 if (sysctlbyname("net.inet.ip.dummynet.pipe_slot_limit",
4374 &limit, &len, NULL, 0) == -1)
4376 if (p.fs.qsize > limit)
4377 errx(EX_DATAERR, "2 <= queue size <= %ld", limit);
4379 if (p.fs.flags_fs & DN_IS_RED) {
4381 int lookup_depth, avg_pkt_size;
4382 double s, idle, weight, w_q;
4383 struct clockinfo ck;
4386 if (p.fs.min_th >= p.fs.max_th)
4387 errx(EX_DATAERR, "min_th %d must be < than max_th %d",
4388 p.fs.min_th, p.fs.max_th);
4389 if (p.fs.max_th == 0)
4390 errx(EX_DATAERR, "max_th must be > 0");
4393 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
4394 &lookup_depth, &len, NULL, 0) == -1)
4395 errx(1, "sysctlbyname(\"%s\")",
4396 "net.inet.ip.dummynet.red_lookup_depth");
4397 if (lookup_depth == 0)
4398 errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
4399 " must be greater than zero");
4402 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
4403 &avg_pkt_size, &len, NULL, 0) == -1)
4405 errx(1, "sysctlbyname(\"%s\")",
4406 "net.inet.ip.dummynet.red_avg_pkt_size");
4407 if (avg_pkt_size == 0)
4409 "net.inet.ip.dummynet.red_avg_pkt_size must"
4410 " be greater than zero");
4412 len = sizeof(struct clockinfo);
4413 if (sysctlbyname("kern.clockrate", &ck, &len, NULL, 0) == -1)
4414 errx(1, "sysctlbyname(\"%s\")", "kern.clockrate");
4417 * Ticks needed for sending a medium-sized packet.
4418 * Unfortunately, when we are configuring a WF2Q+ queue, we
4419 * do not have bandwidth information, because that is stored
4420 * in the parent pipe, and also we have multiple queues
4421 * competing for it. So we set s=0, which is not very
4422 * correct. But on the other hand, why do we want RED with
4425 if (p.bandwidth==0) /* this is a WF2Q+ queue */
4428 s = (double)ck.hz * avg_pkt_size * 8 / p.bandwidth;
4431 * max idle time (in ticks) before avg queue size becomes 0.
4432 * NOTA: (3/w_q) is approx the value x so that
4433 * (1-w_q)^x < 10^-3.
4435 w_q = ((double)p.fs.w_q) / (1 << SCALE_RED);
4436 idle = s * 3. / w_q;
4437 p.fs.lookup_step = (int)idle / lookup_depth;
4438 if (!p.fs.lookup_step)
4439 p.fs.lookup_step = 1;
4441 for (t = p.fs.lookup_step; t > 1; --t)
4443 p.fs.lookup_weight = (int)(weight * (1 << SCALE_RED));
4445 i = do_cmd(IP_DUMMYNET_CONFIGURE, &p, sizeof p);
4447 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
4451 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
4454 char *ap, *ptr, *optr;
4455 struct ether_addr *mac;
4456 const char *macset = "0123456789abcdefABCDEF:";
4458 if (strcmp(p, "any") == 0) {
4459 for (i = 0; i < ETHER_ADDR_LEN; i++)
4460 addr[i] = mask[i] = 0;
4464 optr = ptr = strdup(p);
4465 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
4467 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
4468 errx(EX_DATAERR, "Incorrect MAC address");
4469 bcopy(mac, addr, ETHER_ADDR_LEN);
4471 errx(EX_DATAERR, "Incorrect MAC address");
4473 if (ptr != NULL) { /* we have mask? */
4474 if (p[ptr - optr - 1] == '/') { /* mask len */
4475 l = strtol(ptr, &ap, 10);
4476 if (*ap != 0 || l > ETHER_ADDR_LEN * 8 || l < 0)
4477 errx(EX_DATAERR, "Incorrect mask length");
4478 for (i = 0; l > 0 && i < ETHER_ADDR_LEN; l -= 8, i++)
4479 mask[i] = (l >= 8) ? 0xff: (~0) << (8 - l);
4482 if (strspn(ptr, macset) != l ||
4483 (mac = ether_aton(ptr)) == NULL)
4484 errx(EX_DATAERR, "Incorrect mask");
4485 bcopy(mac, mask, ETHER_ADDR_LEN);
4487 } else { /* default mask: ff:ff:ff:ff:ff:ff */
4488 for (i = 0; i < ETHER_ADDR_LEN; i++)
4491 for (i = 0; i < ETHER_ADDR_LEN; i++)
4498 * helper function, updates the pointer to cmd with the length
4499 * of the current command, and also cleans up the first word of
4500 * the new command in case it has been clobbered before.
4503 next_cmd(ipfw_insn *cmd)
4506 bzero(cmd, sizeof(*cmd));
4511 * Takes arguments and copies them into a comment
4514 fill_comment(ipfw_insn *cmd, int ac, char **av)
4517 char *p = (char *)(cmd + 1);
4519 cmd->opcode = O_NOP;
4520 cmd->len = (cmd->len & (F_NOT | F_OR));
4522 /* Compute length of comment string. */
4523 for (i = 0, l = 0; i < ac; i++)
4524 l += strlen(av[i]) + 1;
4529 "comment too long (max 80 chars)");
4531 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
4532 for (i = 0; i < ac; i++) {
4541 * A function to fill simple commands of size 1.
4542 * Existing flags are preserved.
4545 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
4547 cmd->opcode = opcode;
4548 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
4553 * Fetch and add the MAC address and type, with masks. This generates one or
4554 * two microinstructions, and returns the pointer to the last one.
4557 add_mac(ipfw_insn *cmd, int ac, char *av[])
4562 errx(EX_DATAERR, "MAC dst src");
4564 cmd->opcode = O_MACADDR2;
4565 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
4567 mac = (ipfw_insn_mac *)cmd;
4568 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
4569 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
4570 &(mac->mask[ETHER_ADDR_LEN])); /* src */
4575 add_mactype(ipfw_insn *cmd, int ac, char *av)
4578 errx(EX_DATAERR, "missing MAC type");
4579 if (strcmp(av, "any") != 0) { /* we have a non-null type */
4580 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE);
4581 cmd->opcode = O_MAC_TYPE;
4588 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
4590 struct protoent *pe;
4594 proto = strtol(av, &ep, 10);
4595 if (*ep != '\0' || proto <= 0) {
4596 if ((pe = getprotobyname(av)) == NULL)
4598 proto = pe->p_proto;
4601 fill_cmd(cmd, O_PROTO, 0, proto);
4607 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
4609 u_char proto = IPPROTO_IP;
4611 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
4612 ; /* do not set O_IP4 nor O_IP6 */
4613 else if (strcmp(av, "ip4") == 0)
4614 /* explicit "just IPv4" rule */
4615 fill_cmd(cmd, O_IP4, 0, 0);
4616 else if (strcmp(av, "ip6") == 0) {
4617 /* explicit "just IPv6" rule */
4618 proto = IPPROTO_IPV6;
4619 fill_cmd(cmd, O_IP6, 0, 0);
4621 return add_proto0(cmd, av, protop);
4628 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
4630 u_char proto = IPPROTO_IP;
4632 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
4633 ; /* do not set O_IP4 nor O_IP6 */
4634 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
4635 /* explicit "just IPv4" rule */
4636 fill_cmd(cmd, O_IP4, 0, 0);
4637 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
4638 /* explicit "just IPv6" rule */
4639 proto = IPPROTO_IPV6;
4640 fill_cmd(cmd, O_IP6, 0, 0);
4642 return add_proto0(cmd, av, protop);
4649 add_srcip(ipfw_insn *cmd, char *av)
4651 fill_ip((ipfw_insn_ip *)cmd, av);
4652 if (cmd->opcode == O_IP_DST_SET) /* set */
4653 cmd->opcode = O_IP_SRC_SET;
4654 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
4655 cmd->opcode = O_IP_SRC_LOOKUP;
4656 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
4657 cmd->opcode = O_IP_SRC_ME;
4658 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
4659 cmd->opcode = O_IP_SRC;
4660 else /* addr/mask */
4661 cmd->opcode = O_IP_SRC_MASK;
4666 add_dstip(ipfw_insn *cmd, char *av)
4668 fill_ip((ipfw_insn_ip *)cmd, av);
4669 if (cmd->opcode == O_IP_DST_SET) /* set */
4671 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
4673 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
4674 cmd->opcode = O_IP_DST_ME;
4675 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
4676 cmd->opcode = O_IP_DST;
4677 else /* addr/mask */
4678 cmd->opcode = O_IP_DST_MASK;
4683 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode)
4685 if (_substrcmp(av, "any") == 0) {
4687 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) {
4688 /* XXX todo: check that we have a protocol with ports */
4689 cmd->opcode = opcode;
4696 add_src(ipfw_insn *cmd, char *av, u_char proto)
4700 ipfw_insn *ret = NULL;
4702 if ((host = strdup(av)) == NULL)
4704 if ((ch = strrchr(host, '/')) != NULL)
4707 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
4708 inet_pton(AF_INET6, host, &a))
4709 ret = add_srcip6(cmd, av);
4710 /* XXX: should check for IPv4, not !IPv6 */
4711 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
4712 !inet_pton(AF_INET6, host, &a)))
4713 ret = add_srcip(cmd, av);
4714 if (ret == NULL && strcmp(av, "any") != 0)
4722 add_dst(ipfw_insn *cmd, char *av, u_char proto)
4726 ipfw_insn *ret = NULL;
4728 if ((host = strdup(av)) == NULL)
4730 if ((ch = strrchr(host, '/')) != NULL)
4733 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
4734 inet_pton(AF_INET6, host, &a))
4735 ret = add_dstip6(cmd, av);
4736 /* XXX: should check for IPv4, not !IPv6 */
4737 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
4738 !inet_pton(AF_INET6, host, &a)))
4739 ret = add_dstip(cmd, av);
4740 if (ret == NULL && strcmp(av, "any") != 0)
4748 * Parse arguments and assemble the microinstructions which make up a rule.
4749 * Rules are added into the 'rulebuf' and then copied in the correct order
4750 * into the actual rule.
4752 * The syntax for a rule starts with the action, followed by
4753 * optional action parameters, and the various match patterns.
4754 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
4755 * (generated if the rule includes a keep-state option), then the
4756 * various match patterns, log/altq actions, and the actual action.
4760 add(int ac, char *av[])
4763 * rules are added into the 'rulebuf' and then copied in
4764 * the correct order into the actual rule.
4765 * Some things that need to go out of order (prob, action etc.)
4768 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255];
4770 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
4771 ipfw_insn *first_cmd; /* first match pattern */
4776 * various flags used to record that we entered some fields.
4778 ipfw_insn *have_state = NULL; /* check-state or keep-state */
4779 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
4784 int open_par = 0; /* open parenthesis ( */
4786 /* proto is here because it is used to fetch ports */
4787 u_char proto = IPPROTO_IP; /* default protocol */
4789 double match_prob = 1; /* match probability, default is always match */
4791 bzero(actbuf, sizeof(actbuf)); /* actions go here */
4792 bzero(cmdbuf, sizeof(cmdbuf));
4793 bzero(rulebuf, sizeof(rulebuf));
4795 rule = (struct ip_fw *)rulebuf;
4796 cmd = (ipfw_insn *)cmdbuf;
4797 action = (ipfw_insn *)actbuf;
4801 /* [rule N] -- Rule number optional */
4802 if (ac && isdigit(**av)) {
4803 rule->rulenum = atoi(*av);
4808 /* [set N] -- set number (0..RESVD_SET), optional */
4809 if (ac > 1 && _substrcmp(*av, "set") == 0) {
4810 int set = strtoul(av[1], NULL, 10);
4811 if (set < 0 || set > RESVD_SET)
4812 errx(EX_DATAERR, "illegal set %s", av[1]);
4817 /* [prob D] -- match probability, optional */
4818 if (ac > 1 && _substrcmp(*av, "prob") == 0) {
4819 match_prob = strtod(av[1], NULL);
4821 if (match_prob <= 0 || match_prob > 1)
4822 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
4826 /* action -- mandatory */
4827 NEED1("missing action");
4828 i = match_token(rule_actions, *av);
4830 action->len = 1; /* default */
4832 case TOK_CHECKSTATE:
4833 have_state = action;
4834 action->opcode = O_CHECK_STATE;
4838 action->opcode = O_ACCEPT;
4842 action->opcode = O_DENY;
4847 action->opcode = O_REJECT;
4848 action->arg1 = ICMP_UNREACH_HOST;
4852 action->opcode = O_REJECT;
4853 action->arg1 = ICMP_REJECT_RST;
4857 action->opcode = O_UNREACH6;
4858 action->arg1 = ICMP6_UNREACH_RST;
4862 action->opcode = O_REJECT;
4863 NEED1("missing reject code");
4864 fill_reject_code(&action->arg1, *av);
4869 action->opcode = O_UNREACH6;
4870 NEED1("missing unreach code");
4871 fill_unreach6_code(&action->arg1, *av);
4876 action->opcode = O_COUNT;
4880 action->opcode = O_NAT;
4881 action->len = F_INSN_SIZE(ipfw_insn_nat);
4885 action->opcode = O_QUEUE;
4888 action->opcode = O_PIPE;
4891 action->opcode = O_SKIPTO;
4894 action->opcode = O_NETGRAPH;
4897 action->opcode = O_NGTEE;
4900 action->opcode = O_DIVERT;
4903 action->opcode = O_TEE;
4906 errx(EX_USAGE, "missing argument for %s", *(av - 1));
4907 if (isdigit(**av)) {
4908 action->arg1 = strtoul(*av, NULL, 10);
4909 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
4910 errx(EX_DATAERR, "illegal argument for %s",
4912 } else if (_substrcmp(*av, TABLEARG) == 0) {
4913 action->arg1 = IP_FW_TABLEARG;
4914 } else if (i == TOK_DIVERT || i == TOK_TEE) {
4917 s = getservbyname(av[0], "divert");
4919 action->arg1 = ntohs(s->s_port);
4921 errx(EX_DATAERR, "illegal divert/tee port");
4923 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
4928 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
4931 NEED1("missing forward address[:port]");
4933 action->opcode = O_FORWARD_IP;
4934 action->len = F_INSN_SIZE(ipfw_insn_sa);
4936 p->sa.sin_len = sizeof(struct sockaddr_in);
4937 p->sa.sin_family = AF_INET;
4940 * locate the address-port separator (':' or ',')
4942 s = strchr(*av, ':');
4944 s = strchr(*av, ',');
4947 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
4950 "illegal forwarding port ``%s''", s);
4951 p->sa.sin_port = (u_short)i;
4953 if (_substrcmp(*av, "tablearg") == 0)
4954 p->sa.sin_addr.s_addr = INADDR_ANY;
4956 lookup_host(*av, &(p->sa.sin_addr));
4961 /* pretend it is a 'count' rule followed by the comment */
4962 action->opcode = O_COUNT;
4963 ac++; av--; /* go back... */
4969 size_t intsize = sizeof(int);
4971 action->opcode = O_SETFIB;
4972 NEED1("missing fib number");
4973 action->arg1 = strtoul(*av, NULL, 10);
4974 if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
4975 errx(EX_DATAERR, "fibs not suported.\n");
4976 if (action->arg1 >= numfibs) /* Temporary */
4977 errx(EX_DATAERR, "fib too large.\n");
4983 errx(EX_DATAERR, "invalid action %s\n", av[-1]);
4985 action = next_cmd(action);
4988 * [altq queuename] -- altq tag, optional
4989 * [log [logamount N]] -- log, optional
4991 * If they exist, it go first in the cmdbuf, but then it is
4992 * skipped in the copy section to the end of the buffer.
4994 while (ac != 0 && (i = match_token(rule_action_params, *av)) != -1) {
4999 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
5004 "log cannot be specified more than once");
5005 have_log = (ipfw_insn *)c;
5006 cmd->len = F_INSN_SIZE(ipfw_insn_log);
5007 cmd->opcode = O_LOG;
5008 if (ac && _substrcmp(*av, "logamount") == 0) {
5010 NEED1("logamount requires argument");
5014 "logamount must be positive");
5018 len = sizeof(c->max_log);
5019 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
5020 &c->max_log, &len, NULL, 0) == -1)
5021 errx(1, "sysctlbyname(\"%s\")",
5022 "net.inet.ip.fw.verbose_limit");
5029 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
5031 NEED1("missing altq queue name");
5034 "altq cannot be specified more than once");
5035 have_altq = (ipfw_insn *)a;
5036 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
5037 cmd->opcode = O_ALTQ;
5038 fill_altq_qid(&a->qid, *av);
5048 errx(EX_USAGE, "tag and untag cannot be "
5049 "specified more than once");
5050 GET_UINT_ARG(tag, 1, IPFW_DEFAULT_RULE - 1, i,
5051 rule_action_params);
5053 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
5061 cmd = next_cmd(cmd);
5064 if (have_state) /* must be a check-state, we are done */
5067 #define OR_START(target) \
5068 if (ac && (*av[0] == '(' || *av[0] == '{')) { \
5070 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
5073 if ( (av[0])[1] == '\0') { \
5084 strcmp(*av, ")") == 0 || \
5085 strcmp(*av, "}") == 0)) { \
5090 errx(EX_USAGE, "missing \")\"\n"); \
5094 if (ac && _substrcmp(*av, "not") == 0) { \
5095 if (cmd->len & F_NOT) \
5096 errx(EX_USAGE, "double \"not\" not allowed\n"); \
5097 cmd->len |= F_NOT; \
5101 #define OR_BLOCK(target) \
5102 if (ac && _substrcmp(*av, "or") == 0) { \
5103 if (prev == NULL || open_par == 0) \
5104 errx(EX_DATAERR, "invalid OR block"); \
5105 prev->len |= F_OR; \
5115 * MAC addresses, optional.
5116 * If we have this, we skip the part "proto from src to dst"
5117 * and jump straight to the option parsing.
5120 NEED1("missing protocol");
5121 if (_substrcmp(*av, "MAC") == 0 ||
5122 _substrcmp(*av, "mac") == 0) {
5123 ac--; av++; /* the "MAC" keyword */
5124 add_mac(cmd, ac, av); /* exits in case of errors */
5125 cmd = next_cmd(cmd);
5126 ac -= 2; av += 2; /* dst-mac and src-mac */
5128 NEED1("missing mac type");
5129 if (add_mactype(cmd, ac, av[0]))
5130 cmd = next_cmd(cmd);
5131 ac--; av++; /* any or mac-type */
5137 * protocol, mandatory
5139 OR_START(get_proto);
5141 NEED1("missing protocol");
5142 if (add_proto_compat(cmd, *av, &proto)) {
5144 if (F_LEN(cmd) != 0) {
5146 cmd = next_cmd(cmd);
5148 } else if (first_cmd != cmd) {
5149 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
5152 OR_BLOCK(get_proto);
5157 if (!ac || _substrcmp(*av, "from") != 0)
5158 errx(EX_USAGE, "missing ``from''");
5162 * source IP, mandatory
5164 OR_START(source_ip);
5165 NOT_BLOCK; /* optional "not" */
5166 NEED1("missing source address");
5167 if (add_src(cmd, *av, proto)) {
5169 if (F_LEN(cmd) != 0) { /* ! any */
5171 cmd = next_cmd(cmd);
5174 errx(EX_USAGE, "bad source address %s", *av);
5175 OR_BLOCK(source_ip);
5178 * source ports, optional
5180 NOT_BLOCK; /* optional "not" */
5182 if (_substrcmp(*av, "any") == 0 ||
5183 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
5185 if (F_LEN(cmd) != 0)
5186 cmd = next_cmd(cmd);
5193 if (!ac || _substrcmp(*av, "to") != 0)
5194 errx(EX_USAGE, "missing ``to''");
5198 * destination, mandatory
5201 NOT_BLOCK; /* optional "not" */
5202 NEED1("missing dst address");
5203 if (add_dst(cmd, *av, proto)) {
5205 if (F_LEN(cmd) != 0) { /* ! any */
5207 cmd = next_cmd(cmd);
5210 errx( EX_USAGE, "bad destination address %s", *av);
5214 * dest. ports, optional
5216 NOT_BLOCK; /* optional "not" */
5218 if (_substrcmp(*av, "any") == 0 ||
5219 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
5221 if (F_LEN(cmd) != 0)
5222 cmd = next_cmd(cmd);
5227 if (ac && first_cmd == cmd) {
5229 * nothing specified so far, store in the rule to ease
5237 ipfw_insn_u32 *cmd32; /* alias for cmd */
5240 cmd32 = (ipfw_insn_u32 *)cmd;
5242 if (*s == '!') { /* alternate syntax for NOT */
5243 if (cmd->len & F_NOT)
5244 errx(EX_USAGE, "double \"not\" not allowed\n");
5248 i = match_token(rule_options, s);
5252 if (cmd->len & F_NOT)
5253 errx(EX_USAGE, "double \"not\" not allowed\n");
5258 if (open_par == 0 || prev == NULL)
5259 errx(EX_USAGE, "invalid \"or\" block\n");
5263 case TOK_STARTBRACE:
5265 errx(EX_USAGE, "+nested \"(\" not allowed\n");
5271 errx(EX_USAGE, "+missing \")\"\n");
5277 fill_cmd(cmd, O_IN, 0, 0);
5281 cmd->len ^= F_NOT; /* toggle F_NOT */
5282 fill_cmd(cmd, O_IN, 0, 0);
5286 fill_cmd(cmd, O_DIVERTED, 0, 3);
5289 case TOK_DIVERTEDLOOPBACK:
5290 fill_cmd(cmd, O_DIVERTED, 0, 1);
5293 case TOK_DIVERTEDOUTPUT:
5294 fill_cmd(cmd, O_DIVERTED, 0, 2);
5298 fill_cmd(cmd, O_FRAG, 0, 0);
5302 fill_cmd(cmd, O_LAYER2, 0, 0);
5308 NEED1("recv, xmit, via require interface name"
5310 fill_iface((ipfw_insn_if *)cmd, av[0]);
5312 if (F_LEN(cmd) == 0) /* not a valid address */
5315 cmd->opcode = O_XMIT;
5316 else if (i == TOK_RECV)
5317 cmd->opcode = O_RECV;
5318 else if (i == TOK_VIA)
5319 cmd->opcode = O_VIA;
5323 NEED1("icmptypes requires list of types");
5324 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
5328 case TOK_ICMP6TYPES:
5329 NEED1("icmptypes requires list of types");
5330 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av);
5335 NEED1("ipttl requires TTL");
5336 if (strpbrk(*av, "-,")) {
5337 if (!add_ports(cmd, *av, 0, O_IPTTL))
5338 errx(EX_DATAERR, "invalid ipttl %s", *av);
5340 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
5345 NEED1("ipid requires id");
5346 if (strpbrk(*av, "-,")) {
5347 if (!add_ports(cmd, *av, 0, O_IPID))
5348 errx(EX_DATAERR, "invalid ipid %s", *av);
5350 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
5355 NEED1("iplen requires length");
5356 if (strpbrk(*av, "-,")) {
5357 if (!add_ports(cmd, *av, 0, O_IPLEN))
5358 errx(EX_DATAERR, "invalid ip len %s", *av);
5360 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
5365 NEED1("ipver requires version");
5366 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
5370 case TOK_IPPRECEDENCE:
5371 NEED1("ipprecedence requires value");
5372 fill_cmd(cmd, O_IPPRECEDENCE, 0,
5373 (strtoul(*av, NULL, 0) & 7) << 5);
5378 NEED1("missing argument for ipoptions");
5379 fill_flags(cmd, O_IPOPT, f_ipopts, *av);
5384 NEED1("missing argument for iptos");
5385 fill_flags(cmd, O_IPTOS, f_iptos, *av);
5390 NEED1("uid requires argument");
5396 cmd->opcode = O_UID;
5397 uid = strtoul(*av, &end, 0);
5398 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
5400 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
5401 cmd32->d[0] = pwd->pw_uid;
5402 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
5408 NEED1("gid requires argument");
5414 cmd->opcode = O_GID;
5415 gid = strtoul(*av, &end, 0);
5416 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
5418 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
5419 cmd32->d[0] = grp->gr_gid;
5420 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
5426 NEED1("jail requires argument");
5431 cmd->opcode = O_JAIL;
5432 jid = (int)strtol(*av, &end, 0);
5433 if (jid < 0 || *end != '\0')
5434 errx(EX_DATAERR, "jail requires prison ID");
5435 cmd32->d[0] = (uint32_t)jid;
5436 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
5442 fill_cmd(cmd, O_ESTAB, 0, 0);
5446 fill_cmd(cmd, O_TCPFLAGS, 0,
5447 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
5450 case TOK_TCPDATALEN:
5451 NEED1("tcpdatalen requires length");
5452 if (strpbrk(*av, "-,")) {
5453 if (!add_ports(cmd, *av, 0, O_TCPDATALEN))
5454 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
5456 fill_cmd(cmd, O_TCPDATALEN, 0,
5457 strtoul(*av, NULL, 0));
5462 NEED1("missing argument for tcpoptions");
5463 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
5469 NEED1("tcpseq/tcpack requires argument");
5470 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
5471 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
5472 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
5477 NEED1("tcpwin requires length");
5478 fill_cmd(cmd, O_TCPWIN, 0,
5479 htons(strtoul(*av, NULL, 0)));
5484 NEED1("missing argument for tcpflags");
5485 cmd->opcode = O_TCPFLAGS;
5486 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
5492 errx(EX_USAGE, "keep-state cannot be part "
5495 errx(EX_USAGE, "only one of keep-state "
5496 "and limit is allowed");
5498 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
5502 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
5507 "limit cannot be part of an or block");
5509 errx(EX_USAGE, "only one of keep-state and "
5510 "limit is allowed");
5513 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
5514 cmd->opcode = O_LIMIT;
5515 c->limit_mask = c->conn_limit = 0;
5518 if ((val = match_token(limit_masks, *av)) <= 0)
5520 c->limit_mask |= val;
5524 if (c->limit_mask == 0)
5525 errx(EX_USAGE, "limit: missing limit mask");
5527 GET_UINT_ARG(c->conn_limit, 1, IPFW_DEFAULT_RULE - 1,
5528 TOK_LIMIT, rule_options);
5535 NEED1("missing protocol");
5536 if (add_proto(cmd, *av, &proto)) {
5539 errx(EX_DATAERR, "invalid protocol ``%s''",
5544 NEED1("missing source IP");
5545 if (add_srcip(cmd, *av)) {
5551 NEED1("missing destination IP");
5552 if (add_dstip(cmd, *av)) {
5558 NEED1("missing source IP6");
5559 if (add_srcip6(cmd, *av)) {
5565 NEED1("missing destination IP6");
5566 if (add_dstip6(cmd, *av)) {
5572 NEED1("missing source port");
5573 if (_substrcmp(*av, "any") == 0 ||
5574 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
5577 errx(EX_DATAERR, "invalid source port %s", *av);
5581 NEED1("missing destination port");
5582 if (_substrcmp(*av, "any") == 0 ||
5583 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
5586 errx(EX_DATAERR, "invalid destination port %s",
5591 if (add_mac(cmd, ac, av)) {
5597 NEED1("missing mac type");
5598 if (!add_mactype(cmd, ac, *av))
5599 errx(EX_DATAERR, "invalid mac type %s", *av);
5603 case TOK_VERREVPATH:
5604 fill_cmd(cmd, O_VERREVPATH, 0, 0);
5607 case TOK_VERSRCREACH:
5608 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
5612 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
5616 fill_cmd(cmd, O_IPSEC, 0, 0);
5620 fill_cmd(cmd, O_IP6, 0, 0);
5624 fill_cmd(cmd, O_IP4, 0, 0);
5628 fill_ext6hdr( cmd, *av );
5633 if (proto != IPPROTO_IPV6 )
5634 errx( EX_USAGE, "flow-id filter is active "
5635 "only for ipv6 protocol\n");
5636 fill_flow6( (ipfw_insn_u32 *) cmd, *av );
5641 fill_comment(cmd, ac, av);
5647 if (ac > 0 && strpbrk(*av, "-,")) {
5648 if (!add_ports(cmd, *av, 0, O_TAGGED))
5649 errx(EX_DATAERR, "tagged: invalid tag"
5655 GET_UINT_ARG(tag, 1, IPFW_DEFAULT_RULE - 1,
5656 TOK_TAGGED, rule_options);
5657 fill_cmd(cmd, O_TAGGED, 0, tag);
5663 NEED1("fib requires fib number");
5664 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
5669 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
5671 if (F_LEN(cmd) > 0) { /* prepare to advance */
5673 cmd = next_cmd(cmd);
5679 * Now copy stuff into the rule.
5680 * If we have a keep-state option, the first instruction
5681 * must be a PROBE_STATE (which is generated here).
5682 * If we have a LOG option, it was stored as the first command,
5683 * and now must be moved to the top of the action part.
5685 dst = (ipfw_insn *)rule->cmd;
5688 * First thing to write into the command stream is the match probability.
5690 if (match_prob != 1) { /* 1 means always match */
5691 dst->opcode = O_PROB;
5693 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
5698 * generate O_PROBE_STATE if necessary
5700 if (have_state && have_state->opcode != O_CHECK_STATE) {
5701 fill_cmd(dst, O_PROBE_STATE, 0, 0);
5702 dst = next_cmd(dst);
5705 /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
5706 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
5709 switch (src->opcode) {
5717 bcopy(src, dst, i * sizeof(uint32_t));
5723 * put back the have_state command as last opcode
5725 if (have_state && have_state->opcode != O_CHECK_STATE) {
5726 i = F_LEN(have_state);
5727 bcopy(have_state, dst, i * sizeof(uint32_t));
5731 * start action section
5733 rule->act_ofs = dst - rule->cmd;
5735 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
5737 i = F_LEN(have_log);
5738 bcopy(have_log, dst, i * sizeof(uint32_t));
5742 i = F_LEN(have_altq);
5743 bcopy(have_altq, dst, i * sizeof(uint32_t));
5747 i = F_LEN(have_tag);
5748 bcopy(have_tag, dst, i * sizeof(uint32_t));
5752 * copy all other actions
5754 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
5756 bcopy(src, dst, i * sizeof(uint32_t));
5760 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
5761 i = (char *)dst - (char *)rule;
5762 if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1)
5763 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
5765 show_ipfw(rule, 0, 0);
5769 zero(int ac, char *av[], int optname /* IP_FW_ZERO or IP_FW_RESETLOG */)
5771 uint32_t arg, saved_arg;
5773 char const *name = optname == IP_FW_ZERO ? "ZERO" : "RESETLOG";
5779 /* clear all entries */
5780 if (do_cmd(optname, NULL, 0) < 0)
5781 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name);
5783 printf("%s.\n", optname == IP_FW_ZERO ?
5784 "Accounting cleared":"Logging counts reset");
5791 if (isdigit(**av)) {
5792 arg = strtonum(*av, 0, 0xffff, &errstr);
5795 "invalid rule number %s\n", *av);
5798 arg |= (1 << 24) | ((use_set - 1) << 16);
5801 if (do_cmd(optname, &arg, sizeof(arg))) {
5802 warn("rule %u: setsockopt(IP_FW_%s)",
5804 failed = EX_UNAVAILABLE;
5805 } else if (!do_quiet)
5806 printf("Entry %d %s.\n", saved_arg,
5807 optname == IP_FW_ZERO ?
5808 "cleared" : "logging count reset");
5810 errx(EX_USAGE, "invalid rule number ``%s''", *av);
5813 if (failed != EX_OK)
5820 int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
5822 if (!force && !do_quiet) { /* need to ask user */
5825 printf("Are you sure? [yn] ");
5828 c = toupper(getc(stdin));
5829 while (c != '\n' && getc(stdin) != '\n')
5831 return; /* and do not flush */
5832 } while (c != 'Y' && c != 'N');
5834 if (c == 'N') /* user said no */
5837 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
5839 uint32_t arg = ((use_set - 1) & 0xffff) | (1 << 24);
5840 if (do_cmd(IP_FW_DEL, &arg, sizeof(arg)) < 0)
5841 err(EX_UNAVAILABLE, "setsockopt(IP_FW_DEL)");
5842 } else if (do_cmd(cmd, NULL, 0) < 0)
5843 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
5844 do_pipe ? "DUMMYNET" : "FW");
5846 printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules");
5850 * Free a the (locally allocated) copy of command line arguments.
5853 free_args(int ac, char **av)
5857 for (i=0; i < ac; i++)
5862 static void table_list(ipfw_table_entry ent, int need_header);
5865 * This one handles all table-related commands
5866 * ipfw table N add addr[/masklen] [value]
5867 * ipfw table N delete addr[/masklen]
5868 * ipfw table {N | all} flush
5869 * ipfw table {N | all} list
5872 table_handler(int ac, char *av[])
5874 ipfw_table_entry ent;
5880 uint32_t tables_max;
5882 len = sizeof(tables_max);
5883 if (sysctlbyname("net.inet.ip.fw.tables_max", &tables_max, &len,
5885 #ifdef IPFW_TABLES_MAX
5886 warn("Warn: Failed to get the max tables number via sysctl. "
5887 "Using the compiled in defaults. \nThe reason was");
5888 tables_max = IPFW_TABLES_MAX;
5890 errx(1, "Failed sysctlbyname(\"net.inet.ip.fw.tables_max\")");
5895 if (ac && isdigit(**av)) {
5896 ent.tbl = atoi(*av);
5899 } else if (ac && _substrcmp(*av, "all") == 0) {
5904 errx(EX_USAGE, "table number or 'all' keyword required");
5905 if (ent.tbl >= tables_max)
5906 errx(EX_USAGE, "The table number exceeds the maximum allowed "
5907 "value (%d)", tables_max - 1);
5908 NEED1("table needs command");
5909 if (is_all && _substrcmp(*av, "list") != 0
5910 && _substrcmp(*av, "flush") != 0)
5911 errx(EX_USAGE, "table number required");
5913 if (_substrcmp(*av, "add") == 0 ||
5914 _substrcmp(*av, "delete") == 0) {
5915 do_add = **av == 'a';
5918 errx(EX_USAGE, "IP address required");
5919 p = strchr(*av, '/');
5922 ent.masklen = atoi(p);
5923 if (ent.masklen > 32)
5924 errx(EX_DATAERR, "bad width ``%s''", p);
5927 if (lookup_host(*av, (struct in_addr *)&ent.addr) != 0)
5928 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
5932 /* isdigit is a bit of a hack here.. */
5933 if (strchr(*av, (int)'.') == NULL && isdigit(**av)) {
5934 ent.value = strtoul(*av, NULL, 0);
5936 if (lookup_host(*av, (struct in_addr *)&tval) == 0) {
5937 /* The value must be stored in host order *
5938 * so that the values < 65k can be distinguished */
5939 ent.value = ntohl(tval);
5941 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
5946 if (do_cmd(do_add ? IP_FW_TABLE_ADD : IP_FW_TABLE_DEL,
5947 &ent, sizeof(ent)) < 0) {
5948 /* If running silent, don't bomb out on these errors. */
5949 if (!(do_quiet && (errno == (do_add ? EEXIST : ESRCH))))
5950 err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)",
5951 do_add ? "ADD" : "DEL");
5952 /* In silent mode, react to a failed add by deleting */
5954 do_cmd(IP_FW_TABLE_DEL, &ent, sizeof(ent));
5955 if (do_cmd(IP_FW_TABLE_ADD,
5956 &ent, sizeof(ent)) < 0)
5958 "setsockopt(IP_FW_TABLE_ADD)");
5961 } else if (_substrcmp(*av, "flush") == 0) {
5962 a = is_all ? tables_max : (ent.tbl + 1);
5964 if (do_cmd(IP_FW_TABLE_FLUSH, &ent.tbl,
5965 sizeof(ent.tbl)) < 0)
5966 err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)");
5967 } while (++ent.tbl < a);
5968 } else if (_substrcmp(*av, "list") == 0) {
5969 a = is_all ? tables_max : (ent.tbl + 1);
5971 table_list(ent, is_all);
5972 } while (++ent.tbl < a);
5974 errx(EX_USAGE, "invalid table command %s", *av);
5978 table_list(ipfw_table_entry ent, int need_header)
5986 if (do_cmd(IP_FW_TABLE_GETSIZE, &a, (uintptr_t)&l) < 0)
5987 err(EX_OSERR, "getsockopt(IP_FW_TABLE_GETSIZE)");
5989 /* If a is zero we have nothing to do, the table is empty. */
5993 l = sizeof(*tbl) + a * sizeof(ipfw_table_entry);
5996 err(EX_OSERR, "malloc");
5998 if (do_cmd(IP_FW_TABLE_LIST, tbl, (uintptr_t)&l) < 0)
5999 err(EX_OSERR, "getsockopt(IP_FW_TABLE_LIST)");
6000 if (tbl->cnt && need_header)
6001 printf("---table(%d)---\n", tbl->tbl);
6002 for (a = 0; a < tbl->cnt; a++) {
6004 tval = tbl->ent[a].value;
6005 if (do_value_as_ip) {
6007 strncpy(tbuf, inet_ntoa(*(struct in_addr *)
6008 &tbl->ent[a].addr), 127);
6009 /* inet_ntoa expects network order */
6011 printf("%s/%u %s\n", tbuf, tbl->ent[a].masklen,
6012 inet_ntoa(*(struct in_addr *)&tval));
6014 printf("%s/%u %u\n",
6015 inet_ntoa(*(struct in_addr *)&tbl->ent[a].addr),
6016 tbl->ent[a].masklen, tval);
6023 show_nat(int ac, char **av)
6026 struct cfg_redir *e;
6027 int cmd, i, nbytes, do_cfg, do_rule, frule, lrule, nalloc, size;
6028 int nat_cnt, redir_cnt, r;
6037 lrule = IPFW_DEFAULT_RULE; /* max ipfw rule number */
6043 /* Parse parameters. */
6044 for (cmd = IP_FW_NAT_GET_LOG, do_cfg = 0; ac != 0; ac--, av++) {
6045 if (!strncmp(av[0], "config", strlen(av[0]))) {
6046 cmd = IP_FW_NAT_GET_CONFIG, do_cfg = 1;
6049 /* Convert command line rule #. */
6050 frule = lrule = strtoul(av[0], &endptr, 10);
6052 lrule = strtoul(endptr+1, &endptr, 10);
6054 err(EX_USAGE, "invalid rule number: %s", av[0]);
6059 while (nbytes >= nalloc) {
6060 nalloc = nalloc * 2;
6062 if ((data = realloc(data, nbytes)) == NULL)
6063 err(EX_OSERR, "realloc");
6064 if (do_cmd(cmd, data, (uintptr_t)&nbytes) < 0)
6065 err(EX_OSERR, "getsockopt(IP_FW_GET_%s)",
6066 (cmd == IP_FW_NAT_GET_LOG) ? "LOG" : "CONFIG");
6071 nat_cnt = *((int *)data);
6072 for (i = sizeof(nat_cnt); nat_cnt; nat_cnt--) {
6073 n = (struct cfg_nat *)&data[i];
6074 if (frule <= n->id && lrule >= n->id)
6075 print_nat_config(&data[i]);
6076 i += sizeof(struct cfg_nat);
6077 for (redir_cnt = 0; redir_cnt < n->redir_cnt; redir_cnt++) {
6078 e = (struct cfg_redir *)&data[i];
6079 i += sizeof(struct cfg_redir) + e->spool_cnt *
6080 sizeof(struct cfg_spool);
6084 for (i = 0; 1; i += LIBALIAS_BUF_SIZE + sizeof(int)) {
6086 if (p == data + nbytes)
6088 bcopy(p, &r, sizeof(int));
6090 if (!(frule <= r && lrule >= r))
6093 printf("nat %u: %s\n", r, p+sizeof(int));
6099 * Called with the arguments (excluding program name).
6100 * Returns 0 if successful, 1 if empty command, errx() in case of errors.
6103 ipfw_main(int oldac, char **oldav)
6105 int ch, ac, save_ac;
6107 char **av, **save_av;
6108 int do_acct = 0; /* Show packet/byte count */
6110 #define WHITESP " \t\f\v\n\r"
6113 else if (oldac == 1) {
6115 * If we are called with a single string, try to split it into
6116 * arguments for subsequent parsing.
6117 * But first, remove spaces after a ',', by copying the string
6120 char *arg = oldav[0]; /* The string... */
6121 int l = strlen(arg);
6122 int copy = 0; /* 1 if we need to copy, 0 otherwise */
6124 for (i = j = 0; i < l; i++) {
6125 if (arg[i] == '#') /* comment marker */
6129 copy = !index("," WHITESP, arg[i]);
6131 copy = !index(WHITESP, arg[i]);
6136 if (!copy && j > 0) /* last char was a 'blank', remove it */
6138 l = j; /* the new argument length */
6140 if (l == 0) /* empty string! */
6144 * First, count number of arguments. Because of the previous
6145 * processing, this is just the number of blanks plus 1.
6147 for (i = 0, ac = 1; i < l; i++)
6148 if (index(WHITESP, arg[i]) != NULL)
6151 av = calloc(ac, sizeof(char *));
6154 * Second, copy arguments from cmd[] to av[]. For each one,
6155 * j is the initial character, i is the one past the end.
6157 for (ac = 0, i = j = 0; i < l; i++)
6158 if (index(WHITESP, arg[i]) != NULL || i == l-1) {
6161 av[ac] = calloc(i-j+1, 1);
6162 bcopy(arg+j, av[ac], i-j);
6168 * If an argument ends with ',' join with the next one.
6172 av = calloc(oldac, sizeof(char *));
6173 for (first = i = ac = 0, l = 0; i < oldac; i++) {
6174 char *arg = oldav[i];
6175 int k = strlen(arg);
6178 if (arg[k-1] != ',' || i == oldac-1) {
6180 av[ac] = calloc(l+1, 1);
6181 for (l=0; first <= i; first++) {
6182 strcat(av[ac]+l, oldav[first]);
6183 l += strlen(oldav[first]);
6192 /* Set the force flag for non-interactive processes */
6194 do_force = !isatty(STDIN_FILENO);
6196 /* Save arguments for final freeing of memory. */
6200 optind = optreset = 0;
6201 while ((ch = getopt(ac, av, "abcdefhinNqs:STtv")) != -1)
6228 case 'h': /* help */
6229 free_args(save_ac, save_av);
6231 break; /* NOTREACHED */
6249 case 's': /* sort */
6250 do_sort = atoi(optarg);
6262 do_time = 2; /* numeric timestamp */
6265 case 'v': /* verbose */
6270 free_args(save_ac, save_av);
6276 NEED1("bad arguments, for usage summary ``ipfw''");
6279 * An undocumented behaviour of ipfw1 was to allow rule numbers first,
6280 * e.g. "100 add allow ..." instead of "add 100 allow ...".
6281 * In case, swap first and second argument to get the normal form.
6283 if (ac > 1 && isdigit(*av[0])) {
6291 * Optional: pipe, queue or nat.
6295 if (!strncmp(*av, "nat", strlen(*av)))
6297 else if (!strncmp(*av, "pipe", strlen(*av)))
6299 else if (_substrcmp(*av, "queue") == 0)
6301 else if (!strncmp(*av, "set", strlen(*av))) {
6302 if (ac > 1 && isdigit(av[1][0])) {
6303 use_set = strtonum(av[1], 0, RESVD_SET, &errstr);
6306 "invalid set number %s\n", av[1]);
6307 ac -= 2; av += 2; use_set++;
6311 if (do_pipe || do_nat) {
6315 NEED1("missing command");
6318 * For pipes, queues and nats we normally say 'nat|pipe NN config'
6319 * but the code is easier to parse as 'nat|pipe config NN'
6320 * so we swap the two arguments.
6322 if ((do_pipe || do_nat) && ac > 1 && isdigit(*av[0])) {
6331 if (_substrcmp(*av, "add") == 0)
6333 else if (do_nat && _substrcmp(*av, "show") == 0)
6335 else if (do_pipe && _substrcmp(*av, "config") == 0)
6336 config_pipe(ac, av);
6337 else if (do_nat && _substrcmp(*av, "config") == 0)
6339 else if (_substrcmp(*av, "set") == 0)
6340 sets_handler(ac, av);
6341 else if (_substrcmp(*av, "table") == 0)
6342 table_handler(ac, av);
6343 else if (_substrcmp(*av, "enable") == 0)
6344 sysctl_handler(ac, av, 1);
6345 else if (_substrcmp(*av, "disable") == 0)
6346 sysctl_handler(ac, av, 0);
6351 if (use_set || try_next) {
6352 if (_substrcmp(*av, "delete") == 0)
6354 else if (_substrcmp(*av, "flush") == 0)
6356 else if (_substrcmp(*av, "zero") == 0)
6357 zero(ac, av, IP_FW_ZERO);
6358 else if (_substrcmp(*av, "resetlog") == 0)
6359 zero(ac, av, IP_FW_RESETLOG);
6360 else if (_substrcmp(*av, "print") == 0 ||
6361 _substrcmp(*av, "list") == 0)
6362 list(ac, av, do_acct);
6363 else if (_substrcmp(*av, "show") == 0)
6364 list(ac, av, 1 /* show counters */);
6366 errx(EX_USAGE, "bad command `%s'", *av);
6369 /* Free memory allocated in the argument parsing. */
6370 free_args(save_ac, save_av);
6376 ipfw_readfile(int ac, char *av[])
6380 char *cmd = NULL, *filename = av[ac-1];
6385 filename = av[ac-1];
6387 while ((c = getopt(ac, av, "cfNnp:qS")) != -1) {
6408 * Skip previous args and delete last one, so we
6409 * pass all but the last argument to the preprocessor
6415 errx(EX_USAGE, "no filename argument");
6417 fprintf(stderr, "command is %s\n", av[0]);
6429 errx(EX_USAGE, "bad arguments, for usage"
6430 " summary ``ipfw''");
6437 if (cmd == NULL && ac != optind + 1) {
6438 fprintf(stderr, "ac %d, optind %d\n", ac, optind);
6439 errx(EX_USAGE, "extraneous filename arguments");
6442 if ((f = fopen(filename, "r")) == NULL)
6443 err(EX_UNAVAILABLE, "fopen: %s", filename);
6445 if (cmd != NULL) { /* pipe through preprocessor */
6448 if (pipe(pipedes) == -1)
6449 err(EX_OSERR, "cannot create pipe");
6453 err(EX_OSERR, "cannot fork");
6457 * Child, will run the preprocessor with the
6458 * file on stdin and the pipe on stdout.
6460 if (dup2(fileno(f), 0) == -1
6461 || dup2(pipedes[1], 1) == -1)
6462 err(EX_OSERR, "dup2()");
6467 err(EX_OSERR, "execvp(%s) failed", cmd);
6468 } else { /* parent, will reopen f as the pipe */
6471 if ((f = fdopen(pipedes[0], "r")) == NULL) {
6472 int savederrno = errno;
6474 (void)kill(preproc, SIGTERM);
6476 err(EX_OSERR, "fdopen()");
6481 while (fgets(buf, BUFSIZ, f)) { /* read commands */
6486 sprintf(linename, "Line %d", lineno);
6487 setprogname(linename); /* XXX */
6495 if (waitpid(preproc, &status, 0) == -1)
6496 errx(EX_OSERR, "waitpid()");
6497 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
6498 errx(EX_UNAVAILABLE,
6499 "preprocessor exited with status %d",
6500 WEXITSTATUS(status));
6501 else if (WIFSIGNALED(status))
6502 errx(EX_UNAVAILABLE,
6503 "preprocessor exited with signal %d",
6509 main(int ac, char *av[])
6512 * If the last argument is an absolute pathname, interpret it
6513 * as a file to be preprocessed.
6516 if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0)
6517 ipfw_readfile(ac, av);
6519 if (ipfw_main(ac-1, av+1))