2 * Copyright (c) 2002 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
20 * $FreeBSD: src/sbin/ipfw/ipfw2.c,v 1.4.2.13 2003/05/27 22:21:11 gshapiro Exp $
21 * $DragonFly: src/sbin/ipfw/ipfw2.c,v 1.3 2003/08/08 04:18:39 dillon Exp $
24 #include <sys/param.h>
26 #include <sys/socket.h>
27 #include <sys/sockio.h>
28 #include <sys/sysctl.h>
48 #include <netinet/in.h>
49 #include <netinet/in_systm.h>
50 #include <netinet/ip.h>
51 #include <netinet/ip_icmp.h>
52 #include <net/ipfw/ip_fw.h>
53 #include <net/route.h> /* def. of struct route */
54 #include <net/dummynet/ip_dummynet.h>
55 #include <netinet/tcp.h>
56 #include <arpa/inet.h>
58 int s, /* main RAW socket */
59 do_resolv, /* Would try to resolve all */
60 do_acct, /* Show packet/byte count */
61 do_time, /* Show time stamps */
62 do_quiet, /* Be quiet in add and flush */
63 do_force, /* Don't ask for confirmation */
64 do_pipe, /* this cmd refers to a pipe */
65 do_sort, /* field to sort results (0 = no) */
66 do_dynamic, /* display dynamic rules */
67 do_expired, /* display expired dynamic rules */
68 do_compact, /* show rules in compact mode */
69 show_sets, /* display rule sets */
72 #define IP_MASK_ALL 0xffffffff
75 * structure to hold flag names and associated values to be
76 * set in the appropriate masks.
77 * A NULL string terminates the array.
78 * Often, an element with 0 value contains an error string.
86 static struct _s_x f_tcpflags[] = {
97 static struct _s_x f_tcpopts[] = {
98 { "mss", IP_FW_TCPOPT_MSS },
99 { "maxseg", IP_FW_TCPOPT_MSS },
100 { "window", IP_FW_TCPOPT_WINDOW },
101 { "sack", IP_FW_TCPOPT_SACK },
102 { "ts", IP_FW_TCPOPT_TS },
103 { "timestamp", IP_FW_TCPOPT_TS },
104 { "cc", IP_FW_TCPOPT_CC },
110 * IP options span the range 0 to 255 so we need to remap them
111 * (though in fact only the low 5 bits are significant).
113 static struct _s_x f_ipopts[] = {
114 { "ssrr", IP_FW_IPOPT_SSRR},
115 { "lsrr", IP_FW_IPOPT_LSRR},
116 { "rr", IP_FW_IPOPT_RR},
117 { "ts", IP_FW_IPOPT_TS},
122 static struct _s_x f_iptos[] = {
123 { "lowdelay", IPTOS_LOWDELAY},
124 { "throughput", IPTOS_THROUGHPUT},
125 { "reliability", IPTOS_RELIABILITY},
126 { "mincost", IPTOS_MINCOST},
127 { "congestion", IPTOS_CE},
128 { "ecntransport", IPTOS_ECT},
129 { "ip tos option", 0},
133 static struct _s_x limit_masks[] = {
134 {"all", DYN_SRC_ADDR|DYN_SRC_PORT|DYN_DST_ADDR|DYN_DST_PORT},
135 {"src-addr", DYN_SRC_ADDR},
136 {"src-port", DYN_SRC_PORT},
137 {"dst-addr", DYN_DST_ADDR},
138 {"dst-port", DYN_DST_PORT},
143 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
144 * This is only used in this code.
146 #define IPPROTO_ETHERTYPE 0x1000
147 static struct _s_x ether_types[] = {
149 * Note, we cannot use "-:&/" in the names because they are field
150 * separators in the type specifications. Also, we use s = NULL as
151 * end-delimiter, because a type of 0 can be legal.
164 { "pppoe_disc", 0x8863 },
165 { "pppoe_sess", 0x8864 },
166 { "ipx_8022", 0x00E0 },
167 { "ipx_8023", 0x0000 },
168 { "ipx_ii", 0x8137 },
169 { "ipx_snap", 0x8137 },
175 static void show_usage(void);
246 struct _s_x dummynet_params[] = {
248 { "noerror", TOK_NOERROR },
249 { "buckets", TOK_BUCKETS },
250 { "dst-ip", TOK_DSTIP },
251 { "src-ip", TOK_SRCIP },
252 { "dst-port", TOK_DSTPORT },
253 { "src-port", TOK_SRCPORT },
254 { "proto", TOK_PROTO },
255 { "weight", TOK_WEIGHT },
257 { "mask", TOK_MASK },
258 { "droptail", TOK_DROPTAIL },
260 { "gred", TOK_GRED },
262 { "bandwidth", TOK_BW },
263 { "delay", TOK_DELAY },
264 { "pipe", TOK_PIPE },
265 { "queue", TOK_QUEUE },
266 { "dummynet-params", TOK_NULL },
270 struct _s_x rule_actions[] = {
271 { "accept", TOK_ACCEPT },
272 { "pass", TOK_ACCEPT },
273 { "allow", TOK_ACCEPT },
274 { "permit", TOK_ACCEPT },
275 { "count", TOK_COUNT },
276 { "pipe", TOK_PIPE },
277 { "queue", TOK_QUEUE },
278 { "divert", TOK_DIVERT },
280 { "fwd", TOK_FORWARD },
281 { "forward", TOK_FORWARD },
282 { "skipto", TOK_SKIPTO },
283 { "deny", TOK_DENY },
284 { "drop", TOK_DENY },
285 { "reject", TOK_REJECT },
286 { "reset", TOK_RESET },
287 { "unreach", TOK_UNREACH },
288 { "check-state", TOK_CHECKSTATE },
293 struct _s_x rule_options[] = {
297 { "limit", TOK_LIMIT },
298 { "keep-state", TOK_KEEPSTATE },
299 { "bridged", TOK_LAYER2 },
300 { "layer2", TOK_LAYER2 },
302 { "xmit", TOK_XMIT },
303 { "recv", TOK_RECV },
305 { "fragment", TOK_FRAG },
306 { "frag", TOK_FRAG },
307 { "ipoptions", TOK_IPOPTS },
308 { "ipopts", TOK_IPOPTS },
309 { "iplen", TOK_IPLEN },
310 { "ipid", TOK_IPID },
311 { "ipprecedence", TOK_IPPRECEDENCE },
312 { "iptos", TOK_IPTOS },
313 { "ipttl", TOK_IPTTL },
314 { "ipversion", TOK_IPVER },
315 { "ipver", TOK_IPVER },
316 { "estab", TOK_ESTAB },
317 { "established", TOK_ESTAB },
318 { "setup", TOK_SETUP },
319 { "tcpflags", TOK_TCPFLAGS },
320 { "tcpflgs", TOK_TCPFLAGS },
321 { "tcpoptions", TOK_TCPOPTS },
322 { "tcpopts", TOK_TCPOPTS },
323 { "tcpseq", TOK_TCPSEQ },
324 { "tcpack", TOK_TCPACK },
325 { "tcpwin", TOK_TCPWIN },
326 { "icmptype", TOK_ICMPTYPES },
327 { "icmptypes", TOK_ICMPTYPES },
328 { "dst-ip", TOK_DSTIP },
329 { "src-ip", TOK_SRCIP },
330 { "dst-port", TOK_DSTPORT },
331 { "src-port", TOK_SRCPORT },
332 { "proto", TOK_PROTO },
335 { "mac-type", TOK_MACTYPE },
337 { "not", TOK_NOT }, /* pseudo option */
338 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
339 { "or", TOK_OR }, /* pseudo option */
340 { "|", /* escape */ TOK_OR }, /* pseudo option */
341 { "{", TOK_STARTBRACE }, /* pseudo option */
342 { "(", TOK_STARTBRACE }, /* pseudo option */
343 { "}", TOK_ENDBRACE }, /* pseudo option */
344 { ")", TOK_ENDBRACE }, /* pseudo option */
350 * match_token takes a table and a string, returns the value associated
351 * with the string (0 meaning an error in most cases)
354 match_token(struct _s_x *table, char *string)
357 int i = strlen(string);
359 for (pt = table ; i && pt->s != NULL ; pt++)
360 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
366 match_value(struct _s_x *p, u_int32_t value)
368 for (; p->s != NULL; p++)
375 * prints one port, symbolic or numeric
378 print_port(int proto, u_int16_t port)
381 if (proto == IPPROTO_ETHERTYPE) {
384 if (do_resolv && (s = match_value(ether_types, port)) )
387 printf("0x%04x", port);
389 struct servent *se = NULL;
391 struct protoent *pe = getprotobynumber(proto);
393 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
396 printf("%s", se->s_name);
403 * print the values in a list of ports
404 * XXX todo: add support for mask.
407 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode)
409 u_int16_t *p = cmd->ports;
413 if (cmd->o.len & F_NOT)
416 printf ("%s", opcode == O_MAC_TYPE ? " mac-type" :
417 (opcode == O_IP_DSTPORT ? " dst-port" : " src-port"));
418 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
420 print_port(proto, p[0]);
423 print_port(proto, p[1]);
430 * Like strtol, but also translates service names into port numbers
431 * for some protocols.
433 * proto == -1 disables the protocol check;
434 * proto == IPPROTO_ETHERTYPE looks up an internal table
435 * proto == <some value in /etc/protocols> matches the values there.
436 * Returns *end == s in case the parameter is not found.
439 strtoport(char *s, char **end, int base, int proto)
445 *end = s; /* default - not found */
447 return 0; /* not found */
450 return strtol(s, end, base);
453 * find separator. '\\' escapes the next char.
455 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
456 if (*s1 == '\\' && s1[1] != '\0')
459 buf = malloc(s1 - s + 1);
464 * copy into a buffer skipping backslashes
466 for (p = s, i = 0; p != s1 ; p++)
471 if (proto == IPPROTO_ETHERTYPE) {
472 i = match_token(ether_types, buf);
474 if (i != -1) { /* found */
479 struct protoent *pe = NULL;
483 pe = getprotobynumber(proto);
485 se = getservbyname(buf, pe ? pe->p_name : NULL);
489 return ntohs(se->s_port);
492 return 0; /* not found */
496 * fill the body of the command with the list of port ranges.
497 * At the moment it only understands numeric ranges.
500 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto)
502 u_int16_t *p = cmd->ports;
509 a = strtoport(av, &s, 0, proto);
510 if (s == av) /* no parameter */
512 if (*s == '-') { /* a range */
514 b = strtoport(av, &s, 0, proto);
515 if (s == av) /* no parameter */
519 } else if (*s == ',' || *s == '\0' ) {
521 } else { /* invalid separator */
522 errx(EX_DATAERR, "invalid separator <%c> in <%s>\n",
530 if (i+1 > F_LEN_MASK)
531 errx(EX_DATAERR, "too many ports/ranges\n");
532 cmd->o.len |= i+1; /* leave F_NOT and F_OR untouched */
537 static struct _s_x icmpcodes[] = {
538 { "net", ICMP_UNREACH_NET },
539 { "host", ICMP_UNREACH_HOST },
540 { "protocol", ICMP_UNREACH_PROTOCOL },
541 { "port", ICMP_UNREACH_PORT },
542 { "needfrag", ICMP_UNREACH_NEEDFRAG },
543 { "srcfail", ICMP_UNREACH_SRCFAIL },
544 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
545 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
546 { "isolated", ICMP_UNREACH_ISOLATED },
547 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
548 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
549 { "tosnet", ICMP_UNREACH_TOSNET },
550 { "toshost", ICMP_UNREACH_TOSHOST },
551 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
552 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
553 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
558 fill_reject_code(u_short *codep, char *str)
563 val = strtoul(str, &s, 0);
564 if (s == str || *s != '\0' || val >= 0x100)
565 val = match_token(icmpcodes, str);
567 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
573 print_reject_code(u_int16_t code)
575 char *s = match_value(icmpcodes, code);
578 printf("unreach %s", s);
580 printf("unreach %u", code);
584 * Returns the number of bits set (from left) in a contiguous bitmask,
585 * or -1 if the mask is not contiguous.
586 * XXX this needs a proper fix.
587 * This effectively works on masks in big-endian (network) format.
588 * when compiled on little endian architectures.
590 * First bit is bit 7 of the first byte -- note, for MAC addresses,
591 * the first bit on the wire is bit 0 of the first byte.
592 * len is the max length in bits.
595 contigmask(u_char *p, int len)
598 for (i=0; i<len ; i++)
599 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
601 for (n=i+1; n < len; n++)
602 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
603 return -1; /* mask not contiguous */
608 * print flags set/clear in the two bitmasks passed as parameters.
609 * There is a specialized check for f_tcpflags.
612 print_flags(char *name, ipfw_insn *cmd, struct _s_x *list)
616 u_char set = cmd->arg1 & 0xff;
617 u_char clear = (cmd->arg1 >> 8) & 0xff;
619 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
624 printf(" %s ", name);
625 for (i=0; list[i].x != 0; i++) {
626 if (set & list[i].x) {
628 printf("%s%s", comma, list[i].s);
631 if (clear & list[i].x) {
633 printf("%s!%s", comma, list[i].s);
640 * Print the ip address contained in a command.
643 print_ip(ipfw_insn_ip *cmd, char *s)
645 struct hostent *he = NULL;
648 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
650 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
654 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
661 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
662 printf("%s/%d", inet_ntoa(cmd->addr),
663 contigmask((u_char *)&x, 32));
664 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
665 x &= 0xff; /* base */
666 d = (u_int32_t *)&(cmd->mask);
667 for (i=0; i < cmd->o.arg1; i++)
668 if (d[ i/32] & (1<<(i & 31))) {
669 printf("%c%d", comma, i+x);
675 if (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST)
678 mb = contigmask((u_char *)&(cmd->mask.s_addr), 32);
679 if (mb == 32 && do_resolv)
680 he = gethostbyaddr((char *)&(cmd->addr.s_addr),
681 sizeof(u_long), AF_INET);
682 if (he != NULL) /* resolved to name */
683 printf("%s", he->h_name);
684 else if (mb == 0) /* any */
686 else { /* numeric IP followed by some kind of mask */
687 printf("%s", inet_ntoa(cmd->addr));
689 printf(":%s", inet_ntoa(cmd->mask));
696 * prints a MAC address/mask pair
699 print_mac(u_char *addr, u_char *mask)
701 int l = contigmask(mask, 48);
706 printf(" %02x:%02x:%02x:%02x:%02x:%02x",
707 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
709 printf("&%02x:%02x:%02x:%02x:%02x:%02x",
710 mask[0], mask[1], mask[2],
711 mask[3], mask[4], mask[5]);
718 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
727 type = strtoul(av, &av, 0);
729 if (*av != ',' && *av != '\0')
730 errx(EX_DATAERR, "invalid ICMP type");
733 errx(EX_DATAERR, "ICMP type out of range");
735 cmd->d[0] |= 1 << type;
737 cmd->o.opcode = O_ICMPTYPE;
738 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
742 print_icmptypes(ipfw_insn_u32 *cmd)
747 printf(" icmptypes");
748 for (i = 0; i < 32; i++) {
749 if ( (cmd->d[0] & (1 << (i))) == 0)
751 printf("%c%d", sep, i);
757 * show_ipfw() prints the body of an ipfw rule.
758 * Because the standard rule has at least proto src_ip dst_ip, we use
759 * a helper function to produce these entries if not provided explicitly.
760 * The first argument is the list of fields we have, the second is
761 * the list of fields we want to be printed.
763 * Special cases if we have provided a MAC header:
764 * + if the rule does not contain IP addresses/ports, do not print them;
765 * + if the rule does not contain an IP proto, print "all" instead of "ip";
767 * Once we have 'have_options', IP header fields are printed as options.
769 #define HAVE_PROTO 0x0001
770 #define HAVE_SRCIP 0x0002
771 #define HAVE_DSTIP 0x0004
772 #define HAVE_MAC 0x0008
773 #define HAVE_MACTYPE 0x0010
774 #define HAVE_OPTIONS 0x8000
776 #define HAVE_IP (HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP)
778 show_prerequisites(int *flags, int want, int cmd)
780 if ( (*flags & HAVE_IP) == HAVE_IP)
781 *flags |= HAVE_OPTIONS;
783 if ( (*flags & (HAVE_MAC|HAVE_MACTYPE|HAVE_OPTIONS)) == HAVE_MAC &&
786 * mac-type was optimized out by the compiler,
790 *flags |= HAVE_MACTYPE | HAVE_OPTIONS;
793 if ( !(*flags & HAVE_OPTIONS)) {
794 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO))
796 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
798 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
805 show_ipfw(struct ip_fw *rule, int pcwidth, int bcwidth)
807 static int twidth = 0;
810 int proto = 0; /* default */
811 int flags = 0; /* prerequisites */
812 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
813 int or_block = 0; /* we are in an or block */
815 u_int32_t set_disable = (u_int32_t)(rule->next_rule);
817 if (set_disable & (1 << rule->set)) { /* disabled */
821 printf("# DISABLED ");
823 printf("%05u ", rule->rulenum);
826 printf("%*llu %*llu ", pcwidth, rule->pcnt, bcwidth,
833 strcpy(timestr, ctime((time_t *)&twidth));
834 *strchr(timestr, '\n') = '\0';
835 twidth = strlen(timestr);
837 if (rule->timestamp) {
838 #if _FreeBSD_version < 500000 /* XXX check */
839 #define _long_to_time(x) (time_t)(x)
841 time_t t = _long_to_time(rule->timestamp);
843 strcpy(timestr, ctime(&t));
844 *strchr(timestr, '\n') = '\0';
845 printf("%s ", timestr);
847 printf("%*s ", twidth, " ");
852 printf("set %d ", rule->set);
855 * print the optional "match probability"
857 if (rule->cmd_len > 0) {
859 if (cmd->opcode == O_PROB) {
860 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
861 double d = 1.0 * p->d[0];
863 d = (d / 0x7fffffff);
864 printf("prob %f ", d);
869 * first print actions
871 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
872 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
873 switch(cmd->opcode) {
875 printf("check-state");
876 flags = HAVE_IP; /* avoid printing anything else */
892 if (cmd->arg1 == ICMP_REJECT_RST)
894 else if (cmd->arg1 == ICMP_UNREACH_HOST)
897 print_reject_code(cmd->arg1);
901 printf("skipto %u", cmd->arg1);
905 printf("pipe %u", cmd->arg1);
909 printf("queue %u", cmd->arg1);
913 printf("divert %u", cmd->arg1);
917 printf("tee %u", cmd->arg1);
922 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
924 printf("fwd %s", inet_ntoa(s->sa.sin_addr));
926 printf(",%d", s->sa.sin_port);
930 case O_LOG: /* O_LOG is printed last */
931 logptr = (ipfw_insn_log *)cmd;
935 printf("** unrecognized action %d len %d",
936 cmd->opcode, cmd->len);
940 if (logptr->max_log > 0)
941 printf(" log logamount %d", logptr->max_log);
947 * then print the body.
949 if (rule->_pad & 1) { /* empty rules before options */
951 printf(" ip from any to any");
952 flags |= HAVE_IP | HAVE_OPTIONS;
955 for (l = rule->act_ofs, cmd = rule->cmd ;
956 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
958 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
960 show_prerequisites(&flags, 0, cmd->opcode);
962 switch(cmd->opcode) {
964 break; /* done already */
967 break; /* no need to print anything here */
970 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
972 if ((cmd->len & F_OR) && !or_block)
974 if (cmd->len & F_NOT)
978 print_mac( m->addr, m->mask);
979 print_mac( m->addr + 6, m->mask + 6);
984 if ((cmd->len & F_OR) && !or_block)
986 print_newports((ipfw_insn_u16 *)cmd, IPPROTO_ETHERTYPE,
987 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
988 flags |= HAVE_MAC | HAVE_MACTYPE | HAVE_OPTIONS;
995 show_prerequisites(&flags, HAVE_PROTO, 0);
996 if (!(flags & HAVE_SRCIP))
998 if ((cmd->len & F_OR) && !or_block)
1000 print_ip((ipfw_insn_ip *)cmd,
1001 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1002 flags |= HAVE_SRCIP;
1009 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1010 if (!(flags & HAVE_DSTIP))
1012 if ((cmd->len & F_OR) && !or_block)
1014 print_ip((ipfw_insn_ip *)cmd,
1015 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1016 flags |= HAVE_DSTIP;
1020 show_prerequisites(&flags, HAVE_IP, 0);
1022 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1023 if ((cmd->len & F_OR) && !or_block)
1025 print_newports((ipfw_insn_u16 *)cmd, proto,
1026 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1030 struct protoent *pe;
1032 if ((cmd->len & F_OR) && !or_block)
1034 if (cmd->len & F_NOT)
1037 pe = getprotobynumber(cmd->arg1);
1038 if (flags & HAVE_OPTIONS)
1041 printf(" %s", pe->p_name);
1043 printf(" %u", cmd->arg1);
1045 flags |= HAVE_PROTO;
1048 default: /*options ... */
1049 show_prerequisites(&flags, HAVE_IP | HAVE_OPTIONS, 0);
1050 if ((cmd->len & F_OR) && !or_block)
1052 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1054 switch(cmd->opcode) {
1060 printf(cmd->len & F_NOT ? " out" : " in");
1070 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1072 if (cmd->opcode == O_XMIT)
1074 else if (cmd->opcode == O_RECV)
1076 else if (cmd->opcode == O_VIA)
1078 if (cmdif->name[0] == '\0')
1080 inet_ntoa(cmdif->p.ip));
1081 else if (cmdif->p.unit == -1)
1082 printf(" %s %s*", s, cmdif->name);
1084 printf(" %s %s%d", s, cmdif->name,
1090 printf(" ipid %u", cmd->arg1 );
1094 printf(" ipttl %u", cmd->arg1 );
1098 printf(" ipver %u", cmd->arg1 );
1101 case O_IPPRECEDENCE:
1102 printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1106 printf(" iplen %u", cmd->arg1 );
1110 print_flags("ipoptions", cmd, f_ipopts);
1114 print_flags("iptos", cmd, f_iptos);
1118 print_icmptypes((ipfw_insn_u32 *)cmd);
1122 printf(" established");
1126 print_flags("tcpflags", cmd, f_tcpflags);
1130 print_flags("tcpoptions", cmd, f_tcpopts);
1134 printf(" tcpwin %d", ntohs(cmd->arg1));
1138 printf(" tcpack %d", ntohl(cmd32->d[0]));
1142 printf(" tcpseq %d", ntohl(cmd32->d[0]));
1147 struct passwd *pwd = getpwuid(cmd32->d[0]);
1150 printf(" uid %s", pwd->pw_name);
1152 printf(" uid %u", cmd32->d[0]);
1158 struct group *grp = getgrgid(cmd32->d[0]);
1161 printf(" gid %s", grp->gr_name);
1163 printf(" gid %u", cmd32->d[0]);
1168 printf(" keep-state");
1173 struct _s_x *p = limit_masks;
1174 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1175 u_int8_t x = c->limit_mask;
1179 for ( ; p->x != 0 ; p++)
1180 if ((x & p->x) == p->x) {
1182 printf("%s%s", comma, p->s);
1185 printf(" %d", c->conn_limit);
1190 printf(" [opcode %d len %d]",
1191 cmd->opcode, cmd->len);
1194 if (cmd->len & F_OR) {
1197 } else if (or_block) {
1202 show_prerequisites(&flags, HAVE_IP, 0);
1208 show_dyn_ipfw(ipfw_dyn_rule *d, int pcwidth, int bcwidth)
1210 struct protoent *pe;
1214 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1218 printf("%05d %*llu %*llu (%ds)", (int)(d->rule), pcwidth, d->pcnt,
1219 bcwidth, d->bcnt, d->expire);
1220 switch (d->dyn_type) {
1221 case O_LIMIT_PARENT:
1222 printf(" PARENT %d", d->count);
1227 case O_KEEP_STATE: /* bidir, no mask */
1232 if ((pe = getprotobynumber(d->id.proto)) != NULL)
1233 printf(" %s", pe->p_name);
1235 printf(" proto %u", d->id.proto);
1237 a.s_addr = htonl(d->id.src_ip);
1238 printf(" %s %d", inet_ntoa(a), d->id.src_port);
1240 a.s_addr = htonl(d->id.dst_ip);
1241 printf(" <-> %s %d", inet_ntoa(a), d->id.dst_port);
1246 sort_q(const void *pa, const void *pb)
1248 int rev = (do_sort < 0);
1249 int field = rev ? -do_sort : do_sort;
1251 const struct dn_flow_queue *a = pa;
1252 const struct dn_flow_queue *b = pb;
1256 res = a->len - b->len;
1259 res = a->len_bytes - b->len_bytes;
1262 case 3: /* tot pkts */
1263 res = a->tot_pkts - b->tot_pkts;
1266 case 4: /* tot bytes */
1267 res = a->tot_bytes - b->tot_bytes;
1274 return (int)(rev ? res : -res);
1278 list_queues(struct dn_flow_set *fs, struct dn_flow_queue *q)
1282 printf(" mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
1283 fs->flow_mask.proto,
1284 fs->flow_mask.src_ip, fs->flow_mask.src_port,
1285 fs->flow_mask.dst_ip, fs->flow_mask.dst_port);
1286 if (fs->rq_elements == 0)
1289 printf("BKT Prot ___Source IP/port____ "
1290 "____Dest. IP/port____ Tot_pkt/bytes Pkt/Byte Drp\n");
1292 heapsort(q, fs->rq_elements, sizeof *q, sort_q);
1293 for (l = 0; l < fs->rq_elements; l++) {
1295 struct protoent *pe;
1297 ina.s_addr = htonl(q[l].id.src_ip);
1298 printf("%3d ", q[l].hash_slot);
1299 pe = getprotobynumber(q[l].id.proto);
1301 printf("%-4s ", pe->p_name);
1303 printf("%4u ", q[l].id.proto);
1304 printf("%15s/%-5d ",
1305 inet_ntoa(ina), q[l].id.src_port);
1306 ina.s_addr = htonl(q[l].id.dst_ip);
1307 printf("%15s/%-5d ",
1308 inet_ntoa(ina), q[l].id.dst_port);
1309 printf("%4qu %8qu %2u %4u %3u\n",
1310 q[l].tot_pkts, q[l].tot_bytes,
1311 q[l].len, q[l].len_bytes, q[l].drops);
1313 printf(" S %20qd F %20qd\n",
1319 print_flowset_parms(struct dn_flow_set *fs, char *prefix)
1324 char red[90]; /* Display RED parameters */
1327 if (fs->flags_fs & DN_QSIZE_IS_BYTES) {
1329 sprintf(qs, "%d KB", l / 1024);
1331 sprintf(qs, "%d B", l);
1333 sprintf(qs, "%3d sl.", l);
1335 sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff));
1338 if (fs->flags_fs & DN_IS_RED) /* RED parameters */
1340 "\n\t %cRED w_q %f min_th %d max_th %d max_p %f",
1341 (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ',
1342 1.0 * fs->w_q / (double)(1 << SCALE_RED),
1343 SCALE_VAL(fs->min_th),
1344 SCALE_VAL(fs->max_th),
1345 1.0 * fs->max_p / (double)(1 << SCALE_RED));
1347 sprintf(red, "droptail");
1349 printf("%s %s%s %d queues (%d buckets) %s\n",
1350 prefix, qs, plr, fs->rq_elements, fs->rq_size, red);
1354 list_pipes(void *data, int nbytes, int ac, char *av[])
1358 struct dn_pipe *p = (struct dn_pipe *) data;
1359 struct dn_flow_set *fs;
1360 struct dn_flow_queue *q;
1364 rulenum = strtoul(*av++, NULL, 10);
1367 for (; nbytes >= sizeof *p; p = (struct dn_pipe *)next) {
1368 double b = p->bandwidth;
1372 if (p->next != (struct dn_pipe *)DN_IS_PIPE)
1373 break; /* done with pipes, now queues */
1376 * compute length, as pipe have variable size
1378 l = sizeof(*p) + p->fs.rq_elements * sizeof(*q);
1379 next = (void *)p + l;
1382 if (rulenum != 0 && rulenum != p->pipe_nr)
1386 * Print rate (or clocking interface)
1388 if (p->if_name[0] != '\0')
1389 sprintf(buf, "%s", p->if_name);
1391 sprintf(buf, "unlimited");
1392 else if (b >= 1000000)
1393 sprintf(buf, "%7.3f Mbit/s", b/1000000);
1395 sprintf(buf, "%7.3f Kbit/s", b/1000);
1397 sprintf(buf, "%7.3f bit/s ", b);
1399 sprintf(prefix, "%05d: %s %4d ms ",
1400 p->pipe_nr, buf, p->delay);
1401 print_flowset_parms(&(p->fs), prefix);
1403 printf(" V %20qd\n", p->V >> MY_M);
1405 q = (struct dn_flow_queue *)(p+1);
1406 list_queues(&(p->fs), q);
1408 for (fs = next; nbytes >= sizeof *fs; fs = next) {
1411 if (fs->next != (struct dn_flow_set *)DN_IS_QUEUE)
1413 l = sizeof(*fs) + fs->rq_elements * sizeof(*q);
1414 next = (void *)fs + l;
1416 q = (struct dn_flow_queue *)(fs+1);
1417 sprintf(prefix, "q%05d: weight %d pipe %d ",
1418 fs->fs_nr, fs->weight, fs->parent_nr);
1419 print_flowset_parms(fs, prefix);
1425 * This one handles all set-related commands
1426 * ipfw set { show | enable | disable }
1428 * ipfw set move X to Y
1429 * ipfw set move rule X to Y
1432 sets_handler(int ac, char *av[])
1434 u_int32_t set_disable, masks[2];
1437 u_int8_t cmd, new_set;
1443 errx(EX_USAGE, "set needs command");
1444 if (!strncmp(*av, "show", strlen(*av)) ) {
1448 nbytes = sizeof(struct ip_fw);
1449 if ((data = malloc(nbytes)) == NULL)
1450 err(EX_OSERR, "malloc");
1451 if (getsockopt(s, IPPROTO_IP, IP_FW_GET, data, &nbytes) < 0)
1452 err(EX_OSERR, "getsockopt(IP_FW_GET)");
1453 set_disable = (u_int32_t)(((struct ip_fw *)data)->next_rule);
1455 for (i = 0, msg = "disable" ; i < 31; i++)
1456 if ( (set_disable & (1<<i))) {
1457 printf("%s %d", msg, i);
1460 msg = (set_disable) ? " enable" : "enable";
1461 for (i = 0; i < 31; i++)
1462 if ( !(set_disable & (1<<i))) {
1463 printf("%s %d", msg, i);
1467 } else if (!strncmp(*av, "swap", strlen(*av))) {
1470 errx(EX_USAGE, "set swap needs 2 set numbers\n");
1471 rulenum = atoi(av[0]);
1472 new_set = atoi(av[1]);
1473 if (!isdigit(*(av[0])) || rulenum > 30)
1474 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
1475 if (!isdigit(*(av[1])) || new_set > 30)
1476 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
1477 masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
1478 i = setsockopt(s, IPPROTO_IP, IP_FW_DEL,
1479 masks, sizeof(u_int32_t));
1480 } else if (!strncmp(*av, "move", strlen(*av))) {
1482 if (ac && !strncmp(*av, "rule", strlen(*av))) {
1487 if (ac != 3 || strncmp(av[1], "to", strlen(*av)))
1488 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
1489 rulenum = atoi(av[0]);
1490 new_set = atoi(av[2]);
1491 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > 30) ||
1492 (cmd == 2 && rulenum == 65535) )
1493 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
1494 if (!isdigit(*(av[2])) || new_set > 30)
1495 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
1496 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
1497 i = setsockopt(s, IPPROTO_IP, IP_FW_DEL,
1498 masks, sizeof(u_int32_t));
1499 } else if (!strncmp(*av, "disable", strlen(*av)) ||
1500 !strncmp(*av, "enable", strlen(*av)) ) {
1501 int which = !strncmp(*av, "enable", strlen(*av)) ? 1 : 0;
1504 masks[0] = masks[1] = 0;
1507 if (isdigit(**av)) {
1509 if (i < 0 || i > 30)
1511 "invalid set number %d\n", i);
1512 masks[which] |= (1<<i);
1513 } else if (!strncmp(*av, "disable", strlen(*av)))
1515 else if (!strncmp(*av, "enable", strlen(*av)))
1519 "invalid set command %s\n", *av);
1522 if ( (masks[0] & masks[1]) != 0 )
1524 "cannot enable and disable the same set\n");
1526 i = setsockopt(s, IPPROTO_IP, IP_FW_DEL, masks, sizeof(masks));
1528 warn("set enable/disable: setsockopt(IP_FW_DEL)");
1530 errx(EX_USAGE, "invalid set command %s\n", *av);
1534 sysctl_handler(int ac, char *av[], int which)
1540 warnx("missing keyword to enable/disable\n");
1541 } else if (strncmp(*av, "firewall", strlen(*av)) == 0) {
1542 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
1543 &which, sizeof(which));
1544 } else if (strncmp(*av, "one_pass", strlen(*av)) == 0) {
1545 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
1546 &which, sizeof(which));
1547 } else if (strncmp(*av, "debug", strlen(*av)) == 0) {
1548 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
1549 &which, sizeof(which));
1550 } else if (strncmp(*av, "verbose", strlen(*av)) == 0) {
1551 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
1552 &which, sizeof(which));
1553 } else if (strncmp(*av, "dyn_keepalive", strlen(*av)) == 0) {
1554 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
1555 &which, sizeof(which));
1557 warnx("unrecognize enable/disable keyword: %s\n", *av);
1562 list(int ac, char *av[])
1565 ipfw_dyn_rule *dynrules, *d;
1567 void *lim, *data = NULL;
1568 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
1569 int exitval = EX_OK;
1576 const int ocmd = do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
1577 int nalloc = 1024; /* start somewhere... */
1582 /* get rules or pipes from kernel, resizing array as necessary */
1585 while (nbytes >= nalloc) {
1586 nalloc = nalloc * 2 + 200;
1588 if ((data = realloc(data, nbytes)) == NULL)
1589 err(EX_OSERR, "realloc");
1590 if (getsockopt(s, IPPROTO_IP, ocmd, data, &nbytes) < 0)
1591 err(EX_OSERR, "getsockopt(IP_%s_GET)",
1592 do_pipe ? "DUMMYNET" : "FW");
1596 list_pipes(data, nbytes, ac, av);
1601 * Count static rules. They have variable size so we
1602 * need to scan the list to count them.
1604 for (nstat = 1, r = data, lim = data + nbytes;
1605 r->rulenum < 65535 && (void *)r < lim;
1606 ++nstat, r = (void *)r + RULESIZE(r) )
1610 * Count dynamic rules. This is easier as they have
1613 r = (void *)r + RULESIZE(r);
1614 dynrules = (ipfw_dyn_rule *)r ;
1615 n = (void *)r - data;
1616 ndyn = (nbytes - n) / sizeof *dynrules;
1618 /* if showing stats, figure out column widths ahead of time */
1619 bcwidth = pcwidth = 0;
1621 for (n = 0, r = data; n < nstat;
1622 n++, r = (void *)r + RULESIZE(r)) {
1623 /* packet counter */
1624 width = snprintf(NULL, 0, "%llu", r->pcnt);
1625 if (width > pcwidth)
1629 width = snprintf(NULL, 0, "%llu", r->bcnt);
1630 if (width > bcwidth)
1634 if (do_dynamic && ndyn) {
1635 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1636 width = snprintf(NULL, 0, "%llu", d->pcnt);
1637 if (width > pcwidth)
1640 width = snprintf(NULL, 0, "%llu", d->bcnt);
1641 if (width > bcwidth)
1645 /* if no rule numbers were specified, list all rules */
1647 for (n = 0, r = data; n < nstat;
1648 n++, r = (void *)r + RULESIZE(r) )
1649 show_ipfw(r, pcwidth, bcwidth);
1651 if (do_dynamic && ndyn) {
1652 printf("## Dynamic rules (%d):\n", ndyn);
1653 for (n = 0, d = dynrules; n < ndyn; n++, d++)
1654 show_dyn_ipfw(d, pcwidth, bcwidth);
1659 /* display specific rules requested on command line */
1661 for (lac = ac, lav = av; lac != 0; lac--) {
1662 /* convert command line rule # */
1663 rnum = strtoul(*lav++, &endptr, 10);
1666 warnx("invalid rule number: %s", *(lav - 1));
1669 for (n = seen = 0, r = data; n < nstat;
1670 n++, r = (void *)r + RULESIZE(r) ) {
1671 if (r->rulenum > rnum)
1673 if (r->rulenum == rnum) {
1674 show_ipfw(r, pcwidth, bcwidth);
1679 /* give precedence to other error(s) */
1680 if (exitval == EX_OK)
1681 exitval = EX_UNAVAILABLE;
1682 warnx("rule %lu does not exist", rnum);
1686 if (do_dynamic && ndyn) {
1687 printf("## Dynamic rules:\n");
1688 for (lac = ac, lav = av; lac != 0; lac--) {
1689 rnum = strtoul(*lav++, &endptr, 10);
1691 /* already warned */
1693 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1694 if ((int)(d->rule) > rnum)
1696 if ((int)(d->rule) == rnum)
1697 show_dyn_ipfw(d, pcwidth, bcwidth);
1707 if (exitval != EX_OK)
1714 fprintf(stderr, "usage: ipfw [options]\n"
1715 " add [number] rule\n"
1716 " pipe number config [pipeconfig]\n"
1717 " queue number config [queueconfig]\n"
1719 " [pipe] delete number ...\n"
1720 " [pipe] {list|show} [number ...]\n"
1721 " {zero|resetlog} [number ...]\n"
1722 "do \"ipfw -h\" or see ipfw manpage for details\n"
1732 fprintf(stderr, "ipfw syntax summary:\n"
1733 "ipfw add [N] [prob {0..1}] ACTION [log [logamount N]] ADDR OPTIONS\n"
1734 "ipfw {pipe|queue} N config BODY\n"
1735 "ipfw [pipe] {zero|delete|show} [N{,N}]\n"
1737 "RULE: [1..] [PROB] BODY\n"
1738 "RULENUM: INTEGER(1..65534)\n"
1739 "PROB: prob REAL(0..1)\n"
1740 "BODY: check-state [LOG] (no body) |\n"
1741 " ACTION [LOG] MATCH_ADDR [OPTION_LIST]\n"
1742 "ACTION: check-state | allow | count | deny | reject | skipto N |\n"
1743 " {divert|tee} PORT | forward ADDR | pipe N | queue N\n"
1744 "ADDR: [ MAC dst src ether_type ] \n"
1745 " [ from IPLIST [ PORT ] to IPLIST [ PORTLIST ] ]\n"
1746 "IPLIST: IPADDR | ( IPADDR or ... or IPADDR )\n"
1747 "IPADDR: [not] { any | me | ip | ip/bits | ip:mask | ip/bits{x,y,z} }\n"
1748 "OPTION_LIST: OPTION [,OPTION_LIST]\n"
1755 lookup_host (char *host, struct in_addr *ipaddr)
1759 if (!inet_aton(host, ipaddr)) {
1760 if ((he = gethostbyname(host)) == NULL)
1762 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
1768 * fills the addr and mask fields in the instruction as appropriate from av.
1769 * Update length as appropriate.
1770 * The following formats are allowed:
1771 * any matches any IP. Actually returns an empty instruction.
1772 * me returns O_IP_*_ME
1773 * 1.2.3.4 single IP address
1774 * 1.2.3.4:5.6.7.8 address:mask
1775 * 1.2.3.4/24 address/mask
1776 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
1779 fill_ip(ipfw_insn_ip *cmd, char *av)
1781 char *p = 0, md = 0;
1784 cmd->o.len &= ~F_LEN_MASK; /* zero len */
1786 if (!strncmp(av, "any", strlen(av)))
1789 if (!strncmp(av, "me", strlen(av))) {
1790 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
1794 p = strchr(av, '/');
1796 p = strchr(av, ':');
1802 if (lookup_host(av, &cmd->addr) != 0)
1803 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
1806 if (!inet_aton(p, &cmd->mask))
1807 errx(EX_DATAERR, "bad netmask ``%s''", p);
1812 cmd->mask.s_addr = htonl(0);
1814 errx(EX_DATAERR, "bad width ``%s''", p);
1816 cmd->mask.s_addr = htonl(~0 << (32 - i));
1819 cmd->mask.s_addr = htonl(~0);
1822 cmd->addr.s_addr &= cmd->mask.s_addr;
1824 * now look if we have a set of addresses. They are stored as follows:
1825 * arg1 is the set size (powers of 2, 2..256)
1826 * addr is the base address IN HOST FORMAT
1827 * mask.. is an array of u_int32_t with bits set.
1831 if (p) { /* fetch addresses */
1834 int i = contigmask((u_char *)&(cmd->mask), 32);
1836 if (i < 24 || i > 31) {
1837 fprintf(stderr, "invalid set with mask %d\n",
1841 cmd->o.arg1 = 1<<(32-i);
1842 cmd->addr.s_addr = ntohl(cmd->addr.s_addr);
1843 d = (u_int32_t *)&cmd->mask;
1844 cmd->o.opcode = O_IP_DST_SET; /* default */
1845 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
1846 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
1847 d[i] = 0; /* clear masks */
1850 low = cmd->addr.s_addr & 0xff;
1851 high = low + cmd->o.arg1 - 1;
1852 while (isdigit(*av)) {
1854 u_int16_t a = strtol(av, &s, 0);
1856 if (s == av) /* no parameter */
1858 if (a < low || a > high) {
1859 fprintf(stderr, "addr %d out of range [%d-%d]\n",
1864 d[ a/32] |= 1<<(a & 31);
1872 if (cmd->mask.s_addr == 0) { /* any */
1873 if (cmd->o.len & F_NOT)
1874 errx(EX_DATAERR, "not any never matches");
1875 else /* useless, nuke it */
1877 } else if (cmd->mask.s_addr == IP_MASK_ALL) /* one IP */
1878 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1879 else /* addr/mask */
1880 cmd->o.len |= F_INSN_SIZE(ipfw_insn_ip);
1885 * helper function to process a set of flags and set bits in the
1886 * appropriate masks.
1889 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
1890 struct _s_x *flags, char *p)
1892 u_int8_t set=0, clear=0;
1895 char *q; /* points to the separator */
1897 u_int8_t *which; /* mask we are working on */
1907 val = match_token(flags, p);
1909 errx(EX_DATAERR, "invalid flag %s", p);
1910 *which |= (u_int8_t)val;
1913 cmd->opcode = opcode;
1914 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
1915 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
1920 delete(int ac, char *av[])
1923 struct dn_pipe pipe;
1925 int exitval = EX_OK;
1928 memset(&pipe, 0, sizeof pipe);
1931 if (ac > 0 && !strncmp(*av, "set", strlen(*av))) {
1932 do_set = 1; /* delete set */
1937 while (ac && isdigit(**av)) {
1938 i = atoi(*av); av++; ac--;
1944 i = setsockopt(s, IPPROTO_IP, IP_DUMMYNET_DEL,
1945 &pipe, sizeof pipe);
1948 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)",
1949 do_pipe == 1 ? pipe.pipe_nr :
1953 rulenum = (i & 0xffff) | (do_set << 24);
1954 i = setsockopt(s, IPPROTO_IP, IP_FW_DEL, &rulenum,
1957 exitval = EX_UNAVAILABLE;
1958 warn("rule %u: setsockopt(IP_FW_DEL)",
1963 if (exitval != EX_OK)
1969 * fill the interface structure. We do not check the name as we can
1970 * create interfaces dynamically, so checking them at insert time
1971 * makes relatively little sense.
1972 * A '*' following the name means any unit.
1975 fill_iface(ipfw_insn_if *cmd, char *arg)
1977 cmd->name[0] = '\0';
1978 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
1980 /* Parse the interface or address */
1981 if (!strcmp(arg, "any"))
1982 cmd->o.len = 0; /* effectively ignore this command */
1983 else if (!isdigit(*arg)) {
1986 strncpy(cmd->name, arg, sizeof(cmd->name));
1987 cmd->name[sizeof(cmd->name) - 1] = '\0';
1988 /* find first digit or wildcard */
1989 for (q = cmd->name; *q && !isdigit(*q) && *q != '*'; q++)
1991 cmd->p.unit = (*q == '*') ? -1 : atoi(q);
1993 } else if (!inet_aton(arg, &cmd->p.ip))
1994 errx(EX_DATAERR, "bad ip address ``%s''", arg);
1998 * the following macro returns an error message if we run out of
2001 #define NEED1(msg) {if (!ac) errx(EX_USAGE, msg);}
2004 config_pipe(int ac, char **av)
2006 struct dn_pipe pipe;
2012 memset(&pipe, 0, sizeof pipe);
2016 if (ac && isdigit(**av)) {
2017 i = atoi(*av); av++; ac--;
2025 int tok = match_token(dummynet_params, *av);
2030 pipe.fs.flags_fs |= DN_NOERROR;
2034 NEED1("plr needs argument 0..1\n");
2035 d = strtod(av[0], NULL);
2040 pipe.fs.plr = (int)(d*0x7fffffff);
2045 NEED1("queue needs queue size\n");
2047 pipe.fs.qsize = strtoul(av[0], &end, 0);
2048 if (*end == 'K' || *end == 'k') {
2049 pipe.fs.flags_fs |= DN_QSIZE_IS_BYTES;
2050 pipe.fs.qsize *= 1024;
2051 } else if (*end == 'B' || !strncmp(end, "by", 2)) {
2052 pipe.fs.flags_fs |= DN_QSIZE_IS_BYTES;
2058 NEED1("buckets needs argument\n");
2059 pipe.fs.rq_size = strtoul(av[0], NULL, 0);
2064 NEED1("mask needs mask specifier\n");
2066 * per-flow queue, mask is dst_ip, dst_port,
2067 * src_ip, src_port, proto measured in bits
2071 pipe.fs.flow_mask.dst_ip = 0;
2072 pipe.fs.flow_mask.src_ip = 0;
2073 pipe.fs.flow_mask.dst_port = 0;
2074 pipe.fs.flow_mask.src_port = 0;
2075 pipe.fs.flow_mask.proto = 0;
2079 u_int32_t *p32 = NULL;
2080 u_int16_t *p16 = NULL;
2082 tok = match_token(dummynet_params, *av);
2087 * special case, all bits significant
2089 pipe.fs.flow_mask.dst_ip = ~0;
2090 pipe.fs.flow_mask.src_ip = ~0;
2091 pipe.fs.flow_mask.dst_port = ~0;
2092 pipe.fs.flow_mask.src_port = ~0;
2093 pipe.fs.flow_mask.proto = ~0;
2094 pipe.fs.flags_fs |= DN_HAVE_FLOW_MASK;
2098 p32 = &pipe.fs.flow_mask.dst_ip;
2102 p32 = &pipe.fs.flow_mask.src_ip;
2106 p16 = &pipe.fs.flow_mask.dst_port;
2110 p16 = &pipe.fs.flow_mask.src_port;
2117 ac++; av--; /* backtrack */
2121 errx(EX_USAGE, "mask: value missing");
2122 if (*av[0] == '/') {
2123 a = strtoul(av[0]+1, &end, 0);
2124 a = (a == 32) ? ~0 : (1 << a) - 1;
2126 a = strtoul(av[0], &end, 0);
2129 else if (p16 != NULL) {
2132 "mask: must be 16 bit");
2133 *p16 = (u_int16_t)a;
2137 "mask: must be 8 bit");
2138 pipe.fs.flow_mask.proto = (u_int8_t)a;
2141 pipe.fs.flags_fs |= DN_HAVE_FLOW_MASK;
2143 } /* end while, config masks */
2149 NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
2150 pipe.fs.flags_fs |= DN_IS_RED;
2151 if (tok == TOK_GRED)
2152 pipe.fs.flags_fs |= DN_IS_GENTLE_RED;
2154 * the format for parameters is w_q/min_th/max_th/max_p
2156 if ((end = strsep(&av[0], "/"))) {
2157 double w_q = strtod(end, NULL);
2158 if (w_q > 1 || w_q <= 0)
2159 errx(EX_DATAERR, "0 < w_q <= 1");
2160 pipe.fs.w_q = (int) (w_q * (1 << SCALE_RED));
2162 if ((end = strsep(&av[0], "/"))) {
2163 pipe.fs.min_th = strtoul(end, &end, 0);
2164 if (*end == 'K' || *end == 'k')
2165 pipe.fs.min_th *= 1024;
2167 if ((end = strsep(&av[0], "/"))) {
2168 pipe.fs.max_th = strtoul(end, &end, 0);
2169 if (*end == 'K' || *end == 'k')
2170 pipe.fs.max_th *= 1024;
2172 if ((end = strsep(&av[0], "/"))) {
2173 double max_p = strtod(end, NULL);
2174 if (max_p > 1 || max_p <= 0)
2175 errx(EX_DATAERR, "0 < max_p <= 1");
2176 pipe.fs.max_p = (int)(max_p * (1 << SCALE_RED));
2182 pipe.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
2186 NEED1("bw needs bandwidth or interface\n");
2188 errx(EX_DATAERR, "bandwidth only valid for pipes");
2190 * set clocking interface or bandwidth value
2192 if (av[0][0] >= 'a' && av[0][0] <= 'z') {
2193 int l = sizeof(pipe.if_name)-1;
2194 /* interface name */
2195 strncpy(pipe.if_name, av[0], l);
2196 pipe.if_name[l] = '\0';
2199 pipe.if_name[0] = '\0';
2200 pipe.bandwidth = strtoul(av[0], &end, 0);
2201 if (*end == 'K' || *end == 'k') {
2203 pipe.bandwidth *= 1000;
2204 } else if (*end == 'M') {
2206 pipe.bandwidth *= 1000000;
2208 if (*end == 'B' || !strncmp(end, "by", 2))
2209 pipe.bandwidth *= 8;
2210 if (pipe.bandwidth < 0)
2211 errx(EX_DATAERR, "bandwidth too large");
2218 errx(EX_DATAERR, "delay only valid for pipes");
2219 NEED1("delay needs argument 0..10000ms\n");
2220 pipe.delay = strtoul(av[0], NULL, 0);
2226 errx(EX_DATAERR,"weight only valid for queues");
2227 NEED1("weight needs argument 0..100\n");
2228 pipe.fs.weight = strtoul(av[0], &end, 0);
2234 errx(EX_DATAERR,"pipe only valid for queues");
2235 NEED1("pipe needs pipe_number\n");
2236 pipe.fs.parent_nr = strtoul(av[0], &end, 0);
2241 errx(EX_DATAERR, "unrecognised option ``%s''", *av);
2245 if (pipe.pipe_nr == 0)
2246 errx(EX_DATAERR, "pipe_nr must be > 0");
2247 if (pipe.delay > 10000)
2248 errx(EX_DATAERR, "delay must be < 10000");
2249 } else { /* do_pipe == 2, queue */
2250 if (pipe.fs.parent_nr == 0)
2251 errx(EX_DATAERR, "pipe must be > 0");
2252 if (pipe.fs.weight >100)
2253 errx(EX_DATAERR, "weight must be <= 100");
2255 if (pipe.fs.flags_fs & DN_QSIZE_IS_BYTES) {
2256 if (pipe.fs.qsize > 1024*1024)
2257 errx(EX_DATAERR, "queue size must be < 1MB");
2259 if (pipe.fs.qsize > 100)
2260 errx(EX_DATAERR, "2 <= queue size <= 100");
2262 if (pipe.fs.flags_fs & DN_IS_RED) {
2264 int lookup_depth, avg_pkt_size;
2265 double s, idle, weight, w_q;
2266 struct clockinfo clock;
2269 if (pipe.fs.min_th >= pipe.fs.max_th)
2270 errx(EX_DATAERR, "min_th %d must be < than max_th %d",
2271 pipe.fs.min_th, pipe.fs.max_th);
2272 if (pipe.fs.max_th == 0)
2273 errx(EX_DATAERR, "max_th must be > 0");
2276 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
2277 &lookup_depth, &len, NULL, 0) == -1)
2279 errx(1, "sysctlbyname(\"%s\")",
2280 "net.inet.ip.dummynet.red_lookup_depth");
2281 if (lookup_depth == 0)
2282 errx(EX_DATAERR, "net.inet.ip.dummynet.red_lookup_depth"
2283 " must be greater than zero");
2286 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
2287 &avg_pkt_size, &len, NULL, 0) == -1)
2289 errx(1, "sysctlbyname(\"%s\")",
2290 "net.inet.ip.dummynet.red_avg_pkt_size");
2291 if (avg_pkt_size == 0)
2293 "net.inet.ip.dummynet.red_avg_pkt_size must"
2294 " be greater than zero");
2296 len = sizeof(struct clockinfo);
2297 if (sysctlbyname("kern.clockrate", &clock, &len, NULL, 0) == -1)
2298 errx(1, "sysctlbyname(\"%s\")", "kern.clockrate");
2301 * Ticks needed for sending a medium-sized packet.
2302 * Unfortunately, when we are configuring a WF2Q+ queue, we
2303 * do not have bandwidth information, because that is stored
2304 * in the parent pipe, and also we have multiple queues
2305 * competing for it. So we set s=0, which is not very
2306 * correct. But on the other hand, why do we want RED with
2309 if (pipe.bandwidth==0) /* this is a WF2Q+ queue */
2312 s = clock.hz * avg_pkt_size * 8 / pipe.bandwidth;
2315 * max idle time (in ticks) before avg queue size becomes 0.
2316 * NOTA: (3/w_q) is approx the value x so that
2317 * (1-w_q)^x < 10^-3.
2319 w_q = ((double)pipe.fs.w_q) / (1 << SCALE_RED);
2320 idle = s * 3. / w_q;
2321 pipe.fs.lookup_step = (int)idle / lookup_depth;
2322 if (!pipe.fs.lookup_step)
2323 pipe.fs.lookup_step = 1;
2325 for (t = pipe.fs.lookup_step; t > 0; --t)
2327 pipe.fs.lookup_weight = (int)(weight * (1 << SCALE_RED));
2329 i = setsockopt(s, IPPROTO_IP, IP_DUMMYNET_CONFIGURE, &pipe,
2332 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
2336 get_mac_addr_mask(char *p, u_char *addr, u_char *mask)
2341 addr[i] = mask[i] = 0;
2342 if (!strcmp(p, "any"))
2345 for (i=0; *p && i<6;i++, p++) {
2346 addr[i] = strtol(p, &p, 16);
2347 if (*p != ':') /* we start with the mask */
2350 if (*p == '/') { /* mask len */
2351 l = strtol(p+1, &p, 0);
2352 for (i=0; l>0; l -=8, i++)
2353 mask[i] = (l >=8) ? 0xff : (~0) << (8-l);
2354 } else if (*p == '&') { /* mask */
2355 for (i=0, p++; *p && i<6;i++, p++) {
2356 mask[i] = strtol(p, &p, 16);
2360 } else if (*p == '\0') {
2369 * helper function, updates the pointer to cmd with the length
2370 * of the current command, and also cleans up the first word of
2371 * the new command in case it has been clobbered before.
2374 next_cmd(ipfw_insn *cmd)
2377 bzero(cmd, sizeof(*cmd));
2382 * A function to fill simple commands of size 1.
2383 * Existing flags are preserved.
2386 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, u_int16_t arg)
2388 cmd->opcode = opcode;
2389 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
2394 * Fetch and add the MAC address and type, with masks. This generates one or
2395 * two microinstructions, and returns the pointer to the last one.
2398 add_mac(ipfw_insn *cmd, int ac, char *av[])
2403 errx(EX_DATAERR, "MAC dst src");
2405 cmd->opcode = O_MACADDR2;
2406 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
2408 mac = (ipfw_insn_mac *)cmd;
2409 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
2410 get_mac_addr_mask(av[1], &(mac->addr[6]), &(mac->mask[6])); /* src */
2415 add_mactype(ipfw_insn *cmd, int ac, char *av)
2418 errx(EX_DATAERR, "missing MAC type");
2419 if (strcmp(av, "any") != 0) { /* we have a non-null type */
2420 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE);
2421 cmd->opcode = O_MAC_TYPE;
2428 add_proto(ipfw_insn *cmd, char *av)
2430 struct protoent *pe;
2433 if (!strncmp(av, "all", strlen(av)))
2434 ; /* same as "ip" */
2435 else if ((proto = atoi(av)) > 0)
2437 else if ((pe = getprotobyname(av)) != NULL)
2438 proto = pe->p_proto;
2441 if (proto != IPPROTO_IP)
2442 fill_cmd(cmd, O_PROTO, 0, proto);
2447 add_srcip(ipfw_insn *cmd, char *av)
2449 fill_ip((ipfw_insn_ip *)cmd, av);
2450 if (cmd->opcode == O_IP_DST_SET) /* set */
2451 cmd->opcode = O_IP_SRC_SET;
2452 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2453 cmd->opcode = O_IP_SRC_ME;
2454 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2455 cmd->opcode = O_IP_SRC;
2456 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_ip)) /* addr/mask */
2457 cmd->opcode = O_IP_SRC_MASK;
2462 add_dstip(ipfw_insn *cmd, char *av)
2464 fill_ip((ipfw_insn_ip *)cmd, av);
2465 if (cmd->opcode == O_IP_DST_SET) /* set */
2467 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2468 cmd->opcode = O_IP_DST_ME;
2469 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2470 cmd->opcode = O_IP_DST;
2471 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_ip)) /* addr/mask */
2472 cmd->opcode = O_IP_DST_MASK;
2477 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode)
2479 if (!strncmp(av, "any", strlen(av))) {
2481 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) {
2482 /* XXX todo: check that we have a protocol with ports */
2483 cmd->opcode = opcode;
2490 * Parse arguments and assemble the microinstructions which make up a rule.
2491 * Rules are added into the 'rulebuf' and then copied in the correct order
2492 * into the actual rule.
2494 * The syntax for a rule starts with the action, followed by an
2495 * optional log action, and the various match patterns.
2496 * In the assembled microcode, the first opcode must be a O_PROBE_STATE
2497 * (generated if the rule includes a keep-state option), then the
2498 * various match patterns, the "log" action, and the actual action.
2502 add(int ac, char *av[])
2505 * rules are added into the 'rulebuf' and then copied in
2506 * the correct order into the actual rule.
2507 * Some things that need to go out of order (prob, action etc.)
2510 static u_int32_t rulebuf[255], actbuf[255], cmdbuf[255];
2512 ipfw_insn *src, *dst, *cmd, *action, *prev;
2513 ipfw_insn *first_cmd; /* first match pattern */
2518 * various flags used to record that we entered some fields.
2520 ipfw_insn *have_state = NULL; /* check-state or keep-state */
2524 int open_par = 0; /* open parenthesis ( */
2526 /* proto is here because it is used to fetch ports */
2527 u_char proto = IPPROTO_IP; /* default protocol */
2529 double match_prob = 1; /* match probability, default is always match */
2531 bzero(actbuf, sizeof(actbuf)); /* actions go here */
2532 bzero(cmdbuf, sizeof(cmdbuf));
2533 bzero(rulebuf, sizeof(rulebuf));
2535 rule = (struct ip_fw *)rulebuf;
2536 cmd = (ipfw_insn *)cmdbuf;
2537 action = (ipfw_insn *)actbuf;
2541 /* [rule N] -- Rule number optional */
2542 if (ac && isdigit(**av)) {
2543 rule->rulenum = atoi(*av);
2548 /* [set N] -- set number (0..30), optional */
2549 if (ac > 1 && !strncmp(*av, "set", strlen(*av))) {
2550 int set = strtoul(av[1], NULL, 10);
2551 if (set < 0 || set > 30)
2552 errx(EX_DATAERR, "illegal set %s", av[1]);
2557 /* [prob D] -- match probability, optional */
2558 if (ac > 1 && !strncmp(*av, "prob", strlen(*av))) {
2559 match_prob = strtod(av[1], NULL);
2561 if (match_prob <= 0 || match_prob > 1)
2562 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
2566 /* action -- mandatory */
2567 NEED1("missing action");
2568 i = match_token(rule_actions, *av);
2570 action->len = 1; /* default */
2572 case TOK_CHECKSTATE:
2573 have_state = action;
2574 action->opcode = O_CHECK_STATE;
2578 action->opcode = O_ACCEPT;
2582 action->opcode = O_DENY;
2587 action->opcode = O_REJECT;
2588 action->arg1 = ICMP_UNREACH_HOST;
2592 action->opcode = O_REJECT;
2593 action->arg1 = ICMP_REJECT_RST;
2597 action->opcode = O_REJECT;
2598 NEED1("missing reject code");
2599 fill_reject_code(&action->arg1, *av);
2604 action->opcode = O_COUNT;
2609 action->len = F_INSN_SIZE(ipfw_insn_pipe);
2612 action->opcode = O_QUEUE;
2613 else if (i == TOK_PIPE)
2614 action->opcode = O_PIPE;
2615 else if (i == TOK_SKIPTO)
2616 action->opcode = O_SKIPTO;
2617 NEED1("missing skipto/pipe/queue number");
2618 action->arg1 = strtoul(*av, NULL, 10);
2624 action->opcode = (i == TOK_DIVERT) ? O_DIVERT : O_TEE;
2625 NEED1("missing divert/tee port");
2626 action->arg1 = strtoul(*av, NULL, 0);
2627 if (action->arg1 == 0) {
2630 s = getservbyname(av[0], "divert");
2632 action->arg1 = ntohs(s->s_port);
2634 errx(EX_DATAERR, "illegal divert/tee port");
2640 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
2643 NEED1("missing forward address[:port]");
2645 action->opcode = O_FORWARD_IP;
2646 action->len = F_INSN_SIZE(ipfw_insn_sa);
2648 p->sa.sin_len = sizeof(struct sockaddr_in);
2649 p->sa.sin_family = AF_INET;
2652 * locate the address-port separator (':' or ',')
2654 s = strchr(*av, ':');
2656 s = strchr(*av, ',');
2659 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
2662 "illegal forwarding port ``%s''", s);
2663 p->sa.sin_port = (u_short)i;
2665 lookup_host(*av, &(p->sa.sin_addr));
2671 errx(EX_DATAERR, "invalid action %s\n", av[-1]);
2673 action = next_cmd(action);
2676 * [log [logamount N]] -- log, optional
2678 * If exists, it goes first in the cmdbuf, but then it is
2679 * skipped in the copy section to the end of the buffer.
2681 if (ac && !strncmp(*av, "log", strlen(*av))) {
2682 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
2684 cmd->len = F_INSN_SIZE(ipfw_insn_log);
2685 cmd->opcode = O_LOG;
2687 if (ac && !strncmp(*av, "logamount", strlen(*av))) {
2689 NEED1("logamount requires argument");
2690 c->max_log = atoi(*av);
2692 errx(EX_DATAERR, "logamount must be positive");
2695 cmd = next_cmd(cmd);
2698 if (have_state) /* must be a check-state, we are done */
2701 #define OR_START(target) \
2702 if (ac && (*av[0] == '(' || *av[0] == '{')) { \
2704 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
2707 if ( (av[0])[1] == '\0') { \
2718 !strncmp(*av, ")", strlen(*av)) || \
2719 !strncmp(*av, "}", strlen(*av)) )) { \
2724 errx(EX_USAGE, "missing \")\"\n"); \
2728 if (ac && !strncmp(*av, "not", strlen(*av))) { \
2729 if (cmd->len & F_NOT) \
2730 errx(EX_USAGE, "double \"not\" not allowed\n"); \
2731 cmd->len |= F_NOT; \
2735 #define OR_BLOCK(target) \
2736 if (ac && !strncmp(*av, "or", strlen(*av))) { \
2737 if (prev == NULL || open_par == 0) \
2738 errx(EX_DATAERR, "invalid OR block"); \
2739 prev->len |= F_OR; \
2749 * MAC addresses, optional.
2750 * If we have this, we skip the part "proto from src to dst"
2751 * and jump straight to the option parsing.
2754 NEED1("missing protocol");
2755 if (!strncmp(*av, "MAC", strlen(*av)) ||
2756 !strncmp(*av, "mac", strlen(*av))) {
2757 ac--; av++; /* the "MAC" keyword */
2758 add_mac(cmd, ac, av); /* exits in case of errors */
2759 cmd = next_cmd(cmd);
2760 ac -= 2; av += 2; /* dst-mac and src-mac */
2762 NEED1("missing mac type");
2763 if (add_mactype(cmd, ac, av[0]))
2764 cmd = next_cmd(cmd);
2765 ac--; av++; /* any or mac-type */
2771 * protocol, mandatory
2773 OR_START(get_proto);
2775 NEED1("missing protocol");
2776 if (add_proto(cmd, *av)) {
2778 if (F_LEN(cmd) == 0) /* plain IP */
2783 cmd = next_cmd(cmd);
2785 } else if (first_cmd != cmd) {
2786 errx(EX_DATAERR, "invalid protocol ``%s''", av);
2789 OR_BLOCK(get_proto);
2794 if (!ac || strncmp(*av, "from", strlen(*av)))
2795 errx(EX_USAGE, "missing ``from''");
2799 * source IP, mandatory
2801 OR_START(source_ip);
2802 NOT_BLOCK; /* optional "not" */
2803 NEED1("missing source address");
2804 if (add_srcip(cmd, *av)) {
2806 if (F_LEN(cmd) != 0) { /* ! any */
2808 cmd = next_cmd(cmd);
2811 OR_BLOCK(source_ip);
2814 * source ports, optional
2816 NOT_BLOCK; /* optional "not" */
2818 if (!strncmp(*av, "any", strlen(*av)) ||
2819 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
2821 if (F_LEN(cmd) != 0)
2822 cmd = next_cmd(cmd);
2829 if (!ac || strncmp(*av, "to", strlen(*av)))
2830 errx(EX_USAGE, "missing ``to''");
2834 * destination, mandatory
2837 NOT_BLOCK; /* optional "not" */
2838 NEED1("missing dst address");
2839 if (add_dstip(cmd, *av)) {
2841 if (F_LEN(cmd) != 0) { /* ! any */
2843 cmd = next_cmd(cmd);
2849 * dest. ports, optional
2851 NOT_BLOCK; /* optional "not" */
2853 if (!strncmp(*av, "any", strlen(*av)) ||
2854 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
2856 if (F_LEN(cmd) != 0)
2857 cmd = next_cmd(cmd);
2862 if (ac && first_cmd == cmd) {
2864 * nothing specified so far, store in the rule to ease
2872 ipfw_insn_u32 *cmd32; /* alias for cmd */
2875 cmd32 = (ipfw_insn_u32 *)cmd;
2877 if (*s == '!') { /* alternate syntax for NOT */
2878 if (cmd->len & F_NOT)
2879 errx(EX_USAGE, "double \"not\" not allowed\n");
2883 i = match_token(rule_options, s);
2887 if (cmd->len & F_NOT)
2888 errx(EX_USAGE, "double \"not\" not allowed\n");
2893 if (open_par == 0 || prev == NULL)
2894 errx(EX_USAGE, "invalid \"or\" block\n");
2898 case TOK_STARTBRACE:
2900 errx(EX_USAGE, "+nested \"(\" not allowed\n");
2906 errx(EX_USAGE, "+missing \")\"\n");
2912 fill_cmd(cmd, O_IN, 0, 0);
2916 cmd->len ^= F_NOT; /* toggle F_NOT */
2917 fill_cmd(cmd, O_IN, 0, 0);
2921 fill_cmd(cmd, O_FRAG, 0, 0);
2925 fill_cmd(cmd, O_LAYER2, 0, 0);
2931 NEED1("recv, xmit, via require interface name"
2933 fill_iface((ipfw_insn_if *)cmd, av[0]);
2935 if (F_LEN(cmd) == 0) /* not a valid address */
2938 cmd->opcode = O_XMIT;
2939 else if (i == TOK_RECV)
2940 cmd->opcode = O_RECV;
2941 else if (i == TOK_VIA)
2942 cmd->opcode = O_VIA;
2946 NEED1("icmptypes requires list of types");
2947 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
2952 NEED1("ipttl requires TTL");
2953 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
2958 NEED1("ipid requires length");
2959 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
2964 NEED1("iplen requires length");
2965 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
2970 NEED1("ipver requires version");
2971 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
2975 case TOK_IPPRECEDENCE:
2976 NEED1("ipprecedence requires value");
2977 fill_cmd(cmd, O_IPPRECEDENCE, 0,
2978 (strtoul(*av, NULL, 0) & 7) << 5);
2983 NEED1("missing argument for ipoptions");
2984 fill_flags(cmd, O_IPOPT, f_ipopts, *av);
2989 NEED1("missing argument for iptos");
2990 fill_flags(cmd, O_IPTOS, f_iptos, *av);
2995 NEED1("uid requires argument");
3001 cmd->opcode = O_UID;
3002 uid = strtoul(*av, &end, 0);
3003 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
3005 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
3006 cmd32->d[0] = pwd->pw_uid;
3007 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3013 NEED1("gid requires argument");
3019 cmd->opcode = O_GID;
3020 gid = strtoul(*av, &end, 0);
3021 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
3023 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
3024 cmd32->d[0] = grp->gr_gid;
3025 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3031 fill_cmd(cmd, O_ESTAB, 0, 0);
3035 fill_cmd(cmd, O_TCPFLAGS, 0,
3036 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
3040 NEED1("missing argument for tcpoptions");
3041 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
3047 NEED1("tcpseq/tcpack requires argument");
3048 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3049 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
3050 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
3055 NEED1("tcpwin requires length");
3056 fill_cmd(cmd, O_TCPWIN, 0,
3057 htons(strtoul(*av, NULL, 0)));
3062 NEED1("missing argument for tcpflags");
3063 cmd->opcode = O_TCPFLAGS;
3064 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
3070 errx(EX_USAGE, "keep-state cannot be part "
3073 errx(EX_USAGE, "only one of keep-state "
3074 "and limit is allowed");
3076 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
3081 errx(EX_USAGE, "limit cannot be part "
3084 errx(EX_USAGE, "only one of keep-state "
3085 "and limit is allowed");
3086 NEED1("limit needs mask and # of connections");
3089 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
3091 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
3092 cmd->opcode = O_LIMIT;
3098 val = match_token(limit_masks, *av);
3101 c->limit_mask |= val;
3104 c->conn_limit = atoi(*av);
3105 if (c->conn_limit == 0)
3106 errx(EX_USAGE, "limit: limit must be >0");
3107 if (c->limit_mask == 0)
3108 errx(EX_USAGE, "missing limit mask");
3114 NEED1("missing protocol");
3115 if (add_proto(cmd, *av)) {
3119 errx(EX_DATAERR, "invalid protocol ``%s''", av);
3123 NEED1("missing source IP");
3124 if (add_srcip(cmd, *av)) {
3130 NEED1("missing destination IP");
3131 if (add_dstip(cmd, *av)) {
3137 NEED1("missing source port");
3138 if (!strncmp(*av, "any", strlen(*av)) ||
3139 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
3142 errx(EX_DATAERR, "invalid source port %s", *av);
3146 NEED1("missing destination port");
3147 if (!strncmp(*av, "any", strlen(*av)) ||
3148 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
3151 errx(EX_DATAERR, "invalid destination port %s",
3157 errx(EX_USAGE, "MAC dst-mac src-mac");
3158 if (add_mac(cmd, ac, av)) {
3164 NEED1("missing mac type");
3165 if (!add_mactype(cmd, ac, *av))
3166 errx(EX_DATAERR, "invalid mac type %s", av);
3171 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
3173 if (F_LEN(cmd) > 0) { /* prepare to advance */
3175 cmd = next_cmd(cmd);
3181 * Now copy stuff into the rule.
3182 * If we have a keep-state option, the first instruction
3183 * must be a PROBE_STATE (which is generated here).
3184 * If we have a LOG option, it was stored as the first command,
3185 * and now must be moved to the top of the action part.
3187 dst = (ipfw_insn *)rule->cmd;
3190 * First thing to write into the command stream is the match probability.
3192 if (match_prob != 1) { /* 1 means always match */
3193 dst->opcode = O_PROB;
3195 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
3200 * generate O_PROBE_STATE if necessary
3202 if (have_state && have_state->opcode != O_CHECK_STATE) {
3203 fill_cmd(dst, O_PROBE_STATE, 0, 0);
3204 dst = next_cmd(dst);
3207 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT
3209 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
3212 switch (src->opcode) {
3218 bcopy(src, dst, i * sizeof(u_int32_t));
3224 * put back the have_state command as last opcode
3226 if (have_state && have_state->opcode != O_CHECK_STATE) {
3227 i = F_LEN(have_state);
3228 bcopy(have_state, dst, i * sizeof(u_int32_t));
3232 * start action section
3234 rule->act_ofs = dst - rule->cmd;
3237 * put back O_LOG if necessary
3239 src = (ipfw_insn *)cmdbuf;
3240 if ( src->opcode == O_LOG ) {
3242 bcopy(src, dst, i * sizeof(u_int32_t));
3246 * copy all other actions
3248 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
3250 bcopy(src, dst, i * sizeof(u_int32_t));
3254 rule->cmd_len = (u_int32_t *)dst - (u_int32_t *)(rule->cmd);
3255 i = (void *)dst - (void *)rule;
3256 if (getsockopt(s, IPPROTO_IP, IP_FW_ADD, rule, &i) == -1)
3257 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
3259 show_ipfw(rule, 10, 10);
3263 zero(int ac, char *av[])
3271 /* clear all entries */
3272 if (setsockopt(s, IPPROTO_IP, IP_FW_ZERO, NULL, 0) < 0)
3273 err(EX_UNAVAILABLE, "setsockopt(%s)", "IP_FW_ZERO");
3275 printf("Accounting cleared.\n");
3282 if (isdigit(**av)) {
3283 rulenum = atoi(*av);
3286 if (setsockopt(s, IPPROTO_IP,
3287 IP_FW_ZERO, &rulenum, sizeof rulenum)) {
3288 warn("rule %u: setsockopt(IP_FW_ZERO)",
3290 failed = EX_UNAVAILABLE;
3291 } else if (!do_quiet)
3292 printf("Entry %d cleared\n", rulenum);
3294 errx(EX_USAGE, "invalid rule number ``%s''", *av);
3297 if (failed != EX_OK)
3302 resetlog(int ac, char *av[])
3310 /* clear all entries */
3311 if (setsockopt(s, IPPROTO_IP, IP_FW_RESETLOG, NULL, 0) < 0)
3312 err(EX_UNAVAILABLE, "setsockopt(IP_FW_RESETLOG)");
3314 printf("Logging counts reset.\n");
3321 if (isdigit(**av)) {
3322 rulenum = atoi(*av);
3325 if (setsockopt(s, IPPROTO_IP,
3326 IP_FW_RESETLOG, &rulenum, sizeof rulenum)) {
3327 warn("rule %u: setsockopt(IP_FW_RESETLOG)",
3329 failed = EX_UNAVAILABLE;
3330 } else if (!do_quiet)
3331 printf("Entry %d logging count reset\n",
3334 errx(EX_DATAERR, "invalid rule number ``%s''", *av);
3337 if (failed != EX_OK)
3344 int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
3346 if (!do_force && !do_quiet) { /* need to ask user */
3349 printf("Are you sure? [yn] ");
3352 c = toupper(getc(stdin));
3353 while (c != '\n' && getc(stdin) != '\n')
3355 return; /* and do not flush */
3356 } while (c != 'Y' && c != 'N');
3358 if (c == 'N') /* user said no */
3361 if (setsockopt(s, IPPROTO_IP, cmd, NULL, 0) < 0)
3362 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
3363 do_pipe ? "DUMMYNET" : "FW");
3365 printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules");
3369 ipfw_main(int ac, char **av)
3376 /* Set the force flag for non-interactive processes */
3377 do_force = !isatty(STDIN_FILENO);
3379 optind = optreset = 1;
3380 while ((ch = getopt(ac, av, "hs:acdefNqStv")) != -1)
3382 case 'h': /* help */
3384 break; /* NOTREACHED */
3386 case 's': /* sort */
3387 do_sort = atoi(optarg);
3416 case 'v': /* verbose */
3425 NEED1("bad arguments, for usage summary ``ipfw''");
3428 * optional: pipe or queue
3430 if (!strncmp(*av, "pipe", strlen(*av))) {
3434 } else if (!strncmp(*av, "queue", strlen(*av))) {
3439 NEED1("missing command");
3442 * for pipes and queues we normally say 'pipe NN config'
3443 * but the code is easier to parse as 'pipe config NN'
3444 * so we swap the two arguments.
3446 if (do_pipe > 0 && ac > 1 && *av[0] >= '0' && *av[0] <= '9') {
3451 if (!strncmp(*av, "add", strlen(*av)))
3453 else if (do_pipe && !strncmp(*av, "config", strlen(*av)))
3454 config_pipe(ac, av);
3455 else if (!strncmp(*av, "delete", strlen(*av)))
3457 else if (!strncmp(*av, "flush", strlen(*av)))
3459 else if (!strncmp(*av, "zero", strlen(*av)))
3461 else if (!strncmp(*av, "resetlog", strlen(*av)))
3463 else if (!strncmp(*av, "print", strlen(*av)) ||
3464 !strncmp(*av, "list", strlen(*av)))
3466 else if (!strncmp(*av, "enable", strlen(*av)))
3467 sysctl_handler(ac, av, 1);
3468 else if (!strncmp(*av, "disable", strlen(*av)))
3469 sysctl_handler(ac, av, 0);
3470 else if (!strncmp(*av, "set", strlen(*av)))
3471 sets_handler(ac, av);
3472 else if (!strncmp(*av, "show", strlen(*av))) {
3476 errx(EX_USAGE, "bad command `%s'", *av);
3482 ipfw_readfile(int ac, char *av[])
3485 #define WHITESP " \t\f\v\n\r"
3487 char *a, *p, *args[MAX_ARGS], *cmd = NULL;
3489 int i=0, lineno=0, qflag=0, pflag=0, status;
3494 while ((c = getopt(ac, av, "D:U:p:q")) != -1)
3498 errx(EX_USAGE, "-D requires -p");
3499 if (i > MAX_ARGS - 2)
3501 "too many -D or -U options");
3508 errx(EX_USAGE, "-U requires -p");
3509 if (i > MAX_ARGS - 2)
3511 "too many -D or -U options");
3528 errx(EX_USAGE, "bad arguments, for usage"
3529 " summary ``ipfw''");
3535 errx(EX_USAGE, "extraneous filename arguments");
3537 if ((f = fopen(av[0], "r")) == NULL)
3538 err(EX_UNAVAILABLE, "fopen: %s", av[0]);
3541 /* pipe through preprocessor (cpp or m4) */
3546 if (pipe(pipedes) == -1)
3547 err(EX_OSERR, "cannot create pipe");
3549 switch((preproc = fork())) {
3551 err(EX_OSERR, "cannot fork");
3555 if (dup2(fileno(f), 0) == -1
3556 || dup2(pipedes[1], 1) == -1)
3557 err(EX_OSERR, "dup2()");
3562 err(EX_OSERR, "execvp(%s) failed", cmd);
3568 if ((f = fdopen(pipedes[0], "r")) == NULL) {
3569 int savederrno = errno;
3571 (void)kill(preproc, SIGTERM);
3573 err(EX_OSERR, "fdopen()");
3578 while (fgets(buf, BUFSIZ, f)) {
3580 sprintf(linename, "Line %d", lineno);
3585 if ((p = strchr(buf, '#')) != NULL)
3590 for (a = strtok(buf, WHITESP);
3591 a && i < MAX_ARGS; a = strtok(NULL, WHITESP), i++)
3593 if (i == (qflag? 2: 1))
3596 errx(EX_USAGE, "%s: too many arguments",
3604 if (waitpid(preproc, &status, 0) == -1)
3605 errx(EX_OSERR, "waitpid()");
3606 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
3607 errx(EX_UNAVAILABLE,
3608 "preprocessor exited with status %d",
3609 WEXITSTATUS(status));
3610 else if (WIFSIGNALED(status))
3611 errx(EX_UNAVAILABLE,
3612 "preprocessor exited with signal %d",
3618 main(int ac, char *av[])
3620 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
3622 err(EX_UNAVAILABLE, "socket");
3625 * If the last argument is an absolute pathname, interpret it
3626 * as a file to be preprocessed.
3629 if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0)
3630 ipfw_readfile(ac, av);