2 * Copyright (c) 2002-2003 Luigi Rizzo
3 * Copyright (c) 1996 Alex Nash, Paul Traina, Poul-Henning Kamp
4 * Copyright (c) 1994 Ugen J.S.Antsilevich
6 * Idea and grammar partially left from:
7 * Copyright (c) 1993 Daniel Boulet
9 * Redistribution and use in source forms, with and without modification,
10 * are permitted provided that this entire comment appears intact.
12 * Redistribution in binary form may occur without any restrictions.
13 * Obviously, it would be nice if you gave credit where credit is due
14 * but requiring it would be too onerous.
16 * This software is provided ``AS IS'' without any warranties of any kind.
18 * NEW command line interface for IP firewall facility
23 #include <sys/types.h>
24 #include <sys/socket.h>
25 #include <sys/sockio.h>
26 #include <sys/sysctl.h>
40 #include <timeconv.h> /* _long_to_time */
44 #define IPFW_INTERNAL /* Access to protected structures in ip_fw.h. */
46 #include <net/ethernet.h>
48 #include <net/if_dl.h>
49 #include <net/pfvar.h>
50 #include <net/route.h> /* def. of struct route */
51 #include <netinet/in.h>
52 #include <netinet/in_systm.h>
53 #include <netinet/ip.h>
54 #include <netinet/ip_icmp.h>
55 #include <netinet/icmp6.h>
56 #include <netinet/ip_fw.h>
57 #include <netinet/ip_dummynet.h>
58 #include <netinet/tcp.h>
59 #include <arpa/inet.h>
62 struct cmdline_opts co; /* global options */
64 int resvd_set_number = RESVD_SET;
66 #define GET_UINT_ARG(arg, min, max, tok, s_x) do { \
68 errx(EX_USAGE, "%s: missing argument", match_value(s_x, tok)); \
69 if (_substrcmp(*av, "tablearg") == 0) { \
70 arg = IP_FW_TABLEARG; \
78 val = strtol(*av, &end, 10); \
80 if (!isdigit(**av) || *end != '\0' || (val == 0 && errno == EINVAL)) \
81 errx(EX_DATAERR, "%s: invalid argument: %s", \
82 match_value(s_x, tok), *av); \
84 if (errno == ERANGE || val < min || val > max) \
85 errx(EX_DATAERR, "%s: argument is out of range (%u..%u): %s", \
86 match_value(s_x, tok), min, max, *av); \
88 if (val == IP_FW_TABLEARG) \
89 errx(EX_DATAERR, "%s: illegal argument value: %s", \
90 match_value(s_x, tok), *av); \
96 PRINT_UINT_ARG(const char *str, uint32_t arg)
100 if (arg == IP_FW_TABLEARG)
106 static struct _s_x f_tcpflags[] = {
117 static struct _s_x f_tcpopts[] = {
118 { "mss", IP_FW_TCPOPT_MSS },
119 { "maxseg", IP_FW_TCPOPT_MSS },
120 { "window", IP_FW_TCPOPT_WINDOW },
121 { "sack", IP_FW_TCPOPT_SACK },
122 { "ts", IP_FW_TCPOPT_TS },
123 { "timestamp", IP_FW_TCPOPT_TS },
124 { "cc", IP_FW_TCPOPT_CC },
130 * IP options span the range 0 to 255 so we need to remap them
131 * (though in fact only the low 5 bits are significant).
133 static struct _s_x f_ipopts[] = {
134 { "ssrr", IP_FW_IPOPT_SSRR},
135 { "lsrr", IP_FW_IPOPT_LSRR},
136 { "rr", IP_FW_IPOPT_RR},
137 { "ts", IP_FW_IPOPT_TS},
142 static struct _s_x f_iptos[] = {
143 { "lowdelay", IPTOS_LOWDELAY},
144 { "throughput", IPTOS_THROUGHPUT},
145 { "reliability", IPTOS_RELIABILITY},
146 { "mincost", IPTOS_MINCOST},
147 { "congestion", IPTOS_ECN_CE},
148 { "ecntransport", IPTOS_ECN_ECT0},
149 { "ip tos option", 0},
153 static struct _s_x limit_masks[] = {
154 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
155 {"src-addr", DYN_SRC_ADDR},
156 {"src-port", DYN_SRC_PORT},
157 {"dst-addr", DYN_DST_ADDR},
158 {"dst-port", DYN_DST_PORT},
163 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
164 * This is only used in this code.
166 #define IPPROTO_ETHERTYPE 0x1000
167 static struct _s_x ether_types[] = {
169 * Note, we cannot use "-:&/" in the names because they are field
170 * separators in the type specifications. Also, we use s = NULL as
171 * end-delimiter, because a type of 0 can be legal.
184 { "pppoe_disc", 0x8863 },
185 { "pppoe_sess", 0x8864 },
186 { "ipx_8022", 0x00E0 },
187 { "ipx_8023", 0x0000 },
188 { "ipx_ii", 0x8137 },
189 { "ipx_snap", 0x8137 },
235 TOK_DIVERTEDLOOPBACK,
309 struct _s_x dummynet_params[] = {
311 { "noerror", TOK_NOERROR },
312 { "buckets", TOK_BUCKETS },
313 { "dst-ip", TOK_DSTIP },
314 { "src-ip", TOK_SRCIP },
315 { "dst-port", TOK_DSTPORT },
316 { "src-port", TOK_SRCPORT },
317 { "proto", TOK_PROTO },
318 { "weight", TOK_WEIGHT },
320 { "mask", TOK_MASK },
321 { "droptail", TOK_DROPTAIL },
323 { "gred", TOK_GRED },
325 { "bandwidth", TOK_BW },
326 { "delay", TOK_DELAY },
327 { "pipe", TOK_PIPE },
328 { "queue", TOK_QUEUE },
329 { "flow-id", TOK_FLOWID},
330 { "dst-ipv6", TOK_DSTIP6},
331 { "dst-ip6", TOK_DSTIP6},
332 { "src-ipv6", TOK_SRCIP6},
333 { "src-ip6", TOK_SRCIP6},
334 { "dummynet-params", TOK_NULL },
335 { NULL, 0 } /* terminator */
338 struct _s_x nat_params[] = {
342 { "deny_in", TOK_DENY_INC },
343 { "same_ports", TOK_SAME_PORTS },
344 { "unreg_only", TOK_UNREG_ONLY },
345 { "reset", TOK_RESET_ADDR },
346 { "reverse", TOK_ALIAS_REV },
347 { "proxy_only", TOK_PROXY_ONLY },
348 { "redirect_addr", TOK_REDIR_ADDR },
349 { "redirect_port", TOK_REDIR_PORT },
350 { "redirect_proto", TOK_REDIR_PROTO },
351 { NULL, 0 } /* terminator */
354 struct _s_x rule_actions[] = {
355 { "accept", TOK_ACCEPT },
356 { "pass", TOK_ACCEPT },
357 { "allow", TOK_ACCEPT },
358 { "permit", TOK_ACCEPT },
359 { "count", TOK_COUNT },
360 { "pipe", TOK_PIPE },
361 { "queue", TOK_QUEUE },
362 { "divert", TOK_DIVERT },
364 { "netgraph", TOK_NETGRAPH },
365 { "ngtee", TOK_NGTEE },
366 { "fwd", TOK_FORWARD },
367 { "forward", TOK_FORWARD },
368 { "skipto", TOK_SKIPTO },
369 { "deny", TOK_DENY },
370 { "drop", TOK_DENY },
371 { "reject", TOK_REJECT },
372 { "reset6", TOK_RESET6 },
373 { "reset", TOK_RESET },
374 { "unreach6", TOK_UNREACH6 },
375 { "unreach", TOK_UNREACH },
376 { "check-state", TOK_CHECKSTATE },
377 { "//", TOK_COMMENT },
379 { "setfib", TOK_SETFIB },
380 { NULL, 0 } /* terminator */
383 struct _s_x rule_action_params[] = {
384 { "altq", TOK_ALTQ },
387 { "untag", TOK_UNTAG },
388 { NULL, 0 } /* terminator */
391 struct _s_x rule_options[] = {
392 { "tagged", TOK_TAGGED },
395 { "jail", TOK_JAIL },
397 { "limit", TOK_LIMIT },
398 { "keep-state", TOK_KEEPSTATE },
399 { "bridged", TOK_LAYER2 },
400 { "layer2", TOK_LAYER2 },
402 { "diverted", TOK_DIVERTED },
403 { "diverted-loopback", TOK_DIVERTEDLOOPBACK },
404 { "diverted-output", TOK_DIVERTEDOUTPUT },
405 { "xmit", TOK_XMIT },
406 { "recv", TOK_RECV },
408 { "fragment", TOK_FRAG },
409 { "frag", TOK_FRAG },
411 { "ipoptions", TOK_IPOPTS },
412 { "ipopts", TOK_IPOPTS },
413 { "iplen", TOK_IPLEN },
414 { "ipid", TOK_IPID },
415 { "ipprecedence", TOK_IPPRECEDENCE },
416 { "iptos", TOK_IPTOS },
417 { "ipttl", TOK_IPTTL },
418 { "ipversion", TOK_IPVER },
419 { "ipver", TOK_IPVER },
420 { "estab", TOK_ESTAB },
421 { "established", TOK_ESTAB },
422 { "setup", TOK_SETUP },
423 { "tcpdatalen", TOK_TCPDATALEN },
424 { "tcpflags", TOK_TCPFLAGS },
425 { "tcpflgs", TOK_TCPFLAGS },
426 { "tcpoptions", TOK_TCPOPTS },
427 { "tcpopts", TOK_TCPOPTS },
428 { "tcpseq", TOK_TCPSEQ },
429 { "tcpack", TOK_TCPACK },
430 { "tcpwin", TOK_TCPWIN },
431 { "icmptype", TOK_ICMPTYPES },
432 { "icmptypes", TOK_ICMPTYPES },
433 { "dst-ip", TOK_DSTIP },
434 { "src-ip", TOK_SRCIP },
435 { "dst-port", TOK_DSTPORT },
436 { "src-port", TOK_SRCPORT },
437 { "proto", TOK_PROTO },
440 { "mac-type", TOK_MACTYPE },
441 { "verrevpath", TOK_VERREVPATH },
442 { "versrcreach", TOK_VERSRCREACH },
443 { "antispoof", TOK_ANTISPOOF },
444 { "ipsec", TOK_IPSEC },
445 { "icmp6type", TOK_ICMP6TYPES },
446 { "icmp6types", TOK_ICMP6TYPES },
447 { "ext6hdr", TOK_EXT6HDR},
448 { "flow-id", TOK_FLOWID},
453 { "dst-ipv6", TOK_DSTIP6},
454 { "dst-ip6", TOK_DSTIP6},
455 { "src-ipv6", TOK_SRCIP6},
456 { "src-ip6", TOK_SRCIP6},
457 { "//", TOK_COMMENT },
459 { "not", TOK_NOT }, /* pseudo option */
460 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
461 { "or", TOK_OR }, /* pseudo option */
462 { "|", /* escape */ TOK_OR }, /* pseudo option */
463 { "{", TOK_STARTBRACE }, /* pseudo option */
464 { "(", TOK_STARTBRACE }, /* pseudo option */
465 { "}", TOK_ENDBRACE }, /* pseudo option */
466 { ")", TOK_ENDBRACE }, /* pseudo option */
467 { NULL, 0 } /* terminator */
470 static __inline uint64_t
471 align_uint64(uint64_t *pll) {
474 bcopy (pll, &ret, sizeof(ret));
479 safe_calloc(size_t number, size_t size)
481 void *ret = calloc(number, size);
484 err(EX_OSERR, "calloc");
489 safe_realloc(void *ptr, size_t size)
491 void *ret = realloc(ptr, size);
494 err(EX_OSERR, "realloc");
499 * conditionally runs the command.
502 do_cmd(int optname, void *optval, uintptr_t optlen)
504 static int s = -1; /* the socket */
511 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
513 err(EX_UNAVAILABLE, "socket");
515 if (optname == IP_FW_GET || optname == IP_DUMMYNET_GET ||
516 optname == IP_FW_ADD || optname == IP_FW_TABLE_LIST ||
517 optname == IP_FW_TABLE_GETSIZE ||
518 optname == IP_FW_NAT_GET_CONFIG ||
519 optname == IP_FW_NAT_GET_LOG)
520 i = getsockopt(s, IPPROTO_IP, optname, optval,
521 (socklen_t *)optlen);
523 i = setsockopt(s, IPPROTO_IP, optname, optval, optlen);
528 * match_token takes a table and a string, returns the value associated
529 * with the string (-1 in case of failure).
532 match_token(struct _s_x *table, char *string)
535 uint i = strlen(string);
537 for (pt = table ; i && pt->s != NULL ; pt++)
538 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
544 * match_value takes a table and a value, returns the string associated
545 * with the value (NULL in case of failure).
548 match_value(struct _s_x *p, int value)
550 for (; p->s != NULL; p++)
557 * _substrcmp takes two strings and returns 1 if they do not match,
558 * and 0 if they match exactly or the first string is a sub-string
559 * of the second. A warning is printed to stderr in the case that the
560 * first string is a sub-string of the second.
562 * This function will be removed in the future through the usual
563 * deprecation process.
566 _substrcmp(const char *str1, const char* str2)
569 if (strncmp(str1, str2, strlen(str1)) != 0)
572 if (strlen(str1) != strlen(str2))
573 warnx("DEPRECATED: '%s' matched '%s' as a sub-string",
579 * _substrcmp2 takes three strings and returns 1 if the first two do not match,
580 * and 0 if they match exactly or the second string is a sub-string
581 * of the first. A warning is printed to stderr in the case that the
582 * first string does not match the third.
584 * This function exists to warn about the bizzare construction
585 * strncmp(str, "by", 2) which is used to allow people to use a shotcut
586 * for "bytes". The problem is that in addition to accepting "by",
587 * "byt", "byte", and "bytes", it also excepts "by_rabid_dogs" and any
588 * other string beginning with "by".
590 * This function will be removed in the future through the usual
591 * deprecation process.
594 _substrcmp2(const char *str1, const char* str2, const char* str3)
597 if (strncmp(str1, str2, strlen(str2)) != 0)
600 if (strcmp(str1, str3) != 0)
601 warnx("DEPRECATED: '%s' matched '%s'",
607 * prints one port, symbolic or numeric
610 print_port(int proto, uint16_t port)
613 if (proto == IPPROTO_ETHERTYPE) {
616 if (co.do_resolv && (s = match_value(ether_types, port)) )
619 printf("0x%04x", port);
621 struct servent *se = NULL;
623 struct protoent *pe = getprotobynumber(proto);
625 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
628 printf("%s", se->s_name);
634 struct _s_x _port_name[] = {
635 {"dst-port", O_IP_DSTPORT},
636 {"src-port", O_IP_SRCPORT},
640 {"mac-type", O_MAC_TYPE},
641 {"tcpdatalen", O_TCPDATALEN},
642 {"tagged", O_TAGGED},
647 * Print the values in a list 16-bit items of the types above.
648 * XXX todo: add support for mask.
651 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode)
653 uint16_t *p = cmd->ports;
658 sep = match_value(_port_name, opcode);
664 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
666 print_port(proto, p[0]);
669 print_port(proto, p[1]);
676 * Like strtol, but also translates service names into port numbers
677 * for some protocols.
679 * proto == -1 disables the protocol check;
680 * proto == IPPROTO_ETHERTYPE looks up an internal table
681 * proto == <some value in /etc/protocols> matches the values there.
682 * Returns *end == s in case the parameter is not found.
685 strtoport(char *s, char **end, int base, int proto)
691 *end = s; /* default - not found */
693 return 0; /* not found */
696 return strtol(s, end, base);
699 * find separator. '\\' escapes the next char.
701 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
702 if (*s1 == '\\' && s1[1] != '\0')
705 buf = safe_calloc(s1 - s + 1, 1);
708 * copy into a buffer skipping backslashes
710 for (p = s, i = 0; p != s1 ; p++)
715 if (proto == IPPROTO_ETHERTYPE) {
716 i = match_token(ether_types, buf);
718 if (i != -1) { /* found */
723 struct protoent *pe = NULL;
727 pe = getprotobynumber(proto);
729 se = getservbyname(buf, pe ? pe->p_name : NULL);
733 return ntohs(se->s_port);
736 return 0; /* not found */
740 * Map between current altq queue id numbers and names.
742 static int altq_fetched = 0;
743 static TAILQ_HEAD(, pf_altq) altq_entries =
744 TAILQ_HEAD_INITIALIZER(altq_entries);
747 altq_set_enabled(int enabled)
751 pffd = open("/dev/pf", O_RDWR);
754 "altq support opening pf(4) control device");
756 if (ioctl(pffd, DIOCSTARTALTQ) != 0 && errno != EEXIST)
757 err(EX_UNAVAILABLE, "enabling altq");
759 if (ioctl(pffd, DIOCSTOPALTQ) != 0 && errno != ENOENT)
760 err(EX_UNAVAILABLE, "disabling altq");
768 struct pfioc_altq pfioc;
769 struct pf_altq *altq;
776 pffd = open("/dev/pf", O_RDONLY);
778 warn("altq support opening pf(4) control device");
781 bzero(&pfioc, sizeof(pfioc));
782 if (ioctl(pffd, DIOCGETALTQS, &pfioc) != 0) {
783 warn("altq support getting queue list");
788 for (pfioc.nr = 0; pfioc.nr < mnr; pfioc.nr++) {
789 if (ioctl(pffd, DIOCGETALTQ, &pfioc) != 0) {
792 warn("altq support getting queue list");
796 if (pfioc.altq.qid == 0)
798 altq = safe_calloc(1, sizeof(*altq));
800 TAILQ_INSERT_TAIL(&altq_entries, altq, entries);
806 altq_name_to_qid(const char *name)
808 struct pf_altq *altq;
811 TAILQ_FOREACH(altq, &altq_entries, entries)
812 if (strcmp(name, altq->qname) == 0)
815 errx(EX_DATAERR, "altq has no queue named `%s'", name);
820 altq_qid_to_name(u_int32_t qid)
822 struct pf_altq *altq;
825 TAILQ_FOREACH(altq, &altq_entries, entries)
826 if (qid == altq->qid)
834 fill_altq_qid(u_int32_t *qid, const char *av)
836 *qid = altq_name_to_qid(av);
840 * Fill the body of the command with the list of port ranges.
843 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto)
845 uint16_t a, b, *p = cmd->ports;
850 a = strtoport(av, &s, 0, proto);
851 if (s == av) /* empty or invalid argument */
855 case '-': /* a range */
857 b = strtoport(av, &s, 0, proto);
858 /* Reject expressions like '1-abc' or '1-2-3'. */
859 if (s == av || (*s != ',' && *s != '\0'))
864 case ',': /* comma separated list */
869 warnx("port list: invalid separator <%c> in <%s>",
879 if (i + 1 > F_LEN_MASK)
880 errx(EX_DATAERR, "too many ports/ranges\n");
881 cmd->o.len |= i + 1; /* leave F_NOT and F_OR untouched */
886 static struct _s_x icmpcodes[] = {
887 { "net", ICMP_UNREACH_NET },
888 { "host", ICMP_UNREACH_HOST },
889 { "protocol", ICMP_UNREACH_PROTOCOL },
890 { "port", ICMP_UNREACH_PORT },
891 { "needfrag", ICMP_UNREACH_NEEDFRAG },
892 { "srcfail", ICMP_UNREACH_SRCFAIL },
893 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
894 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
895 { "isolated", ICMP_UNREACH_ISOLATED },
896 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
897 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
898 { "tosnet", ICMP_UNREACH_TOSNET },
899 { "toshost", ICMP_UNREACH_TOSHOST },
900 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
901 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
902 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
907 fill_reject_code(u_short *codep, char *str)
912 val = strtoul(str, &s, 0);
913 if (s == str || *s != '\0' || val >= 0x100)
914 val = match_token(icmpcodes, str);
916 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
922 print_reject_code(uint16_t code)
924 char const *s = match_value(icmpcodes, code);
927 printf("unreach %s", s);
929 printf("unreach %u", code);
932 static struct _s_x icmp6codes[] = {
933 { "no-route", ICMP6_DST_UNREACH_NOROUTE },
934 { "admin-prohib", ICMP6_DST_UNREACH_ADMIN },
935 { "address", ICMP6_DST_UNREACH_ADDR },
936 { "port", ICMP6_DST_UNREACH_NOPORT },
941 fill_unreach6_code(u_short *codep, char *str)
946 val = strtoul(str, &s, 0);
947 if (s == str || *s != '\0' || val >= 0x100)
948 val = match_token(icmp6codes, str);
950 errx(EX_DATAERR, "unknown ICMPv6 unreachable code ``%s''", str);
956 print_unreach6_code(uint16_t code)
958 char const *s = match_value(icmp6codes, code);
961 printf("unreach6 %s", s);
963 printf("unreach6 %u", code);
967 * Returns the number of bits set (from left) in a contiguous bitmask,
968 * or -1 if the mask is not contiguous.
969 * XXX this needs a proper fix.
970 * This effectively works on masks in big-endian (network) format.
971 * when compiled on little endian architectures.
973 * First bit is bit 7 of the first byte -- note, for MAC addresses,
974 * the first bit on the wire is bit 0 of the first byte.
975 * len is the max length in bits.
978 contigmask(uint8_t *p, int len)
982 for (i=0; i<len ; i++)
983 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
985 for (n=i+1; n < len; n++)
986 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
987 return -1; /* mask not contiguous */
992 * print flags set/clear in the two bitmasks passed as parameters.
993 * There is a specialized check for f_tcpflags.
996 print_flags(char const *name, ipfw_insn *cmd, struct _s_x *list)
998 char const *comma = "";
1000 uint8_t set = cmd->arg1 & 0xff;
1001 uint8_t clear = (cmd->arg1 >> 8) & 0xff;
1003 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
1008 printf(" %s ", name);
1009 for (i=0; list[i].x != 0; i++) {
1010 if (set & list[i].x) {
1012 printf("%s%s", comma, list[i].s);
1015 if (clear & list[i].x) {
1016 clear &= ~list[i].x;
1017 printf("%s!%s", comma, list[i].s);
1024 * Print the ip address contained in a command.
1027 print_ip(ipfw_insn_ip *cmd, char const *s)
1029 struct hostent *he = NULL;
1030 int len = F_LEN((ipfw_insn *)cmd);
1031 uint32_t *a = ((ipfw_insn_u32 *)cmd)->d;
1033 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
1035 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
1039 if (cmd->o.opcode == O_IP_SRC_LOOKUP ||
1040 cmd->o.opcode == O_IP_DST_LOOKUP) {
1041 printf("table(%u", ((ipfw_insn *)cmd)->arg1);
1042 if (len == F_INSN_SIZE(ipfw_insn_u32))
1047 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
1048 uint32_t x, *map = (uint32_t *)&(cmd->mask);
1052 x = cmd->o.arg1 - 1;
1054 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1055 printf("%s/%d", inet_ntoa(cmd->addr),
1056 contigmask((uint8_t *)&x, 32));
1057 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
1058 x &= 0xff; /* base */
1060 * Print bits and ranges.
1061 * Locate first bit set (i), then locate first bit unset (j).
1062 * If we have 3+ consecutive bits set, then print them as a
1063 * range, otherwise only print the initial bit and rescan.
1065 for (i=0; i < cmd->o.arg1; i++)
1066 if (map[i/32] & (1<<(i & 31))) {
1067 for (j=i+1; j < cmd->o.arg1; j++)
1068 if (!(map[ j/32] & (1<<(j & 31))))
1070 printf("%c%d", comma, i+x);
1071 if (j>i+2) { /* range has at least 3 elements */
1072 printf("-%d", j-1+x);
1081 * len == 2 indicates a single IP, whereas lists of 1 or more
1082 * addr/mask pairs have len = (2n+1). We convert len to n so we
1083 * use that to count the number of entries.
1085 for (len = len / 2; len > 0; len--, a += 2) {
1086 int mb = /* mask length */
1087 (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST) ?
1088 32 : contigmask((uint8_t *)&(a[1]), 32);
1089 if (mb == 32 && co.do_resolv)
1090 he = gethostbyaddr((char *)&(a[0]), sizeof(u_long), AF_INET);
1091 if (he != NULL) /* resolved to name */
1092 printf("%s", he->h_name);
1093 else if (mb == 0) /* any */
1095 else { /* numeric IP followed by some kind of mask */
1096 printf("%s", inet_ntoa( *((struct in_addr *)&a[0]) ) );
1098 printf(":%s", inet_ntoa( *((struct in_addr *)&a[1]) ) );
1108 * prints a MAC address/mask pair
1111 print_mac(uint8_t *addr, uint8_t *mask)
1113 int l = contigmask(mask, 48);
1118 printf(" %02x:%02x:%02x:%02x:%02x:%02x",
1119 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
1121 printf("&%02x:%02x:%02x:%02x:%02x:%02x",
1122 mask[0], mask[1], mask[2],
1123 mask[3], mask[4], mask[5]);
1130 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
1139 type = strtoul(av, &av, 0);
1141 if (*av != ',' && *av != '\0')
1142 errx(EX_DATAERR, "invalid ICMP type");
1145 errx(EX_DATAERR, "ICMP type out of range");
1147 cmd->d[0] |= 1 << type;
1149 cmd->o.opcode = O_ICMPTYPE;
1150 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1154 print_icmptypes(ipfw_insn_u32 *cmd)
1159 printf(" icmptypes");
1160 for (i = 0; i < 32; i++) {
1161 if ( (cmd->d[0] & (1 << (i))) == 0)
1163 printf("%c%d", sep, i);
1169 * Print the ip address contained in a command.
1172 print_ip6(ipfw_insn_ip6 *cmd, char const *s)
1174 struct hostent *he = NULL;
1175 int len = F_LEN((ipfw_insn *) cmd) - 1;
1176 struct in6_addr *a = &(cmd->addr6);
1179 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
1181 if (cmd->o.opcode == O_IP6_SRC_ME || cmd->o.opcode == O_IP6_DST_ME) {
1185 if (cmd->o.opcode == O_IP6) {
1191 * len == 4 indicates a single IP, whereas lists of 1 or more
1192 * addr/mask pairs have len = (2n+1). We convert len to n so we
1193 * use that to count the number of entries.
1196 for (len = len / 4; len > 0; len -= 2, a += 2) {
1197 int mb = /* mask length */
1198 (cmd->o.opcode == O_IP6_SRC || cmd->o.opcode == O_IP6_DST) ?
1199 128 : contigmask((uint8_t *)&(a[1]), 128);
1201 if (mb == 128 && co.do_resolv)
1202 he = gethostbyaddr((char *)a, sizeof(*a), AF_INET6);
1203 if (he != NULL) /* resolved to name */
1204 printf("%s", he->h_name);
1205 else if (mb == 0) /* any */
1207 else { /* numeric IP followed by some kind of mask */
1208 if (inet_ntop(AF_INET6, a, trad, sizeof( trad ) ) == NULL)
1209 printf("Error ntop in print_ip6\n");
1210 printf("%s", trad );
1211 if (mb < 0) /* XXX not really legal... */
1213 inet_ntop(AF_INET6, &a[1], trad, sizeof(trad)));
1223 fill_icmp6types(ipfw_insn_icmp6 *cmd, char *av)
1227 bzero(cmd, sizeof(*cmd));
1231 type = strtoul(av, &av, 0);
1232 if (*av != ',' && *av != '\0')
1233 errx(EX_DATAERR, "invalid ICMP6 type");
1235 * XXX: shouldn't this be 0xFF? I can't see any reason why
1236 * we shouldn't be able to filter all possiable values
1237 * regardless of the ability of the rest of the kernel to do
1238 * anything useful with them.
1240 if (type > ICMP6_MAXTYPE)
1241 errx(EX_DATAERR, "ICMP6 type out of range");
1242 cmd->d[type / 32] |= ( 1 << (type % 32));
1244 cmd->o.opcode = O_ICMP6TYPE;
1245 cmd->o.len |= F_INSN_SIZE(ipfw_insn_icmp6);
1250 print_icmp6types(ipfw_insn_u32 *cmd)
1255 printf(" ip6 icmp6types");
1256 for (i = 0; i < 7; i++)
1257 for (j=0; j < 32; ++j) {
1258 if ( (cmd->d[i] & (1 << (j))) == 0)
1260 printf("%c%d", sep, (i*32 + j));
1266 print_flow6id( ipfw_insn_u32 *cmd)
1268 uint16_t i, limit = cmd->o.arg1;
1271 printf(" flow-id ");
1272 for( i=0; i < limit; ++i) {
1275 printf("%d%c", cmd->d[i], sep);
1279 /* structure and define for the extension header in ipv6 */
1280 static struct _s_x ext6hdrcodes[] = {
1281 { "frag", EXT_FRAGMENT },
1282 { "hopopt", EXT_HOPOPTS },
1283 { "route", EXT_ROUTING },
1284 { "dstopt", EXT_DSTOPTS },
1287 { "rthdr0", EXT_RTHDR0 },
1288 { "rthdr2", EXT_RTHDR2 },
1292 /* fills command for the extension header filtering */
1294 fill_ext6hdr( ipfw_insn *cmd, char *av)
1302 av = strsep( &s, ",") ;
1303 tok = match_token(ext6hdrcodes, av);
1306 cmd->arg1 |= EXT_FRAGMENT;
1310 cmd->arg1 |= EXT_HOPOPTS;
1314 cmd->arg1 |= EXT_ROUTING;
1318 cmd->arg1 |= EXT_DSTOPTS;
1322 cmd->arg1 |= EXT_AH;
1326 cmd->arg1 |= EXT_ESP;
1330 cmd->arg1 |= EXT_RTHDR0;
1334 cmd->arg1 |= EXT_RTHDR2;
1338 errx( EX_DATAERR, "invalid option for ipv6 exten header" );
1342 if (cmd->arg1 == 0 )
1344 cmd->opcode = O_EXT_HDR;
1345 cmd->len |= F_INSN_SIZE( ipfw_insn );
1350 print_ext6hdr( ipfw_insn *cmd )
1354 printf(" extension header:");
1355 if (cmd->arg1 & EXT_FRAGMENT ) {
1356 printf("%cfragmentation", sep);
1359 if (cmd->arg1 & EXT_HOPOPTS ) {
1360 printf("%chop options", sep);
1363 if (cmd->arg1 & EXT_ROUTING ) {
1364 printf("%crouting options", sep);
1367 if (cmd->arg1 & EXT_RTHDR0 ) {
1368 printf("%crthdr0", sep);
1371 if (cmd->arg1 & EXT_RTHDR2 ) {
1372 printf("%crthdr2", sep);
1375 if (cmd->arg1 & EXT_DSTOPTS ) {
1376 printf("%cdestination options", sep);
1379 if (cmd->arg1 & EXT_AH ) {
1380 printf("%cauthentication header", sep);
1383 if (cmd->arg1 & EXT_ESP ) {
1384 printf("%cencapsulated security payload", sep);
1389 * show_ipfw() prints the body of an ipfw rule.
1390 * Because the standard rule has at least proto src_ip dst_ip, we use
1391 * a helper function to produce these entries if not provided explicitly.
1392 * The first argument is the list of fields we have, the second is
1393 * the list of fields we want to be printed.
1395 * Special cases if we have provided a MAC header:
1396 * + if the rule does not contain IP addresses/ports, do not print them;
1397 * + if the rule does not contain an IP proto, print "all" instead of "ip";
1399 * Once we have 'have_options', IP header fields are printed as options.
1401 #define HAVE_PROTO 0x0001
1402 #define HAVE_SRCIP 0x0002
1403 #define HAVE_DSTIP 0x0004
1404 #define HAVE_PROTO4 0x0008
1405 #define HAVE_PROTO6 0x0010
1406 #define HAVE_OPTIONS 0x8000
1408 #define HAVE_IP (HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP)
1410 show_prerequisites(int *flags, int want, int cmd __unused)
1412 if (co.comment_only)
1414 if ( (*flags & HAVE_IP) == HAVE_IP)
1415 *flags |= HAVE_OPTIONS;
1417 if ( !(*flags & HAVE_OPTIONS)) {
1418 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO)) {
1419 if ( (*flags & HAVE_PROTO4))
1421 else if ( (*flags & HAVE_PROTO6))
1426 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
1427 printf(" from any");
1428 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
1435 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth)
1437 static int twidth = 0;
1439 ipfw_insn *cmd, *tagptr = NULL;
1440 const char *comment = NULL; /* ptr to comment if we have one */
1441 int proto = 0; /* default */
1442 int flags = 0; /* prerequisites */
1443 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
1444 ipfw_insn_altq *altqptr = NULL; /* set if we find an O_ALTQ */
1445 int or_block = 0; /* we are in an or block */
1446 uint32_t set_disable;
1448 bcopy(&rule->next_rule, &set_disable, sizeof(set_disable));
1450 if (set_disable & (1 << rule->set)) { /* disabled */
1454 printf("# DISABLED ");
1456 printf("%05u ", rule->rulenum);
1458 if (pcwidth>0 || bcwidth>0)
1459 printf("%*llu %*llu ", pcwidth, align_uint64(&rule->pcnt),
1460 bcwidth, align_uint64(&rule->bcnt));
1462 if (co.do_time == 2)
1463 printf("%10u ", rule->timestamp);
1464 else if (co.do_time == 1) {
1466 time_t t = (time_t)0;
1469 strcpy(timestr, ctime(&t));
1470 *strchr(timestr, '\n') = '\0';
1471 twidth = strlen(timestr);
1473 if (rule->timestamp) {
1474 t = _long_to_time(rule->timestamp);
1476 strcpy(timestr, ctime(&t));
1477 *strchr(timestr, '\n') = '\0';
1478 printf("%s ", timestr);
1480 printf("%*s", twidth, " ");
1485 printf("set %d ", rule->set);
1488 * print the optional "match probability"
1490 if (rule->cmd_len > 0) {
1492 if (cmd->opcode == O_PROB) {
1493 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
1494 double d = 1.0 * p->d[0];
1496 d = (d / 0x7fffffff);
1497 printf("prob %f ", d);
1502 * first print actions
1504 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
1505 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
1506 switch(cmd->opcode) {
1508 printf("check-state");
1509 flags = HAVE_IP; /* avoid printing anything else */
1525 if (cmd->arg1 == ICMP_REJECT_RST)
1527 else if (cmd->arg1 == ICMP_UNREACH_HOST)
1530 print_reject_code(cmd->arg1);
1534 if (cmd->arg1 == ICMP6_UNREACH_RST)
1537 print_unreach6_code(cmd->arg1);
1541 PRINT_UINT_ARG("skipto ", cmd->arg1);
1545 PRINT_UINT_ARG("pipe ", cmd->arg1);
1549 PRINT_UINT_ARG("queue ", cmd->arg1);
1553 PRINT_UINT_ARG("divert ", cmd->arg1);
1557 PRINT_UINT_ARG("tee ", cmd->arg1);
1561 PRINT_UINT_ARG("netgraph ", cmd->arg1);
1565 PRINT_UINT_ARG("ngtee ", cmd->arg1);
1570 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
1572 if (s->sa.sin_addr.s_addr == INADDR_ANY) {
1573 printf("fwd tablearg");
1575 printf("fwd %s", inet_ntoa(s->sa.sin_addr));
1578 printf(",%d", s->sa.sin_port);
1582 case O_LOG: /* O_LOG is printed last */
1583 logptr = (ipfw_insn_log *)cmd;
1586 case O_ALTQ: /* O_ALTQ is printed after O_LOG */
1587 altqptr = (ipfw_insn_altq *)cmd;
1595 PRINT_UINT_ARG("nat ", cmd->arg1);
1599 PRINT_UINT_ARG("setfib ", cmd->arg1);
1603 printf("** unrecognized action %d len %d ",
1604 cmd->opcode, cmd->len);
1608 if (logptr->max_log > 0)
1609 printf(" log logamount %d", logptr->max_log);
1616 qname = altq_qid_to_name(altqptr->qid);
1618 printf(" altq ?<%u>", altqptr->qid);
1620 printf(" altq %s", qname);
1623 if (tagptr->len & F_NOT)
1624 PRINT_UINT_ARG(" untag ", tagptr->arg1);
1626 PRINT_UINT_ARG(" tag ", tagptr->arg1);
1630 * then print the body.
1632 for (l = rule->act_ofs, cmd = rule->cmd ;
1633 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1634 if ((cmd->len & F_OR) || (cmd->len & F_NOT))
1636 if (cmd->opcode == O_IP4) {
1637 flags |= HAVE_PROTO4;
1639 } else if (cmd->opcode == O_IP6) {
1640 flags |= HAVE_PROTO6;
1644 if (rule->_pad & 1) { /* empty rules before options */
1645 if (!co.do_compact) {
1646 show_prerequisites(&flags, HAVE_PROTO, 0);
1647 printf(" from any to any");
1649 flags |= HAVE_IP | HAVE_OPTIONS;
1652 if (co.comment_only)
1655 for (l = rule->act_ofs, cmd = rule->cmd ;
1656 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
1658 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
1660 if (co.comment_only) {
1661 if (cmd->opcode != O_NOP)
1663 printf(" // %s\n", (char *)(cmd + 1));
1667 show_prerequisites(&flags, 0, cmd->opcode);
1669 switch(cmd->opcode) {
1671 break; /* done already */
1674 break; /* no need to print anything here */
1677 case O_IP_SRC_LOOKUP:
1681 show_prerequisites(&flags, HAVE_PROTO, 0);
1682 if (!(flags & HAVE_SRCIP))
1684 if ((cmd->len & F_OR) && !or_block)
1686 print_ip((ipfw_insn_ip *)cmd,
1687 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1688 flags |= HAVE_SRCIP;
1692 case O_IP_DST_LOOKUP:
1696 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1697 if (!(flags & HAVE_DSTIP))
1699 if ((cmd->len & F_OR) && !or_block)
1701 print_ip((ipfw_insn_ip *)cmd,
1702 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1703 flags |= HAVE_DSTIP;
1707 case O_IP6_SRC_MASK:
1709 show_prerequisites(&flags, HAVE_PROTO, 0);
1710 if (!(flags & HAVE_SRCIP))
1712 if ((cmd->len & F_OR) && !or_block)
1714 print_ip6((ipfw_insn_ip6 *)cmd,
1715 (flags & HAVE_OPTIONS) ? " src-ip6" : "");
1716 flags |= HAVE_SRCIP | HAVE_PROTO;
1720 case O_IP6_DST_MASK:
1722 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1723 if (!(flags & HAVE_DSTIP))
1725 if ((cmd->len & F_OR) && !or_block)
1727 print_ip6((ipfw_insn_ip6 *)cmd,
1728 (flags & HAVE_OPTIONS) ? " dst-ip6" : "");
1729 flags |= HAVE_DSTIP;
1733 print_flow6id( (ipfw_insn_u32 *) cmd );
1734 flags |= HAVE_OPTIONS;
1738 show_prerequisites(&flags, HAVE_IP, 0);
1740 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1741 if ((cmd->len & F_OR) && !or_block)
1743 if (cmd->len & F_NOT)
1745 print_newports((ipfw_insn_u16 *)cmd, proto,
1746 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1750 struct protoent *pe = NULL;
1752 if ((cmd->len & F_OR) && !or_block)
1754 if (cmd->len & F_NOT)
1757 pe = getprotobynumber(cmd->arg1);
1758 if ((flags & (HAVE_PROTO4 | HAVE_PROTO6)) &&
1759 !(flags & HAVE_PROTO))
1760 show_prerequisites(&flags,
1761 HAVE_IP | HAVE_OPTIONS, 0);
1762 if (flags & HAVE_OPTIONS)
1765 printf(" %s", pe->p_name);
1767 printf(" %u", cmd->arg1);
1769 flags |= HAVE_PROTO;
1772 default: /*options ... */
1773 if (!(cmd->len & (F_OR|F_NOT)))
1774 if (((cmd->opcode == O_IP6) &&
1775 (flags & HAVE_PROTO6)) ||
1776 ((cmd->opcode == O_IP4) &&
1777 (flags & HAVE_PROTO4)))
1779 show_prerequisites(&flags, HAVE_IP | HAVE_OPTIONS, 0);
1780 if ((cmd->len & F_OR) && !or_block)
1782 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1784 switch(cmd->opcode) {
1786 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
1789 print_mac(m->addr, m->mask);
1790 print_mac(m->addr + 6, m->mask + 6);
1795 print_newports((ipfw_insn_u16 *)cmd,
1796 IPPROTO_ETHERTYPE, cmd->opcode);
1805 printf(" fib %u", cmd->arg1 );
1809 printf(cmd->len & F_NOT ? " out" : " in");
1813 switch (cmd->arg1) {
1815 printf(" diverted");
1818 printf(" diverted-loopback");
1821 printf(" diverted-output");
1824 printf(" diverted-?<%u>", cmd->arg1);
1837 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1839 if (cmd->opcode == O_XMIT)
1841 else if (cmd->opcode == O_RECV)
1843 else /* if (cmd->opcode == O_VIA) */
1845 if (cmdif->name[0] == '\0')
1847 inet_ntoa(cmdif->p.ip));
1849 printf(" %s %s", s, cmdif->name);
1854 if (F_LEN(cmd) == 1)
1855 printf(" ipid %u", cmd->arg1 );
1857 print_newports((ipfw_insn_u16 *)cmd, 0,
1862 if (F_LEN(cmd) == 1)
1863 printf(" ipttl %u", cmd->arg1 );
1865 print_newports((ipfw_insn_u16 *)cmd, 0,
1870 printf(" ipver %u", cmd->arg1 );
1873 case O_IPPRECEDENCE:
1874 printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1878 if (F_LEN(cmd) == 1)
1879 printf(" iplen %u", cmd->arg1 );
1881 print_newports((ipfw_insn_u16 *)cmd, 0,
1886 print_flags("ipoptions", cmd, f_ipopts);
1890 print_flags("iptos", cmd, f_iptos);
1894 print_icmptypes((ipfw_insn_u32 *)cmd);
1898 printf(" established");
1902 if (F_LEN(cmd) == 1)
1903 printf(" tcpdatalen %u", cmd->arg1 );
1905 print_newports((ipfw_insn_u16 *)cmd, 0,
1910 print_flags("tcpflags", cmd, f_tcpflags);
1914 print_flags("tcpoptions", cmd, f_tcpopts);
1918 printf(" tcpwin %d", ntohs(cmd->arg1));
1922 printf(" tcpack %d", ntohl(cmd32->d[0]));
1926 printf(" tcpseq %d", ntohl(cmd32->d[0]));
1931 struct passwd *pwd = getpwuid(cmd32->d[0]);
1934 printf(" uid %s", pwd->pw_name);
1936 printf(" uid %u", cmd32->d[0]);
1942 struct group *grp = getgrgid(cmd32->d[0]);
1945 printf(" gid %s", grp->gr_name);
1947 printf(" gid %u", cmd32->d[0]);
1952 printf(" jail %d", cmd32->d[0]);
1956 printf(" verrevpath");
1960 printf(" versrcreach");
1964 printf(" antispoof");
1972 comment = (char *)(cmd + 1);
1976 printf(" keep-state");
1980 struct _s_x *p = limit_masks;
1981 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1982 uint8_t x = c->limit_mask;
1983 char const *comma = " ";
1986 for (; p->x != 0 ; p++)
1987 if ((x & p->x) == p->x) {
1989 printf("%s%s", comma, p->s);
1992 PRINT_UINT_ARG(" ", c->conn_limit);
2005 print_icmp6types((ipfw_insn_u32 *)cmd);
2009 print_ext6hdr( (ipfw_insn *) cmd );
2013 if (F_LEN(cmd) == 1)
2014 PRINT_UINT_ARG(" tagged ", cmd->arg1);
2016 print_newports((ipfw_insn_u16 *)cmd, 0,
2021 printf(" [opcode %d len %d]",
2022 cmd->opcode, cmd->len);
2025 if (cmd->len & F_OR) {
2028 } else if (or_block) {
2033 show_prerequisites(&flags, HAVE_IP, 0);
2035 printf(" // %s", comment);
2040 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth)
2042 struct protoent *pe;
2045 char buf[INET6_ADDRSTRLEN];
2047 if (!co.do_expired) {
2048 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
2051 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2052 printf("%05d", rulenum);
2053 if (pcwidth>0 || bcwidth>0)
2054 printf(" %*llu %*llu (%ds)", pcwidth,
2055 align_uint64(&d->pcnt), bcwidth,
2056 align_uint64(&d->bcnt), d->expire);
2057 switch (d->dyn_type) {
2058 case O_LIMIT_PARENT:
2059 printf(" PARENT %d", d->count);
2064 case O_KEEP_STATE: /* bidir, no mask */
2069 if ((pe = getprotobynumber(d->id.proto)) != NULL)
2070 printf(" %s", pe->p_name);
2072 printf(" proto %u", d->id.proto);
2074 if (d->id.addr_type == 4) {
2075 a.s_addr = htonl(d->id.src_ip);
2076 printf(" %s %d", inet_ntoa(a), d->id.src_port);
2078 a.s_addr = htonl(d->id.dst_ip);
2079 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
2080 } else if (d->id.addr_type == 6) {
2081 printf(" %s %d", inet_ntop(AF_INET6, &d->id.src_ip6, buf,
2082 sizeof(buf)), d->id.src_port);
2083 printf(" <-> %s %d", inet_ntop(AF_INET6, &d->id.dst_ip6, buf,
2084 sizeof(buf)), d->id.dst_port);
2086 printf(" UNKNOWN <-> UNKNOWN\n");
2092 sort_q(const void *pa, const void *pb)
2094 int rev = (co.do_sort < 0);
2095 int field = rev ? -co.do_sort : co.do_sort;
2097 const struct dn_flow_queue *a = pa;
2098 const struct dn_flow_queue *b = pb;
2102 res = a->len - b->len;
2105 res = a->len_bytes - b->len_bytes;
2108 case 3: /* tot pkts */
2109 res = a->tot_pkts - b->tot_pkts;
2112 case 4: /* tot bytes */
2113 res = a->tot_bytes - b->tot_bytes;
2120 return (int)(rev ? res : -res);
2124 list_queues(struct dn_flow_set *fs, struct dn_flow_queue *q)
2127 int index_printed, indexes = 0;
2129 struct protoent *pe;
2131 if (fs->rq_elements == 0)
2134 if (co.do_sort != 0)
2135 heapsort(q, fs->rq_elements, sizeof *q, sort_q);
2137 /* Print IPv4 flows */
2139 for (l = 0; l < fs->rq_elements; l++) {
2142 /* XXX: Should check for IPv4 flows */
2143 if (IS_IP6_FLOW_ID(&(q[l].id)))
2146 if (!index_printed) {
2148 if (indexes > 0) /* currently a no-op */
2152 "mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
2153 fs->flow_mask.proto,
2154 fs->flow_mask.src_ip, fs->flow_mask.src_port,
2155 fs->flow_mask.dst_ip, fs->flow_mask.dst_port);
2157 printf("BKT Prot ___Source IP/port____ "
2158 "____Dest. IP/port____ "
2159 "Tot_pkt/bytes Pkt/Byte Drp\n");
2162 printf("%3d ", q[l].hash_slot);
2163 pe = getprotobynumber(q[l].id.proto);
2165 printf("%-4s ", pe->p_name);
2167 printf("%4u ", q[l].id.proto);
2168 ina.s_addr = htonl(q[l].id.src_ip);
2169 printf("%15s/%-5d ",
2170 inet_ntoa(ina), q[l].id.src_port);
2171 ina.s_addr = htonl(q[l].id.dst_ip);
2172 printf("%15s/%-5d ",
2173 inet_ntoa(ina), q[l].id.dst_port);
2174 printf("%4qu %8qu %2u %4u %3u\n",
2175 q[l].tot_pkts, q[l].tot_bytes,
2176 q[l].len, q[l].len_bytes, q[l].drops);
2178 printf(" S %20qd F %20qd\n",
2182 /* Print IPv6 flows */
2184 for (l = 0; l < fs->rq_elements; l++) {
2185 if (!IS_IP6_FLOW_ID(&(q[l].id)))
2188 if (!index_printed) {
2193 printf("\n mask: proto: 0x%02x, flow_id: 0x%08x, ",
2194 fs->flow_mask.proto, fs->flow_mask.flow_id6);
2195 inet_ntop(AF_INET6, &(fs->flow_mask.src_ip6),
2196 buff, sizeof(buff));
2197 printf("%s/0x%04x -> ", buff, fs->flow_mask.src_port);
2198 inet_ntop( AF_INET6, &(fs->flow_mask.dst_ip6),
2199 buff, sizeof(buff) );
2200 printf("%s/0x%04x\n", buff, fs->flow_mask.dst_port);
2202 printf("BKT ___Prot___ _flow-id_ "
2203 "______________Source IPv6/port_______________ "
2204 "_______________Dest. IPv6/port_______________ "
2205 "Tot_pkt/bytes Pkt/Byte Drp\n");
2207 printf("%3d ", q[l].hash_slot);
2208 pe = getprotobynumber(q[l].id.proto);
2210 printf("%9s ", pe->p_name);
2212 printf("%9u ", q[l].id.proto);
2213 printf("%7d %39s/%-5d ", q[l].id.flow_id6,
2214 inet_ntop(AF_INET6, &(q[l].id.src_ip6), buff, sizeof(buff)),
2216 printf(" %39s/%-5d ",
2217 inet_ntop(AF_INET6, &(q[l].id.dst_ip6), buff, sizeof(buff)),
2219 printf(" %4qu %8qu %2u %4u %3u\n",
2220 q[l].tot_pkts, q[l].tot_bytes,
2221 q[l].len, q[l].len_bytes, q[l].drops);
2223 printf(" S %20qd F %20qd\n", q[l].S, q[l].F);
2228 print_flowset_parms(struct dn_flow_set *fs, char *prefix)
2233 char red[90]; /* Display RED parameters */
2236 if (fs->flags_fs & DN_QSIZE_IS_BYTES) {
2238 sprintf(qs, "%d KB", l / 1024);
2240 sprintf(qs, "%d B", l);
2242 sprintf(qs, "%3d sl.", l);
2244 sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff));
2247 if (fs->flags_fs & DN_IS_RED) /* RED parameters */
2249 "\n\t %cRED w_q %f min_th %d max_th %d max_p %f",
2250 (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ',
2251 1.0 * fs->w_q / (double)(1 << SCALE_RED),
2252 SCALE_VAL(fs->min_th),
2253 SCALE_VAL(fs->max_th),
2254 1.0 * fs->max_p / (double)(1 << SCALE_RED));
2256 sprintf(red, "droptail");
2258 printf("%s %s%s %d queues (%d buckets) %s\n",
2259 prefix, qs, plr, fs->rq_elements, fs->rq_size, red);
2263 list_pipes(void *data, uint nbytes, int ac, char *av[])
2267 struct dn_pipe *p = (struct dn_pipe *) data;
2268 struct dn_flow_set *fs;
2269 struct dn_flow_queue *q;
2273 rulenum = strtoul(*av++, NULL, 10);
2276 for (; nbytes >= sizeof *p; p = (struct dn_pipe *)next) {
2277 double b = p->bandwidth;
2281 if (SLIST_NEXT(p, next) != (struct dn_pipe *)DN_IS_PIPE)
2282 break; /* done with pipes, now queues */
2285 * compute length, as pipe have variable size
2287 l = sizeof(*p) + p->fs.rq_elements * sizeof(*q);
2288 next = (char *)p + l;
2291 if ((rulenum != 0 && rulenum != p->pipe_nr) || co.do_pipe == 2)
2295 * Print rate (or clocking interface)
2297 if (p->if_name[0] != '\0')
2298 sprintf(buf, "%s", p->if_name);
2300 sprintf(buf, "unlimited");
2301 else if (b >= 1000000)
2302 sprintf(buf, "%7.3f Mbit/s", b/1000000);
2304 sprintf(buf, "%7.3f Kbit/s", b/1000);
2306 sprintf(buf, "%7.3f bit/s ", b);
2308 sprintf(prefix, "%05d: %s %4d ms ",
2309 p->pipe_nr, buf, p->delay);
2310 print_flowset_parms(&(p->fs), prefix);
2312 printf(" V %20qd\n", p->V >> MY_M);
2314 q = (struct dn_flow_queue *)(p+1);
2315 list_queues(&(p->fs), q);
2317 for (fs = next; nbytes >= sizeof *fs; fs = next) {
2320 if (SLIST_NEXT(fs, next) != (struct dn_flow_set *)DN_IS_QUEUE)
2322 l = sizeof(*fs) + fs->rq_elements * sizeof(*q);
2323 next = (char *)fs + l;
2326 if (rulenum != 0 && ((rulenum != fs->fs_nr && co.do_pipe == 2) ||
2327 (rulenum != fs->parent_nr && co.do_pipe == 1))) {
2331 q = (struct dn_flow_queue *)(fs+1);
2332 sprintf(prefix, "q%05d: weight %d pipe %d ",
2333 fs->fs_nr, fs->weight, fs->parent_nr);
2334 print_flowset_parms(fs, prefix);
2340 * This one handles all set-related commands
2341 * ipfw set { show | enable | disable }
2343 * ipfw set move X to Y
2344 * ipfw set move rule X to Y
2347 ipfw_sets_handler(int ac, char *av[])
2349 uint32_t set_disable, masks[2];
2352 uint8_t cmd, new_set;
2358 errx(EX_USAGE, "set needs command");
2359 if (_substrcmp(*av, "show") == 0) {
2363 nbytes = sizeof(struct ip_fw);
2364 data = safe_calloc(1, nbytes);
2365 if (do_cmd(IP_FW_GET, data, (uintptr_t)&nbytes) < 0)
2366 err(EX_OSERR, "getsockopt(IP_FW_GET)");
2367 bcopy(&((struct ip_fw *)data)->next_rule,
2368 &set_disable, sizeof(set_disable));
2370 for (i = 0, msg = "disable" ; i < RESVD_SET; i++)
2371 if ((set_disable & (1<<i))) {
2372 printf("%s %d", msg, i);
2375 msg = (set_disable) ? " enable" : "enable";
2376 for (i = 0; i < RESVD_SET; i++)
2377 if (!(set_disable & (1<<i))) {
2378 printf("%s %d", msg, i);
2382 } else if (_substrcmp(*av, "swap") == 0) {
2385 errx(EX_USAGE, "set swap needs 2 set numbers\n");
2386 rulenum = atoi(av[0]);
2387 new_set = atoi(av[1]);
2388 if (!isdigit(*(av[0])) || rulenum > RESVD_SET)
2389 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
2390 if (!isdigit(*(av[1])) || new_set > RESVD_SET)
2391 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
2392 masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
2393 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
2394 } else if (_substrcmp(*av, "move") == 0) {
2396 if (ac && _substrcmp(*av, "rule") == 0) {
2401 if (ac != 3 || _substrcmp(av[1], "to") != 0)
2402 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
2403 rulenum = atoi(av[0]);
2404 new_set = atoi(av[2]);
2405 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > RESVD_SET) ||
2406 (cmd == 2 && rulenum == IPFW_DEFAULT_RULE) )
2407 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
2408 if (!isdigit(*(av[2])) || new_set > RESVD_SET)
2409 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
2410 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
2411 i = do_cmd(IP_FW_DEL, masks, sizeof(uint32_t));
2412 } else if (_substrcmp(*av, "disable") == 0 ||
2413 _substrcmp(*av, "enable") == 0 ) {
2414 int which = _substrcmp(*av, "enable") == 0 ? 1 : 0;
2417 masks[0] = masks[1] = 0;
2420 if (isdigit(**av)) {
2422 if (i < 0 || i > RESVD_SET)
2424 "invalid set number %d\n", i);
2425 masks[which] |= (1<<i);
2426 } else if (_substrcmp(*av, "disable") == 0)
2428 else if (_substrcmp(*av, "enable") == 0)
2432 "invalid set command %s\n", *av);
2435 if ( (masks[0] & masks[1]) != 0 )
2437 "cannot enable and disable the same set\n");
2439 i = do_cmd(IP_FW_DEL, masks, sizeof(masks));
2441 warn("set enable/disable: setsockopt(IP_FW_DEL)");
2443 errx(EX_USAGE, "invalid set command %s\n", *av);
2447 ipfw_sysctl_handler(int ac, char *av[], int which)
2453 warnx("missing keyword to enable/disable\n");
2454 } else if (_substrcmp(*av, "firewall") == 0) {
2455 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
2456 &which, sizeof(which));
2457 } else if (_substrcmp(*av, "one_pass") == 0) {
2458 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
2459 &which, sizeof(which));
2460 } else if (_substrcmp(*av, "debug") == 0) {
2461 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
2462 &which, sizeof(which));
2463 } else if (_substrcmp(*av, "verbose") == 0) {
2464 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
2465 &which, sizeof(which));
2466 } else if (_substrcmp(*av, "dyn_keepalive") == 0) {
2467 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
2468 &which, sizeof(which));
2469 } else if (_substrcmp(*av, "altq") == 0) {
2470 altq_set_enabled(which);
2472 warnx("unrecognize enable/disable keyword: %s\n", *av);
2477 ipfw_list(int ac, char *av[], int show_counters)
2480 ipfw_dyn_rule *dynrules, *d;
2482 #define NEXT(r) ((struct ip_fw *)((char *)r + RULESIZE(r)))
2485 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
2486 int exitval = EX_OK;
2494 const int ocmd = co.do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
2495 int nalloc = 1024; /* start somewhere... */
2500 fprintf(stderr, "Testing only, list disabled\n");
2507 /* get rules or pipes from kernel, resizing array as necessary */
2510 while (nbytes >= nalloc) {
2511 nalloc = nalloc * 2 + 200;
2513 data = safe_realloc(data, nbytes);
2514 if (do_cmd(ocmd, data, (uintptr_t)&nbytes) < 0)
2515 err(EX_OSERR, "getsockopt(IP_%s_GET)",
2516 co.do_pipe ? "DUMMYNET" : "FW");
2520 list_pipes(data, nbytes, ac, av);
2525 * Count static rules. They have variable size so we
2526 * need to scan the list to count them.
2528 for (nstat = 1, r = data, lim = (char *)data + nbytes;
2529 r->rulenum < IPFW_DEFAULT_RULE && (char *)r < lim;
2530 ++nstat, r = NEXT(r) )
2534 * Count dynamic rules. This is easier as they have
2538 dynrules = (ipfw_dyn_rule *)r ;
2539 n = (char *)r - (char *)data;
2540 ndyn = (nbytes - n) / sizeof *dynrules;
2542 /* if showing stats, figure out column widths ahead of time */
2543 bcwidth = pcwidth = 0;
2544 if (show_counters) {
2545 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
2546 /* skip rules from another set */
2547 if (co.use_set && r->set != co.use_set - 1)
2550 /* packet counter */
2551 width = snprintf(NULL, 0, "%llu",
2552 align_uint64(&r->pcnt));
2553 if (width > pcwidth)
2557 width = snprintf(NULL, 0, "%llu",
2558 align_uint64(&r->bcnt));
2559 if (width > bcwidth)
2563 if (co.do_dynamic && ndyn) {
2564 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2566 /* skip rules from another set */
2567 bcopy((char *)&d->rule + sizeof(uint16_t),
2568 &set, sizeof(uint8_t));
2569 if (set != co.use_set - 1)
2572 width = snprintf(NULL, 0, "%llu",
2573 align_uint64(&d->pcnt));
2574 if (width > pcwidth)
2577 width = snprintf(NULL, 0, "%llu",
2578 align_uint64(&d->bcnt));
2579 if (width > bcwidth)
2583 /* if no rule numbers were specified, list all rules */
2585 for (n = 0, r = data; n < nstat; n++, r = NEXT(r)) {
2586 if (co.use_set && r->set != co.use_set - 1)
2588 show_ipfw(r, pcwidth, bcwidth);
2591 if (co.do_dynamic && ndyn) {
2592 printf("## Dynamic rules (%d):\n", ndyn);
2593 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2595 bcopy((char *)&d->rule + sizeof(uint16_t),
2596 &set, sizeof(uint8_t));
2597 if (set != co.use_set - 1)
2600 show_dyn_ipfw(d, pcwidth, bcwidth);
2606 /* display specific rules requested on command line */
2608 for (lac = ac, lav = av; lac != 0; lac--) {
2609 /* convert command line rule # */
2610 last = rnum = strtoul(*lav++, &endptr, 10);
2612 last = strtoul(endptr+1, &endptr, 10);
2615 warnx("invalid rule number: %s", *(lav - 1));
2618 for (n = seen = 0, r = data; n < nstat; n++, r = NEXT(r) ) {
2619 if (r->rulenum > last)
2621 if (co.use_set && r->set != co.use_set - 1)
2623 if (r->rulenum >= rnum && r->rulenum <= last) {
2624 show_ipfw(r, pcwidth, bcwidth);
2629 /* give precedence to other error(s) */
2630 if (exitval == EX_OK)
2631 exitval = EX_UNAVAILABLE;
2632 warnx("rule %lu does not exist", rnum);
2636 if (co.do_dynamic && ndyn) {
2637 printf("## Dynamic rules:\n");
2638 for (lac = ac, lav = av; lac != 0; lac--) {
2639 last = rnum = strtoul(*lav++, &endptr, 10);
2641 last = strtoul(endptr+1, &endptr, 10);
2643 /* already warned */
2645 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
2648 bcopy(&d->rule, &rulenum, sizeof(rulenum));
2652 bcopy((char *)&d->rule + sizeof(uint16_t),
2653 &set, sizeof(uint8_t));
2654 if (set != co.use_set - 1)
2657 if (r->rulenum >= rnum && r->rulenum <= last)
2658 show_dyn_ipfw(d, pcwidth, bcwidth);
2668 if (exitval != EX_OK)
2674 lookup_host (char *host, struct in_addr *ipaddr)
2678 if (!inet_aton(host, ipaddr)) {
2679 if ((he = gethostbyname(host)) == NULL)
2681 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
2687 * fills the addr and mask fields in the instruction as appropriate from av.
2688 * Update length as appropriate.
2689 * The following formats are allowed:
2690 * me returns O_IP_*_ME
2691 * 1.2.3.4 single IP address
2692 * 1.2.3.4:5.6.7.8 address:mask
2693 * 1.2.3.4/24 address/mask
2694 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
2695 * We can have multiple comma-separated address/mask entries.
2698 fill_ip(ipfw_insn_ip *cmd, char *av)
2701 uint32_t *d = ((ipfw_insn_u32 *)cmd)->d;
2703 cmd->o.len &= ~F_LEN_MASK; /* zero len */
2705 if (_substrcmp(av, "any") == 0)
2708 if (_substrcmp(av, "me") == 0) {
2709 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2713 if (strncmp(av, "table(", 6) == 0) {
2714 char *p = strchr(av + 6, ',');
2718 cmd->o.opcode = O_IP_DST_LOOKUP;
2719 cmd->o.arg1 = strtoul(av + 6, NULL, 0);
2721 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2722 d[0] = strtoul(p, NULL, 0);
2724 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2730 * After the address we can have '/' or ':' indicating a mask,
2731 * ',' indicating another address follows, '{' indicating a
2732 * set of addresses of unspecified size.
2734 char *t = NULL, *p = strpbrk(av, "/:,{");
2741 if ((t = strpbrk(p, ",{")) != NULL) {
2748 if (lookup_host(av, (struct in_addr *)&d[0]) != 0)
2749 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
2752 if (!inet_aton(p, (struct in_addr *)&d[1]))
2753 errx(EX_DATAERR, "bad netmask ``%s''", p);
2758 d[1] = htonl(0); /* mask */
2759 else if (masklen > 32)
2760 errx(EX_DATAERR, "bad width ``%s''", p);
2762 d[1] = htonl(~0 << (32 - masklen));
2764 case '{': /* no mask, assume /24 and put back the '{' */
2765 d[1] = htonl(~0 << (32 - 24));
2769 case ',': /* single address plus continuation */
2772 case 0: /* initialization value */
2774 d[1] = htonl(~0); /* force /32 */
2777 d[0] &= d[1]; /* mask base address with mask */
2780 /* find next separator */
2782 p = strpbrk(p, ",{");
2783 if (p && *p == '{') {
2785 * We have a set of addresses. They are stored as follows:
2786 * arg1 is the set size (powers of 2, 2..256)
2787 * addr is the base address IN HOST FORMAT
2788 * mask.. is an array of arg1 bits (rounded up to
2789 * the next multiple of 32) with bits set
2790 * for each host in the map.
2792 uint32_t *map = (uint32_t *)&cmd->mask;
2794 int i = contigmask((uint8_t *)&(d[1]), 32);
2797 errx(EX_DATAERR, "address set cannot be in a list");
2798 if (i < 24 || i > 31)
2799 errx(EX_DATAERR, "invalid set with mask %d\n", i);
2800 cmd->o.arg1 = 1<<(32-i); /* map length */
2801 d[0] = ntohl(d[0]); /* base addr in host format */
2802 cmd->o.opcode = O_IP_DST_SET; /* default */
2803 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
2804 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
2805 map[i] = 0; /* clear map */
2809 high = low + cmd->o.arg1 - 1;
2811 * Here, i stores the previous value when we specify a range
2812 * of addresses within a mask, e.g. 45-63. i = -1 means we
2813 * have no previous value.
2815 i = -1; /* previous value in a range */
2816 while (isdigit(*av)) {
2818 int a = strtol(av, &s, 0);
2820 if (s == av) { /* no parameter */
2822 errx(EX_DATAERR, "set not closed\n");
2824 errx(EX_DATAERR, "incomplete range %d-", i);
2827 if (a < low || a > high)
2828 errx(EX_DATAERR, "addr %d out of range [%d-%d]\n",
2831 if (i == -1) /* no previous in range */
2833 else { /* check that range is valid */
2835 errx(EX_DATAERR, "invalid range %d-%d",
2838 errx(EX_DATAERR, "double '-' in range");
2841 map[i/32] |= 1<<(i & 31);
2852 if (av) /* then *av must be a ',' */
2855 /* Check this entry */
2856 if (d[1] == 0) { /* "any", specified as x.x.x.x/0 */
2858 * 'any' turns the entire list into a NOP.
2859 * 'not any' never matches, so it is removed from the
2860 * list unless it is the only item, in which case we
2863 if (cmd->o.len & F_NOT) { /* "not any" never matches */
2864 if (av == NULL && len == 0) /* only this entry */
2865 errx(EX_DATAERR, "not any never matches");
2867 /* else do nothing and skip this entry */
2870 /* A single IP can be stored in an optimized format */
2871 if (d[1] == ~0 && av == NULL && len == 0) {
2872 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
2875 len += 2; /* two words... */
2878 if (len + 1 > F_LEN_MASK)
2879 errx(EX_DATAERR, "address list too long");
2880 cmd->o.len |= len+1;
2884 /* Try to find ipv6 address by hostname */
2886 lookup_host6 (char *host, struct in6_addr *ip6addr)
2890 if (!inet_pton(AF_INET6, host, ip6addr)) {
2891 if ((he = gethostbyname2(host, AF_INET6)) == NULL)
2893 memcpy(ip6addr, he->h_addr_list[0], sizeof( struct in6_addr));
2899 /* n2mask sets n bits of the mask */
2901 n2mask(struct in6_addr *mask, int n)
2903 static int minimask[9] =
2904 { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
2907 memset(mask, 0, sizeof(struct in6_addr));
2908 p = (u_char *) mask;
2909 for (; n > 0; p++, n -= 8) {
2920 * fill the addr and mask fields in the instruction as appropriate from av.
2921 * Update length as appropriate.
2922 * The following formats are allowed:
2923 * any matches any IP6. Actually returns an empty instruction.
2924 * me returns O_IP6_*_ME
2926 * 03f1::234:123:0342 single IP6 addres
2927 * 03f1::234:123:0342/24 address/mask
2928 * 03f1::234:123:0342/24,03f1::234:123:0343/ List of address
2930 * Set of address (as in ipv6) not supported because ipv6 address
2931 * are typically random past the initial prefix.
2932 * Return 1 on success, 0 on failure.
2935 fill_ip6(ipfw_insn_ip6 *cmd, char *av)
2938 struct in6_addr *d = &(cmd->addr6);
2940 * Needed for multiple address.
2941 * Note d[1] points to struct in6_add r mask6 of cmd
2944 cmd->o.len &= ~F_LEN_MASK; /* zero len */
2946 if (strcmp(av, "any") == 0)
2950 if (strcmp(av, "me") == 0) { /* Set the data for "me" opt*/
2951 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2955 if (strcmp(av, "me6") == 0) { /* Set the data for "me" opt*/
2956 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
2963 * After the address we can have '/' indicating a mask,
2964 * or ',' indicating another address follows.
2971 if ((p = strpbrk(av, "/,")) ) {
2972 md = *p; /* save the separator */
2973 *p = '\0'; /* terminate address string */
2974 p++; /* and skip past it */
2976 /* now p points to NULL, mask or next entry */
2978 /* lookup stores address in *d as a side effect */
2979 if (lookup_host6(av, d) != 0) {
2980 /* XXX: failed. Free memory and go */
2981 errx(EX_DATAERR, "bad address \"%s\"", av);
2983 /* next, look at the mask, if any */
2984 masklen = (md == '/') ? atoi(p) : 128;
2985 if (masklen > 128 || masklen < 0)
2986 errx(EX_DATAERR, "bad width \"%s\''", p);
2988 n2mask(&d[1], masklen);
2990 APPLY_MASK(d, &d[1]) /* mask base address with mask */
2992 /* find next separator */
2994 if (md == '/') { /* find separator past the mask */
2995 p = strpbrk(p, ",");
3001 /* Check this entry */
3004 * 'any' turns the entire list into a NOP.
3005 * 'not any' never matches, so it is removed from the
3006 * list unless it is the only item, in which case we
3009 if (cmd->o.len & F_NOT && av == NULL && len == 0)
3010 errx(EX_DATAERR, "not any never matches");
3015 * A single IP can be stored alone
3017 if (masklen == 128 && av == NULL && len == 0) {
3018 len = F_INSN_SIZE(struct in6_addr);
3022 /* Update length and pointer to arguments */
3023 len += F_INSN_SIZE(struct in6_addr)*2;
3028 * Total length of the command, remember that 1 is the size of
3031 if (len + 1 > F_LEN_MASK)
3032 errx(EX_DATAERR, "address list too long");
3033 cmd->o.len |= len+1;
3039 * fills command for ipv6 flow-id filtering
3040 * note that the 20 bit flow number is stored in a array of u_int32_t
3041 * it's supported lists of flow-id, so in the o.arg1 we store how many
3042 * additional flow-id we want to filter, the basic is 1
3045 fill_flow6( ipfw_insn_u32 *cmd, char *av )
3047 u_int32_t type; /* Current flow number */
3048 u_int16_t nflow = 0; /* Current flow index */
3050 cmd->d[0] = 0; /* Initializing the base number*/
3053 av = strsep( &s, ",") ;
3054 type = strtoul(av, &av, 0);
3055 if (*av != ',' && *av != '\0')
3056 errx(EX_DATAERR, "invalid ipv6 flow number %s", av);
3058 errx(EX_DATAERR, "flow number out of range %s", av);
3059 cmd->d[nflow] |= type;
3063 cmd->o.opcode = O_FLOW6ID;
3064 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + nflow;
3065 cmd->o.arg1 = nflow;
3068 errx(EX_DATAERR, "invalid ipv6 flow number %s", av);
3073 add_srcip6(ipfw_insn *cmd, char *av)
3076 fill_ip6((ipfw_insn_ip6 *)cmd, av);
3077 if (F_LEN(cmd) == 0) { /* any */
3078 } else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) { /* "me" */
3079 cmd->opcode = O_IP6_SRC_ME;
3080 } else if (F_LEN(cmd) ==
3081 (F_INSN_SIZE(struct in6_addr) + F_INSN_SIZE(ipfw_insn))) {
3082 /* single IP, no mask*/
3083 cmd->opcode = O_IP6_SRC;
3084 } else { /* addr/mask opt */
3085 cmd->opcode = O_IP6_SRC_MASK;
3091 add_dstip6(ipfw_insn *cmd, char *av)
3094 fill_ip6((ipfw_insn_ip6 *)cmd, av);
3095 if (F_LEN(cmd) == 0) { /* any */
3096 } else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) { /* "me" */
3097 cmd->opcode = O_IP6_DST_ME;
3098 } else if (F_LEN(cmd) ==
3099 (F_INSN_SIZE(struct in6_addr) + F_INSN_SIZE(ipfw_insn))) {
3100 /* single IP, no mask*/
3101 cmd->opcode = O_IP6_DST;
3102 } else { /* addr/mask opt */
3103 cmd->opcode = O_IP6_DST_MASK;
3110 * helper function to process a set of flags and set bits in the
3111 * appropriate masks.
3114 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
3115 struct _s_x *flags, char *p)
3117 uint8_t set=0, clear=0;
3120 char *q; /* points to the separator */
3122 uint8_t *which; /* mask we are working on */
3132 val = match_token(flags, p);
3134 errx(EX_DATAERR, "invalid flag %s", p);
3135 *which |= (uint8_t)val;
3138 cmd->opcode = opcode;
3139 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
3140 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
3145 ipfw_delete(int ac, char *av[])
3150 int exitval = EX_OK;
3153 memset(&p, 0, sizeof p);
3156 NEED1("missing rule specification");
3157 if (ac > 0 && _substrcmp(*av, "set") == 0) {
3158 /* Do not allow using the following syntax:
3159 * ipfw set N delete set M
3162 errx(EX_DATAERR, "invalid syntax");
3163 do_set = 1; /* delete set */
3168 while (ac && isdigit(**av)) {
3169 i = atoi(*av); av++; ac--;
3171 exitval = do_cmd(IP_FW_NAT_DEL, &i, sizeof i);
3173 exitval = EX_UNAVAILABLE;
3174 warn("rule %u not available", i);
3176 } else if (co.do_pipe) {
3177 if (co.do_pipe == 1)
3181 i = do_cmd(IP_DUMMYNET_DEL, &p, sizeof p);
3184 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)",
3185 co.do_pipe == 1 ? p.pipe_nr : p.fs.fs_nr);
3189 rulenum = (i & 0xffff) | (5 << 24) |
3190 ((co.use_set - 1) << 16);
3192 rulenum = (i & 0xffff) | (do_set << 24);
3193 i = do_cmd(IP_FW_DEL, &rulenum, sizeof rulenum);
3195 exitval = EX_UNAVAILABLE;
3196 warn("rule %u: setsockopt(IP_FW_DEL)",
3201 if (exitval != EX_OK)
3207 * fill the interface structure. We do not check the name as we can
3208 * create interfaces dynamically, so checking them at insert time
3209 * makes relatively little sense.
3210 * Interface names containing '*', '?', or '[' are assumed to be shell
3211 * patterns which match interfaces.
3214 fill_iface(ipfw_insn_if *cmd, char *arg)
3216 cmd->name[0] = '\0';
3217 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
3219 /* Parse the interface or address */
3220 if (strcmp(arg, "any") == 0)
3221 cmd->o.len = 0; /* effectively ignore this command */
3222 else if (!isdigit(*arg)) {
3223 strlcpy(cmd->name, arg, sizeof(cmd->name));
3224 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
3225 } else if (!inet_aton(arg, &cmd->p.ip))
3226 errx(EX_DATAERR, "bad ip address ``%s''", arg);
3230 * Search for interface with name "ifn", and fill n accordingly:
3232 * n->ip ip address of interface "ifn"
3233 * n->if_name copy of interface name "ifn"
3236 set_addr_dynamic(const char *ifn, struct cfg_nat *n)
3240 char *buf, *lim, *next;
3241 struct if_msghdr *ifm;
3242 struct ifa_msghdr *ifam;
3243 struct sockaddr_dl *sdl;
3244 struct sockaddr_in *sin;
3251 mib[4] = NET_RT_IFLIST;
3254 * Get interface data.
3256 if (sysctl(mib, 6, NULL, &needed, NULL, 0) == -1)
3257 err(1, "iflist-sysctl-estimate");
3258 buf = safe_calloc(1, needed);
3259 if (sysctl(mib, 6, buf, &needed, NULL, 0) == -1)
3260 err(1, "iflist-sysctl-get");
3263 * Loop through interfaces until one with
3264 * given name is found. This is done to
3265 * find correct interface index for routing
3266 * message processing.
3270 while (next < lim) {
3271 ifm = (struct if_msghdr *)next;
3272 next += ifm->ifm_msglen;
3273 if (ifm->ifm_version != RTM_VERSION) {
3275 warnx("routing message version %d "
3276 "not understood", ifm->ifm_version);
3279 if (ifm->ifm_type == RTM_IFINFO) {
3280 sdl = (struct sockaddr_dl *)(ifm + 1);
3281 if (strlen(ifn) == sdl->sdl_nlen &&
3282 strncmp(ifn, sdl->sdl_data, sdl->sdl_nlen) == 0) {
3283 ifIndex = ifm->ifm_index;
3284 ifMTU = ifm->ifm_data.ifi_mtu;
3290 errx(1, "unknown interface name %s", ifn);
3292 * Get interface address.
3295 while (next < lim) {
3296 ifam = (struct ifa_msghdr *)next;
3297 next += ifam->ifam_msglen;
3298 if (ifam->ifam_version != RTM_VERSION) {
3300 warnx("routing message version %d "
3301 "not understood", ifam->ifam_version);
3304 if (ifam->ifam_type != RTM_NEWADDR)
3306 if (ifam->ifam_addrs & RTA_IFA) {
3308 char *cp = (char *)(ifam + 1);
3310 for (i = 1; i < RTA_IFA; i <<= 1) {
3311 if (ifam->ifam_addrs & i)
3312 cp += SA_SIZE((struct sockaddr *)cp);
3314 if (((struct sockaddr *)cp)->sa_family == AF_INET) {
3315 sin = (struct sockaddr_in *)cp;
3321 errx(1, "%s: cannot get interface address", ifn);
3323 n->ip = sin->sin_addr;
3324 strncpy(n->if_name, ifn, IF_NAMESIZE);
3330 * XXX - The following functions, macros and definitions come from natd.c:
3331 * it would be better to move them outside natd.c, in a file
3332 * (redirect_support.[ch]?) shared by ipfw and natd, but for now i can live
3337 * Definition of a port range, and macros to deal with values.
3338 * FORMAT: HI 16-bits == first port in range, 0 == all ports.
3339 * LO 16-bits == number of ports in range
3340 * NOTES: - Port values are not stored in network byte order.
3343 #define port_range u_long
3345 #define GETLOPORT(x) ((x) >> 0x10)
3346 #define GETNUMPORTS(x) ((x) & 0x0000ffff)
3347 #define GETHIPORT(x) (GETLOPORT((x)) + GETNUMPORTS((x)))
3349 /* Set y to be the low-port value in port_range variable x. */
3350 #define SETLOPORT(x,y) ((x) = ((x) & 0x0000ffff) | ((y) << 0x10))
3352 /* Set y to be the number of ports in port_range variable x. */
3353 #define SETNUMPORTS(x,y) ((x) = ((x) & 0xffff0000) | (y))
3356 StrToAddr (const char* str, struct in_addr* addr)
3360 if (inet_aton (str, addr))
3363 hp = gethostbyname (str);
3365 errx (1, "unknown host %s", str);
3367 memcpy (addr, hp->h_addr, sizeof (struct in_addr));
3371 StrToPortRange (const char* str, const char* proto, port_range *portRange)
3379 /* First see if this is a service, return corresponding port if so. */
3380 sp = getservbyname (str,proto);
3382 SETLOPORT(*portRange, ntohs(sp->s_port));
3383 SETNUMPORTS(*portRange, 1);
3387 /* Not a service, see if it's a single port or port range. */
3388 sep = strchr (str, '-');
3390 SETLOPORT(*portRange, strtol(str, &end, 10));
3393 SETNUMPORTS(*portRange, 1);
3397 /* Error in port range field. */
3398 errx (EX_DATAERR, "%s/%s: unknown service", str, proto);
3401 /* Port range, get the values and sanity check. */
3402 sscanf (str, "%hu-%hu", &loPort, &hiPort);
3403 SETLOPORT(*portRange, loPort);
3404 SETNUMPORTS(*portRange, 0); /* Error by default */
3405 if (loPort <= hiPort)
3406 SETNUMPORTS(*portRange, hiPort - loPort + 1);
3408 if (GETNUMPORTS(*portRange) == 0)
3409 errx (EX_DATAERR, "invalid port range %s", str);
3415 StrToProto (const char* str)
3417 if (!strcmp (str, "tcp"))
3420 if (!strcmp (str, "udp"))
3423 errx (EX_DATAERR, "unknown protocol %s. Expected tcp or udp", str);
3427 StrToAddrAndPortRange (const char* str, struct in_addr* addr, char* proto,
3428 port_range *portRange)
3432 ptr = strchr (str, ':');
3434 errx (EX_DATAERR, "%s is missing port number", str);
3439 StrToAddr (str, addr);
3440 return StrToPortRange (ptr, proto, portRange);
3443 /* End of stuff taken from natd.c. */
3445 #define INC_ARGCV() do { \
3453 * The next 3 functions add support for the addr, port and proto redirect and
3454 * their logic is loosely based on SetupAddressRedirect(), SetupPortRedirect()
3455 * and SetupProtoRedirect() from natd.c.
3457 * Every setup_* function fills at least one redirect entry
3458 * (struct cfg_redir) and zero or more server pool entry (struct cfg_spool)
3461 * The format of data in buf is:
3464 * cfg_nat cfg_redir cfg_spool ...... cfg_spool
3466 * ------------------------------------- ------------
3467 * | | .....X ... | | | | .....
3468 * ------------------------------------- ...... ------------
3470 * spool_cnt n=0 ...... n=(X-1)
3472 * len points to the amount of available space in buf
3473 * space counts the memory consumed by every function
3475 * XXX - Every function get all the argv params so it
3476 * has to check, in optional parameters, that the next
3477 * args is a valid option for the redir entry and not
3478 * another token. Only redir_port and redir_proto are
3483 setup_redir_addr(char *spool_buf, int len,
3484 int *_ac, char ***_av)
3486 char **av, *sep; /* Token separator. */
3487 /* Temporary buffer used to hold server pool ip's. */
3488 char tmp_spool_buf[NAT_BUF_LEN];
3489 int ac, space, lsnat;
3490 struct cfg_redir *r;
3491 struct cfg_spool *tmp;
3497 if (len >= SOF_REDIR) {
3498 r = (struct cfg_redir *)spool_buf;
3499 /* Skip cfg_redir at beginning of buf. */
3500 spool_buf = &spool_buf[SOF_REDIR];
3505 r->mode = REDIR_ADDR;
3506 /* Extract local address. */
3508 errx(EX_DATAERR, "redirect_addr: missing local address");
3509 sep = strchr(*av, ',');
3510 if (sep) { /* LSNAT redirection syntax. */
3511 r->laddr.s_addr = INADDR_NONE;
3512 /* Preserve av, copy spool servers to tmp_spool_buf. */
3513 strncpy(tmp_spool_buf, *av, strlen(*av)+1);
3516 StrToAddr(*av, &r->laddr);
3519 /* Extract public address. */
3521 errx(EX_DATAERR, "redirect_addr: missing public address");
3522 StrToAddr(*av, &r->paddr);
3525 /* Setup LSNAT server pool. */
3527 sep = strtok(tmp_spool_buf, ",");
3528 while (sep != NULL) {
3529 tmp = (struct cfg_spool *)spool_buf;
3530 if (len < SOF_SPOOL)
3534 StrToAddr(sep, &tmp->addr);
3537 /* Point to the next possible cfg_spool. */
3538 spool_buf = &spool_buf[SOF_SPOOL];
3539 sep = strtok(NULL, ",");
3544 errx(EX_DATAERR, "redirect_addr: buf is too small\n");
3548 setup_redir_port(char *spool_buf, int len,
3549 int *_ac, char ***_av)
3551 char **av, *sep, *protoName;
3552 char tmp_spool_buf[NAT_BUF_LEN];
3553 int ac, space, lsnat;
3554 struct cfg_redir *r;
3555 struct cfg_spool *tmp;
3556 u_short numLocalPorts;
3557 port_range portRange;
3565 if (len >= SOF_REDIR) {
3566 r = (struct cfg_redir *)spool_buf;
3567 /* Skip cfg_redir at beginning of buf. */
3568 spool_buf = &spool_buf[SOF_REDIR];
3573 r->mode = REDIR_PORT;
3578 errx (EX_DATAERR, "redirect_port: missing protocol");
3579 r->proto = StrToProto(*av);
3584 * Extract local address.
3587 errx (EX_DATAERR, "redirect_port: missing local address");
3589 sep = strchr(*av, ',');
3590 /* LSNAT redirection syntax. */
3592 r->laddr.s_addr = INADDR_NONE;
3595 /* Preserve av, copy spool servers to tmp_spool_buf. */
3596 strncpy(tmp_spool_buf, *av, strlen(*av)+1);
3599 if (StrToAddrAndPortRange (*av, &r->laddr, protoName,
3601 errx(EX_DATAERR, "redirect_port:"
3602 "invalid local port range");
3604 r->lport = GETLOPORT(portRange);
3605 numLocalPorts = GETNUMPORTS(portRange);
3610 * Extract public port and optionally address.
3613 errx (EX_DATAERR, "redirect_port: missing public port");
3615 sep = strchr (*av, ':');
3617 if (StrToAddrAndPortRange (*av, &r->paddr, protoName,
3619 errx(EX_DATAERR, "redirect_port:"
3620 "invalid public port range");
3622 r->paddr.s_addr = INADDR_ANY;
3623 if (StrToPortRange (*av, protoName, &portRange) != 0)
3624 errx(EX_DATAERR, "redirect_port:"
3625 "invalid public port range");
3628 r->pport = GETLOPORT(portRange);
3629 r->pport_cnt = GETNUMPORTS(portRange);
3633 * Extract remote address and optionally port.
3636 * NB: isalpha(**av) => we've to check that next parameter is really an
3637 * option for this redirect entry, else stop here processing arg[cv].
3639 if (ac != 0 && !isalpha(**av)) {
3640 sep = strchr (*av, ':');
3642 if (StrToAddrAndPortRange (*av, &r->raddr, protoName,
3644 errx(EX_DATAERR, "redirect_port:"
3645 "invalid remote port range");
3647 SETLOPORT(portRange, 0);
3648 SETNUMPORTS(portRange, 1);
3649 StrToAddr (*av, &r->raddr);
3653 SETLOPORT(portRange, 0);
3654 SETNUMPORTS(portRange, 1);
3655 r->raddr.s_addr = INADDR_ANY;
3657 r->rport = GETLOPORT(portRange);
3658 r->rport_cnt = GETNUMPORTS(portRange);
3661 * Make sure port ranges match up, then add the redirect ports.
3663 if (numLocalPorts != r->pport_cnt)
3664 errx(EX_DATAERR, "redirect_port:"
3665 "port ranges must be equal in size");
3667 /* Remote port range is allowed to be '0' which means all ports. */
3668 if (r->rport_cnt != numLocalPorts &&
3669 (r->rport_cnt != 1 || r->rport != 0))
3670 errx(EX_DATAERR, "redirect_port: remote port must"
3671 "be 0 or equal to local port range in size");
3674 * Setup LSNAT server pool.
3677 sep = strtok(tmp_spool_buf, ",");
3678 while (sep != NULL) {
3679 tmp = (struct cfg_spool *)spool_buf;
3680 if (len < SOF_SPOOL)
3684 if (StrToAddrAndPortRange(sep, &tmp->addr, protoName,
3686 errx(EX_DATAERR, "redirect_port:"
3687 "invalid local port range");
3688 if (GETNUMPORTS(portRange) != 1)
3689 errx(EX_DATAERR, "redirect_port: local port"
3690 "must be single in this context");
3691 tmp->port = GETLOPORT(portRange);
3693 /* Point to the next possible cfg_spool. */
3694 spool_buf = &spool_buf[SOF_SPOOL];
3695 sep = strtok(NULL, ",");
3700 errx(EX_DATAERR, "redirect_port: buf is too small\n");
3704 setup_redir_proto(char *spool_buf, int len,
3705 int *_ac, char ***_av)
3709 struct protoent *protoent;
3710 struct cfg_redir *r;
3714 if (len >= SOF_REDIR) {
3715 r = (struct cfg_redir *)spool_buf;
3716 /* Skip cfg_redir at beginning of buf. */
3717 spool_buf = &spool_buf[SOF_REDIR];
3722 r->mode = REDIR_PROTO;
3727 errx(EX_DATAERR, "redirect_proto: missing protocol");
3729 protoent = getprotobyname(*av);
3730 if (protoent == NULL)
3731 errx(EX_DATAERR, "redirect_proto: unknown protocol %s", *av);
3733 r->proto = protoent->p_proto;
3738 * Extract local address.
3741 errx(EX_DATAERR, "redirect_proto: missing local address");
3743 StrToAddr(*av, &r->laddr);
3748 * Extract optional public address.
3751 r->paddr.s_addr = INADDR_ANY;
3752 r->raddr.s_addr = INADDR_ANY;
3754 /* see above in setup_redir_port() */
3755 if (!isalpha(**av)) {
3756 StrToAddr(*av, &r->paddr);
3760 * Extract optional remote address.
3762 /* see above in setup_redir_port() */
3763 if (ac!=0 && !isalpha(**av)) {
3764 StrToAddr(*av, &r->raddr);
3771 errx(EX_DATAERR, "redirect_proto: buf is too small\n");
3775 print_nat_config(unsigned char *buf)
3778 int i, cnt, flag, off;
3779 struct cfg_redir *t;
3780 struct cfg_spool *s;
3783 n = (struct cfg_nat *)buf;
3786 printf("ipfw nat %u config", n->id);
3787 if (strlen(n->if_name) != 0)
3788 printf(" if %s", n->if_name);
3789 else if (n->ip.s_addr != 0)
3790 printf(" ip %s", inet_ntoa(n->ip));
3791 while (n->mode != 0) {
3792 if (n->mode & PKT_ALIAS_LOG) {
3794 n->mode &= ~PKT_ALIAS_LOG;
3795 } else if (n->mode & PKT_ALIAS_DENY_INCOMING) {
3797 n->mode &= ~PKT_ALIAS_DENY_INCOMING;
3798 } else if (n->mode & PKT_ALIAS_SAME_PORTS) {
3799 printf(" same_ports");
3800 n->mode &= ~PKT_ALIAS_SAME_PORTS;
3801 } else if (n->mode & PKT_ALIAS_UNREGISTERED_ONLY) {
3802 printf(" unreg_only");
3803 n->mode &= ~PKT_ALIAS_UNREGISTERED_ONLY;
3804 } else if (n->mode & PKT_ALIAS_RESET_ON_ADDR_CHANGE) {
3806 n->mode &= ~PKT_ALIAS_RESET_ON_ADDR_CHANGE;
3807 } else if (n->mode & PKT_ALIAS_REVERSE) {
3809 n->mode &= ~PKT_ALIAS_REVERSE;
3810 } else if (n->mode & PKT_ALIAS_PROXY_ONLY) {
3811 printf(" proxy_only");
3812 n->mode &= ~PKT_ALIAS_PROXY_ONLY;
3815 /* Print all the redirect's data configuration. */
3816 for (cnt = 0; cnt < n->redir_cnt; cnt++) {
3817 t = (struct cfg_redir *)&buf[off];
3821 printf(" redirect_addr");
3822 if (t->spool_cnt == 0)
3823 printf(" %s", inet_ntoa(t->laddr));
3825 for (i = 0; i < t->spool_cnt; i++) {
3826 s = (struct cfg_spool *)&buf[off];
3831 printf("%s", inet_ntoa(s->addr));
3834 printf(" %s", inet_ntoa(t->paddr));
3837 p = getprotobynumber(t->proto);
3838 printf(" redirect_port %s ", p->p_name);
3839 if (!t->spool_cnt) {
3840 printf("%s:%u", inet_ntoa(t->laddr), t->lport);
3841 if (t->pport_cnt > 1)
3842 printf("-%u", t->lport +
3845 for (i=0; i < t->spool_cnt; i++) {
3846 s = (struct cfg_spool *)&buf[off];
3849 printf("%s:%u", inet_ntoa(s->addr),
3855 if (t->paddr.s_addr)
3856 printf("%s:", inet_ntoa(t->paddr));
3857 printf("%u", t->pport);
3858 if (!t->spool_cnt && t->pport_cnt > 1)
3859 printf("-%u", t->pport + t->pport_cnt - 1);
3861 if (t->raddr.s_addr) {
3862 printf(" %s", inet_ntoa(t->raddr));
3864 printf(":%u", t->rport);
3865 if (!t->spool_cnt && t->rport_cnt > 1)
3866 printf("-%u", t->rport +
3872 p = getprotobynumber(t->proto);
3873 printf(" redirect_proto %s %s", p->p_name,
3874 inet_ntoa(t->laddr));
3875 if (t->paddr.s_addr != 0) {
3876 printf(" %s", inet_ntoa(t->paddr));
3877 if (t->raddr.s_addr)
3878 printf(" %s", inet_ntoa(t->raddr));
3882 errx(EX_DATAERR, "unknown redir mode");
3890 ipfw_config_nat(int ac, char **av)
3892 struct cfg_nat *n; /* Nat instance configuration. */
3893 int i, len, off, tok;
3894 char *id, buf[NAT_BUF_LEN]; /* Buffer for serialized data. */
3897 /* Offset in buf: save space for n at the beginning. */
3899 memset(buf, 0, sizeof(buf));
3900 n = (struct cfg_nat *)buf;
3904 if (ac && isdigit(**av)) {
3910 errx(EX_DATAERR, "missing nat id");
3912 errx(EX_DATAERR, "missing option");
3915 tok = match_token(nat_params, *av);
3920 errx(EX_DATAERR, "missing option");
3921 if (!inet_aton(av[0], &(n->ip)))
3922 errx(EX_DATAERR, "bad ip address ``%s''",
3928 errx(EX_DATAERR, "missing option");
3929 set_addr_dynamic(av[0], n);
3933 n->mode |= PKT_ALIAS_LOG;
3936 n->mode |= PKT_ALIAS_DENY_INCOMING;
3938 case TOK_SAME_PORTS:
3939 n->mode |= PKT_ALIAS_SAME_PORTS;
3941 case TOK_UNREG_ONLY:
3942 n->mode |= PKT_ALIAS_UNREGISTERED_ONLY;
3944 case TOK_RESET_ADDR:
3945 n->mode |= PKT_ALIAS_RESET_ON_ADDR_CHANGE;
3948 n->mode |= PKT_ALIAS_REVERSE;
3950 case TOK_PROXY_ONLY:
3951 n->mode |= PKT_ALIAS_PROXY_ONLY;
3954 * All the setup_redir_* functions work directly in the final
3955 * buffer, see above for details.
3957 case TOK_REDIR_ADDR:
3958 case TOK_REDIR_PORT:
3959 case TOK_REDIR_PROTO:
3961 case TOK_REDIR_ADDR:
3962 i = setup_redir_addr(&buf[off], len, &ac, &av);
3964 case TOK_REDIR_PORT:
3965 i = setup_redir_port(&buf[off], len, &ac, &av);
3967 case TOK_REDIR_PROTO:
3968 i = setup_redir_proto(&buf[off], len, &ac, &av);
3976 errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]);
3980 i = do_cmd(IP_FW_NAT_CFG, buf, off);
3982 err(1, "setsockopt(%s)", "IP_FW_NAT_CFG");
3985 /* After every modification, we show the resultant rule. */
3987 char *_av[] = {"show", "config", id};
3988 ipfw_show_nat(_ac, _av);
3993 ipfw_config_pipe(int ac, char **av)
4000 memset(&p, 0, sizeof p);
4004 if (ac && isdigit(**av)) {
4005 i = atoi(*av); av++; ac--;
4006 if (co.do_pipe == 1)
4013 int tok = match_token(dummynet_params, *av);
4018 p.fs.flags_fs |= DN_NOERROR;
4022 NEED1("plr needs argument 0..1\n");
4023 d = strtod(av[0], NULL);
4028 p.fs.plr = (int)(d*0x7fffffff);
4033 NEED1("queue needs queue size\n");
4035 p.fs.qsize = strtoul(av[0], &end, 0);
4036 if (*end == 'K' || *end == 'k') {
4037 p.fs.flags_fs |= DN_QSIZE_IS_BYTES;
4039 } else if (*end == 'B' ||
4040 _substrcmp2(end, "by", "bytes") == 0) {
4041 p.fs.flags_fs |= DN_QSIZE_IS_BYTES;
4047 NEED1("buckets needs argument\n");
4048 p.fs.rq_size = strtoul(av[0], NULL, 0);
4053 NEED1("mask needs mask specifier\n");
4055 * per-flow queue, mask is dst_ip, dst_port,
4056 * src_ip, src_port, proto measured in bits
4060 bzero(&p.fs.flow_mask, sizeof(p.fs.flow_mask));
4064 uint32_t *p32 = NULL;
4065 uint16_t *p16 = NULL;
4066 uint32_t *p20 = NULL;
4067 struct in6_addr *pa6 = NULL;
4070 tok = match_token(dummynet_params, *av);
4075 * special case, all bits significant
4077 p.fs.flow_mask.dst_ip = ~0;
4078 p.fs.flow_mask.src_ip = ~0;
4079 p.fs.flow_mask.dst_port = ~0;
4080 p.fs.flow_mask.src_port = ~0;
4081 p.fs.flow_mask.proto = ~0;
4082 n2mask(&(p.fs.flow_mask.dst_ip6), 128);
4083 n2mask(&(p.fs.flow_mask.src_ip6), 128);
4084 p.fs.flow_mask.flow_id6 = ~0;
4085 p.fs.flags_fs |= DN_HAVE_FLOW_MASK;
4089 p32 = &p.fs.flow_mask.dst_ip;
4093 p32 = &p.fs.flow_mask.src_ip;
4097 pa6 = &(p.fs.flow_mask.dst_ip6);
4101 pa6 = &(p.fs.flow_mask.src_ip6);
4105 p20 = &p.fs.flow_mask.flow_id6;
4109 p16 = &p.fs.flow_mask.dst_port;
4113 p16 = &p.fs.flow_mask.src_port;
4120 ac++; av--; /* backtrack */
4124 errx(EX_USAGE, "mask: value missing");
4125 if (*av[0] == '/') {
4126 a = strtoul(av[0]+1, &end, 0);
4128 a = (a == 32) ? ~0 : (1 << a) - 1;
4130 a = strtoul(av[0], &end, 0);
4133 else if (p16 != NULL) {
4136 "port mask must be 16 bit");
4138 } else if (p20 != NULL) {
4141 "flow_id mask must be 20 bit");
4143 } else if (pa6 != NULL) {
4146 "in6addr invalid mask len");
4152 "proto mask must be 8 bit");
4153 p.fs.flow_mask.proto = (uint8_t)a;
4156 p.fs.flags_fs |= DN_HAVE_FLOW_MASK;
4158 } /* end while, config masks */
4164 NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
4165 p.fs.flags_fs |= DN_IS_RED;
4166 if (tok == TOK_GRED)
4167 p.fs.flags_fs |= DN_IS_GENTLE_RED;
4169 * the format for parameters is w_q/min_th/max_th/max_p
4171 if ((end = strsep(&av[0], "/"))) {
4172 double w_q = strtod(end, NULL);
4173 if (w_q > 1 || w_q <= 0)
4174 errx(EX_DATAERR, "0 < w_q <= 1");
4175 p.fs.w_q = (int) (w_q * (1 << SCALE_RED));
4177 if ((end = strsep(&av[0], "/"))) {
4178 p.fs.min_th = strtoul(end, &end, 0);
4179 if (*end == 'K' || *end == 'k')
4180 p.fs.min_th *= 1024;
4182 if ((end = strsep(&av[0], "/"))) {
4183 p.fs.max_th = strtoul(end, &end, 0);
4184 if (*end == 'K' || *end == 'k')
4185 p.fs.max_th *= 1024;
4187 if ((end = strsep(&av[0], "/"))) {
4188 double max_p = strtod(end, NULL);
4189 if (max_p > 1 || max_p <= 0)
4190 errx(EX_DATAERR, "0 < max_p <= 1");
4191 p.fs.max_p = (int)(max_p * (1 << SCALE_RED));
4197 p.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
4201 NEED1("bw needs bandwidth or interface\n");
4202 if (co.do_pipe != 1)
4203 errx(EX_DATAERR, "bandwidth only valid for pipes");
4205 * set clocking interface or bandwidth value
4207 if (av[0][0] >= 'a' && av[0][0] <= 'z') {
4208 int l = sizeof(p.if_name)-1;
4209 /* interface name */
4210 strncpy(p.if_name, av[0], l);
4211 p.if_name[l] = '\0';
4214 p.if_name[0] = '\0';
4215 p.bandwidth = strtoul(av[0], &end, 0);
4216 if (*end == 'K' || *end == 'k') {
4218 p.bandwidth *= 1000;
4219 } else if (*end == 'M') {
4221 p.bandwidth *= 1000000;
4224 _substrcmp2(end, "Bi", "Bit/s") != 0) ||
4225 _substrcmp2(end, "by", "bytes") == 0)
4227 if (p.bandwidth < 0)
4228 errx(EX_DATAERR, "bandwidth too large");
4234 if (co.do_pipe != 1)
4235 errx(EX_DATAERR, "delay only valid for pipes");
4236 NEED1("delay needs argument 0..10000ms\n");
4237 p.delay = strtoul(av[0], NULL, 0);
4242 if (co.do_pipe == 1)
4243 errx(EX_DATAERR,"weight only valid for queues");
4244 NEED1("weight needs argument 0..100\n");
4245 p.fs.weight = strtoul(av[0], &end, 0);
4250 if (co.do_pipe == 1)
4251 errx(EX_DATAERR,"pipe only valid for queues");
4252 NEED1("pipe needs pipe_number\n");
4253 p.fs.parent_nr = strtoul(av[0], &end, 0);
4258 errx(EX_DATAERR, "unrecognised option ``%s''", av[-1]);
4261 if (co.do_pipe == 1) {
4263 errx(EX_DATAERR, "pipe_nr must be > 0");
4264 if (p.delay > 10000)
4265 errx(EX_DATAERR, "delay must be < 10000");
4266 } else { /* co.do_pipe == 2, queue */
4267 if (p.fs.parent_nr == 0)
4268 errx(EX_DATAERR, "pipe must be > 0");
4269 if (p.fs.weight >100)
4270 errx(EX_DATAERR, "weight must be <= 100");
4272 if (p.fs.flags_fs & DN_QSIZE_IS_BYTES) {
4276 len = sizeof(limit);
4277 if (sysctlbyname("net.inet.ip.dummynet.pipe_byte_limit",
4278 &limit, &len, NULL, 0) == -1)
4280 if (p.fs.qsize > limit)
4281 errx(EX_DATAERR, "queue size must be < %ldB", limit);
4286 len = sizeof(limit);
4287 if (sysctlbyname("net.inet.ip.dummynet.pipe_slot_limit",
4288 &limit, &len, NULL, 0) == -1)
4290 if (p.fs.qsize > limit)
4291 errx(EX_DATAERR, "2 <= queue size <= %ld", limit);
4293 if (p.fs.flags_fs & DN_IS_RED) {
4295 int lookup_depth, avg_pkt_size;
4296 double s, idle, weight, w_q;
4297 struct clockinfo ck;
4300 if (p.fs.min_th >= p.fs.max_th)
4301 errx(EX_DATAERR, "min_th %d must be < than max_th %d",
4302 p.fs.min_th, p.fs.max_th);
4303 if (p.fs.max_th == 0)
4304 errx(EX_DATAERR, "max_th must be > 0");
4307 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
4308 &lookup_depth, &len, NULL, 0) == -1)
4309 errx(1, "sysctlbyname(\"%s\")",
4310 "net.inet.ip.dummynet.red_lookup_depth");
4311 if (lookup_depth == 0)
4312 errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
4313 " must be greater than zero");
4316 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
4317 &avg_pkt_size, &len, NULL, 0) == -1)
4319 errx(1, "sysctlbyname(\"%s\")",
4320 "net.inet.ip.dummynet.red_avg_pkt_size");
4321 if (avg_pkt_size == 0)
4323 "net.inet.ip.dummynet.red_avg_pkt_size must"
4324 " be greater than zero");
4326 len = sizeof(struct clockinfo);
4327 if (sysctlbyname("kern.clockrate", &ck, &len, NULL, 0) == -1)
4328 errx(1, "sysctlbyname(\"%s\")", "kern.clockrate");
4331 * Ticks needed for sending a medium-sized packet.
4332 * Unfortunately, when we are configuring a WF2Q+ queue, we
4333 * do not have bandwidth information, because that is stored
4334 * in the parent pipe, and also we have multiple queues
4335 * competing for it. So we set s=0, which is not very
4336 * correct. But on the other hand, why do we want RED with
4339 if (p.bandwidth==0) /* this is a WF2Q+ queue */
4342 s = (double)ck.hz * avg_pkt_size * 8 / p.bandwidth;
4345 * max idle time (in ticks) before avg queue size becomes 0.
4346 * NOTA: (3/w_q) is approx the value x so that
4347 * (1-w_q)^x < 10^-3.
4349 w_q = ((double)p.fs.w_q) / (1 << SCALE_RED);
4350 idle = s * 3. / w_q;
4351 p.fs.lookup_step = (int)idle / lookup_depth;
4352 if (!p.fs.lookup_step)
4353 p.fs.lookup_step = 1;
4355 for (t = p.fs.lookup_step; t > 1; --t)
4357 p.fs.lookup_weight = (int)(weight * (1 << SCALE_RED));
4359 i = do_cmd(IP_DUMMYNET_CONFIGURE, &p, sizeof p);
4361 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
4365 get_mac_addr_mask(const char *p, uint8_t *addr, uint8_t *mask)
4368 char *ap, *ptr, *optr;
4369 struct ether_addr *mac;
4370 const char *macset = "0123456789abcdefABCDEF:";
4372 if (strcmp(p, "any") == 0) {
4373 for (i = 0; i < ETHER_ADDR_LEN; i++)
4374 addr[i] = mask[i] = 0;
4378 optr = ptr = strdup(p);
4379 if ((ap = strsep(&ptr, "&/")) != NULL && *ap != 0) {
4381 if (strspn(ap, macset) != l || (mac = ether_aton(ap)) == NULL)
4382 errx(EX_DATAERR, "Incorrect MAC address");
4383 bcopy(mac, addr, ETHER_ADDR_LEN);
4385 errx(EX_DATAERR, "Incorrect MAC address");
4387 if (ptr != NULL) { /* we have mask? */
4388 if (p[ptr - optr - 1] == '/') { /* mask len */
4389 l = strtol(ptr, &ap, 10);
4390 if (*ap != 0 || l > ETHER_ADDR_LEN * 8 || l < 0)
4391 errx(EX_DATAERR, "Incorrect mask length");
4392 for (i = 0; l > 0 && i < ETHER_ADDR_LEN; l -= 8, i++)
4393 mask[i] = (l >= 8) ? 0xff: (~0) << (8 - l);
4396 if (strspn(ptr, macset) != l ||
4397 (mac = ether_aton(ptr)) == NULL)
4398 errx(EX_DATAERR, "Incorrect mask");
4399 bcopy(mac, mask, ETHER_ADDR_LEN);
4401 } else { /* default mask: ff:ff:ff:ff:ff:ff */
4402 for (i = 0; i < ETHER_ADDR_LEN; i++)
4405 for (i = 0; i < ETHER_ADDR_LEN; i++)
4412 * helper function, updates the pointer to cmd with the length
4413 * of the current command, and also cleans up the first word of
4414 * the new command in case it has been clobbered before.
4417 next_cmd(ipfw_insn *cmd)
4420 bzero(cmd, sizeof(*cmd));
4425 * Takes arguments and copies them into a comment
4428 fill_comment(ipfw_insn *cmd, int ac, char **av)
4431 char *p = (char *)(cmd + 1);
4433 cmd->opcode = O_NOP;
4434 cmd->len = (cmd->len & (F_NOT | F_OR));
4436 /* Compute length of comment string. */
4437 for (i = 0, l = 0; i < ac; i++)
4438 l += strlen(av[i]) + 1;
4443 "comment too long (max 80 chars)");
4445 cmd->len = (cmd->len & (F_NOT | F_OR)) | l;
4446 for (i = 0; i < ac; i++) {
4455 * A function to fill simple commands of size 1.
4456 * Existing flags are preserved.
4459 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, uint16_t arg)
4461 cmd->opcode = opcode;
4462 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
4467 * Fetch and add the MAC address and type, with masks. This generates one or
4468 * two microinstructions, and returns the pointer to the last one.
4471 add_mac(ipfw_insn *cmd, int ac, char *av[])
4476 errx(EX_DATAERR, "MAC dst src");
4478 cmd->opcode = O_MACADDR2;
4479 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
4481 mac = (ipfw_insn_mac *)cmd;
4482 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
4483 get_mac_addr_mask(av[1], &(mac->addr[ETHER_ADDR_LEN]),
4484 &(mac->mask[ETHER_ADDR_LEN])); /* src */
4489 add_mactype(ipfw_insn *cmd, int ac, char *av)
4492 errx(EX_DATAERR, "missing MAC type");
4493 if (strcmp(av, "any") != 0) { /* we have a non-null type */
4494 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE);
4495 cmd->opcode = O_MAC_TYPE;
4502 add_proto0(ipfw_insn *cmd, char *av, u_char *protop)
4504 struct protoent *pe;
4508 proto = strtol(av, &ep, 10);
4509 if (*ep != '\0' || proto <= 0) {
4510 if ((pe = getprotobyname(av)) == NULL)
4512 proto = pe->p_proto;
4515 fill_cmd(cmd, O_PROTO, 0, proto);
4521 add_proto(ipfw_insn *cmd, char *av, u_char *protop)
4523 u_char proto = IPPROTO_IP;
4525 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
4526 ; /* do not set O_IP4 nor O_IP6 */
4527 else if (strcmp(av, "ip4") == 0)
4528 /* explicit "just IPv4" rule */
4529 fill_cmd(cmd, O_IP4, 0, 0);
4530 else if (strcmp(av, "ip6") == 0) {
4531 /* explicit "just IPv6" rule */
4532 proto = IPPROTO_IPV6;
4533 fill_cmd(cmd, O_IP6, 0, 0);
4535 return add_proto0(cmd, av, protop);
4542 add_proto_compat(ipfw_insn *cmd, char *av, u_char *protop)
4544 u_char proto = IPPROTO_IP;
4546 if (_substrcmp(av, "all") == 0 || strcmp(av, "ip") == 0)
4547 ; /* do not set O_IP4 nor O_IP6 */
4548 else if (strcmp(av, "ipv4") == 0 || strcmp(av, "ip4") == 0)
4549 /* explicit "just IPv4" rule */
4550 fill_cmd(cmd, O_IP4, 0, 0);
4551 else if (strcmp(av, "ipv6") == 0 || strcmp(av, "ip6") == 0) {
4552 /* explicit "just IPv6" rule */
4553 proto = IPPROTO_IPV6;
4554 fill_cmd(cmd, O_IP6, 0, 0);
4556 return add_proto0(cmd, av, protop);
4563 add_srcip(ipfw_insn *cmd, char *av)
4565 fill_ip((ipfw_insn_ip *)cmd, av);
4566 if (cmd->opcode == O_IP_DST_SET) /* set */
4567 cmd->opcode = O_IP_SRC_SET;
4568 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
4569 cmd->opcode = O_IP_SRC_LOOKUP;
4570 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
4571 cmd->opcode = O_IP_SRC_ME;
4572 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
4573 cmd->opcode = O_IP_SRC;
4574 else /* addr/mask */
4575 cmd->opcode = O_IP_SRC_MASK;
4580 add_dstip(ipfw_insn *cmd, char *av)
4582 fill_ip((ipfw_insn_ip *)cmd, av);
4583 if (cmd->opcode == O_IP_DST_SET) /* set */
4585 else if (cmd->opcode == O_IP_DST_LOOKUP) /* table */
4587 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
4588 cmd->opcode = O_IP_DST_ME;
4589 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
4590 cmd->opcode = O_IP_DST;
4591 else /* addr/mask */
4592 cmd->opcode = O_IP_DST_MASK;
4597 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode)
4599 if (_substrcmp(av, "any") == 0) {
4601 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) {
4602 /* XXX todo: check that we have a protocol with ports */
4603 cmd->opcode = opcode;
4610 add_src(ipfw_insn *cmd, char *av, u_char proto)
4614 ipfw_insn *ret = NULL;
4616 if ((host = strdup(av)) == NULL)
4618 if ((ch = strrchr(host, '/')) != NULL)
4621 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
4622 inet_pton(AF_INET6, host, &a))
4623 ret = add_srcip6(cmd, av);
4624 /* XXX: should check for IPv4, not !IPv6 */
4625 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
4626 !inet_pton(AF_INET6, host, &a)))
4627 ret = add_srcip(cmd, av);
4628 if (ret == NULL && strcmp(av, "any") != 0)
4636 add_dst(ipfw_insn *cmd, char *av, u_char proto)
4640 ipfw_insn *ret = NULL;
4642 if ((host = strdup(av)) == NULL)
4644 if ((ch = strrchr(host, '/')) != NULL)
4647 if (proto == IPPROTO_IPV6 || strcmp(av, "me6") == 0 ||
4648 inet_pton(AF_INET6, host, &a))
4649 ret = add_dstip6(cmd, av);
4650 /* XXX: should check for IPv4, not !IPv6 */
4651 if (ret == NULL && (proto == IPPROTO_IP || strcmp(av, "me") == 0 ||
4652 !inet_pton(AF_INET6, host, &a)))
4653 ret = add_dstip(cmd, av);
4654 if (ret == NULL && strcmp(av, "any") != 0)
4662 * Parse arguments and assemble the microinstructions which make up a rule.
4663 * Rules are added into the 'rulebuf' and then copied in the correct order
4664 * into the actual rule.
4666 * The syntax for a rule starts with the action, followed by
4667 * optional action parameters, and the various match patterns.
4668 * In the assembled microcode, the first opcode must be an O_PROBE_STATE
4669 * (generated if the rule includes a keep-state option), then the
4670 * various match patterns, log/altq actions, and the actual action.
4674 ipfw_add(int ac, char *av[])
4677 * rules are added into the 'rulebuf' and then copied in
4678 * the correct order into the actual rule.
4679 * Some things that need to go out of order (prob, action etc.)
4682 static uint32_t rulebuf[255], actbuf[255], cmdbuf[255];
4684 ipfw_insn *src, *dst, *cmd, *action, *prev=NULL;
4685 ipfw_insn *first_cmd; /* first match pattern */
4690 * various flags used to record that we entered some fields.
4692 ipfw_insn *have_state = NULL; /* check-state or keep-state */
4693 ipfw_insn *have_log = NULL, *have_altq = NULL, *have_tag = NULL;
4698 int open_par = 0; /* open parenthesis ( */
4700 /* proto is here because it is used to fetch ports */
4701 u_char proto = IPPROTO_IP; /* default protocol */
4703 double match_prob = 1; /* match probability, default is always match */
4705 bzero(actbuf, sizeof(actbuf)); /* actions go here */
4706 bzero(cmdbuf, sizeof(cmdbuf));
4707 bzero(rulebuf, sizeof(rulebuf));
4709 rule = (struct ip_fw *)rulebuf;
4710 cmd = (ipfw_insn *)cmdbuf;
4711 action = (ipfw_insn *)actbuf;
4715 /* [rule N] -- Rule number optional */
4716 if (ac && isdigit(**av)) {
4717 rule->rulenum = atoi(*av);
4722 /* [set N] -- set number (0..RESVD_SET), optional */
4723 if (ac > 1 && _substrcmp(*av, "set") == 0) {
4724 int set = strtoul(av[1], NULL, 10);
4725 if (set < 0 || set > RESVD_SET)
4726 errx(EX_DATAERR, "illegal set %s", av[1]);
4731 /* [prob D] -- match probability, optional */
4732 if (ac > 1 && _substrcmp(*av, "prob") == 0) {
4733 match_prob = strtod(av[1], NULL);
4735 if (match_prob <= 0 || match_prob > 1)
4736 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
4740 /* action -- mandatory */
4741 NEED1("missing action");
4742 i = match_token(rule_actions, *av);
4744 action->len = 1; /* default */
4746 case TOK_CHECKSTATE:
4747 have_state = action;
4748 action->opcode = O_CHECK_STATE;
4752 action->opcode = O_ACCEPT;
4756 action->opcode = O_DENY;
4761 action->opcode = O_REJECT;
4762 action->arg1 = ICMP_UNREACH_HOST;
4766 action->opcode = O_REJECT;
4767 action->arg1 = ICMP_REJECT_RST;
4771 action->opcode = O_UNREACH6;
4772 action->arg1 = ICMP6_UNREACH_RST;
4776 action->opcode = O_REJECT;
4777 NEED1("missing reject code");
4778 fill_reject_code(&action->arg1, *av);
4783 action->opcode = O_UNREACH6;
4784 NEED1("missing unreach code");
4785 fill_unreach6_code(&action->arg1, *av);
4790 action->opcode = O_COUNT;
4794 action->opcode = O_NAT;
4795 action->len = F_INSN_SIZE(ipfw_insn_nat);
4799 action->opcode = O_QUEUE;
4802 action->opcode = O_PIPE;
4805 action->opcode = O_SKIPTO;
4808 action->opcode = O_NETGRAPH;
4811 action->opcode = O_NGTEE;
4814 action->opcode = O_DIVERT;
4817 action->opcode = O_TEE;
4820 errx(EX_USAGE, "missing argument for %s", *(av - 1));
4821 if (isdigit(**av)) {
4822 action->arg1 = strtoul(*av, NULL, 10);
4823 if (action->arg1 <= 0 || action->arg1 >= IP_FW_TABLEARG)
4824 errx(EX_DATAERR, "illegal argument for %s",
4826 } else if (_substrcmp(*av, "tablearg") == 0) {
4827 action->arg1 = IP_FW_TABLEARG;
4828 } else if (i == TOK_DIVERT || i == TOK_TEE) {
4831 s = getservbyname(av[0], "divert");
4833 action->arg1 = ntohs(s->s_port);
4835 errx(EX_DATAERR, "illegal divert/tee port");
4837 errx(EX_DATAERR, "illegal argument for %s", *(av - 1));
4842 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
4845 NEED1("missing forward address[:port]");
4847 action->opcode = O_FORWARD_IP;
4848 action->len = F_INSN_SIZE(ipfw_insn_sa);
4850 p->sa.sin_len = sizeof(struct sockaddr_in);
4851 p->sa.sin_family = AF_INET;
4854 * locate the address-port separator (':' or ',')
4856 s = strchr(*av, ':');
4858 s = strchr(*av, ',');
4861 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
4864 "illegal forwarding port ``%s''", s);
4865 p->sa.sin_port = (u_short)i;
4867 if (_substrcmp(*av, "tablearg") == 0)
4868 p->sa.sin_addr.s_addr = INADDR_ANY;
4870 lookup_host(*av, &(p->sa.sin_addr));
4875 /* pretend it is a 'count' rule followed by the comment */
4876 action->opcode = O_COUNT;
4877 ac++; av--; /* go back... */
4883 size_t intsize = sizeof(int);
4885 action->opcode = O_SETFIB;
4886 NEED1("missing fib number");
4887 action->arg1 = strtoul(*av, NULL, 10);
4888 if (sysctlbyname("net.fibs", &numfibs, &intsize, NULL, 0) == -1)
4889 errx(EX_DATAERR, "fibs not suported.\n");
4890 if (action->arg1 >= numfibs) /* Temporary */
4891 errx(EX_DATAERR, "fib too large.\n");
4897 errx(EX_DATAERR, "invalid action %s\n", av[-1]);
4899 action = next_cmd(action);
4902 * [altq queuename] -- altq tag, optional
4903 * [log [logamount N]] -- log, optional
4905 * If they exist, it go first in the cmdbuf, but then it is
4906 * skipped in the copy section to the end of the buffer.
4908 while (ac != 0 && (i = match_token(rule_action_params, *av)) != -1) {
4913 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
4918 "log cannot be specified more than once");
4919 have_log = (ipfw_insn *)c;
4920 cmd->len = F_INSN_SIZE(ipfw_insn_log);
4921 cmd->opcode = O_LOG;
4922 if (ac && _substrcmp(*av, "logamount") == 0) {
4924 NEED1("logamount requires argument");
4928 "logamount must be positive");
4932 len = sizeof(c->max_log);
4933 if (sysctlbyname("net.inet.ip.fw.verbose_limit",
4934 &c->max_log, &len, NULL, 0) == -1)
4935 errx(1, "sysctlbyname(\"%s\")",
4936 "net.inet.ip.fw.verbose_limit");
4943 ipfw_insn_altq *a = (ipfw_insn_altq *)cmd;
4945 NEED1("missing altq queue name");
4948 "altq cannot be specified more than once");
4949 have_altq = (ipfw_insn *)a;
4950 cmd->len = F_INSN_SIZE(ipfw_insn_altq);
4951 cmd->opcode = O_ALTQ;
4952 fill_altq_qid(&a->qid, *av);
4962 errx(EX_USAGE, "tag and untag cannot be "
4963 "specified more than once");
4964 GET_UINT_ARG(tag, 1, IPFW_DEFAULT_RULE - 1, i,
4965 rule_action_params);
4967 fill_cmd(cmd, O_TAG, (i == TOK_TAG) ? 0: F_NOT, tag);
4975 cmd = next_cmd(cmd);
4978 if (have_state) /* must be a check-state, we are done */
4981 #define OR_START(target) \
4982 if (ac && (*av[0] == '(' || *av[0] == '{')) { \
4984 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
4987 if ( (av[0])[1] == '\0') { \
4998 strcmp(*av, ")") == 0 || \
4999 strcmp(*av, "}") == 0)) { \
5004 errx(EX_USAGE, "missing \")\"\n"); \
5008 if (ac && _substrcmp(*av, "not") == 0) { \
5009 if (cmd->len & F_NOT) \
5010 errx(EX_USAGE, "double \"not\" not allowed\n"); \
5011 cmd->len |= F_NOT; \
5015 #define OR_BLOCK(target) \
5016 if (ac && _substrcmp(*av, "or") == 0) { \
5017 if (prev == NULL || open_par == 0) \
5018 errx(EX_DATAERR, "invalid OR block"); \
5019 prev->len |= F_OR; \
5029 * MAC addresses, optional.
5030 * If we have this, we skip the part "proto from src to dst"
5031 * and jump straight to the option parsing.
5034 NEED1("missing protocol");
5035 if (_substrcmp(*av, "MAC") == 0 ||
5036 _substrcmp(*av, "mac") == 0) {
5037 ac--; av++; /* the "MAC" keyword */
5038 add_mac(cmd, ac, av); /* exits in case of errors */
5039 cmd = next_cmd(cmd);
5040 ac -= 2; av += 2; /* dst-mac and src-mac */
5042 NEED1("missing mac type");
5043 if (add_mactype(cmd, ac, av[0]))
5044 cmd = next_cmd(cmd);
5045 ac--; av++; /* any or mac-type */
5051 * protocol, mandatory
5053 OR_START(get_proto);
5055 NEED1("missing protocol");
5056 if (add_proto_compat(cmd, *av, &proto)) {
5058 if (F_LEN(cmd) != 0) {
5060 cmd = next_cmd(cmd);
5062 } else if (first_cmd != cmd) {
5063 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
5066 OR_BLOCK(get_proto);
5071 if (!ac || _substrcmp(*av, "from") != 0)
5072 errx(EX_USAGE, "missing ``from''");
5076 * source IP, mandatory
5078 OR_START(source_ip);
5079 NOT_BLOCK; /* optional "not" */
5080 NEED1("missing source address");
5081 if (add_src(cmd, *av, proto)) {
5083 if (F_LEN(cmd) != 0) { /* ! any */
5085 cmd = next_cmd(cmd);
5088 errx(EX_USAGE, "bad source address %s", *av);
5089 OR_BLOCK(source_ip);
5092 * source ports, optional
5094 NOT_BLOCK; /* optional "not" */
5096 if (_substrcmp(*av, "any") == 0 ||
5097 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
5099 if (F_LEN(cmd) != 0)
5100 cmd = next_cmd(cmd);
5107 if (!ac || _substrcmp(*av, "to") != 0)
5108 errx(EX_USAGE, "missing ``to''");
5112 * destination, mandatory
5115 NOT_BLOCK; /* optional "not" */
5116 NEED1("missing dst address");
5117 if (add_dst(cmd, *av, proto)) {
5119 if (F_LEN(cmd) != 0) { /* ! any */
5121 cmd = next_cmd(cmd);
5124 errx( EX_USAGE, "bad destination address %s", *av);
5128 * dest. ports, optional
5130 NOT_BLOCK; /* optional "not" */
5132 if (_substrcmp(*av, "any") == 0 ||
5133 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
5135 if (F_LEN(cmd) != 0)
5136 cmd = next_cmd(cmd);
5141 if (ac && first_cmd == cmd) {
5143 * nothing specified so far, store in the rule to ease
5151 ipfw_insn_u32 *cmd32; /* alias for cmd */
5154 cmd32 = (ipfw_insn_u32 *)cmd;
5156 if (*s == '!') { /* alternate syntax for NOT */
5157 if (cmd->len & F_NOT)
5158 errx(EX_USAGE, "double \"not\" not allowed\n");
5162 i = match_token(rule_options, s);
5166 if (cmd->len & F_NOT)
5167 errx(EX_USAGE, "double \"not\" not allowed\n");
5172 if (open_par == 0 || prev == NULL)
5173 errx(EX_USAGE, "invalid \"or\" block\n");
5177 case TOK_STARTBRACE:
5179 errx(EX_USAGE, "+nested \"(\" not allowed\n");
5185 errx(EX_USAGE, "+missing \")\"\n");
5191 fill_cmd(cmd, O_IN, 0, 0);
5195 cmd->len ^= F_NOT; /* toggle F_NOT */
5196 fill_cmd(cmd, O_IN, 0, 0);
5200 fill_cmd(cmd, O_DIVERTED, 0, 3);
5203 case TOK_DIVERTEDLOOPBACK:
5204 fill_cmd(cmd, O_DIVERTED, 0, 1);
5207 case TOK_DIVERTEDOUTPUT:
5208 fill_cmd(cmd, O_DIVERTED, 0, 2);
5212 fill_cmd(cmd, O_FRAG, 0, 0);
5216 fill_cmd(cmd, O_LAYER2, 0, 0);
5222 NEED1("recv, xmit, via require interface name"
5224 fill_iface((ipfw_insn_if *)cmd, av[0]);
5226 if (F_LEN(cmd) == 0) /* not a valid address */
5229 cmd->opcode = O_XMIT;
5230 else if (i == TOK_RECV)
5231 cmd->opcode = O_RECV;
5232 else if (i == TOK_VIA)
5233 cmd->opcode = O_VIA;
5237 NEED1("icmptypes requires list of types");
5238 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
5242 case TOK_ICMP6TYPES:
5243 NEED1("icmptypes requires list of types");
5244 fill_icmp6types((ipfw_insn_icmp6 *)cmd, *av);
5249 NEED1("ipttl requires TTL");
5250 if (strpbrk(*av, "-,")) {
5251 if (!add_ports(cmd, *av, 0, O_IPTTL))
5252 errx(EX_DATAERR, "invalid ipttl %s", *av);
5254 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
5259 NEED1("ipid requires id");
5260 if (strpbrk(*av, "-,")) {
5261 if (!add_ports(cmd, *av, 0, O_IPID))
5262 errx(EX_DATAERR, "invalid ipid %s", *av);
5264 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
5269 NEED1("iplen requires length");
5270 if (strpbrk(*av, "-,")) {
5271 if (!add_ports(cmd, *av, 0, O_IPLEN))
5272 errx(EX_DATAERR, "invalid ip len %s", *av);
5274 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
5279 NEED1("ipver requires version");
5280 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
5284 case TOK_IPPRECEDENCE:
5285 NEED1("ipprecedence requires value");
5286 fill_cmd(cmd, O_IPPRECEDENCE, 0,
5287 (strtoul(*av, NULL, 0) & 7) << 5);
5292 NEED1("missing argument for ipoptions");
5293 fill_flags(cmd, O_IPOPT, f_ipopts, *av);
5298 NEED1("missing argument for iptos");
5299 fill_flags(cmd, O_IPTOS, f_iptos, *av);
5304 NEED1("uid requires argument");
5310 cmd->opcode = O_UID;
5311 uid = strtoul(*av, &end, 0);
5312 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
5314 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
5315 cmd32->d[0] = pwd->pw_uid;
5316 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
5322 NEED1("gid requires argument");
5328 cmd->opcode = O_GID;
5329 gid = strtoul(*av, &end, 0);
5330 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
5332 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
5333 cmd32->d[0] = grp->gr_gid;
5334 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
5340 NEED1("jail requires argument");
5345 cmd->opcode = O_JAIL;
5346 jid = (int)strtol(*av, &end, 0);
5347 if (jid < 0 || *end != '\0')
5348 errx(EX_DATAERR, "jail requires prison ID");
5349 cmd32->d[0] = (uint32_t)jid;
5350 cmd->len |= F_INSN_SIZE(ipfw_insn_u32);
5356 fill_cmd(cmd, O_ESTAB, 0, 0);
5360 fill_cmd(cmd, O_TCPFLAGS, 0,
5361 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
5364 case TOK_TCPDATALEN:
5365 NEED1("tcpdatalen requires length");
5366 if (strpbrk(*av, "-,")) {
5367 if (!add_ports(cmd, *av, 0, O_TCPDATALEN))
5368 errx(EX_DATAERR, "invalid tcpdata len %s", *av);
5370 fill_cmd(cmd, O_TCPDATALEN, 0,
5371 strtoul(*av, NULL, 0));
5376 NEED1("missing argument for tcpoptions");
5377 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
5383 NEED1("tcpseq/tcpack requires argument");
5384 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
5385 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
5386 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
5391 NEED1("tcpwin requires length");
5392 fill_cmd(cmd, O_TCPWIN, 0,
5393 htons(strtoul(*av, NULL, 0)));
5398 NEED1("missing argument for tcpflags");
5399 cmd->opcode = O_TCPFLAGS;
5400 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
5406 errx(EX_USAGE, "keep-state cannot be part "
5409 errx(EX_USAGE, "only one of keep-state "
5410 "and limit is allowed");
5412 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
5416 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
5421 "limit cannot be part of an or block");
5423 errx(EX_USAGE, "only one of keep-state and "
5424 "limit is allowed");
5427 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
5428 cmd->opcode = O_LIMIT;
5429 c->limit_mask = c->conn_limit = 0;
5432 if ((val = match_token(limit_masks, *av)) <= 0)
5434 c->limit_mask |= val;
5438 if (c->limit_mask == 0)
5439 errx(EX_USAGE, "limit: missing limit mask");
5441 GET_UINT_ARG(c->conn_limit, 1, IPFW_DEFAULT_RULE - 1,
5442 TOK_LIMIT, rule_options);
5449 NEED1("missing protocol");
5450 if (add_proto(cmd, *av, &proto)) {
5453 errx(EX_DATAERR, "invalid protocol ``%s''",
5458 NEED1("missing source IP");
5459 if (add_srcip(cmd, *av)) {
5465 NEED1("missing destination IP");
5466 if (add_dstip(cmd, *av)) {
5472 NEED1("missing source IP6");
5473 if (add_srcip6(cmd, *av)) {
5479 NEED1("missing destination IP6");
5480 if (add_dstip6(cmd, *av)) {
5486 NEED1("missing source port");
5487 if (_substrcmp(*av, "any") == 0 ||
5488 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
5491 errx(EX_DATAERR, "invalid source port %s", *av);
5495 NEED1("missing destination port");
5496 if (_substrcmp(*av, "any") == 0 ||
5497 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
5500 errx(EX_DATAERR, "invalid destination port %s",
5505 if (add_mac(cmd, ac, av)) {
5511 NEED1("missing mac type");
5512 if (!add_mactype(cmd, ac, *av))
5513 errx(EX_DATAERR, "invalid mac type %s", *av);
5517 case TOK_VERREVPATH:
5518 fill_cmd(cmd, O_VERREVPATH, 0, 0);
5521 case TOK_VERSRCREACH:
5522 fill_cmd(cmd, O_VERSRCREACH, 0, 0);
5526 fill_cmd(cmd, O_ANTISPOOF, 0, 0);
5530 fill_cmd(cmd, O_IPSEC, 0, 0);
5534 fill_cmd(cmd, O_IP6, 0, 0);
5538 fill_cmd(cmd, O_IP4, 0, 0);
5542 fill_ext6hdr( cmd, *av );
5547 if (proto != IPPROTO_IPV6 )
5548 errx( EX_USAGE, "flow-id filter is active "
5549 "only for ipv6 protocol\n");
5550 fill_flow6( (ipfw_insn_u32 *) cmd, *av );
5555 fill_comment(cmd, ac, av);
5561 if (ac > 0 && strpbrk(*av, "-,")) {
5562 if (!add_ports(cmd, *av, 0, O_TAGGED))
5563 errx(EX_DATAERR, "tagged: invalid tag"
5569 GET_UINT_ARG(tag, 1, IPFW_DEFAULT_RULE - 1,
5570 TOK_TAGGED, rule_options);
5571 fill_cmd(cmd, O_TAGGED, 0, tag);
5577 NEED1("fib requires fib number");
5578 fill_cmd(cmd, O_FIB, 0, strtoul(*av, NULL, 0));
5583 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
5585 if (F_LEN(cmd) > 0) { /* prepare to advance */
5587 cmd = next_cmd(cmd);
5593 * Now copy stuff into the rule.
5594 * If we have a keep-state option, the first instruction
5595 * must be a PROBE_STATE (which is generated here).
5596 * If we have a LOG option, it was stored as the first command,
5597 * and now must be moved to the top of the action part.
5599 dst = (ipfw_insn *)rule->cmd;
5602 * First thing to write into the command stream is the match probability.
5604 if (match_prob != 1) { /* 1 means always match */
5605 dst->opcode = O_PROB;
5607 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
5612 * generate O_PROBE_STATE if necessary
5614 if (have_state && have_state->opcode != O_CHECK_STATE) {
5615 fill_cmd(dst, O_PROBE_STATE, 0, 0);
5616 dst = next_cmd(dst);
5619 /* copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_ALTQ, O_TAG */
5620 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
5623 switch (src->opcode) {
5631 bcopy(src, dst, i * sizeof(uint32_t));
5637 * put back the have_state command as last opcode
5639 if (have_state && have_state->opcode != O_CHECK_STATE) {
5640 i = F_LEN(have_state);
5641 bcopy(have_state, dst, i * sizeof(uint32_t));
5645 * start action section
5647 rule->act_ofs = dst - rule->cmd;
5649 /* put back O_LOG, O_ALTQ, O_TAG if necessary */
5651 i = F_LEN(have_log);
5652 bcopy(have_log, dst, i * sizeof(uint32_t));
5656 i = F_LEN(have_altq);
5657 bcopy(have_altq, dst, i * sizeof(uint32_t));
5661 i = F_LEN(have_tag);
5662 bcopy(have_tag, dst, i * sizeof(uint32_t));
5666 * copy all other actions
5668 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
5670 bcopy(src, dst, i * sizeof(uint32_t));
5674 rule->cmd_len = (uint32_t *)dst - (uint32_t *)(rule->cmd);
5675 i = (char *)dst - (char *)rule;
5676 if (do_cmd(IP_FW_ADD, rule, (uintptr_t)&i) == -1)
5677 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
5679 show_ipfw(rule, 0, 0);
5683 * clear the counters or the log counters.
5686 ipfw_zero(int ac, char *av[], int optname /* 0 = IP_FW_ZERO, 1 = IP_FW_RESETLOG */)
5688 uint32_t arg, saved_arg;
5691 char const *name = optname ? "RESETLOG" : "ZERO";
5693 optname = optname ? IP_FW_RESETLOG : IP_FW_ZERO;
5698 /* clear all entries */
5699 if (do_cmd(optname, NULL, 0) < 0)
5700 err(EX_UNAVAILABLE, "setsockopt(IP_FW_%s)", name);
5702 printf("%s.\n", optname == IP_FW_ZERO ?
5703 "Accounting cleared":"Logging counts reset");
5710 if (isdigit(**av)) {
5711 arg = strtonum(*av, 0, 0xffff, &errstr);
5714 "invalid rule number %s\n", *av);
5717 arg |= (1 << 24) | ((co.use_set - 1) << 16);
5720 if (do_cmd(optname, &arg, sizeof(arg))) {
5721 warn("rule %u: setsockopt(IP_FW_%s)",
5723 failed = EX_UNAVAILABLE;
5724 } else if (!co.do_quiet)
5725 printf("Entry %d %s.\n", saved_arg,
5726 optname == IP_FW_ZERO ?
5727 "cleared" : "logging count reset");
5729 errx(EX_USAGE, "invalid rule number ``%s''", *av);
5732 if (failed != EX_OK)
5737 ipfw_flush(int force)
5739 int cmd = co.do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
5741 if (!force && !co.do_quiet) { /* need to ask user */
5744 printf("Are you sure? [yn] ");
5747 c = toupper(getc(stdin));
5748 while (c != '\n' && getc(stdin) != '\n')
5750 return; /* and do not flush */
5751 } while (c != 'Y' && c != 'N');
5753 if (c == 'N') /* user said no */
5756 /* `ipfw set N flush` - is the same that `ipfw delete set N` */
5758 uint32_t arg = ((co.use_set - 1) & 0xffff) | (1 << 24);
5759 if (do_cmd(IP_FW_DEL, &arg, sizeof(arg)) < 0)
5760 err(EX_UNAVAILABLE, "setsockopt(IP_FW_DEL)");
5761 } else if (do_cmd(cmd, NULL, 0) < 0)
5762 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
5763 co.do_pipe ? "DUMMYNET" : "FW");
5765 printf("Flushed all %s.\n", co.do_pipe ? "pipes" : "rules");
5769 static void table_list(ipfw_table_entry ent, int need_header);
5772 * This one handles all table-related commands
5773 * ipfw table N add addr[/masklen] [value]
5774 * ipfw table N delete addr[/masklen]
5775 * ipfw table {N | all} flush
5776 * ipfw table {N | all} list
5779 ipfw_table_handler(int ac, char *av[])
5781 ipfw_table_entry ent;
5787 uint32_t tables_max;
5789 len = sizeof(tables_max);
5790 if (sysctlbyname("net.inet.ip.fw.tables_max", &tables_max, &len,
5792 #ifdef IPFW_TABLES_MAX
5793 warn("Warn: Failed to get the max tables number via sysctl. "
5794 "Using the compiled in defaults. \nThe reason was");
5795 tables_max = IPFW_TABLES_MAX;
5797 errx(1, "Failed sysctlbyname(\"net.inet.ip.fw.tables_max\")");
5802 if (ac && isdigit(**av)) {
5803 ent.tbl = atoi(*av);
5806 } else if (ac && _substrcmp(*av, "all") == 0) {
5811 errx(EX_USAGE, "table number or 'all' keyword required");
5812 if (ent.tbl >= tables_max)
5813 errx(EX_USAGE, "The table number exceeds the maximum allowed "
5814 "value (%d)", tables_max - 1);
5815 NEED1("table needs command");
5816 if (is_all && _substrcmp(*av, "list") != 0
5817 && _substrcmp(*av, "flush") != 0)
5818 errx(EX_USAGE, "table number required");
5820 if (_substrcmp(*av, "add") == 0 ||
5821 _substrcmp(*av, "delete") == 0) {
5822 do_add = **av == 'a';
5825 errx(EX_USAGE, "IP address required");
5826 p = strchr(*av, '/');
5829 ent.masklen = atoi(p);
5830 if (ent.masklen > 32)
5831 errx(EX_DATAERR, "bad width ``%s''", p);
5834 if (lookup_host(*av, (struct in_addr *)&ent.addr) != 0)
5835 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
5839 /* isdigit is a bit of a hack here.. */
5840 if (strchr(*av, (int)'.') == NULL && isdigit(**av)) {
5841 ent.value = strtoul(*av, NULL, 0);
5843 if (lookup_host(*av, (struct in_addr *)&tval) == 0) {
5844 /* The value must be stored in host order *
5845 * so that the values < 65k can be distinguished */
5846 ent.value = ntohl(tval);
5848 errx(EX_NOHOST, "hostname ``%s'' unknown", *av);
5853 if (do_cmd(do_add ? IP_FW_TABLE_ADD : IP_FW_TABLE_DEL,
5854 &ent, sizeof(ent)) < 0) {
5855 /* If running silent, don't bomb out on these errors. */
5856 if (!(co.do_quiet && (errno == (do_add ? EEXIST : ESRCH))))
5857 err(EX_OSERR, "setsockopt(IP_FW_TABLE_%s)",
5858 do_add ? "ADD" : "DEL");
5859 /* In silent mode, react to a failed add by deleting */
5861 do_cmd(IP_FW_TABLE_DEL, &ent, sizeof(ent));
5862 if (do_cmd(IP_FW_TABLE_ADD,
5863 &ent, sizeof(ent)) < 0)
5865 "setsockopt(IP_FW_TABLE_ADD)");
5868 } else if (_substrcmp(*av, "flush") == 0) {
5869 a = is_all ? tables_max : (ent.tbl + 1);
5871 if (do_cmd(IP_FW_TABLE_FLUSH, &ent.tbl,
5872 sizeof(ent.tbl)) < 0)
5873 err(EX_OSERR, "setsockopt(IP_FW_TABLE_FLUSH)");
5874 } while (++ent.tbl < a);
5875 } else if (_substrcmp(*av, "list") == 0) {
5876 a = is_all ? tables_max : (ent.tbl + 1);
5878 table_list(ent, is_all);
5879 } while (++ent.tbl < a);
5881 errx(EX_USAGE, "invalid table command %s", *av);
5885 table_list(ipfw_table_entry ent, int need_header)
5893 if (do_cmd(IP_FW_TABLE_GETSIZE, &a, (uintptr_t)&l) < 0)
5894 err(EX_OSERR, "getsockopt(IP_FW_TABLE_GETSIZE)");
5896 /* If a is zero we have nothing to do, the table is empty. */
5900 l = sizeof(*tbl) + a * sizeof(ipfw_table_entry);
5901 tbl = safe_calloc(1, l);
5903 if (do_cmd(IP_FW_TABLE_LIST, tbl, (uintptr_t)&l) < 0)
5904 err(EX_OSERR, "getsockopt(IP_FW_TABLE_LIST)");
5905 if (tbl->cnt && need_header)
5906 printf("---table(%d)---\n", tbl->tbl);
5907 for (a = 0; a < tbl->cnt; a++) {
5909 tval = tbl->ent[a].value;
5910 if (co.do_value_as_ip) {
5912 strncpy(tbuf, inet_ntoa(*(struct in_addr *)
5913 &tbl->ent[a].addr), 127);
5914 /* inet_ntoa expects network order */
5916 printf("%s/%u %s\n", tbuf, tbl->ent[a].masklen,
5917 inet_ntoa(*(struct in_addr *)&tval));
5919 printf("%s/%u %u\n",
5920 inet_ntoa(*(struct in_addr *)&tbl->ent[a].addr),
5921 tbl->ent[a].masklen, tval);
5928 ipfw_show_nat(int ac, char **av)
5931 struct cfg_redir *e;
5932 int cmd, i, nbytes, do_cfg, do_rule, frule, lrule, nalloc, size;
5933 int nat_cnt, redir_cnt, r;
5942 lrule = IPFW_DEFAULT_RULE; /* max ipfw rule number */
5948 /* Parse parameters. */
5949 for (cmd = IP_FW_NAT_GET_LOG, do_cfg = 0; ac != 0; ac--, av++) {
5950 if (!strncmp(av[0], "config", strlen(av[0]))) {
5951 cmd = IP_FW_NAT_GET_CONFIG, do_cfg = 1;
5954 /* Convert command line rule #. */
5955 frule = lrule = strtoul(av[0], &endptr, 10);
5957 lrule = strtoul(endptr+1, &endptr, 10);
5959 err(EX_USAGE, "invalid rule number: %s", av[0]);
5964 while (nbytes >= nalloc) {
5965 nalloc = nalloc * 2;
5967 data = safe_realloc(data, nbytes);
5968 if (do_cmd(cmd, data, (uintptr_t)&nbytes) < 0)
5969 err(EX_OSERR, "getsockopt(IP_FW_GET_%s)",
5970 (cmd == IP_FW_NAT_GET_LOG) ? "LOG" : "CONFIG");
5975 nat_cnt = *((int *)data);
5976 for (i = sizeof(nat_cnt); nat_cnt; nat_cnt--) {
5977 n = (struct cfg_nat *)&data[i];
5978 if (frule <= n->id && lrule >= n->id)
5979 print_nat_config(&data[i]);
5980 i += sizeof(struct cfg_nat);
5981 for (redir_cnt = 0; redir_cnt < n->redir_cnt; redir_cnt++) {
5982 e = (struct cfg_redir *)&data[i];
5983 i += sizeof(struct cfg_redir) + e->spool_cnt *
5984 sizeof(struct cfg_spool);
5988 for (i = 0; 1; i += LIBALIAS_BUF_SIZE + sizeof(int)) {
5990 if (p == data + nbytes)
5992 bcopy(p, &r, sizeof(int));
5994 if (!(frule <= r && lrule >= r))
5997 printf("nat %u: %s\n", r, p+sizeof(int));