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 $
23 #include <sys/param.h>
25 #include <sys/socket.h>
26 #include <sys/sockio.h>
27 #include <sys/sysctl.h>
47 #include <netinet/in.h>
48 #include <netinet/in_systm.h>
49 #include <netinet/ip.h>
50 #include <netinet/ip_icmp.h>
51 #include <net/ipfw/ip_fw.h>
52 #include <net/route.h> /* def. of struct route */
53 #include <net/ethernet.h>
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.
161 { "pppoe_disc", 0x8863 },
162 { "pppoe_sess", 0x8864 },
163 { "ipx_8022", 0x00E0 },
164 { "ipx_8023", 0x0000 },
165 { "ipx_ii", 0x8137 },
166 { "ipx_snap", 0x8137 },
172 static void show_usage(void);
243 struct _s_x dummynet_params[] = {
245 { "noerror", TOK_NOERROR },
246 { "buckets", TOK_BUCKETS },
247 { "dst-ip", TOK_DSTIP },
248 { "src-ip", TOK_SRCIP },
249 { "dst-port", TOK_DSTPORT },
250 { "src-port", TOK_SRCPORT },
251 { "proto", TOK_PROTO },
252 { "weight", TOK_WEIGHT },
254 { "mask", TOK_MASK },
255 { "droptail", TOK_DROPTAIL },
257 { "gred", TOK_GRED },
259 { "bandwidth", TOK_BW },
260 { "delay", TOK_DELAY },
261 { "pipe", TOK_PIPE },
262 { "queue", TOK_QUEUE },
263 { "dummynet-params", TOK_NULL },
267 struct _s_x rule_actions[] = {
268 { "accept", TOK_ACCEPT },
269 { "pass", TOK_ACCEPT },
270 { "allow", TOK_ACCEPT },
271 { "permit", TOK_ACCEPT },
272 { "count", TOK_COUNT },
273 { "pipe", TOK_PIPE },
274 { "queue", TOK_QUEUE },
275 { "divert", TOK_DIVERT },
277 { "fwd", TOK_FORWARD },
278 { "forward", TOK_FORWARD },
279 { "skipto", TOK_SKIPTO },
280 { "deny", TOK_DENY },
281 { "drop", TOK_DENY },
282 { "reject", TOK_REJECT },
283 { "reset", TOK_RESET },
284 { "unreach", TOK_UNREACH },
285 { "check-state", TOK_CHECKSTATE },
290 struct _s_x rule_options[] = {
294 { "limit", TOK_LIMIT },
295 { "keep-state", TOK_KEEPSTATE },
296 { "layer2", TOK_LAYER2 },
298 { "xmit", TOK_XMIT },
299 { "recv", TOK_RECV },
301 { "fragment", TOK_FRAG },
302 { "frag", TOK_FRAG },
303 { "ipoptions", TOK_IPOPTS },
304 { "ipopts", TOK_IPOPTS },
305 { "iplen", TOK_IPLEN },
306 { "ipid", TOK_IPID },
307 { "ipprecedence", TOK_IPPRECEDENCE },
308 { "iptos", TOK_IPTOS },
309 { "ipttl", TOK_IPTTL },
310 { "ipversion", TOK_IPVER },
311 { "ipver", TOK_IPVER },
312 { "estab", TOK_ESTAB },
313 { "established", TOK_ESTAB },
314 { "setup", TOK_SETUP },
315 { "tcpflags", TOK_TCPFLAGS },
316 { "tcpflgs", TOK_TCPFLAGS },
317 { "tcpoptions", TOK_TCPOPTS },
318 { "tcpopts", TOK_TCPOPTS },
319 { "tcpseq", TOK_TCPSEQ },
320 { "tcpack", TOK_TCPACK },
321 { "tcpwin", TOK_TCPWIN },
322 { "icmptype", TOK_ICMPTYPES },
323 { "icmptypes", TOK_ICMPTYPES },
324 { "dst-ip", TOK_DSTIP },
325 { "src-ip", TOK_SRCIP },
326 { "dst-port", TOK_DSTPORT },
327 { "src-port", TOK_SRCPORT },
328 { "proto", TOK_PROTO },
331 { "mac-type", TOK_MACTYPE },
333 { "not", TOK_NOT }, /* pseudo option */
334 { "!", /* escape ? */ TOK_NOT }, /* pseudo option */
335 { "or", TOK_OR }, /* pseudo option */
336 { "|", /* escape */ TOK_OR }, /* pseudo option */
337 { "{", TOK_STARTBRACE }, /* pseudo option */
338 { "(", TOK_STARTBRACE }, /* pseudo option */
339 { "}", TOK_ENDBRACE }, /* pseudo option */
340 { ")", TOK_ENDBRACE }, /* pseudo option */
346 * match_token takes a table and a string, returns the value associated
347 * with the string (0 meaning an error in most cases)
350 match_token(struct _s_x *table, char *string)
353 int i = strlen(string);
355 for (pt = table ; i && pt->s != NULL ; pt++)
356 if (strlen(pt->s) == i && !bcmp(string, pt->s, i))
362 match_value(struct _s_x *p, u_int32_t value)
364 for (; p->s != NULL; p++)
371 * prints one port, symbolic or numeric
374 print_port(int proto, u_int16_t port)
377 if (proto == IPPROTO_ETHERTYPE) {
380 if (do_resolv && (s = match_value(ether_types, port)) )
383 printf("0x%04x", port);
385 struct servent *se = NULL;
387 struct protoent *pe = getprotobynumber(proto);
389 se = getservbyport(htons(port), pe ? pe->p_name : NULL);
392 printf("%s", se->s_name);
399 * print the values in a list of ports
400 * XXX todo: add support for mask.
403 print_newports(ipfw_insn_u16 *cmd, int proto, int opcode)
405 u_int16_t *p = cmd->ports;
409 if (cmd->o.len & F_NOT)
412 printf ("%s", opcode == O_MAC_TYPE ? " mac-type" :
413 (opcode == O_IP_DSTPORT ? " dst-port" : " src-port"));
414 for (i = F_LEN((ipfw_insn *)cmd) - 1; i > 0; i--, p += 2) {
416 print_port(proto, p[0]);
419 print_port(proto, p[1]);
426 * Like strtol, but also translates service names into port numbers
427 * for some protocols.
429 * proto == -1 disables the protocol check;
430 * proto == IPPROTO_ETHERTYPE looks up an internal table
431 * proto == <some value in /etc/protocols> matches the values there.
432 * Returns *end == s in case the parameter is not found.
435 strtoport(char *s, char **end, int base, int proto)
441 *end = s; /* default - not found */
443 return 0; /* not found */
446 return strtol(s, end, base);
449 * find separator. '\\' escapes the next char.
451 for (s1 = s; *s1 && (isalnum(*s1) || *s1 == '\\') ; s1++)
452 if (*s1 == '\\' && s1[1] != '\0')
455 buf = malloc(s1 - s + 1);
460 * copy into a buffer skipping backslashes
462 for (p = s, i = 0; p != s1 ; p++)
467 if (proto == IPPROTO_ETHERTYPE) {
468 i = match_token(ether_types, buf);
470 if (i != -1) { /* found */
475 struct protoent *pe = NULL;
479 pe = getprotobynumber(proto);
481 se = getservbyname(buf, pe ? pe->p_name : NULL);
485 return ntohs(se->s_port);
488 return 0; /* not found */
492 * fill the body of the command with the list of port ranges.
493 * At the moment it only understands numeric ranges.
496 fill_newports(ipfw_insn_u16 *cmd, char *av, int proto)
498 u_int16_t *p = cmd->ports;
505 a = strtoport(av, &s, 0, proto);
506 if (s == av) /* no parameter */
508 if (*s == '-') { /* a range */
510 b = strtoport(av, &s, 0, proto);
511 if (s == av) /* no parameter */
515 } else if (*s == ',' || *s == '\0' ) {
517 } else { /* invalid separator */
518 errx(EX_DATAERR, "invalid separator <%c> in <%s>\n",
526 if (i+1 > F_LEN_MASK)
527 errx(EX_DATAERR, "too many ports/ranges\n");
528 cmd->o.len |= i+1; /* leave F_NOT and F_OR untouched */
533 static struct _s_x icmpcodes[] = {
534 { "net", ICMP_UNREACH_NET },
535 { "host", ICMP_UNREACH_HOST },
536 { "protocol", ICMP_UNREACH_PROTOCOL },
537 { "port", ICMP_UNREACH_PORT },
538 { "needfrag", ICMP_UNREACH_NEEDFRAG },
539 { "srcfail", ICMP_UNREACH_SRCFAIL },
540 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN },
541 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN },
542 { "isolated", ICMP_UNREACH_ISOLATED },
543 { "net-prohib", ICMP_UNREACH_NET_PROHIB },
544 { "host-prohib", ICMP_UNREACH_HOST_PROHIB },
545 { "tosnet", ICMP_UNREACH_TOSNET },
546 { "toshost", ICMP_UNREACH_TOSHOST },
547 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB },
548 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE },
549 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF },
554 fill_reject_code(u_short *codep, char *str)
559 val = strtoul(str, &s, 0);
560 if (s == str || *s != '\0' || val >= 0x100)
561 val = match_token(icmpcodes, str);
563 errx(EX_DATAERR, "unknown ICMP unreachable code ``%s''", str);
569 print_reject_code(u_int16_t code)
571 char *s = match_value(icmpcodes, code);
574 printf("unreach %s", s);
576 printf("unreach %u", code);
580 * Returns the number of bits set (from left) in a contiguous bitmask,
581 * or -1 if the mask is not contiguous.
582 * XXX this needs a proper fix.
583 * This effectively works on masks in big-endian (network) format.
584 * when compiled on little endian architectures.
586 * First bit is bit 7 of the first byte -- note, for MAC addresses,
587 * the first bit on the wire is bit 0 of the first byte.
588 * len is the max length in bits.
591 contigmask(u_char *p, int len)
594 for (i=0; i<len ; i++)
595 if ( (p[i/8] & (1 << (7 - (i%8)))) == 0) /* first bit unset */
597 for (n=i+1; n < len; n++)
598 if ( (p[n/8] & (1 << (7 - (n%8)))) != 0)
599 return -1; /* mask not contiguous */
604 * print flags set/clear in the two bitmasks passed as parameters.
605 * There is a specialized check for f_tcpflags.
608 print_flags(char *name, ipfw_insn *cmd, struct _s_x *list)
612 u_char set = cmd->arg1 & 0xff;
613 u_char clear = (cmd->arg1 >> 8) & 0xff;
615 if (list == f_tcpflags && set == TH_SYN && clear == TH_ACK) {
620 printf(" %s ", name);
621 for (i=0; list[i].x != 0; i++) {
622 if (set & list[i].x) {
624 printf("%s%s", comma, list[i].s);
627 if (clear & list[i].x) {
629 printf("%s!%s", comma, list[i].s);
636 * Print the ip address contained in a command.
639 print_ip(ipfw_insn_ip *cmd, char *s)
641 struct hostent *he = NULL;
644 printf("%s%s ", cmd->o.len & F_NOT ? " not": "", s);
646 if (cmd->o.opcode == O_IP_SRC_ME || cmd->o.opcode == O_IP_DST_ME) {
650 if (cmd->o.opcode == O_IP_SRC_SET || cmd->o.opcode == O_IP_DST_SET) {
657 cmd->addr.s_addr = htonl(cmd->addr.s_addr);
658 printf("%s/%d", inet_ntoa(cmd->addr),
659 contigmask((u_char *)&x, 32));
660 x = cmd->addr.s_addr = htonl(cmd->addr.s_addr);
661 x &= 0xff; /* base */
662 d = (u_int32_t *)&(cmd->mask);
663 for (i=0; i < cmd->o.arg1; i++)
664 if (d[ i/32] & (1<<(i & 31))) {
665 printf("%c%d", comma, i+x);
671 if (cmd->o.opcode == O_IP_SRC || cmd->o.opcode == O_IP_DST)
674 mb = contigmask((u_char *)&(cmd->mask.s_addr), 32);
675 if (mb == 32 && do_resolv)
676 he = gethostbyaddr(&(cmd->addr.s_addr), sizeof(u_long),
678 if (he != NULL) /* resolved to name */
679 printf("%s", he->h_name);
680 else if (mb == 0) /* any */
682 else { /* numeric IP followed by some kind of mask */
683 printf("%s", inet_ntoa(cmd->addr));
685 printf(":%s", inet_ntoa(cmd->mask));
692 * prints a MAC address/mask pair
695 print_mac(u_char *addr, u_char *mask)
697 int l = contigmask(mask, 48);
702 printf(" %02x:%02x:%02x:%02x:%02x:%02x",
703 addr[0], addr[1], addr[2], addr[3], addr[4], addr[5]);
705 printf("&%02x:%02x:%02x:%02x:%02x:%02x",
706 mask[0], mask[1], mask[2],
707 mask[3], mask[4], mask[5]);
714 fill_icmptypes(ipfw_insn_u32 *cmd, char *av)
723 type = strtoul(av, &av, 0);
725 if (*av != ',' && *av != '\0')
726 errx(EX_DATAERR, "invalid ICMP type");
729 errx(EX_DATAERR, "ICMP type out of range");
731 cmd->d[0] |= 1 << type;
733 cmd->o.opcode = O_ICMPTYPE;
734 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
738 print_icmptypes(ipfw_insn_u32 *cmd)
743 printf(" icmptypes");
744 for (i = 0; i < 32; i++) {
745 if ( (cmd->d[0] & (1 << (i))) == 0)
747 printf("%c%d", sep, i);
753 * show_ipfw() prints the body of an ipfw rule.
754 * Because the standard rule has at least proto src_ip dst_ip, we use
755 * a helper function to produce these entries if not provided explicitly.
756 * The first argument is the list of fields we have, the second is
757 * the list of fields we want to be printed.
759 * Special cases if we have provided a MAC header:
760 * + if the rule does not contain IP addresses/ports, do not print them;
761 * + if the rule does not contain an IP proto, print "all" instead of "ip";
763 * Once we have 'have_options', IP header fields are printed as options.
765 #define HAVE_PROTO 0x0001
766 #define HAVE_SRCIP 0x0002
767 #define HAVE_DSTIP 0x0004
768 #define HAVE_MAC 0x0008
769 #define HAVE_MACTYPE 0x0010
770 #define HAVE_OPTIONS 0x8000
772 #define HAVE_IP (HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP)
774 show_prerequisites(int *flags, int want, int cmd)
776 if ( (*flags & HAVE_IP) == HAVE_IP)
777 *flags |= HAVE_OPTIONS;
779 if ( (*flags & (HAVE_MAC|HAVE_MACTYPE|HAVE_OPTIONS)) == HAVE_MAC &&
782 * mac-type was optimized out by the compiler,
786 *flags |= HAVE_MACTYPE | HAVE_OPTIONS;
789 if ( !(*flags & HAVE_OPTIONS)) {
790 if ( !(*flags & HAVE_PROTO) && (want & HAVE_PROTO))
792 if ( !(*flags & HAVE_SRCIP) && (want & HAVE_SRCIP))
794 if ( !(*flags & HAVE_DSTIP) && (want & HAVE_DSTIP))
801 show_ipfw(struct ipfw_ioc_rule *rule, int pcwidth, int bcwidth)
803 static int twidth = 0;
806 int proto = 0; /* default */
807 int flags = 0; /* prerequisites */
808 ipfw_insn_log *logptr = NULL; /* set if we find an O_LOG */
809 int or_block = 0; /* we are in an or block */
811 u_int32_t set_disable = rule->set_disable;
813 if (set_disable & (1 << rule->set)) { /* disabled */
817 printf("# DISABLED ");
819 printf("%05u ", rule->rulenum);
822 printf("%*llu %*llu ", pcwidth, rule->pcnt, bcwidth,
829 strcpy(timestr, ctime((time_t *)&twidth));
830 *strchr(timestr, '\n') = '\0';
831 twidth = strlen(timestr);
833 if (rule->timestamp) {
834 #if _FreeBSD_version < 500000 /* XXX check */
835 #define _long_to_time(x) (time_t)(x)
837 time_t t = _long_to_time(rule->timestamp);
839 strcpy(timestr, ctime(&t));
840 *strchr(timestr, '\n') = '\0';
841 printf("%s ", timestr);
843 printf("%*s ", twidth, " ");
848 printf("set %d ", rule->set);
851 * print the optional "match probability"
853 if (rule->cmd_len > 0) {
855 if (cmd->opcode == O_PROB) {
856 ipfw_insn_u32 *p = (ipfw_insn_u32 *)cmd;
857 double d = 1.0 * p->d[0];
859 d = (d / 0x7fffffff);
860 printf("prob %f ", d);
865 * first print actions
867 for (l = rule->cmd_len - rule->act_ofs, cmd = ACTION_PTR(rule);
868 l > 0 ; l -= F_LEN(cmd), cmd += F_LEN(cmd)) {
869 switch(cmd->opcode) {
871 printf("check-state");
872 flags = HAVE_IP; /* avoid printing anything else */
888 if (cmd->arg1 == ICMP_REJECT_RST)
890 else if (cmd->arg1 == ICMP_UNREACH_HOST)
893 print_reject_code(cmd->arg1);
897 printf("skipto %u", cmd->arg1);
901 printf("pipe %u", cmd->arg1);
905 printf("queue %u", cmd->arg1);
909 printf("divert %u", cmd->arg1);
913 printf("tee %u", cmd->arg1);
918 ipfw_insn_sa *s = (ipfw_insn_sa *)cmd;
920 printf("fwd %s", inet_ntoa(s->sa.sin_addr));
922 printf(",%d", s->sa.sin_port);
926 case O_LOG: /* O_LOG is printed last */
927 logptr = (ipfw_insn_log *)cmd;
931 printf("** unrecognized action %d len %d",
932 cmd->opcode, cmd->len);
936 if (logptr->max_log > 0)
937 printf(" log logamount %d", logptr->max_log);
943 * then print the body.
945 if (rule->usr_flags & IPFW_USR_F_NORULE) {
946 /* empty rules before options */
948 printf(" ip from any to any");
949 flags |= HAVE_IP | HAVE_OPTIONS;
952 for (l = rule->act_ofs, cmd = rule->cmd ;
953 l > 0 ; l -= F_LEN(cmd) , cmd += F_LEN(cmd)) {
955 ipfw_insn_u32 *cmd32 = (ipfw_insn_u32 *)cmd;
957 show_prerequisites(&flags, 0, cmd->opcode);
959 switch(cmd->opcode) {
961 break; /* done already */
964 break; /* no need to print anything here */
967 ipfw_insn_mac *m = (ipfw_insn_mac *)cmd;
969 if ((cmd->len & F_OR) && !or_block)
971 if (cmd->len & F_NOT)
975 print_mac( m->addr, m->mask);
976 print_mac( m->addr + 6, m->mask + 6);
981 if ((cmd->len & F_OR) && !or_block)
983 print_newports((ipfw_insn_u16 *)cmd, IPPROTO_ETHERTYPE,
984 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
985 flags |= HAVE_MAC | HAVE_MACTYPE | HAVE_OPTIONS;
992 show_prerequisites(&flags, HAVE_PROTO, 0);
993 if (!(flags & HAVE_SRCIP))
995 if ((cmd->len & F_OR) && !or_block)
997 print_ip((ipfw_insn_ip *)cmd,
998 (flags & HAVE_OPTIONS) ? " src-ip" : "");
1006 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1007 if (!(flags & HAVE_DSTIP))
1009 if ((cmd->len & F_OR) && !or_block)
1011 print_ip((ipfw_insn_ip *)cmd,
1012 (flags & HAVE_OPTIONS) ? " dst-ip" : "");
1013 flags |= HAVE_DSTIP;
1017 show_prerequisites(&flags, HAVE_IP, 0);
1019 show_prerequisites(&flags, HAVE_PROTO|HAVE_SRCIP, 0);
1020 if ((cmd->len & F_OR) && !or_block)
1022 print_newports((ipfw_insn_u16 *)cmd, proto,
1023 (flags & HAVE_OPTIONS) ? cmd->opcode : 0);
1027 struct protoent *pe;
1029 if ((cmd->len & F_OR) && !or_block)
1031 if (cmd->len & F_NOT)
1034 pe = getprotobynumber(cmd->arg1);
1035 if (flags & HAVE_OPTIONS)
1038 printf(" %s", pe->p_name);
1040 printf(" %u", cmd->arg1);
1042 flags |= HAVE_PROTO;
1045 default: /*options ... */
1046 show_prerequisites(&flags, HAVE_IP | HAVE_OPTIONS, 0);
1047 if ((cmd->len & F_OR) && !or_block)
1049 if (cmd->len & F_NOT && cmd->opcode != O_IN)
1051 switch(cmd->opcode) {
1057 printf(cmd->len & F_NOT ? " out" : " in");
1067 ipfw_insn_if *cmdif = (ipfw_insn_if *)cmd;
1069 if (cmd->opcode == O_XMIT)
1071 else if (cmd->opcode == O_RECV)
1073 else if (cmd->opcode == O_VIA)
1077 if (cmdif->name[0] == '\0')
1079 inet_ntoa(cmdif->p.ip));
1080 printf(" %s %s", s, cmdif->name);
1085 printf(" ipid %u", cmd->arg1 );
1089 printf(" ipttl %u", cmd->arg1 );
1093 printf(" ipver %u", cmd->arg1 );
1096 case O_IPPRECEDENCE:
1097 printf(" ipprecedence %u", (cmd->arg1) >> 5 );
1101 printf(" iplen %u", cmd->arg1 );
1105 print_flags("ipoptions", cmd, f_ipopts);
1109 print_flags("iptos", cmd, f_iptos);
1113 print_icmptypes((ipfw_insn_u32 *)cmd);
1117 printf(" established");
1121 print_flags("tcpflags", cmd, f_tcpflags);
1125 print_flags("tcpoptions", cmd, f_tcpopts);
1129 printf(" tcpwin %d", ntohs(cmd->arg1));
1133 printf(" tcpack %ld", ntohl(cmd32->d[0]));
1137 printf(" tcpseq %ld", ntohl(cmd32->d[0]));
1142 struct passwd *pwd = getpwuid(cmd32->d[0]);
1145 printf(" uid %s", pwd->pw_name);
1147 printf(" uid %u", cmd32->d[0]);
1153 struct group *grp = getgrgid(cmd32->d[0]);
1156 printf(" gid %s", grp->gr_name);
1158 printf(" gid %u", cmd32->d[0]);
1163 printf(" keep-state");
1168 struct _s_x *p = limit_masks;
1169 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
1170 u_int8_t x = c->limit_mask;
1174 for ( ; p->x != 0 ; p++)
1175 if ((x & p->x) == p->x) {
1177 printf("%s%s", comma, p->s);
1180 printf(" %d", c->conn_limit);
1185 printf(" [opcode %d len %d]",
1186 cmd->opcode, cmd->len);
1189 if (cmd->len & F_OR) {
1192 } else if (or_block) {
1197 show_prerequisites(&flags, HAVE_IP, 0);
1203 show_dyn_ipfw(struct ipfw_ioc_state *d, int pcwidth, int bcwidth)
1205 struct protoent *pe;
1209 if (!d->expire && !(d->dyn_type == O_LIMIT_PARENT))
1213 printf("%05u %*llu %*llu (%ds)", d->rulenum, pcwidth, d->pcnt,
1214 bcwidth, d->bcnt, d->expire);
1215 switch (d->dyn_type) {
1216 case O_LIMIT_PARENT:
1217 printf(" PARENT %d", d->count);
1222 case O_KEEP_STATE: /* bidir, no mask */
1227 if ((pe = getprotobynumber(d->id.u.ip.proto)) != NULL)
1228 printf(" %s", pe->p_name);
1230 printf(" proto %u", d->id.u.ip.proto);
1232 a.s_addr = htonl(d->id.u.ip.src_ip);
1233 printf(" %s %d", inet_ntoa(a), d->id.u.ip.src_port);
1235 a.s_addr = htonl(d->id.u.ip.dst_ip);
1236 printf(" <-> %s %d", inet_ntoa(a), d->id.u.ip.dst_port);
1241 sort_q(const void *pa, const void *pb)
1243 int rev = (do_sort < 0);
1244 int field = rev ? -do_sort : do_sort;
1246 const struct dn_ioc_flowqueue *a = pa;
1247 const struct dn_ioc_flowqueue *b = pb;
1251 res = a->len - b->len;
1254 res = a->len_bytes - b->len_bytes;
1257 case 3: /* tot pkts */
1258 res = a->tot_pkts - b->tot_pkts;
1261 case 4: /* tot bytes */
1262 res = a->tot_bytes - b->tot_bytes;
1269 return (int)(rev ? res : -res);
1273 list_queues(struct dn_ioc_flowset *fs, struct dn_ioc_flowqueue *q)
1277 printf(" mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
1278 fs->flow_mask.u.ip.proto,
1279 fs->flow_mask.u.ip.src_ip, fs->flow_mask.u.ip.src_port,
1280 fs->flow_mask.u.ip.dst_ip, fs->flow_mask.u.ip.dst_port);
1281 if (fs->rq_elements == 0)
1284 printf("BKT Prot ___Source IP/port____ "
1285 "____Dest. IP/port____ Tot_pkt/bytes Pkt/Byte Drp\n");
1287 heapsort(q, fs->rq_elements, sizeof(*q), sort_q);
1288 for (l = 0; l < fs->rq_elements; l++) {
1290 struct protoent *pe;
1292 ina.s_addr = htonl(q[l].id.u.ip.src_ip);
1293 printf("%3d ", q[l].hash_slot);
1294 pe = getprotobynumber(q[l].id.u.ip.proto);
1296 printf("%-4s ", pe->p_name);
1298 printf("%4u ", q[l].id.u.ip.proto);
1299 printf("%15s/%-5d ",
1300 inet_ntoa(ina), q[l].id.u.ip.src_port);
1301 ina.s_addr = htonl(q[l].id.u.ip.dst_ip);
1302 printf("%15s/%-5d ",
1303 inet_ntoa(ina), q[l].id.u.ip.dst_port);
1304 printf("%4qu %8qu %2u %4u %3u\n",
1305 q[l].tot_pkts, q[l].tot_bytes,
1306 q[l].len, q[l].len_bytes, q[l].drops);
1308 printf(" S %20qd F %20qd\n",
1314 print_flowset_parms(struct dn_ioc_flowset *fs, char *prefix)
1319 char red[90]; /* Display RED parameters */
1322 if (fs->flags_fs & DN_QSIZE_IS_BYTES) {
1324 sprintf(qs, "%d KB", l / 1024);
1326 sprintf(qs, "%d B", l);
1328 sprintf(qs, "%3d sl.", l);
1330 sprintf(plr, "plr %f", 1.0 * fs->plr / (double)(0x7fffffff));
1333 if (fs->flags_fs & DN_IS_RED) /* RED parameters */
1335 "\n\t %cRED w_q %f min_th %d max_th %d max_p %f",
1336 (fs->flags_fs & DN_IS_GENTLE_RED) ? 'G' : ' ',
1337 1.0 * fs->w_q / (double)(1 << SCALE_RED),
1338 SCALE_VAL(fs->min_th),
1339 SCALE_VAL(fs->max_th),
1340 1.0 * fs->max_p / (double)(1 << SCALE_RED));
1342 sprintf(red, "droptail");
1344 printf("%s %s%s %d queues (%d buckets) %s\n",
1345 prefix, qs, plr, fs->rq_elements, fs->rq_size, red);
1349 list_pipes(void *data, int nbytes, int ac, char *av[])
1353 struct dn_ioc_pipe *p = (struct dn_ioc_pipe *)data;
1354 struct dn_ioc_flowset *fs;
1355 struct dn_ioc_flowqueue *q;
1359 rulenum = strtoul(*av++, NULL, 10);
1362 for (; nbytes >= sizeof(*p); p = (struct dn_ioc_pipe *)next) {
1363 double b = p->bandwidth;
1367 if (p->fs.fs_type != DN_IS_PIPE)
1368 break; /* done with pipes, now queues */
1371 * compute length, as pipe have variable size
1373 l = sizeof(*p) + p->fs.rq_elements * sizeof(*q);
1374 next = (void *)p + l;
1377 if (rulenum != 0 && rulenum != p->pipe_nr)
1384 sprintf(buf, "unlimited");
1385 else if (b >= 1000000)
1386 sprintf(buf, "%7.3f Mbit/s", b/1000000);
1388 sprintf(buf, "%7.3f Kbit/s", b/1000);
1390 sprintf(buf, "%7.3f bit/s ", b);
1392 sprintf(prefix, "%05d: %s %4d ms ",
1393 p->pipe_nr, buf, p->delay);
1394 print_flowset_parms(&p->fs, prefix);
1396 printf(" V %20qd\n", p->V >> MY_M);
1398 q = (struct dn_ioc_flowqueue *)(p+1);
1399 list_queues(&p->fs, q);
1401 for (fs = next; nbytes >= sizeof(*fs); fs = next) {
1404 if (fs->fs_type != DN_IS_QUEUE)
1406 l = sizeof(*fs) + fs->rq_elements * sizeof(*q);
1407 next = (void *)fs + l;
1409 q = (struct dn_ioc_flowqueue *)(fs+1);
1410 sprintf(prefix, "q%05d: weight %d pipe %d ",
1411 fs->fs_nr, fs->weight, fs->parent_nr);
1412 print_flowset_parms(fs, prefix);
1418 * This one handles all set-related commands
1419 * ipfw set { show | enable | disable }
1421 * ipfw set move X to Y
1422 * ipfw set move rule X to Y
1425 sets_handler(int ac, char *av[])
1427 u_int32_t set_disable, masks[2];
1430 u_int8_t cmd, new_set;
1436 errx(EX_USAGE, "set needs command");
1437 if (!strncmp(*av, "show", strlen(*av)) ) {
1441 nbytes = sizeof(struct ipfw_ioc_rule);
1442 if ((data = malloc(nbytes)) == NULL)
1443 err(EX_OSERR, "malloc");
1444 if (getsockopt(s, IPPROTO_IP, IP_FW_GET, data, &nbytes) < 0)
1445 err(EX_OSERR, "getsockopt(IP_FW_GET)");
1446 set_disable = ((struct ipfw_ioc_rule *)data)->set_disable;
1448 for (i = 0, msg = "disable" ; i < 31; i++)
1449 if ( (set_disable & (1<<i))) {
1450 printf("%s %d", msg, i);
1453 msg = (set_disable) ? " enable" : "enable";
1454 for (i = 0; i < 31; i++)
1455 if ( !(set_disable & (1<<i))) {
1456 printf("%s %d", msg, i);
1460 } else if (!strncmp(*av, "swap", strlen(*av))) {
1463 errx(EX_USAGE, "set swap needs 2 set numbers\n");
1464 rulenum = atoi(av[0]);
1465 new_set = atoi(av[1]);
1466 if (!isdigit(*(av[0])) || rulenum > 30)
1467 errx(EX_DATAERR, "invalid set number %s\n", av[0]);
1468 if (!isdigit(*(av[1])) || new_set > 30)
1469 errx(EX_DATAERR, "invalid set number %s\n", av[1]);
1470 masks[0] = (4 << 24) | (new_set << 16) | (rulenum);
1471 i = setsockopt(s, IPPROTO_IP, IP_FW_DEL,
1472 masks, sizeof(u_int32_t));
1473 } else if (!strncmp(*av, "move", strlen(*av))) {
1475 if (ac && !strncmp(*av, "rule", strlen(*av))) {
1480 if (ac != 3 || strncmp(av[1], "to", strlen(*av)))
1481 errx(EX_USAGE, "syntax: set move [rule] X to Y\n");
1482 rulenum = atoi(av[0]);
1483 new_set = atoi(av[2]);
1484 if (!isdigit(*(av[0])) || (cmd == 3 && rulenum > 30) ||
1485 (cmd == 2 && rulenum == 65535) )
1486 errx(EX_DATAERR, "invalid source number %s\n", av[0]);
1487 if (!isdigit(*(av[2])) || new_set > 30)
1488 errx(EX_DATAERR, "invalid dest. set %s\n", av[1]);
1489 masks[0] = (cmd << 24) | (new_set << 16) | (rulenum);
1490 i = setsockopt(s, IPPROTO_IP, IP_FW_DEL,
1491 masks, sizeof(u_int32_t));
1492 } else if (!strncmp(*av, "disable", strlen(*av)) ||
1493 !strncmp(*av, "enable", strlen(*av)) ) {
1494 int which = !strncmp(*av, "enable", strlen(*av)) ? 1 : 0;
1497 masks[0] = masks[1] = 0;
1500 if (isdigit(**av)) {
1502 if (i < 0 || i > 30)
1504 "invalid set number %d\n", i);
1505 masks[which] |= (1<<i);
1506 } else if (!strncmp(*av, "disable", strlen(*av)))
1508 else if (!strncmp(*av, "enable", strlen(*av)))
1512 "invalid set command %s\n", *av);
1515 if ( (masks[0] & masks[1]) != 0 )
1517 "cannot enable and disable the same set\n");
1519 i = setsockopt(s, IPPROTO_IP, IP_FW_DEL, masks, sizeof(masks));
1521 warn("set enable/disable: setsockopt(IP_FW_DEL)");
1523 errx(EX_USAGE, "invalid set command %s\n", *av);
1527 sysctl_handler(int ac, char *av[], int which)
1533 warnx("missing keyword to enable/disable\n");
1534 } else if (strncmp(*av, "firewall", strlen(*av)) == 0) {
1535 sysctlbyname("net.inet.ip.fw.enable", NULL, 0,
1536 &which, sizeof(which));
1537 } else if (strncmp(*av, "one_pass", strlen(*av)) == 0) {
1538 sysctlbyname("net.inet.ip.fw.one_pass", NULL, 0,
1539 &which, sizeof(which));
1540 } else if (strncmp(*av, "debug", strlen(*av)) == 0) {
1541 sysctlbyname("net.inet.ip.fw.debug", NULL, 0,
1542 &which, sizeof(which));
1543 } else if (strncmp(*av, "verbose", strlen(*av)) == 0) {
1544 sysctlbyname("net.inet.ip.fw.verbose", NULL, 0,
1545 &which, sizeof(which));
1546 } else if (strncmp(*av, "dyn_keepalive", strlen(*av)) == 0) {
1547 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL, 0,
1548 &which, sizeof(which));
1550 warnx("unrecognize enable/disable keyword: %s\n", *av);
1555 list(int ac, char *av[])
1557 struct ipfw_ioc_rule *r;
1558 struct ipfw_ioc_state *dynrules, *d;
1561 int bcwidth, n, nbytes, nstat, ndyn, pcwidth, width;
1562 int exitval = EX_OK;
1569 const int ocmd = do_pipe ? IP_DUMMYNET_GET : IP_FW_GET;
1570 int nalloc = 1024; /* start somewhere... */
1575 /* get rules or pipes from kernel, resizing array as necessary */
1578 while (nbytes >= nalloc) {
1579 nalloc = nalloc * 2 + 200;
1581 if ((data = realloc(data, nbytes)) == NULL)
1582 err(EX_OSERR, "realloc");
1583 if (getsockopt(s, IPPROTO_IP, ocmd, data, &nbytes) < 0)
1584 err(EX_OSERR, "getsockopt(IP_%s_GET)",
1585 do_pipe ? "DUMMYNET" : "FW");
1589 list_pipes(data, nbytes, ac, av);
1594 * Count static rules.
1597 nstat = r->static_count;
1600 * Count dynamic rules. This is easier as they have
1603 dynrules = (struct ipfw_ioc_state *)((void *)r + r->static_len);
1604 ndyn = (nbytes - r->static_len) / sizeof(*dynrules);
1606 /* if showing stats, figure out column widths ahead of time */
1607 bcwidth = pcwidth = 0;
1609 for (n = 0, r = data; n < nstat;
1610 n++, r = (void *)r + IOC_RULESIZE(r)) {
1611 /* packet counter */
1612 width = snprintf(NULL, 0, "%llu", r->pcnt);
1613 if (width > pcwidth)
1617 width = snprintf(NULL, 0, "%llu", r->bcnt);
1618 if (width > bcwidth)
1622 if (do_dynamic && ndyn) {
1623 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1624 width = snprintf(NULL, 0, "%llu", d->pcnt);
1625 if (width > pcwidth)
1628 width = snprintf(NULL, 0, "%llu", d->bcnt);
1629 if (width > bcwidth)
1633 /* if no rule numbers were specified, list all rules */
1635 for (n = 0, r = data; n < nstat;
1636 n++, r = (void *)r + IOC_RULESIZE(r) )
1637 show_ipfw(r, pcwidth, bcwidth);
1639 if (do_dynamic && ndyn) {
1640 printf("## Dynamic rules (%d):\n", ndyn);
1641 for (n = 0, d = dynrules; n < ndyn; n++, d++)
1642 show_dyn_ipfw(d, pcwidth, bcwidth);
1647 /* display specific rules requested on command line */
1649 for (lac = ac, lav = av; lac != 0; lac--) {
1650 /* convert command line rule # */
1651 rnum = strtoul(*lav++, &endptr, 10);
1654 warnx("invalid rule number: %s", *(lav - 1));
1657 for (n = seen = 0, r = data; n < nstat;
1658 n++, r = (void *)r + IOC_RULESIZE(r) ) {
1659 if (r->rulenum > rnum)
1661 if (r->rulenum == rnum) {
1662 show_ipfw(r, pcwidth, bcwidth);
1667 /* give precedence to other error(s) */
1668 if (exitval == EX_OK)
1669 exitval = EX_UNAVAILABLE;
1670 warnx("rule %lu does not exist", rnum);
1674 if (do_dynamic && ndyn) {
1675 printf("## Dynamic rules:\n");
1676 for (lac = ac, lav = av; lac != 0; lac--) {
1677 rnum = strtoul(*lav++, &endptr, 10);
1679 /* already warned */
1681 for (n = 0, d = dynrules; n < ndyn; n++, d++) {
1682 if (d->rulenum > rnum)
1684 if (d->rulenum == rnum)
1685 show_dyn_ipfw(d, pcwidth, bcwidth);
1695 if (exitval != EX_OK)
1702 fprintf(stderr, "usage: ipfw [options]\n"
1703 " add [number] rule\n"
1704 " pipe number config [pipeconfig]\n"
1705 " queue number config [queueconfig]\n"
1707 " [pipe] delete number ...\n"
1708 " [pipe] {list|show} [number ...]\n"
1709 " {zero|resetlog} [number ...]\n"
1710 "do \"ipfw -h\" or see ipfw manpage for details\n"
1720 fprintf(stderr, "ipfw syntax summary:\n"
1721 "ipfw add [N] [prob {0..1}] ACTION [log [logamount N]] ADDR OPTIONS\n"
1722 "ipfw {pipe|queue} N config BODY\n"
1723 "ipfw [pipe] {zero|delete|show} [N{,N}]\n"
1725 "RULE: [1..] [PROB] BODY\n"
1726 "RULENUM: INTEGER(1..65534)\n"
1727 "PROB: prob REAL(0..1)\n"
1728 "BODY: check-state [LOG] (no body) |\n"
1729 " ACTION [LOG] MATCH_ADDR [OPTION_LIST]\n"
1730 "ACTION: check-state | allow | count | deny | reject | skipto N |\n"
1731 " {divert|tee} PORT | forward ADDR | pipe N | queue N\n"
1732 "ADDR: [ MAC dst src ether_type ] \n"
1733 " [ from IPLIST [ PORT ] to IPLIST [ PORTLIST ] ]\n"
1734 "IPLIST: IPADDR | ( IPADDR or ... or IPADDR )\n"
1735 "IPADDR: [not] { any | me | ip | ip/bits | ip:mask | ip/bits{x,y,z} }\n"
1736 "OPTION_LIST: OPTION [,OPTION_LIST]\n"
1743 lookup_host (char *host, struct in_addr *ipaddr)
1747 if (!inet_aton(host, ipaddr)) {
1748 if ((he = gethostbyname(host)) == NULL)
1750 *ipaddr = *(struct in_addr *)he->h_addr_list[0];
1756 * fills the addr and mask fields in the instruction as appropriate from av.
1757 * Update length as appropriate.
1758 * The following formats are allowed:
1759 * any matches any IP. Actually returns an empty instruction.
1760 * me returns O_IP_*_ME
1761 * 1.2.3.4 single IP address
1762 * 1.2.3.4:5.6.7.8 address:mask
1763 * 1.2.3.4/24 address/mask
1764 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
1767 fill_ip(ipfw_insn_ip *cmd, char *av)
1769 char *p = NULL, md = 0;
1772 cmd->o.len &= ~F_LEN_MASK; /* zero len */
1774 if (!strncmp(av, "any", strlen(av)))
1777 if (!strncmp(av, "me", strlen(av))) {
1778 cmd->o.len |= F_INSN_SIZE(ipfw_insn);
1782 p = strchr(av, '/');
1784 p = strchr(av, ':');
1790 if (lookup_host(av, &cmd->addr) != 0)
1791 errx(EX_NOHOST, "hostname ``%s'' unknown", av);
1794 if (!inet_aton(p, &cmd->mask))
1795 errx(EX_DATAERR, "bad netmask ``%s''", p);
1800 cmd->mask.s_addr = htonl(0);
1802 errx(EX_DATAERR, "bad width ``%s''", p);
1804 cmd->mask.s_addr = htonl(~0 << (32 - i));
1807 cmd->mask.s_addr = htonl(~0);
1810 cmd->addr.s_addr &= cmd->mask.s_addr;
1812 * now look if we have a set of addresses. They are stored as follows:
1813 * arg1 is the set size (powers of 2, 2..256)
1814 * addr is the base address IN HOST FORMAT
1815 * mask.. is an array of u_int32_t with bits set.
1819 if (p) { /* fetch addresses */
1822 int i = contigmask((u_char *)&(cmd->mask), 32);
1824 if (i < 24 || i > 31) {
1825 fprintf(stderr, "invalid set with mask %d\n",
1829 cmd->o.arg1 = 1<<(32-i);
1830 cmd->addr.s_addr = ntohl(cmd->addr.s_addr);
1831 d = (u_int32_t *)&cmd->mask;
1832 cmd->o.opcode = O_IP_DST_SET; /* default */
1833 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32) + (cmd->o.arg1+31)/32;
1834 for (i = 0; i < (cmd->o.arg1+31)/32 ; i++)
1835 d[i] = 0; /* clear masks */
1838 low = cmd->addr.s_addr & 0xff;
1839 high = low + cmd->o.arg1 - 1;
1840 while (isdigit(*av)) {
1842 u_int16_t a = strtol(av, &s, 0);
1844 if (s == av) /* no parameter */
1846 if (a < low || a > high) {
1847 fprintf(stderr, "addr %d out of range [%d-%d]\n",
1852 d[ a/32] |= 1<<(a & 31);
1860 if (cmd->mask.s_addr == 0) { /* any */
1861 if (cmd->o.len & F_NOT)
1862 errx(EX_DATAERR, "not any never matches");
1863 else /* useless, nuke it */
1865 } else if (cmd->mask.s_addr == IP_MASK_ALL) /* one IP */
1866 cmd->o.len |= F_INSN_SIZE(ipfw_insn_u32);
1867 else /* addr/mask */
1868 cmd->o.len |= F_INSN_SIZE(ipfw_insn_ip);
1873 * helper function to process a set of flags and set bits in the
1874 * appropriate masks.
1877 fill_flags(ipfw_insn *cmd, enum ipfw_opcodes opcode,
1878 struct _s_x *flags, char *p)
1880 u_int8_t set=0, clear=0;
1883 char *q; /* points to the separator */
1885 u_int8_t *which; /* mask we are working on */
1895 val = match_token(flags, p);
1897 errx(EX_DATAERR, "invalid flag %s", p);
1898 *which |= (u_int8_t)val;
1901 cmd->opcode = opcode;
1902 cmd->len = (cmd->len & (F_NOT | F_OR)) | 1;
1903 cmd->arg1 = (set & 0xff) | ( (clear & 0xff) << 8);
1908 delete(int ac, char *av[])
1911 struct dn_ioc_pipe pipe;
1913 int exitval = EX_OK;
1916 memset(&pipe, 0, sizeof pipe);
1919 if (ac > 0 && !strncmp(*av, "set", strlen(*av))) {
1920 do_set = 1; /* delete set */
1925 while (ac && isdigit(**av)) {
1926 i = atoi(*av); av++; ac--;
1932 i = setsockopt(s, IPPROTO_IP, IP_DUMMYNET_DEL,
1933 &pipe, sizeof pipe);
1936 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)",
1937 do_pipe == 1 ? pipe.pipe_nr :
1941 rulenum = (i & 0xffff) | (do_set << 24);
1942 i = setsockopt(s, IPPROTO_IP, IP_FW_DEL, &rulenum,
1945 exitval = EX_UNAVAILABLE;
1946 warn("rule %u: setsockopt(IP_FW_DEL)",
1951 if (exitval != EX_OK)
1957 * fill the interface structure. We do not check the name as we can
1958 * create interfaces dynamically, so checking them at insert time
1959 * makes relatively little sense.
1960 * Interface names containing '*', '?', or '[' are assumed to be shell
1961 * patterns which match interfaces.
1964 fill_iface(ipfw_insn_if *cmd, char *arg)
1966 cmd->name[0] = '\0';
1967 cmd->o.len |= F_INSN_SIZE(ipfw_insn_if);
1969 /* Parse the interface or address */
1970 if (!strcmp(arg, "any"))
1971 cmd->o.len = 0; /* effectively ignore this command */
1972 else if (!isdigit(*arg)) {
1973 strlcpy(cmd->name, arg, sizeof(cmd->name));
1974 cmd->p.glob = strpbrk(arg, "*?[") != NULL ? 1 : 0;
1975 } else if (!inet_aton(arg, &cmd->p.ip))
1976 errx(EX_DATAERR, "bad ip address ``%s''", arg);
1979 static unsigned long
1980 getbw(const char *str, u_short *flags, int kb)
1986 val = strtoul(str, &end, 0);
1987 if (*end == 'k' || *end == 'K') {
1990 } else if (*end == 'm' || *end == 'M') {
1996 * Deal with bits or bytes or b(bits) or B(bytes). If there is no
1997 * trailer assume bits.
1999 if (strncasecmp(end, "bit", 3) == 0) {
2001 } else if (strncasecmp(end, "byte", 4) == 0) {
2003 } else if (*end == 'b') {
2005 } else if (*end == 'B') {
2010 * Return in bits if flags is NULL, else flag bits
2011 * or bytes in flags and return the unconverted value.
2013 if (inbytes && flags)
2014 *flags |= DN_QSIZE_IS_BYTES;
2015 else if (inbytes && flags == NULL)
2021 * the following macro returns an error message if we run out of
2024 #define NEED1(msg) {if (!ac) errx(EX_USAGE, msg);}
2027 config_pipe(int ac, char **av)
2029 struct dn_ioc_pipe pipe;
2035 memset(&pipe, 0, sizeof pipe);
2039 if (ac && isdigit(**av)) {
2040 i = atoi(*av); av++; ac--;
2048 int tok = match_token(dummynet_params, *av);
2053 pipe.fs.flags_fs |= DN_NOERROR;
2057 NEED1("plr needs argument 0..1\n");
2058 d = strtod(av[0], NULL);
2063 pipe.fs.plr = (int)(d*0x7fffffff);
2068 NEED1("queue needs queue size\n");
2070 pipe.fs.qsize = getbw(av[0], &pipe.fs.flags_fs, 1024);
2075 NEED1("buckets needs argument\n");
2076 pipe.fs.rq_size = strtoul(av[0], NULL, 0);
2081 NEED1("mask needs mask specifier\n");
2083 * per-flow queue, mask is dst_ip, dst_port,
2084 * src_ip, src_port, proto measured in bits
2088 pipe.fs.flow_mask.type = ETHERTYPE_IP;
2089 pipe.fs.flow_mask.u.ip.dst_ip = 0;
2090 pipe.fs.flow_mask.u.ip.src_ip = 0;
2091 pipe.fs.flow_mask.u.ip.dst_port = 0;
2092 pipe.fs.flow_mask.u.ip.src_port = 0;
2093 pipe.fs.flow_mask.u.ip.proto = 0;
2097 u_int32_t *p32 = NULL;
2098 u_int16_t *p16 = NULL;
2100 tok = match_token(dummynet_params, *av);
2105 * special case, all bits significant
2107 pipe.fs.flow_mask.u.ip.dst_ip = ~0;
2108 pipe.fs.flow_mask.u.ip.src_ip = ~0;
2109 pipe.fs.flow_mask.u.ip.dst_port = ~0;
2110 pipe.fs.flow_mask.u.ip.src_port = ~0;
2111 pipe.fs.flow_mask.u.ip.proto = ~0;
2112 pipe.fs.flags_fs |= DN_HAVE_FLOW_MASK;
2116 p32 = &pipe.fs.flow_mask.u.ip.dst_ip;
2120 p32 = &pipe.fs.flow_mask.u.ip.src_ip;
2124 p16 = &pipe.fs.flow_mask.u.ip.dst_port;
2128 p16 = &pipe.fs.flow_mask.u.ip.src_port;
2135 ac++; av--; /* backtrack */
2139 errx(EX_USAGE, "mask: value missing");
2140 if (*av[0] == '/') {
2141 a = strtoul(av[0]+1, &end, 0);
2142 a = (a == 32) ? ~0 : (1 << a) - 1;
2144 a = strtoul(av[0], &end, 0);
2147 else if (p16 != NULL) {
2150 "mask: must be 16 bit");
2151 *p16 = (u_int16_t)a;
2155 "mask: must be 8 bit");
2156 pipe.fs.flow_mask.u.ip.proto = (uint8_t)a;
2159 pipe.fs.flags_fs |= DN_HAVE_FLOW_MASK;
2161 } /* end while, config masks */
2167 NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
2168 pipe.fs.flags_fs |= DN_IS_RED;
2169 if (tok == TOK_GRED)
2170 pipe.fs.flags_fs |= DN_IS_GENTLE_RED;
2172 * the format for parameters is w_q/min_th/max_th/max_p
2174 if ((end = strsep(&av[0], "/"))) {
2175 double w_q = strtod(end, NULL);
2176 if (w_q > 1 || w_q <= 0)
2177 errx(EX_DATAERR, "0 < w_q <= 1");
2178 pipe.fs.w_q = (int) (w_q * (1 << SCALE_RED));
2180 if ((end = strsep(&av[0], "/"))) {
2181 pipe.fs.min_th = strtoul(end, &end, 0);
2182 if (*end == 'K' || *end == 'k')
2183 pipe.fs.min_th *= 1024;
2185 if ((end = strsep(&av[0], "/"))) {
2186 pipe.fs.max_th = strtoul(end, &end, 0);
2187 if (*end == 'K' || *end == 'k')
2188 pipe.fs.max_th *= 1024;
2190 if ((end = strsep(&av[0], "/"))) {
2191 double max_p = strtod(end, NULL);
2192 if (max_p > 1 || max_p <= 0)
2193 errx(EX_DATAERR, "0 < max_p <= 1");
2194 pipe.fs.max_p = (int)(max_p * (1 << SCALE_RED));
2200 pipe.fs.flags_fs &= ~(DN_IS_RED|DN_IS_GENTLE_RED);
2204 NEED1("bw needs bandwidth\n");
2206 errx(EX_DATAERR, "bandwidth only valid for pipes");
2208 * set bandwidth value
2210 pipe.bandwidth = getbw(av[0], NULL, 1000);
2211 if (pipe.bandwidth < 0)
2212 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;
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(clock_hz);
2297 if (sysctlbyname("net.inet.ip.dummynet.hz", &clock_hz, &len,
2299 errx(1, "sysctlbyname(\"%s\")",
2300 "net.inet.ip.dummynet.hz");
2304 * Ticks needed for sending a medium-sized packet.
2305 * Unfortunately, when we are configuring a WF2Q+ queue, we
2306 * do not have bandwidth information, because that is stored
2307 * in the parent pipe, and also we have multiple queues
2308 * competing for it. So we set s=0, which is not very
2309 * correct. But on the other hand, why do we want RED with
2312 if (pipe.bandwidth==0) /* this is a WF2Q+ queue */
2315 s = clock_hz * avg_pkt_size * 8 / pipe.bandwidth;
2318 * max idle time (in ticks) before avg queue size becomes 0.
2319 * NOTA: (3/w_q) is approx the value x so that
2320 * (1-w_q)^x < 10^-3.
2322 w_q = ((double)pipe.fs.w_q) / (1 << SCALE_RED);
2323 idle = s * 3. / w_q;
2324 pipe.fs.lookup_step = (int)idle / lookup_depth;
2325 if (!pipe.fs.lookup_step)
2326 pipe.fs.lookup_step = 1;
2328 for (t = pipe.fs.lookup_step; t > 0; --t)
2330 pipe.fs.lookup_weight = (int)(weight * (1 << SCALE_RED));
2332 i = setsockopt(s, IPPROTO_IP, IP_DUMMYNET_CONFIGURE, &pipe,
2335 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
2339 get_mac_addr_mask(char *p, u_char *addr, u_char *mask)
2344 addr[i] = mask[i] = 0;
2345 if (!strcmp(p, "any"))
2348 for (i=0; *p && i<6;i++, p++) {
2349 addr[i] = strtol(p, &p, 16);
2350 if (*p != ':') /* we start with the mask */
2353 if (*p == '/') { /* mask len */
2354 l = strtol(p+1, &p, 0);
2355 for (i=0; l>0; l -=8, i++)
2356 mask[i] = (l >=8) ? 0xff : (~0) << (8-l);
2357 } else if (*p == '&') { /* mask */
2358 for (i=0, p++; *p && i<6;i++, p++) {
2359 mask[i] = strtol(p, &p, 16);
2363 } else if (*p == '\0') {
2372 * helper function, updates the pointer to cmd with the length
2373 * of the current command, and also cleans up the first word of
2374 * the new command in case it has been clobbered before.
2377 next_cmd(ipfw_insn *cmd)
2380 bzero(cmd, sizeof(*cmd));
2385 * A function to fill simple commands of size 1.
2386 * Existing flags are preserved.
2389 fill_cmd(ipfw_insn *cmd, enum ipfw_opcodes opcode, int flags, u_int16_t arg)
2391 cmd->opcode = opcode;
2392 cmd->len = ((cmd->len | flags) & (F_NOT | F_OR)) | 1;
2397 * Fetch and add the MAC address and type, with masks. This generates one or
2398 * two microinstructions, and returns the pointer to the last one.
2401 add_mac(ipfw_insn *cmd, int ac, char *av[])
2406 errx(EX_DATAERR, "MAC dst src");
2408 cmd->opcode = O_MACADDR2;
2409 cmd->len = (cmd->len & (F_NOT | F_OR)) | F_INSN_SIZE(ipfw_insn_mac);
2411 mac = (ipfw_insn_mac *)cmd;
2412 get_mac_addr_mask(av[0], mac->addr, mac->mask); /* dst */
2413 get_mac_addr_mask(av[1], &(mac->addr[6]), &(mac->mask[6])); /* src */
2418 add_mactype(ipfw_insn *cmd, int ac, char *av)
2421 errx(EX_DATAERR, "missing MAC type");
2422 if (strcmp(av, "any") != 0) { /* we have a non-null type */
2423 fill_newports((ipfw_insn_u16 *)cmd, av, IPPROTO_ETHERTYPE);
2424 cmd->opcode = O_MAC_TYPE;
2431 add_proto(ipfw_insn *cmd, char *av)
2433 struct protoent *pe;
2436 if (!strncmp(av, "all", strlen(av)))
2437 ; /* same as "ip" */
2438 else if ((proto = atoi(av)) > 0)
2440 else if ((pe = getprotobyname(av)) != NULL)
2441 proto = pe->p_proto;
2444 if (proto != IPPROTO_IP)
2445 fill_cmd(cmd, O_PROTO, 0, proto);
2450 add_srcip(ipfw_insn *cmd, char *av)
2452 fill_ip((ipfw_insn_ip *)cmd, av);
2453 if (cmd->opcode == O_IP_DST_SET) /* set */
2454 cmd->opcode = O_IP_SRC_SET;
2455 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2456 cmd->opcode = O_IP_SRC_ME;
2457 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2458 cmd->opcode = O_IP_SRC;
2459 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_ip)) /* addr/mask */
2460 cmd->opcode = O_IP_SRC_MASK;
2465 add_dstip(ipfw_insn *cmd, char *av)
2467 fill_ip((ipfw_insn_ip *)cmd, av);
2468 if (cmd->opcode == O_IP_DST_SET) /* set */
2470 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn)) /* me */
2471 cmd->opcode = O_IP_DST_ME;
2472 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_u32)) /* one IP */
2473 cmd->opcode = O_IP_DST;
2474 else if (F_LEN(cmd) == F_INSN_SIZE(ipfw_insn_ip)) /* addr/mask */
2475 cmd->opcode = O_IP_DST_MASK;
2480 add_ports(ipfw_insn *cmd, char *av, u_char proto, int opcode)
2482 if (!strncmp(av, "any", strlen(av))) {
2484 } else if (fill_newports((ipfw_insn_u16 *)cmd, av, proto)) {
2485 /* XXX todo: check that we have a protocol with ports */
2486 cmd->opcode = opcode;
2493 * Parse arguments and assemble the microinstructions which make up a rule.
2494 * Rules are added into the 'rulebuf' and then copied in the correct order
2495 * into the actual rule.
2497 * The syntax for a rule starts with the action, followed by an
2498 * optional log action, and the various match patterns.
2499 * In the assembled microcode, the first opcode must be a O_PROBE_STATE
2500 * (generated if the rule includes a keep-state option), then the
2501 * various match patterns, the "log" action, and the actual action.
2505 add(int ac, char *av[])
2508 * rules are added into the 'rulebuf' and then copied in
2509 * the correct order into the actual rule.
2510 * Some things that need to go out of order (prob, action etc.)
2513 static uint32_t rulebuf[IPFW_RULE_SIZE_MAX];
2514 static uint32_t actbuf[IPFW_RULE_SIZE_MAX];
2515 static uint32_t cmdbuf[IPFW_RULE_SIZE_MAX];
2517 ipfw_insn *src, *dst, *cmd, *action, *prev = NULL;
2518 ipfw_insn *first_cmd; /* first match pattern */
2520 struct ipfw_ioc_rule *rule;
2523 * various flags used to record that we entered some fields.
2525 ipfw_insn *have_state = NULL; /* check-state or keep-state */
2529 int open_par = 0; /* open parenthesis ( */
2531 /* proto is here because it is used to fetch ports */
2532 u_char proto = IPPROTO_IP; /* default protocol */
2534 double match_prob = 1; /* match probability, default is always match */
2536 bzero(actbuf, sizeof(actbuf)); /* actions go here */
2537 bzero(cmdbuf, sizeof(cmdbuf));
2538 bzero(rulebuf, sizeof(rulebuf));
2540 rule = (struct ipfw_ioc_rule *)rulebuf;
2541 cmd = (ipfw_insn *)cmdbuf;
2542 action = (ipfw_insn *)actbuf;
2546 /* [rule N] -- Rule number optional */
2547 if (ac && isdigit(**av)) {
2548 rule->rulenum = atoi(*av);
2553 /* [set N] -- set number (0..30), optional */
2554 if (ac > 1 && !strncmp(*av, "set", strlen(*av))) {
2555 int set = strtoul(av[1], NULL, 10);
2556 if (set < 0 || set > 30)
2557 errx(EX_DATAERR, "illegal set %s", av[1]);
2562 /* [prob D] -- match probability, optional */
2563 if (ac > 1 && !strncmp(*av, "prob", strlen(*av))) {
2564 match_prob = strtod(av[1], NULL);
2566 if (match_prob <= 0 || match_prob > 1)
2567 errx(EX_DATAERR, "illegal match prob. %s", av[1]);
2571 /* action -- mandatory */
2572 NEED1("missing action");
2573 i = match_token(rule_actions, *av);
2575 action->len = 1; /* default */
2577 case TOK_CHECKSTATE:
2578 have_state = action;
2579 action->opcode = O_CHECK_STATE;
2583 action->opcode = O_ACCEPT;
2587 action->opcode = O_DENY;
2592 action->opcode = O_REJECT;
2593 action->arg1 = ICMP_UNREACH_HOST;
2597 action->opcode = O_REJECT;
2598 action->arg1 = ICMP_REJECT_RST;
2602 action->opcode = O_REJECT;
2603 NEED1("missing reject code");
2604 fill_reject_code(&action->arg1, *av);
2609 action->opcode = O_COUNT;
2614 action->len = F_INSN_SIZE(ipfw_insn_pipe);
2617 action->opcode = O_QUEUE;
2618 else if (i == TOK_PIPE)
2619 action->opcode = O_PIPE;
2620 else if (i == TOK_SKIPTO)
2621 action->opcode = O_SKIPTO;
2622 NEED1("missing skipto/pipe/queue number");
2623 action->arg1 = strtoul(*av, NULL, 10);
2629 action->opcode = (i == TOK_DIVERT) ? O_DIVERT : O_TEE;
2630 NEED1("missing divert/tee port");
2631 action->arg1 = strtoul(*av, NULL, 0);
2632 if (action->arg1 == 0) {
2635 s = getservbyname(av[0], "divert");
2637 action->arg1 = ntohs(s->s_port);
2639 errx(EX_DATAERR, "illegal divert/tee port");
2645 ipfw_insn_sa *p = (ipfw_insn_sa *)action;
2648 NEED1("missing forward address[:port]");
2650 action->opcode = O_FORWARD_IP;
2651 action->len = F_INSN_SIZE(ipfw_insn_sa);
2653 p->sa.sin_len = sizeof(struct sockaddr_in);
2654 p->sa.sin_family = AF_INET;
2657 * locate the address-port separator (':' or ',')
2659 s = strchr(*av, ':');
2661 s = strchr(*av, ',');
2664 i = strtoport(s, &end, 0 /* base */, 0 /* proto */);
2667 "illegal forwarding port ``%s''", s);
2668 p->sa.sin_port = (u_short)i;
2670 lookup_host(*av, &(p->sa.sin_addr));
2676 errx(EX_DATAERR, "invalid action %s\n", av[-1]);
2678 action = next_cmd(action);
2681 * [log [logamount N]] -- log, optional
2683 * If exists, it goes first in the cmdbuf, but then it is
2684 * skipped in the copy section to the end of the buffer.
2686 if (ac && !strncmp(*av, "log", strlen(*av))) {
2687 ipfw_insn_log *c = (ipfw_insn_log *)cmd;
2689 cmd->len = F_INSN_SIZE(ipfw_insn_log);
2690 cmd->opcode = O_LOG;
2692 if (ac && !strncmp(*av, "logamount", strlen(*av))) {
2694 NEED1("logamount requires argument");
2695 c->max_log = atoi(*av);
2697 errx(EX_DATAERR, "logamount must be positive");
2700 cmd = next_cmd(cmd);
2703 if (have_state) /* must be a check-state, we are done */
2706 #define OR_START(target) \
2707 if (ac && (*av[0] == '(' || *av[0] == '{')) { \
2709 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
2712 if ( (av[0])[1] == '\0') { \
2723 !strncmp(*av, ")", strlen(*av)) || \
2724 !strncmp(*av, "}", strlen(*av)) )) { \
2729 errx(EX_USAGE, "missing \")\"\n"); \
2733 if (ac && !strncmp(*av, "not", strlen(*av))) { \
2734 if (cmd->len & F_NOT) \
2735 errx(EX_USAGE, "double \"not\" not allowed\n"); \
2736 cmd->len |= F_NOT; \
2740 #define OR_BLOCK(target) \
2741 if (ac && !strncmp(*av, "or", strlen(*av))) { \
2742 if (prev == NULL || open_par == 0) \
2743 errx(EX_DATAERR, "invalid OR block"); \
2744 prev->len |= F_OR; \
2754 * MAC addresses, optional.
2755 * If we have this, we skip the part "proto from src to dst"
2756 * and jump straight to the option parsing.
2759 NEED1("missing protocol");
2760 if (!strncmp(*av, "MAC", strlen(*av)) ||
2761 !strncmp(*av, "mac", strlen(*av))) {
2762 ac--; av++; /* the "MAC" keyword */
2763 add_mac(cmd, ac, av); /* exits in case of errors */
2764 cmd = next_cmd(cmd);
2765 ac -= 2; av += 2; /* dst-mac and src-mac */
2767 NEED1("missing mac type");
2768 if (add_mactype(cmd, ac, av[0]))
2769 cmd = next_cmd(cmd);
2770 ac--; av++; /* any or mac-type */
2776 * protocol, mandatory
2778 OR_START(get_proto);
2780 NEED1("missing protocol");
2781 if (add_proto(cmd, *av)) {
2783 if (F_LEN(cmd) == 0) /* plain IP */
2788 cmd = next_cmd(cmd);
2790 } else if (first_cmd != cmd) {
2791 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
2794 OR_BLOCK(get_proto);
2799 if (!ac || strncmp(*av, "from", strlen(*av)))
2800 errx(EX_USAGE, "missing ``from''");
2804 * source IP, mandatory
2806 OR_START(source_ip);
2807 NOT_BLOCK; /* optional "not" */
2808 NEED1("missing source address");
2809 if (add_srcip(cmd, *av)) {
2811 if (F_LEN(cmd) != 0) { /* ! any */
2813 cmd = next_cmd(cmd);
2816 OR_BLOCK(source_ip);
2819 * source ports, optional
2821 NOT_BLOCK; /* optional "not" */
2823 if (!strncmp(*av, "any", strlen(*av)) ||
2824 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
2826 if (F_LEN(cmd) != 0)
2827 cmd = next_cmd(cmd);
2834 if (!ac || strncmp(*av, "to", strlen(*av)))
2835 errx(EX_USAGE, "missing ``to''");
2839 * destination, mandatory
2842 NOT_BLOCK; /* optional "not" */
2843 NEED1("missing dst address");
2844 if (add_dstip(cmd, *av)) {
2846 if (F_LEN(cmd) != 0) { /* ! any */
2848 cmd = next_cmd(cmd);
2854 * dest. ports, optional
2856 NOT_BLOCK; /* optional "not" */
2858 if (!strncmp(*av, "any", strlen(*av)) ||
2859 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
2861 if (F_LEN(cmd) != 0)
2862 cmd = next_cmd(cmd);
2867 if (ac && first_cmd == cmd) {
2869 * nothing specified so far, store in the rule to ease
2872 rule->usr_flags = IPFW_USR_F_NORULE;
2877 ipfw_insn_u32 *cmd32; /* alias for cmd */
2880 cmd32 = (ipfw_insn_u32 *)cmd;
2882 if (*s == '!') { /* alternate syntax for NOT */
2883 if (cmd->len & F_NOT)
2884 errx(EX_USAGE, "double \"not\" not allowed\n");
2888 i = match_token(rule_options, s);
2892 if (cmd->len & F_NOT)
2893 errx(EX_USAGE, "double \"not\" not allowed\n");
2898 if (open_par == 0 || prev == NULL)
2899 errx(EX_USAGE, "invalid \"or\" block\n");
2903 case TOK_STARTBRACE:
2905 errx(EX_USAGE, "+nested \"(\" not allowed\n");
2911 errx(EX_USAGE, "+missing \")\"\n");
2917 fill_cmd(cmd, O_IN, 0, 0);
2921 cmd->len ^= F_NOT; /* toggle F_NOT */
2922 fill_cmd(cmd, O_IN, 0, 0);
2926 fill_cmd(cmd, O_FRAG, 0, 0);
2930 fill_cmd(cmd, O_LAYER2, 0, 0);
2936 NEED1("recv, xmit, via require interface name"
2938 fill_iface((ipfw_insn_if *)cmd, av[0]);
2940 if (F_LEN(cmd) == 0) /* not a valid address */
2943 cmd->opcode = O_XMIT;
2944 else if (i == TOK_RECV)
2945 cmd->opcode = O_RECV;
2946 else if (i == TOK_VIA)
2947 cmd->opcode = O_VIA;
2951 NEED1("icmptypes requires list of types");
2952 fill_icmptypes((ipfw_insn_u32 *)cmd, *av);
2957 NEED1("ipttl requires TTL");
2958 fill_cmd(cmd, O_IPTTL, 0, strtoul(*av, NULL, 0));
2963 NEED1("ipid requires length");
2964 fill_cmd(cmd, O_IPID, 0, strtoul(*av, NULL, 0));
2969 NEED1("iplen requires length");
2970 fill_cmd(cmd, O_IPLEN, 0, strtoul(*av, NULL, 0));
2975 NEED1("ipver requires version");
2976 fill_cmd(cmd, O_IPVER, 0, strtoul(*av, NULL, 0));
2980 case TOK_IPPRECEDENCE:
2981 NEED1("ipprecedence requires value");
2982 fill_cmd(cmd, O_IPPRECEDENCE, 0,
2983 (strtoul(*av, NULL, 0) & 7) << 5);
2988 NEED1("missing argument for ipoptions");
2989 fill_flags(cmd, O_IPOPT, f_ipopts, *av);
2994 NEED1("missing argument for iptos");
2995 fill_flags(cmd, O_IPTOS, f_iptos, *av);
3000 NEED1("uid requires argument");
3006 cmd->opcode = O_UID;
3007 uid = strtoul(*av, &end, 0);
3008 pwd = (*end == '\0') ? getpwuid(uid) : getpwnam(*av);
3010 errx(EX_DATAERR, "uid \"%s\" nonexistent", *av);
3011 cmd32->d[0] = pwd->pw_uid;
3012 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3018 NEED1("gid requires argument");
3024 cmd->opcode = O_GID;
3025 gid = strtoul(*av, &end, 0);
3026 grp = (*end == '\0') ? getgrgid(gid) : getgrnam(*av);
3028 errx(EX_DATAERR, "gid \"%s\" nonexistent", *av);
3029 cmd32->d[0] = grp->gr_gid;
3030 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3036 fill_cmd(cmd, O_ESTAB, 0, 0);
3040 fill_cmd(cmd, O_TCPFLAGS, 0,
3041 (TH_SYN) | ( (TH_ACK) & 0xff) <<8 );
3045 NEED1("missing argument for tcpoptions");
3046 fill_flags(cmd, O_TCPOPTS, f_tcpopts, *av);
3052 NEED1("tcpseq/tcpack requires argument");
3053 cmd->len = F_INSN_SIZE(ipfw_insn_u32);
3054 cmd->opcode = (i == TOK_TCPSEQ) ? O_TCPSEQ : O_TCPACK;
3055 cmd32->d[0] = htonl(strtoul(*av, NULL, 0));
3060 NEED1("tcpwin requires length");
3061 fill_cmd(cmd, O_TCPWIN, 0,
3062 htons(strtoul(*av, NULL, 0)));
3067 NEED1("missing argument for tcpflags");
3068 cmd->opcode = O_TCPFLAGS;
3069 fill_flags(cmd, O_TCPFLAGS, f_tcpflags, *av);
3075 errx(EX_USAGE, "keep-state cannot be part "
3078 errx(EX_USAGE, "only one of keep-state "
3079 "and limit is allowed");
3081 fill_cmd(cmd, O_KEEP_STATE, 0, 0);
3086 errx(EX_USAGE, "limit cannot be part "
3089 errx(EX_USAGE, "only one of keep-state "
3090 "and limit is allowed");
3091 NEED1("limit needs mask and # of connections");
3094 ipfw_insn_limit *c = (ipfw_insn_limit *)cmd;
3096 cmd->len = F_INSN_SIZE(ipfw_insn_limit);
3097 cmd->opcode = O_LIMIT;
3103 val = match_token(limit_masks, *av);
3106 c->limit_mask |= val;
3109 c->conn_limit = atoi(*av);
3110 if (c->conn_limit == 0)
3111 errx(EX_USAGE, "limit: limit must be >0");
3112 if (c->limit_mask == 0)
3113 errx(EX_USAGE, "missing limit mask");
3119 NEED1("missing protocol");
3120 if (add_proto(cmd, *av)) {
3124 errx(EX_DATAERR, "invalid protocol ``%s''", *av);
3128 NEED1("missing source IP");
3129 if (add_srcip(cmd, *av)) {
3135 NEED1("missing destination IP");
3136 if (add_dstip(cmd, *av)) {
3142 NEED1("missing source port");
3143 if (!strncmp(*av, "any", strlen(*av)) ||
3144 add_ports(cmd, *av, proto, O_IP_SRCPORT)) {
3147 errx(EX_DATAERR, "invalid source port %s", *av);
3151 NEED1("missing destination port");
3152 if (!strncmp(*av, "any", strlen(*av)) ||
3153 add_ports(cmd, *av, proto, O_IP_DSTPORT)) {
3156 errx(EX_DATAERR, "invalid destination port %s",
3162 errx(EX_USAGE, "MAC dst-mac src-mac");
3163 if (add_mac(cmd, ac, av)) {
3169 NEED1("missing mac type");
3170 if (!add_mactype(cmd, ac, *av))
3171 errx(EX_DATAERR, "invalid mac type %s", *av);
3176 errx(EX_USAGE, "unrecognised option [%d] %s\n", i, s);
3178 if (F_LEN(cmd) > 0) { /* prepare to advance */
3180 cmd = next_cmd(cmd);
3186 * Now copy stuff into the rule.
3187 * If we have a keep-state option, the first instruction
3188 * must be a PROBE_STATE (which is generated here).
3189 * If we have a LOG option, it was stored as the first command,
3190 * and now must be moved to the top of the action part.
3192 dst = (ipfw_insn *)rule->cmd;
3195 * First thing to write into the command stream is the match probability.
3197 if (match_prob != 1) { /* 1 means always match */
3198 dst->opcode = O_PROB;
3200 *((int32_t *)(dst+1)) = (int32_t)(match_prob * 0x7fffffff);
3205 * generate O_PROBE_STATE if necessary
3207 if (have_state && have_state->opcode != O_CHECK_STATE) {
3208 fill_cmd(dst, O_PROBE_STATE, 0, 0);
3209 dst = next_cmd(dst);
3212 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT
3214 for (src = (ipfw_insn *)cmdbuf; src != cmd; src += i) {
3217 switch (src->opcode) {
3223 bcopy(src, dst, i * sizeof(u_int32_t));
3229 * put back the have_state command as last opcode
3231 if (have_state && have_state->opcode != O_CHECK_STATE) {
3232 i = F_LEN(have_state);
3233 bcopy(have_state, dst, i * sizeof(u_int32_t));
3237 * start action section
3239 rule->act_ofs = dst - rule->cmd;
3242 * put back O_LOG if necessary
3244 src = (ipfw_insn *)cmdbuf;
3245 if ( src->opcode == O_LOG ) {
3247 bcopy(src, dst, i * sizeof(u_int32_t));
3251 * copy all other actions
3253 for (src = (ipfw_insn *)actbuf; src != action; src += i) {
3255 bcopy(src, dst, i * sizeof(u_int32_t));
3259 rule->cmd_len = (u_int32_t *)dst - (u_int32_t *)(rule->cmd);
3260 i = (void *)dst - (void *)rule;
3261 if (getsockopt(s, IPPROTO_IP, IP_FW_ADD, rule, &i) == -1)
3262 err(EX_UNAVAILABLE, "getsockopt(%s)", "IP_FW_ADD");
3264 show_ipfw(rule, 10, 10);
3268 zero(int ac, char *av[])
3276 /* clear all entries */
3277 if (setsockopt(s, IPPROTO_IP, IP_FW_ZERO, NULL, 0) < 0)
3278 err(EX_UNAVAILABLE, "setsockopt(%s)", "IP_FW_ZERO");
3280 printf("Accounting cleared.\n");
3287 if (isdigit(**av)) {
3288 rulenum = atoi(*av);
3291 if (setsockopt(s, IPPROTO_IP,
3292 IP_FW_ZERO, &rulenum, sizeof rulenum)) {
3293 warn("rule %u: setsockopt(IP_FW_ZERO)",
3295 failed = EX_UNAVAILABLE;
3296 } else if (!do_quiet)
3297 printf("Entry %d cleared\n", rulenum);
3299 errx(EX_USAGE, "invalid rule number ``%s''", *av);
3302 if (failed != EX_OK)
3307 resetlog(int ac, char *av[])
3315 /* clear all entries */
3316 if (setsockopt(s, IPPROTO_IP, IP_FW_RESETLOG, NULL, 0) < 0)
3317 err(EX_UNAVAILABLE, "setsockopt(IP_FW_RESETLOG)");
3319 printf("Logging counts reset.\n");
3326 if (isdigit(**av)) {
3327 rulenum = atoi(*av);
3330 if (setsockopt(s, IPPROTO_IP,
3331 IP_FW_RESETLOG, &rulenum, sizeof rulenum)) {
3332 warn("rule %u: setsockopt(IP_FW_RESETLOG)",
3334 failed = EX_UNAVAILABLE;
3335 } else if (!do_quiet)
3336 printf("Entry %d logging count reset\n",
3339 errx(EX_DATAERR, "invalid rule number ``%s''", *av);
3342 if (failed != EX_OK)
3349 int cmd = do_pipe ? IP_DUMMYNET_FLUSH : IP_FW_FLUSH;
3351 if (!do_force && !do_quiet) { /* need to ask user */
3354 printf("Are you sure? [yn] ");
3357 c = toupper(getc(stdin));
3358 while (c != '\n' && getc(stdin) != '\n')
3360 return; /* and do not flush */
3361 } while (c != 'Y' && c != 'N');
3363 if (c == 'N') /* user said no */
3366 if (setsockopt(s, IPPROTO_IP, cmd, NULL, 0) < 0)
3367 err(EX_UNAVAILABLE, "setsockopt(IP_%s_FLUSH)",
3368 do_pipe ? "DUMMYNET" : "FW");
3370 printf("Flushed all %s.\n", do_pipe ? "pipes" : "rules");
3374 ipfw_main(int ac, char **av)
3381 /* Set the force flag for non-interactive processes */
3382 do_force = !isatty(STDIN_FILENO);
3384 optind = optreset = 1;
3385 while ((ch = getopt(ac, av, "hs:acdefNqStv")) != -1)
3387 case 'h': /* help */
3389 break; /* NOTREACHED */
3391 case 's': /* sort */
3392 do_sort = atoi(optarg);
3421 case 'v': /* verbose */
3430 NEED1("bad arguments, for usage summary ``ipfw''");
3433 * optional: pipe or queue
3435 if (!strncmp(*av, "pipe", strlen(*av))) {
3439 } else if (!strncmp(*av, "queue", strlen(*av))) {
3444 NEED1("missing command");
3447 * for pipes and queues we normally say 'pipe NN config'
3448 * but the code is easier to parse as 'pipe config NN'
3449 * so we swap the two arguments.
3451 if (do_pipe > 0 && ac > 1 && *av[0] >= '0' && *av[0] <= '9') {
3456 if (!strncmp(*av, "add", strlen(*av)))
3458 else if (do_pipe && !strncmp(*av, "config", strlen(*av)))
3459 config_pipe(ac, av);
3460 else if (!strncmp(*av, "delete", strlen(*av)))
3462 else if (!strncmp(*av, "flush", strlen(*av)))
3464 else if (!strncmp(*av, "zero", strlen(*av)))
3466 else if (!strncmp(*av, "resetlog", strlen(*av)))
3468 else if (!strncmp(*av, "print", strlen(*av)) ||
3469 !strncmp(*av, "list", strlen(*av)))
3471 else if (!strncmp(*av, "enable", strlen(*av)))
3472 sysctl_handler(ac, av, 1);
3473 else if (!strncmp(*av, "disable", strlen(*av)))
3474 sysctl_handler(ac, av, 0);
3475 else if (!strncmp(*av, "set", strlen(*av)))
3476 sets_handler(ac, av);
3477 else if (!strncmp(*av, "show", strlen(*av))) {
3481 errx(EX_USAGE, "bad command `%s'", *av);
3487 ipfw_readfile(int ac, char *av[])
3490 #define WHITESP " \t\f\v\n\r"
3492 char *a, *p, *args[MAX_ARGS], *cmd = NULL;
3494 int i=0, lineno=0, qflag=0, pflag=0, status;
3499 while ((c = getopt(ac, av, "D:U:p:q")) != -1)
3503 errx(EX_USAGE, "-D requires -p");
3504 if (i > MAX_ARGS - 2)
3506 "too many -D or -U options");
3513 errx(EX_USAGE, "-U requires -p");
3514 if (i > MAX_ARGS - 2)
3516 "too many -D or -U options");
3533 errx(EX_USAGE, "bad arguments, for usage"
3534 " summary ``ipfw''");
3540 errx(EX_USAGE, "extraneous filename arguments");
3542 if ((f = fopen(av[0], "r")) == NULL)
3543 err(EX_UNAVAILABLE, "fopen: %s", av[0]);
3546 /* pipe through preprocessor (cpp or m4) */
3551 if (pipe(pipedes) == -1)
3552 err(EX_OSERR, "cannot create pipe");
3554 switch((preproc = fork())) {
3556 err(EX_OSERR, "cannot fork");
3560 if (dup2(fileno(f), 0) == -1
3561 || dup2(pipedes[1], 1) == -1)
3562 err(EX_OSERR, "dup2()");
3567 err(EX_OSERR, "execvp(%s) failed", cmd);
3573 if ((f = fdopen(pipedes[0], "r")) == NULL) {
3574 int savederrno = errno;
3576 kill(preproc, SIGTERM);
3578 err(EX_OSERR, "fdopen()");
3583 while (fgets(buf, BUFSIZ, f)) {
3585 sprintf(linename, "Line %d", lineno);
3590 if ((p = strchr(buf, '#')) != NULL)
3595 for (a = strtok(buf, WHITESP);
3596 a && i < MAX_ARGS; a = strtok(NULL, WHITESP), i++)
3598 if (i == (qflag? 2: 1))
3601 errx(EX_USAGE, "%s: too many arguments",
3609 if (waitpid(preproc, &status, 0) == -1)
3610 errx(EX_OSERR, "waitpid()");
3611 if (WIFEXITED(status) && WEXITSTATUS(status) != EX_OK)
3612 errx(EX_UNAVAILABLE,
3613 "preprocessor exited with status %d",
3614 WEXITSTATUS(status));
3615 else if (WIFSIGNALED(status))
3616 errx(EX_UNAVAILABLE,
3617 "preprocessor exited with signal %d",
3623 main(int ac, char *av[])
3625 s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);
3627 err(EX_UNAVAILABLE, "socket");
3630 * If the last argument is an absolute pathname, interpret it
3631 * as a file to be preprocessed.
3634 if (ac > 1 && av[ac - 1][0] == '/' && access(av[ac - 1], R_OK) == 0)
3635 ipfw_readfile(ac, av);