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>
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/ethernet.h>
55 #include <net/dummynet/ip_dummynet.h>
56 #include <netinet/tcp.h>
57 #include <arpa/inet.h>
59 int s
, /* main RAW socket */
60 do_resolv
, /* Would try to resolve all */
61 do_acct
, /* Show packet/byte count */
62 do_time
, /* Show time stamps */
63 do_quiet
, /* Be quiet in add and flush */
64 do_force
, /* Don't ask for confirmation */
65 do_pipe
, /* this cmd refers to a pipe */
66 do_table
, /* this cmd referes to a table */
67 do_sort
, /* field to sort results (0 = no) */
68 do_dynamic
, /* display dynamic rules */
69 do_expired
, /* display expired dynamic rules */
70 do_compact
, /* show rules in compact mode */
71 show_sets
, /* display rule sets */
74 #define IP_MASK_ALL 0xffffffff
77 * structure to hold flag names and associated values to be
78 * set in the appropriate masks.
79 * A NULL string terminates the array.
80 * Often, an element with 0 value contains an error string.
88 static struct _s_x f_tcpflags
[] = {
99 static struct _s_x f_tcpopts
[] = {
100 { "mss", IP_FW_TCPOPT_MSS
},
101 { "maxseg", IP_FW_TCPOPT_MSS
},
102 { "window", IP_FW_TCPOPT_WINDOW
},
103 { "sack", IP_FW_TCPOPT_SACK
},
104 { "ts", IP_FW_TCPOPT_TS
},
105 { "timestamp", IP_FW_TCPOPT_TS
},
106 { "cc", IP_FW_TCPOPT_CC
},
112 * IP options span the range 0 to 255 so we need to remap them
113 * (though in fact only the low 5 bits are significant).
115 static struct _s_x f_ipopts
[] = {
116 { "ssrr", IP_FW_IPOPT_SSRR
},
117 { "lsrr", IP_FW_IPOPT_LSRR
},
118 { "rr", IP_FW_IPOPT_RR
},
119 { "ts", IP_FW_IPOPT_TS
},
124 static struct _s_x f_iptos
[] = {
125 { "lowdelay", IPTOS_LOWDELAY
},
126 { "throughput", IPTOS_THROUGHPUT
},
127 { "reliability", IPTOS_RELIABILITY
},
128 { "mincost", IPTOS_MINCOST
},
129 { "congestion", IPTOS_CE
},
130 { "ecntransport", IPTOS_ECT
},
131 { "ip tos option", 0},
135 static struct _s_x limit_masks
[] = {
136 {"all", DYN_SRC_ADDR
|DYN_SRC_PORT
|DYN_DST_ADDR
|DYN_DST_PORT
},
137 {"src-addr", DYN_SRC_ADDR
},
138 {"src-port", DYN_SRC_PORT
},
139 {"dst-addr", DYN_DST_ADDR
},
140 {"dst-port", DYN_DST_PORT
},
145 * we use IPPROTO_ETHERTYPE as a fake protocol id to call the print routines
146 * This is only used in this code.
148 #define IPPROTO_ETHERTYPE 0x1000
149 static struct _s_x ether_types
[] = {
151 * Note, we cannot use "-:&/" in the names because they are field
152 * separators in the type specifications. Also, we use s = NULL as
153 * end-delimiter, because a type of 0 can be legal.
163 { "pppoe_disc", 0x8863 },
164 { "pppoe_sess", 0x8864 },
165 { "ipx_8022", 0x00E0 },
166 { "ipx_8023", 0x0000 },
167 { "ipx_ii", 0x8137 },
168 { "ipx_snap", 0x8137 },
174 static void show_usage(void);
249 struct _s_x dummynet_params
[] = {
251 { "noerror", TOK_NOERROR
},
252 { "buckets", TOK_BUCKETS
},
253 { "dst-ip", TOK_DSTIP
},
254 { "src-ip", TOK_SRCIP
},
255 { "dst-port", TOK_DSTPORT
},
256 { "src-port", TOK_SRCPORT
},
257 { "proto", TOK_PROTO
},
258 { "weight", TOK_WEIGHT
},
260 { "mask", TOK_MASK
},
261 { "droptail", TOK_DROPTAIL
},
263 { "gred", TOK_GRED
},
265 { "bandwidth", TOK_BW
},
266 { "delay", TOK_DELAY
},
267 { "pipe", TOK_PIPE
},
268 { "queue", TOK_QUEUE
},
269 { "dummynet-params", TOK_NULL
},
273 struct _s_x rule_actions
[] = {
274 { "accept", TOK_ACCEPT
},
275 { "pass", TOK_ACCEPT
},
276 { "allow", TOK_ACCEPT
},
277 { "permit", TOK_ACCEPT
},
278 { "count", TOK_COUNT
},
279 { "pipe", TOK_PIPE
},
280 { "queue", TOK_QUEUE
},
281 { "divert", TOK_DIVERT
},
283 { "fwd", TOK_FORWARD
},
284 { "forward", TOK_FORWARD
},
285 { "skipto", TOK_SKIPTO
},
286 { "deny", TOK_DENY
},
287 { "drop", TOK_DENY
},
288 { "reject", TOK_REJECT
},
289 { "reset", TOK_RESET
},
290 { "unreach", TOK_UNREACH
},
291 { "check-state", TOK_CHECKSTATE
},
292 { "defrag", TOK_DEFRAG
},
297 struct _s_x rule_options
[] = {
301 { "limit", TOK_LIMIT
},
302 { "keep-state", TOK_KEEPSTATE
},
303 { "redirect", TOK_REDIRECT
},
304 { "rdr", TOK_REDIRECT
},
305 { "layer2", TOK_LAYER2
},
307 { "xmit", TOK_XMIT
},
308 { "recv", TOK_RECV
},
310 { "fragment", TOK_FRAG
},
311 { "frag", TOK_FRAG
},
312 { "ipfrag", TOK_IPFRAG
},
313 { "ipoptions", TOK_IPOPTS
},
314 { "ipopts", TOK_IPOPTS
},
315 { "iplen", TOK_IPLEN
},
316 { "ipid", TOK_IPID
},
317 { "ipprecedence", TOK_IPPRECEDENCE
},
318 { "iptos", TOK_IPTOS
},
319 { "ipttl", TOK_IPTTL
},
320 { "ipversion", TOK_IPVER
},
321 { "ipver", TOK_IPVER
},
322 { "estab", TOK_ESTAB
},
323 { "established", TOK_ESTAB
},
324 { "setup", TOK_SETUP
},
325 { "tcpflags", TOK_TCPFLAGS
},
326 { "tcpflgs", TOK_TCPFLAGS
},
327 { "tcpoptions", TOK_TCPOPTS
},
328 { "tcpopts", TOK_TCPOPTS
},
329 { "tcpseq", TOK_TCPSEQ
},
330 { "tcpack", TOK_TCPACK
},
331 { "tcpwin", TOK_TCPWIN
},
332 { "icmpcode", TOK_ICMPCODES
},
333 { "icmpcodes", TOK_ICMPCODES
},
334 { "icmptype", TOK_ICMPTYPES
},
335 { "icmptypes", TOK_ICMPTYPES
},
336 { "dst-ip", TOK_DSTIP
},
337 { "src-ip", TOK_SRCIP
},
338 { "dst-port", TOK_DSTPORT
},
339 { "src-port", TOK_SRCPORT
},
340 { "proto", TOK_PROTO
},
343 { "mac-type", TOK_MACTYPE
},
345 { "not", TOK_NOT
}, /* pseudo option */
346 { "!", /* escape ? */ TOK_NOT
}, /* pseudo option */
347 { "or", TOK_OR
}, /* pseudo option */
348 { "|", /* escape */ TOK_OR
}, /* pseudo option */
349 { "{", TOK_STARTBRACE
}, /* pseudo option */
350 { "(", TOK_STARTBRACE
}, /* pseudo option */
351 { "}", TOK_ENDBRACE
}, /* pseudo option */
352 { ")", TOK_ENDBRACE
}, /* pseudo option */
358 * match_token takes a table and a string, returns the value associated
359 * with the string (0 meaning an error in most cases)
362 match_token(struct _s_x
*table
, char *string
)
365 int i
= strlen(string
);
367 for (pt
= table
; i
&& pt
->s
!= NULL
; pt
++)
368 if ((int)strlen(pt
->s
) == i
&& !bcmp(string
, pt
->s
, i
))
374 match_value(struct _s_x
*p
, u_int32_t value
)
376 for (; p
->s
!= NULL
; p
++)
383 * prints one port, symbolic or numeric
386 print_port(int proto
, u_int16_t port
)
389 if (proto
== IPPROTO_ETHERTYPE
) {
392 if (do_resolv
&& (str
= match_value(ether_types
, port
)) )
395 printf("0x%04x", port
);
397 struct servent
*se
= NULL
;
399 struct protoent
*pe
= getprotobynumber(proto
);
401 se
= getservbyport(htons(port
), pe
? pe
->p_name
: NULL
);
404 printf("%s", se
->s_name
);
411 * print the values in a list of ports
412 * XXX todo: add support for mask.
415 print_newports(ipfw_insn_u16
*cmd
, int proto
, int opcode
)
417 u_int16_t
*p
= cmd
->ports
;
419 const char *sep
= " ";
421 if (cmd
->o
.len
& F_NOT
)
424 printf ("%s", opcode
== O_MAC_TYPE
? " mac-type" :
425 (opcode
== O_IP_DSTPORT
? " dst-port" : " src-port"));
426 for (i
= F_LEN((ipfw_insn
*)cmd
) - 1; i
> 0; i
--, p
+= 2) {
428 print_port(proto
, p
[0]);
431 print_port(proto
, p
[1]);
438 * Like strtol, but also translates service names into port numbers
439 * for some protocols.
441 * proto == -1 disables the protocol check;
442 * proto == IPPROTO_ETHERTYPE looks up an internal table
443 * proto == <some value in /etc/protocols> matches the values there.
444 * Returns *end == s in case the parameter is not found.
447 strtoport(char *str
, char **end
, int base
, int proto
)
453 *end
= str
; /* default - not found */
455 return 0; /* not found */
458 return strtol(str
, end
, base
);
461 * find separator. '\\' escapes the next char.
463 for (s1
= str
; *s1
&& (isalnum(*s1
) || *s1
== '\\') ; s1
++)
464 if (*s1
== '\\' && s1
[1] != '\0')
467 buf
= malloc(s1
- str
+ 1);
472 * copy into a buffer skipping backslashes
474 for (p
= str
, i
= 0; p
!= s1
; p
++)
479 if (proto
== IPPROTO_ETHERTYPE
) {
480 i
= match_token(ether_types
, buf
);
482 if (i
!= -1) { /* found */
487 struct protoent
*pe
= NULL
;
491 pe
= getprotobynumber(proto
);
493 se
= getservbyname(buf
, pe
? pe
->p_name
: NULL
);
497 return ntohs(se
->s_port
);
500 return 0; /* not found */
504 * fill the body of the command with the list of port ranges.
505 * At the moment it only understands numeric ranges.
508 fill_newports(ipfw_insn_u16
*cmd
, char *av
, int proto
)
510 u_int16_t
*p
= cmd
->ports
;
517 a
= strtoport(av
, &str
, 0, proto
);
518 if (str
== av
) /* no parameter */
520 if (*str
== '-') { /* a range */
522 b
= strtoport(av
, &str
, 0, proto
);
523 if (str
== av
) /* no parameter */
527 } else if (*str
== ',' || *str
== '\0' ) {
529 } else { /* invalid separator */
530 errx(EX_DATAERR
, "invalid separator <%c> in <%s>\n",
538 if (i
+1 > F_LEN_MASK
)
539 errx(EX_DATAERR
, "too many ports/ranges\n");
540 cmd
->o
.len
|= i
+1; /* leave F_NOT and F_OR untouched */
545 static struct _s_x icmpcodes
[] = {
546 { "net", ICMP_UNREACH_NET
},
547 { "host", ICMP_UNREACH_HOST
},
548 { "protocol", ICMP_UNREACH_PROTOCOL
},
549 { "port", ICMP_UNREACH_PORT
},
550 { "needfrag", ICMP_UNREACH_NEEDFRAG
},
551 { "srcfail", ICMP_UNREACH_SRCFAIL
},
552 { "net-unknown", ICMP_UNREACH_NET_UNKNOWN
},
553 { "host-unknown", ICMP_UNREACH_HOST_UNKNOWN
},
554 { "isolated", ICMP_UNREACH_ISOLATED
},
555 { "net-prohib", ICMP_UNREACH_NET_PROHIB
},
556 { "host-prohib", ICMP_UNREACH_HOST_PROHIB
},
557 { "tosnet", ICMP_UNREACH_TOSNET
},
558 { "toshost", ICMP_UNREACH_TOSHOST
},
559 { "filter-prohib", ICMP_UNREACH_FILTER_PROHIB
},
560 { "host-precedence", ICMP_UNREACH_HOST_PRECEDENCE
},
561 { "precedence-cutoff", ICMP_UNREACH_PRECEDENCE_CUTOFF
},
566 fill_reject_code(u_short
*codep
, char *str
)
571 val
= strtoul(str
, &s1
, 0);
572 if (s1
== str
|| *s1
!= '\0' || val
>= 0x100)
573 val
= match_token(icmpcodes
, str
);
575 errx(EX_DATAERR
, "unknown ICMP unreachable code ``%s''", str
);
581 print_reject_code(u_int16_t code
)
583 const char *str
= match_value(icmpcodes
, code
);
586 printf("unreach %s", str
);
588 printf("unreach %u", code
);
592 * Returns the number of bits set (from left) in a contiguous bitmask,
593 * or -1 if the mask is not contiguous.
594 * XXX this needs a proper fix.
595 * This effectively works on masks in big-endian (network) format.
596 * when compiled on little endian architectures.
598 * First bit is bit 7 of the first byte -- note, for MAC addresses,
599 * the first bit on the wire is bit 0 of the first byte.
600 * len is the max length in bits.
603 contigmask(u_char
*p
, int len
)
606 for (i
=0; i
<len
; i
++)
607 if ( (p
[i
/8] & (1 << (7 - (i
%8)))) == 0) /* first bit unset */
609 for (n
=i
+1; n
< len
; n
++)
610 if ( (p
[n
/8] & (1 << (7 - (n
%8)))) != 0)
611 return -1; /* mask not contiguous */
616 * print flags set/clear in the two bitmasks passed as parameters.
617 * There is a specialized check for f_tcpflags.
620 print_flags(const char *name
, ipfw_insn
*cmd
, struct _s_x
*list
)
622 const char *comma
="";
624 u_char set
= cmd
->arg1
& 0xff;
625 u_char clear
= (cmd
->arg1
>> 8) & 0xff;
627 if (list
== f_tcpflags
&& set
== TH_SYN
&& clear
== TH_ACK
) {
632 printf(" %s ", name
);
633 for (i
=0; list
[i
].x
!= 0; i
++) {
634 if (set
& list
[i
].x
) {
636 printf("%s%s", comma
, list
[i
].s
);
639 if (clear
& list
[i
].x
) {
641 printf("%s!%s", comma
, list
[i
].s
);
648 * Print the ip address contained in a command.
651 print_ip(ipfw_insn_ip
*cmd
, const char *str
)
653 struct hostent
*he
= NULL
;
656 printf("%s%s ", cmd
->o
.len
& F_NOT
? " not": "", str
);
658 if (cmd
->o
.opcode
== O_IP_SRC_ME
|| cmd
->o
.opcode
== O_IP_DST_ME
) {
662 if (cmd
->o
.opcode
== O_IP_SRC_TABLE
||
663 cmd
->o
.opcode
== O_IP_DST_TABLE
) {
664 printf("<%u>", cmd
->o
.arg1
);
667 if (cmd
->o
.opcode
== O_IP_SRC_IFIP
||
668 cmd
->o
.opcode
== O_IP_DST_IFIP
) {
669 printf("[%s%s]", ((ipfw_insn_ifip
*)cmd
)->ifname
,
670 (cmd
->o
.arg1
& IPFW_IFIP_NET
) ? ":net" : "");
673 if (cmd
->o
.opcode
== O_IP_SRC_SET
|| cmd
->o
.opcode
== O_IP_DST_SET
) {
680 cmd
->addr
.s_addr
= htonl(cmd
->addr
.s_addr
);
681 printf("%s/%d", inet_ntoa(cmd
->addr
),
682 contigmask((u_char
*)&x
, 32));
683 x
= cmd
->addr
.s_addr
= htonl(cmd
->addr
.s_addr
);
684 x
&= 0xff; /* base */
685 d
= (u_int32_t
*)&(cmd
->mask
);
686 for (i
=0; i
< cmd
->o
.arg1
; i
++)
687 if (d
[ i
/32] & (1<<(i
& 31))) {
688 printf("%c%d", comma
, i
+x
);
694 if (cmd
->o
.opcode
== O_IP_SRC
|| cmd
->o
.opcode
== O_IP_DST
)
697 mb
= contigmask((u_char
*)&(cmd
->mask
.s_addr
), 32);
698 if (mb
== 32 && do_resolv
)
699 he
= gethostbyaddr(&(cmd
->addr
.s_addr
), sizeof(u_long
),
701 if (he
!= NULL
) /* resolved to name */
702 printf("%s", he
->h_name
);
703 else if (mb
== 0) /* any */
705 else { /* numeric IP followed by some kind of mask */
706 printf("%s", inet_ntoa(cmd
->addr
));
708 printf(":%s", inet_ntoa(cmd
->mask
));
715 * prints a MAC address/mask pair
718 print_mac(u_char
*addr
, u_char
*mask
)
720 int l
= contigmask(mask
, 48);
725 printf(" %02x:%02x:%02x:%02x:%02x:%02x",
726 addr
[0], addr
[1], addr
[2], addr
[3], addr
[4], addr
[5]);
728 printf("&%02x:%02x:%02x:%02x:%02x:%02x",
729 mask
[0], mask
[1], mask
[2],
730 mask
[3], mask
[4], mask
[5]);
737 fill_icmp(enum ipfw_opcodes op
, ipfw_insn_u32
*cmd
, char *av
)
740 int idx_max
= 0, idx
;
742 /* 256 / 32, (max icmp types / 32 bits). */
743 for (idx
= 0; idx
< 8; ++idx
)
750 type
= strtoul(av
, &av
, 0);
751 if (*av
!= ',' && *av
!= '\0') {
752 errx(EX_DATAERR
, "invalid ICMP %s",
753 op
== O_ICMPTYPE
? "types" : "codes");
757 cmd
->d
[idx
] |= 1 << (type
% 32);
763 cmd
->o
.len
|= (F_INSN_SIZE(ipfw_insn_u32
) + idx_max
);
767 print_icmp(ipfw_insn_u32
*cmd
)
772 idx_max
= F_LEN(&cmd
->o
) - F_INSN_SIZE(ipfw_insn
);
774 if (cmd
->o
.opcode
== O_ICMPTYPE
)
775 printf(" icmptypes");
777 printf(" icmpcodes");
778 for (idx
= 0; idx
< idx_max
; ++idx
) {
779 uint32_t types
= cmd
->d
[idx
];
782 int type_shift
= ffs(types
) - 1;
784 types
&= ~(1 << type_shift
);
785 printf("%c%d", sep
, (idx
* 32) + type_shift
);
792 * show_ipfw() prints the body of an ipfw rule.
793 * Because the standard rule has at least proto src_ip dst_ip, we use
794 * a helper function to produce these entries if not provided explicitly.
795 * The first argument is the list of fields we have, the second is
796 * the list of fields we want to be printed.
798 * Special cases if we have provided a MAC header:
799 * + if the rule does not contain IP addresses/ports, do not print them;
800 * + if the rule does not contain an IP proto, print "all" instead of "ip";
802 * Once we have 'have_options', IP header fields are printed as options.
804 #define HAVE_PROTO 0x0001
805 #define HAVE_SRCIP 0x0002
806 #define HAVE_DSTIP 0x0004
807 #define HAVE_MAC 0x0008
808 #define HAVE_MACTYPE 0x0010
809 #define HAVE_OPTIONS 0x8000
811 #define HAVE_IP (HAVE_PROTO | HAVE_SRCIP | HAVE_DSTIP)
813 show_prerequisites(int *flags
, int want
, int cmd
)
815 if ( (*flags
& HAVE_IP
) == HAVE_IP
)
816 *flags
|= HAVE_OPTIONS
;
818 if ( (*flags
& (HAVE_MAC
|HAVE_MACTYPE
|HAVE_OPTIONS
)) == HAVE_MAC
&&
821 * mac-type was optimized out by the compiler,
825 *flags
|= HAVE_MACTYPE
| HAVE_OPTIONS
;
828 if ( !(*flags
& HAVE_OPTIONS
)) {
829 if ( !(*flags
& HAVE_PROTO
) && (want
& HAVE_PROTO
))
831 if ( !(*flags
& HAVE_SRCIP
) && (want
& HAVE_SRCIP
))
833 if ( !(*flags
& HAVE_DSTIP
) && (want
& HAVE_DSTIP
))
840 show_ipfw(struct ipfw_ioc_rule
*rule
, int pcwidth
, int bcwidth
)
842 static int twidth
= 0;
845 int proto
= 0; /* default */
846 int flags
= 0; /* prerequisites */
847 ipfw_insn_log
*logptr
= NULL
; /* set if we find an O_LOG */
848 int or_block
= 0; /* we are in an or block */
850 u_int32_t set_disable
= rule
->set_disable
;
852 if (set_disable
& (1 << rule
->set
)) { /* disabled */
856 printf("# DISABLED ");
858 printf("%05u ", rule
->rulenum
);
861 printf("%*ju %*ju ", pcwidth
, (uintmax_t)rule
->pcnt
, bcwidth
,
862 (uintmax_t)rule
->bcnt
);
870 strcpy(timestr
, ctime((time_t *)&t0
));
871 *strchr(timestr
, '\n') = '\0';
872 twidth
= strlen(timestr
);
874 if (rule
->timestamp
) {
875 time_t t
= _long_to_time(rule
->timestamp
);
877 strcpy(timestr
, ctime(&t
));
878 *strchr(timestr
, '\n') = '\0';
879 printf("%s ", timestr
);
881 printf("%*s ", twidth
, " ");
886 printf("set %d ", rule
->set
);
889 * print the optional "match probability"
891 if (rule
->cmd_len
> 0) {
893 if (cmd
->opcode
== O_PROB
) {
894 ipfw_insn_u32
*p
= (ipfw_insn_u32
*)cmd
;
895 double d
= 1.0 * p
->d
[0];
897 d
= (d
/ 0x7fffffff);
898 printf("prob %f ", d
);
903 * first print actions
905 for (l
= rule
->cmd_len
- rule
->act_ofs
, cmd
= ACTION_PTR(rule
);
906 l
> 0 ; l
-= F_LEN(cmd
), cmd
+= F_LEN(cmd
)) {
907 switch(cmd
->opcode
) {
909 printf("check-state");
910 flags
= HAVE_IP
; /* avoid printing anything else */
930 if (cmd
->arg1
== ICMP_REJECT_RST
)
932 else if (cmd
->arg1
== ICMP_UNREACH_HOST
)
935 print_reject_code(cmd
->arg1
);
939 printf("skipto %u", cmd
->arg1
);
943 printf("pipe %u", cmd
->arg1
);
947 printf("queue %u", cmd
->arg1
);
951 printf("divert %u", cmd
->arg1
);
955 printf("tee %u", cmd
->arg1
);
960 ipfw_insn_sa
*sa
= (ipfw_insn_sa
*)cmd
;
962 printf("fwd %s", inet_ntoa(sa
->sa
.sin_addr
));
964 printf(",%d", sa
->sa
.sin_port
);
968 case O_LOG
: /* O_LOG is printed last */
969 logptr
= (ipfw_insn_log
*)cmd
;
973 printf("** unrecognized action %d len %d",
974 cmd
->opcode
, cmd
->len
);
978 if (logptr
->max_log
> 0)
979 printf(" log logamount %d", logptr
->max_log
);
985 * then print the body.
987 if (rule
->usr_flags
& IPFW_USR_F_NORULE
) {
988 /* empty rules before options */
990 printf(" ip from any to any");
991 flags
|= HAVE_IP
| HAVE_OPTIONS
;
994 for (l
= rule
->act_ofs
, cmd
= rule
->cmd
;
995 l
> 0 ; l
-= F_LEN(cmd
) , cmd
+= F_LEN(cmd
)) {
997 ipfw_insn_u32
*cmd32
= (ipfw_insn_u32
*)cmd
;
999 show_prerequisites(&flags
, 0, cmd
->opcode
);
1001 switch(cmd
->opcode
) {
1003 break; /* done already */
1006 break; /* no need to print anything here */
1009 ipfw_insn_mac
*m
= (ipfw_insn_mac
*)cmd
;
1011 if ((cmd
->len
& F_OR
) && !or_block
)
1013 if (cmd
->len
& F_NOT
)
1017 print_mac( m
->addr
, m
->mask
);
1018 print_mac( m
->addr
+ 6, m
->mask
+ 6);
1023 if ((cmd
->len
& F_OR
) && !or_block
)
1025 print_newports((ipfw_insn_u16
*)cmd
, IPPROTO_ETHERTYPE
,
1026 (flags
& HAVE_OPTIONS
) ? cmd
->opcode
: 0);
1027 flags
|= HAVE_MAC
| HAVE_MACTYPE
| HAVE_OPTIONS
;
1034 case O_IP_SRC_TABLE
:
1036 show_prerequisites(&flags
, HAVE_PROTO
, 0);
1037 if (!(flags
& HAVE_SRCIP
))
1039 if ((cmd
->len
& F_OR
) && !or_block
)
1041 print_ip((ipfw_insn_ip
*)cmd
,
1042 (flags
& HAVE_OPTIONS
) ? " src-ip" : "");
1043 flags
|= HAVE_SRCIP
;
1050 case O_IP_DST_TABLE
:
1052 show_prerequisites(&flags
, HAVE_PROTO
|HAVE_SRCIP
, 0);
1053 if (!(flags
& HAVE_DSTIP
))
1055 if ((cmd
->len
& F_OR
) && !or_block
)
1057 print_ip((ipfw_insn_ip
*)cmd
,
1058 (flags
& HAVE_OPTIONS
) ? " dst-ip" : "");
1059 flags
|= HAVE_DSTIP
;
1063 show_prerequisites(&flags
, HAVE_IP
, 0);
1066 show_prerequisites(&flags
, HAVE_PROTO
|HAVE_SRCIP
, 0);
1067 if ((cmd
->len
& F_OR
) && !or_block
)
1069 print_newports((ipfw_insn_u16
*)cmd
, proto
,
1070 (flags
& HAVE_OPTIONS
) ? cmd
->opcode
: 0);
1074 struct protoent
*pe
;
1076 if ((cmd
->len
& F_OR
) && !or_block
)
1078 if (cmd
->len
& F_NOT
)
1081 pe
= getprotobynumber(cmd
->arg1
);
1082 if (flags
& HAVE_OPTIONS
)
1085 printf(" %s", pe
->p_name
);
1087 printf(" %u", cmd
->arg1
);
1089 flags
|= HAVE_PROTO
;
1092 default: /*options ... */
1093 show_prerequisites(&flags
, HAVE_IP
| HAVE_OPTIONS
, 0);
1094 if ((cmd
->len
& F_OR
) && !or_block
)
1096 if (cmd
->len
& F_NOT
&& cmd
->opcode
!= O_IN
)
1098 switch(cmd
->opcode
) {
1108 printf(cmd
->len
& F_NOT
? " out" : " in");
1118 ipfw_insn_if
*cmdif
= (ipfw_insn_if
*)cmd
;
1120 if (cmd
->opcode
== O_XMIT
)
1122 else if (cmd
->opcode
== O_RECV
)
1124 else if (cmd
->opcode
== O_VIA
)
1128 if (cmdif
->name
[0] == '\0')
1129 printf(" %s %s", dir
,
1130 inet_ntoa(cmdif
->p
.ip
));
1131 printf(" %s %s", dir
, cmdif
->name
);
1136 printf(" ipid %u", cmd
->arg1
);
1140 printf(" ipttl %u", cmd
->arg1
);
1144 printf(" ipver %u", cmd
->arg1
);
1147 case O_IPPRECEDENCE
:
1148 printf(" ipprecedence %u", (cmd
->arg1
) >> 5 );
1152 printf(" iplen %u", cmd
->arg1
);
1156 print_flags("ipoptions", cmd
, f_ipopts
);
1160 print_flags("iptos", cmd
, f_iptos
);
1165 print_icmp((ipfw_insn_u32
*)cmd
);
1169 printf(" established");
1173 print_flags("tcpflags", cmd
, f_tcpflags
);
1177 print_flags("tcpoptions", cmd
, f_tcpopts
);
1181 printf(" tcpwin %d", ntohs(cmd
->arg1
));
1185 printf(" tcpack %u", ntohl(cmd32
->d
[0]));
1189 printf(" tcpseq %u", ntohl(cmd32
->d
[0]));
1194 struct passwd
*pwd
= getpwuid(cmd32
->d
[0]);
1197 printf(" uid %s", pwd
->pw_name
);
1199 printf(" uid %u", cmd32
->d
[0]);
1205 struct group
*grp
= getgrgid(cmd32
->d
[0]);
1208 printf(" gid %s", grp
->gr_name
);
1210 printf(" gid %u", cmd32
->d
[0]);
1215 printf(" keep-state");
1220 ipfw_insn_rdr
*c
= (ipfw_insn_rdr
*)cmd
;
1222 printf(" rdr %s", inet_ntoa(c
->addr
));
1224 printf(",%u", ntohs(c
->port
));
1230 struct _s_x
*p
= limit_masks
;
1231 ipfw_insn_limit
*c
= (ipfw_insn_limit
*)cmd
;
1232 u_int8_t x
= c
->limit_mask
;
1233 const char *comma
= " ";
1236 for ( ; p
->x
!= 0 ; p
++)
1237 if ((x
& p
->x
) == p
->x
) {
1239 printf("%s%s", comma
, p
->s
);
1242 printf(" %d", c
->conn_limit
);
1247 printf(" [opcode %d len %d]",
1248 cmd
->opcode
, cmd
->len
);
1251 if (cmd
->len
& F_OR
) {
1254 } else if (or_block
) {
1259 show_prerequisites(&flags
, HAVE_IP
, 0);
1265 show_dyn_ipfw(struct ipfw_ioc_state
*d
, int pcwidth
, int bcwidth
)
1267 struct protoent
*pe
;
1271 if (!d
->expire
&& !(d
->dyn_type
== O_LIMIT_PARENT
))
1275 printf("%05u %*ju %*ju (%ds)", d
->rulenum
, pcwidth
, (uintmax_t)d
->pcnt
,
1276 bcwidth
, (uintmax_t)d
->bcnt
, d
->expire
);
1277 switch (d
->dyn_type
) {
1278 case O_LIMIT_PARENT
:
1279 printf(" PARENT %d", d
->count
);
1284 case O_KEEP_STATE
: /* bidir, no mask */
1288 printf(" REDIRECT");
1292 if ((pe
= getprotobynumber(d
->id
.u
.ip
.proto
)) != NULL
)
1293 printf(" %s", pe
->p_name
);
1295 printf(" proto %u", d
->id
.u
.ip
.proto
);
1297 a
.s_addr
= htonl(d
->id
.u
.ip
.src_ip
);
1298 printf(" %s %d", inet_ntoa(a
), d
->id
.u
.ip
.src_port
);
1300 a
.s_addr
= htonl(d
->id
.u
.ip
.dst_ip
);
1301 printf(" <-> %s %d", inet_ntoa(a
), d
->id
.u
.ip
.dst_port
);
1303 if (d
->dyn_type
== O_REDIRECT
) {
1304 struct in_addr xlat_addr
;
1306 xlat_addr
.s_addr
= htonl(d
->xlat_addr
);
1307 printf(" => %s %d", inet_ntoa(xlat_addr
), d
->xlat_port
);
1313 sort_q(const void *pa
, const void *pb
)
1315 int rev
= (do_sort
< 0);
1316 int field
= rev
? -do_sort
: do_sort
;
1318 const struct dn_ioc_flowqueue
*a
= pa
;
1319 const struct dn_ioc_flowqueue
*b
= pb
;
1323 res
= a
->len
- b
->len
;
1326 res
= a
->len_bytes
- b
->len_bytes
;
1329 case 3: /* tot pkts */
1330 res
= a
->tot_pkts
- b
->tot_pkts
;
1333 case 4: /* tot bytes */
1334 res
= a
->tot_bytes
- b
->tot_bytes
;
1341 return (int)(rev
? res
: -res
);
1345 list_queues(struct dn_ioc_flowset
*fs
, struct dn_ioc_flowqueue
*q
)
1349 printf(" mask: 0x%02x 0x%08x/0x%04x -> 0x%08x/0x%04x\n",
1350 fs
->flow_mask
.u
.ip
.proto
,
1351 fs
->flow_mask
.u
.ip
.src_ip
, fs
->flow_mask
.u
.ip
.src_port
,
1352 fs
->flow_mask
.u
.ip
.dst_ip
, fs
->flow_mask
.u
.ip
.dst_port
);
1353 if (fs
->rq_elements
== 0)
1356 printf("BKT Prot ___Source IP/port____ "
1357 "____Dest. IP/port____ Tot_pkt/bytes Pkt/Byte Drp\n");
1359 heapsort(q
, fs
->rq_elements
, sizeof(*q
), sort_q
);
1360 for (l
= 0; l
< fs
->rq_elements
; l
++) {
1362 struct protoent
*pe
;
1364 ina
.s_addr
= htonl(q
[l
].id
.u
.ip
.src_ip
);
1365 printf("%3d ", q
[l
].hash_slot
);
1366 pe
= getprotobynumber(q
[l
].id
.u
.ip
.proto
);
1368 printf("%-4s ", pe
->p_name
);
1370 printf("%4u ", q
[l
].id
.u
.ip
.proto
);
1371 printf("%15s/%-5d ",
1372 inet_ntoa(ina
), q
[l
].id
.u
.ip
.src_port
);
1373 ina
.s_addr
= htonl(q
[l
].id
.u
.ip
.dst_ip
);
1374 printf("%15s/%-5d ",
1375 inet_ntoa(ina
), q
[l
].id
.u
.ip
.dst_port
);
1376 printf("%4ju %8ju %2u %4u %3u\n",
1377 (uintmax_t)q
[l
].tot_pkts
, (uintmax_t)q
[l
].tot_bytes
,
1378 q
[l
].len
, q
[l
].len_bytes
, q
[l
].drops
);
1380 printf(" S %20ju F %20ju\n",
1381 (uintmax_t)q
[l
].S
, (uintmax_t)q
[l
].F
);
1386 print_flowset_parms(struct dn_ioc_flowset
*fs
, char *prefix
)
1391 char red
[90]; /* Display RED parameters */
1394 if (fs
->flags_fs
& DN_QSIZE_IS_BYTES
) {
1396 sprintf(qs
, "%d KB", l
/ 1024);
1398 sprintf(qs
, "%d B", l
);
1400 sprintf(qs
, "%3d sl.", l
);
1402 sprintf(plr
, "plr %f", 1.0 * fs
->plr
/ (double)(0x7fffffff));
1405 if (fs
->flags_fs
& DN_IS_RED
) /* RED parameters */
1407 "\n\t %cRED w_q %f min_th %d max_th %d max_p %f",
1408 (fs
->flags_fs
& DN_IS_GENTLE_RED
) ? 'G' : ' ',
1409 1.0 * fs
->w_q
/ (double)(1 << SCALE_RED
),
1410 SCALE_VAL(fs
->min_th
),
1411 SCALE_VAL(fs
->max_th
),
1412 1.0 * fs
->max_p
/ (double)(1 << SCALE_RED
));
1414 sprintf(red
, "droptail");
1416 printf("%s %s%s %d queues (%d buckets) %s\n",
1417 prefix
, qs
, plr
, fs
->rq_elements
, fs
->rq_size
, red
);
1421 list_pipes(void *data
, int nbytes
, int ac
, char *av
[])
1425 struct dn_ioc_pipe
*p
= (struct dn_ioc_pipe
*)data
;
1426 struct dn_ioc_flowset
*fs
;
1427 struct dn_ioc_flowqueue
*q
;
1431 rulenum
= strtoul(*av
++, NULL
, 10);
1434 for (; nbytes
>= (int)sizeof(*p
); p
= (struct dn_ioc_pipe
*)next
) {
1435 double b
= p
->bandwidth
;
1439 if (p
->fs
.fs_type
!= DN_IS_PIPE
)
1440 break; /* done with pipes, now queues */
1443 * compute length, as pipe have variable size
1445 l
= sizeof(*p
) + p
->fs
.rq_elements
* sizeof(*q
);
1446 next
= (uint8_t *)p
+ l
;
1449 if (rulenum
!= 0 && rulenum
!= (u_long
)p
->pipe_nr
)
1456 sprintf(buf
, "unlimited");
1457 else if (b
>= 1000000)
1458 sprintf(buf
, "%7.3f Mbit/s", b
/1000000);
1460 sprintf(buf
, "%7.3f Kbit/s", b
/1000);
1462 sprintf(buf
, "%7.3f bit/s ", b
);
1464 sprintf(prefix
, "%05d: %s %4d ms ",
1465 p
->pipe_nr
, buf
, p
->delay
);
1466 print_flowset_parms(&p
->fs
, prefix
);
1468 printf(" V %20ju\n", (uintmax_t)p
->V
>> MY_M
);
1470 q
= (struct dn_ioc_flowqueue
*)(p
+1);
1471 list_queues(&p
->fs
, q
);
1473 for (fs
= next
; nbytes
>= (int)sizeof(*fs
); fs
= next
) {
1476 if (fs
->fs_type
!= DN_IS_QUEUE
)
1478 l
= sizeof(*fs
) + fs
->rq_elements
* sizeof(*q
);
1479 next
= (uint8_t *)fs
+ l
;
1481 q
= (struct dn_ioc_flowqueue
*)(fs
+1);
1482 sprintf(prefix
, "q%05d: weight %d pipe %d ",
1483 fs
->fs_nr
, fs
->weight
, fs
->parent_nr
);
1484 print_flowset_parms(fs
, prefix
);
1490 * This one handles all set-related commands
1491 * ipfw set { show | enable | disable }
1493 * ipfw set move X to Y
1494 * ipfw set move rule X to Y
1497 sets_handler(int ac
, char *av
[])
1499 u_int32_t set_disable
, masks
[2];
1502 u_int8_t cmd
, new_set
;
1508 errx(EX_USAGE
, "set needs command");
1509 if (!strncmp(*av
, "show", strlen(*av
)) ) {
1513 nbytes
= sizeof(struct ipfw_ioc_rule
);
1514 if ((data
= malloc(nbytes
)) == NULL
)
1515 err(EX_OSERR
, "malloc");
1516 if (getsockopt(s
, IPPROTO_IP
, IP_FW_GET
, data
, &nbytes
) < 0)
1517 err(EX_OSERR
, "getsockopt(IP_FW_GET)");
1518 set_disable
= ((struct ipfw_ioc_rule
*)data
)->set_disable
;
1520 for (i
= 0, msg
= "disable" ; i
< 31; i
++)
1521 if ( (set_disable
& (1<<i
))) {
1522 printf("%s %d", msg
, i
);
1525 msg
= (set_disable
) ? " enable" : "enable";
1526 for (i
= 0; i
< 31; i
++)
1527 if ( !(set_disable
& (1<<i
))) {
1528 printf("%s %d", msg
, i
);
1532 } else if (!strncmp(*av
, "swap", strlen(*av
))) {
1535 errx(EX_USAGE
, "set swap needs 2 set numbers\n");
1536 rulenum
= atoi(av
[0]);
1537 new_set
= atoi(av
[1]);
1538 if (!isdigit(*(av
[0])) || rulenum
> 30)
1539 errx(EX_DATAERR
, "invalid set number %s\n", av
[0]);
1540 if (!isdigit(*(av
[1])) || new_set
> 30)
1541 errx(EX_DATAERR
, "invalid set number %s\n", av
[1]);
1542 masks
[0] = (4 << 24) | (new_set
<< 16) | (rulenum
);
1543 i
= setsockopt(s
, IPPROTO_IP
, IP_FW_DEL
,
1544 masks
, sizeof(u_int32_t
));
1545 } else if (!strncmp(*av
, "move", strlen(*av
))) {
1547 if (ac
&& !strncmp(*av
, "rule", strlen(*av
))) {
1552 if (ac
!= 3 || strncmp(av
[1], "to", strlen(*av
)))
1553 errx(EX_USAGE
, "syntax: set move [rule] X to Y\n");
1554 rulenum
= atoi(av
[0]);
1555 new_set
= atoi(av
[2]);
1556 if (!isdigit(*(av
[0])) || (cmd
== 3 && rulenum
> 30) ||
1557 (cmd
== 2 && rulenum
== 65535) )
1558 errx(EX_DATAERR
, "invalid source number %s\n", av
[0]);
1559 if (!isdigit(*(av
[2])) || new_set
> 30)
1560 errx(EX_DATAERR
, "invalid dest. set %s\n", av
[1]);
1561 masks
[0] = (cmd
<< 24) | (new_set
<< 16) | (rulenum
);
1562 i
= setsockopt(s
, IPPROTO_IP
, IP_FW_DEL
,
1563 masks
, sizeof(u_int32_t
));
1564 } else if (!strncmp(*av
, "disable", strlen(*av
)) ||
1565 !strncmp(*av
, "enable", strlen(*av
)) ) {
1566 int which
= !strncmp(*av
, "enable", strlen(*av
)) ? 1 : 0;
1569 masks
[0] = masks
[1] = 0;
1572 if (isdigit(**av
)) {
1574 if (i
< 0 || i
> 30)
1576 "invalid set number %d\n", i
);
1577 masks
[which
] |= (1<<i
);
1578 } else if (!strncmp(*av
, "disable", strlen(*av
)))
1580 else if (!strncmp(*av
, "enable", strlen(*av
)))
1584 "invalid set command %s\n", *av
);
1587 if ( (masks
[0] & masks
[1]) != 0 )
1589 "cannot enable and disable the same set\n");
1591 i
= setsockopt(s
, IPPROTO_IP
, IP_FW_DEL
, masks
, sizeof(masks
));
1593 warn("set enable/disable: setsockopt(IP_FW_DEL)");
1595 errx(EX_USAGE
, "invalid set command %s\n", *av
);
1599 sysctl_handler(int ac
, char *av
[], int which
)
1605 warnx("missing keyword to enable/disable\n");
1606 } else if (strncmp(*av
, "firewall", strlen(*av
)) == 0) {
1607 sysctlbyname("net.inet.ip.fw.enable", NULL
, 0,
1608 &which
, sizeof(which
));
1609 } else if (strncmp(*av
, "one_pass", strlen(*av
)) == 0) {
1610 sysctlbyname("net.inet.ip.fw.one_pass", NULL
, 0,
1611 &which
, sizeof(which
));
1612 } else if (strncmp(*av
, "debug", strlen(*av
)) == 0) {
1613 sysctlbyname("net.inet.ip.fw.debug", NULL
, 0,
1614 &which
, sizeof(which
));
1615 } else if (strncmp(*av
, "verbose", strlen(*av
)) == 0) {
1616 sysctlbyname("net.inet.ip.fw.verbose", NULL
, 0,
1617 &which
, sizeof(which
));
1618 } else if (strncmp(*av
, "dyn_keepalive", strlen(*av
)) == 0) {
1619 sysctlbyname("net.inet.ip.fw.dyn_keepalive", NULL
, 0,
1620 &which
, sizeof(which
));
1622 warnx("unrecognize enable/disable keyword: %s\n", *av
);
1627 list(int ac
, char *av
[])
1629 struct ipfw_ioc_rule
*r
;
1630 struct ipfw_ioc_state
*dynrules
, *d
;
1633 int bcwidth
, n
, nbytes
, nstat
, ndyn
, pcwidth
, width
;
1634 int exitval
= EX_OK
;
1641 const int ocmd
= do_pipe
? IP_DUMMYNET_GET
: IP_FW_GET
;
1642 int nalloc
= 1024; /* start somewhere... */
1647 /* get rules or pipes from kernel, resizing array as necessary */
1650 while (nbytes
>= nalloc
) {
1651 nalloc
= nalloc
* 2 + 200;
1653 if ((data
= realloc(data
, nbytes
)) == NULL
)
1654 err(EX_OSERR
, "realloc");
1655 if (getsockopt(s
, IPPROTO_IP
, ocmd
, data
, &nbytes
) < 0)
1656 err(EX_OSERR
, "getsockopt(IP_%s_GET)",
1657 do_pipe
? "DUMMYNET" : "FW");
1661 list_pipes(data
, nbytes
, ac
, av
);
1666 * Count static rules.
1669 nstat
= r
->static_count
;
1672 * Count dynamic rules. This is easier as they have
1675 dynrules
= (struct ipfw_ioc_state
*)((uint8_t *)r
+ r
->static_len
);
1676 ndyn
= (nbytes
- r
->static_len
) / sizeof(*dynrules
);
1678 /* if showing stats, figure out column widths ahead of time */
1679 bcwidth
= pcwidth
= 0;
1681 for (n
= 0, r
= data
; n
< nstat
; n
++,
1682 r
= (struct ipfw_ioc_rule
*)((uint8_t *)r
+ IOC_RULESIZE(r
))) {
1683 /* packet counter */
1684 width
= snprintf(NULL
, 0, "%ju", (uintmax_t)r
->pcnt
);
1685 if (width
> pcwidth
)
1689 width
= snprintf(NULL
, 0, "%ju", (uintmax_t)r
->bcnt
);
1690 if (width
> bcwidth
)
1694 if (do_dynamic
&& ndyn
) {
1695 for (n
= 0, d
= dynrules
; n
< ndyn
; n
++, d
++) {
1696 width
= snprintf(NULL
, 0, "%ju", (uintmax_t)d
->pcnt
);
1697 if (width
> pcwidth
)
1700 width
= snprintf(NULL
, 0, "%ju", (uintmax_t)d
->bcnt
);
1701 if (width
> bcwidth
)
1705 /* if no rule numbers were specified, list all rules */
1707 for (n
= 0, r
= data
; n
< nstat
; n
++,
1708 r
= (struct ipfw_ioc_rule
*)((uint8_t *)r
+ IOC_RULESIZE(r
)))
1709 show_ipfw(r
, pcwidth
, bcwidth
);
1711 if (do_dynamic
&& ndyn
) {
1712 printf("## Dynamic rules (%d):\n", ndyn
);
1713 for (n
= 0, d
= dynrules
; n
< ndyn
; n
++, d
++)
1714 show_dyn_ipfw(d
, pcwidth
, bcwidth
);
1719 /* display specific rules requested on command line */
1721 for (lac
= ac
, lav
= av
; lac
!= 0; lac
--) {
1722 /* convert command line rule # */
1723 rnum
= strtoul(*lav
++, &endptr
, 10);
1726 warnx("invalid rule number: %s", *(lav
- 1));
1729 for (n
= seen
= 0, r
= data
; n
< nstat
; n
++,
1730 r
= (struct ipfw_ioc_rule
*)((uint8_t *)r
+ IOC_RULESIZE(r
))) {
1731 if (r
->rulenum
> rnum
)
1733 if (r
->rulenum
== rnum
) {
1734 show_ipfw(r
, pcwidth
, bcwidth
);
1739 /* give precedence to other error(s) */
1740 if (exitval
== EX_OK
)
1741 exitval
= EX_UNAVAILABLE
;
1742 warnx("rule %lu does not exist", rnum
);
1746 if (do_dynamic
&& ndyn
) {
1747 printf("## Dynamic rules:\n");
1748 for (lac
= ac
, lav
= av
; lac
!= 0; lac
--) {
1749 rnum
= strtoul(*lav
++, &endptr
, 10);
1751 /* already warned */
1753 for (n
= 0, d
= dynrules
; n
< ndyn
; n
++, d
++) {
1754 if (d
->rulenum
> rnum
)
1756 if (d
->rulenum
== rnum
)
1757 show_dyn_ipfw(d
, pcwidth
, bcwidth
);
1767 if (exitval
!= EX_OK
)
1774 fprintf(stderr
, "usage: ipfw [options]\n"
1775 " add [number] rule\n"
1776 " pipe number config [pipeconfig]\n"
1777 " queue number config [queueconfig]\n"
1779 " [pipe] delete number ...\n"
1780 " [pipe] {list|show} [number ...]\n"
1781 " {zero|resetlog} [number ...]\n"
1782 "do \"ipfw -h\" or see ipfw manpage for details\n"
1792 fprintf(stderr
, "ipfw syntax summary:\n"
1793 "ipfw add [N] [prob {0..1}] ACTION [log [logamount N]] ADDR OPTIONS\n"
1794 "ipfw {pipe|queue} N config BODY\n"
1795 "ipfw [pipe] {zero|delete|show} [N{,N}]\n"
1797 "RULE: [1..] [PROB] BODY\n"
1798 "RULENUM: INTEGER(1..65534)\n"
1799 "PROB: prob REAL(0..1)\n"
1800 "BODY: check-state [LOG] (no body) |\n"
1801 " ACTION [LOG] MATCH_ADDR [OPTION_LIST]\n"
1802 "ACTION: check-state | allow | count | deny | reject | skipto N |\n"
1803 " {divert|tee} PORT | forward ADDR | pipe N | queue N\n"
1804 "ADDR: [ MAC dst src ether_type ] \n"
1805 " [ from IPLIST [ PORT ] to IPLIST [ PORTLIST ] ]\n"
1806 "IPLIST: IPADDR | ( IPADDR or ... or IPADDR )\n"
1807 "IPADDR: [not] { any | me | ip | ip/bits | ip:mask | ip/bits{x,y,z} }\n"
1808 "OPTION_LIST: OPTION [,OPTION_LIST]\n"
1815 lookup_host (char *host
, struct in_addr
*ipaddr
)
1819 if (!inet_aton(host
, ipaddr
)) {
1820 if ((he
= gethostbyname(host
)) == NULL
)
1822 *ipaddr
= *(struct in_addr
*)he
->h_addr_list
[0];
1828 * fills the addr and mask fields in the instruction as appropriate from av.
1829 * Update length as appropriate.
1830 * The following formats are allowed:
1831 * any matches any IP. Actually returns an empty instruction.
1832 * me returns O_IP_*_ME
1833 * <table_id> O_IP_*_TABLE
1834 * [iface[:net]] O_IP_*_IFIP
1835 * 1.2.3.4 single IP address
1836 * 1.2.3.4:5.6.7.8 address:mask
1837 * 1.2.3.4/24 address/mask
1838 * 1.2.3.4/26{1,6,5,4,23} set of addresses in a subnet
1841 fill_ip(ipfw_insn_ip
*cmd
, char *av
)
1843 char *p
= NULL
, md
= 0;
1846 cmd
->o
.len
&= ~F_LEN_MASK
; /* zero len */
1848 if (!strncmp(av
, "any", strlen(av
)))
1851 if (!strncmp(av
, "me", strlen(av
))) {
1852 cmd
->o
.len
|= F_INSN_SIZE(ipfw_insn
);
1856 if (strlen(av
) >= 3 && av
[0] == '<' && av
[strlen(av
) - 1] == '>') {
1857 int pos
= strlen(av
) - 1;
1862 * Table: "<tableid>"
1865 tableid
= strtoul(&av
[1], &eptr
, 0);
1866 if (*eptr
!= '\0') {
1868 errx(EX_DATAERR
, "invalid tableid ``%s''", av
);
1871 cmd
->o
.len
|= F_INSN_SIZE(ipfw_insn
);
1872 cmd
->o
.opcode
= O_IP_DST_TABLE
;
1873 cmd
->o
.arg1
= tableid
;
1877 if (strlen(av
) >= 3 && av
[0] == '[' && av
[strlen(av
) - 1] == ']') {
1878 int pos
= strlen(av
) - 1;
1879 ipfw_insn_ifip
*cmd1
= (ipfw_insn_ifip
*)cmd
;
1883 * Interface IP: "[ifname[:net]]"
1885 cmd1
->o
.len
|= F_INSN_SIZE(ipfw_insn_ifip
);
1886 cmd1
->o
.opcode
= O_IP_DST_IFIP
;
1888 cmd1
->addr
.s_addr
= 0;
1889 cmd1
->mask
.s_addr
= 0;
1892 c
= strchr(av
, ':');
1894 if (strcmp(c
+ 1, "net") == 0) {
1895 cmd1
->o
.arg1
|= IPFW_IFIP_NET
;
1897 errx(EX_DATAERR
, "invalid ifname modifier: %s",
1903 strlcpy(cmd1
->ifname
, &av
[1], sizeof(cmd1
->ifname
));
1910 p
= strchr(av
, '/');
1912 p
= strchr(av
, ':');
1918 if (lookup_host(av
, &cmd
->addr
) != 0)
1919 errx(EX_NOHOST
, "hostname ``%s'' unknown", av
);
1922 if (!inet_aton(p
, &cmd
->mask
))
1923 errx(EX_DATAERR
, "bad netmask ``%s''", p
);
1928 cmd
->mask
.s_addr
= htonl(0);
1930 errx(EX_DATAERR
, "bad width ``%s''", p
);
1932 cmd
->mask
.s_addr
= htonl(~0U << (32 - i
));
1935 cmd
->mask
.s_addr
= htonl(~0);
1938 cmd
->addr
.s_addr
&= cmd
->mask
.s_addr
;
1940 * now look if we have a set of addresses. They are stored as follows:
1941 * arg1 is the set size (powers of 2, 2..256)
1942 * addr is the base address IN HOST FORMAT
1943 * mask.. is an array of u_int32_t with bits set.
1947 if (p
) { /* fetch addresses */
1950 int ii
= contigmask((u_char
*)&(cmd
->mask
), 32);
1952 if (ii
< 24 || ii
> 31) {
1953 fprintf(stderr
, "invalid set with mask %d\n",
1957 cmd
->o
.arg1
= 1<<(32-ii
);
1958 cmd
->addr
.s_addr
= ntohl(cmd
->addr
.s_addr
);
1959 d
= (u_int32_t
*)&cmd
->mask
;
1960 cmd
->o
.opcode
= O_IP_DST_SET
; /* default */
1961 cmd
->o
.len
|= F_INSN_SIZE(ipfw_insn_u32
) + (cmd
->o
.arg1
+31)/32;
1962 for (ii
= 0; ii
< (cmd
->o
.arg1
+31)/32 ; ii
++)
1963 d
[ii
] = 0; /* clear masks */
1966 low
= cmd
->addr
.s_addr
& 0xff;
1967 high
= low
+ cmd
->o
.arg1
- 1;
1968 while (isdigit(*av
)) {
1970 u_int16_t a
= strtol(av
, &str
, 0);
1972 if (str
== av
) /* no parameter */
1974 if (a
< low
|| a
> high
) {
1975 fprintf(stderr
, "addr %d out of range [%d-%d]\n",
1980 d
[ a
/32] |= 1<<(a
& 31);
1988 if (cmd
->mask
.s_addr
== 0) { /* any */
1989 if (cmd
->o
.len
& F_NOT
)
1990 errx(EX_DATAERR
, "not any never matches");
1991 else /* useless, nuke it */
1993 } else if (cmd
->mask
.s_addr
== IP_MASK_ALL
) /* one IP */
1994 cmd
->o
.len
|= F_INSN_SIZE(ipfw_insn_u32
);
1995 else /* addr/mask */
1996 cmd
->o
.len
|= F_INSN_SIZE(ipfw_insn_ip
);
2001 * helper function to process a set of flags and set bits in the
2002 * appropriate masks.
2005 fill_flags(ipfw_insn
*cmd
, enum ipfw_opcodes opcode
,
2006 struct _s_x
*flags
, char *p
)
2008 u_int8_t set
=0, clear
=0;
2011 char *q
; /* points to the separator */
2013 u_int8_t
*which
; /* mask we are working on */
2023 val
= match_token(flags
, p
);
2025 errx(EX_DATAERR
, "invalid flag %s", p
);
2026 *which
|= (u_int8_t
)val
;
2029 cmd
->opcode
= opcode
;
2030 cmd
->len
= (cmd
->len
& (F_NOT
| F_OR
)) | 1;
2031 cmd
->arg1
= (set
& 0xff) | ( (clear
& 0xff) << 8);
2036 delete(int ac
, char *av
[])
2039 struct dn_ioc_pipe pipe
;
2041 int exitval
= EX_OK
;
2044 memset(&pipe
, 0, sizeof pipe
);
2047 if (ac
> 0 && !strncmp(*av
, "set", strlen(*av
))) {
2048 do_set
= 1; /* delete set */
2053 while (ac
&& isdigit(**av
)) {
2054 i
= atoi(*av
); av
++; ac
--;
2060 i
= setsockopt(s
, IPPROTO_IP
, IP_DUMMYNET_DEL
,
2061 &pipe
, sizeof pipe
);
2064 warn("rule %u: setsockopt(IP_DUMMYNET_DEL)",
2065 do_pipe
== 1 ? pipe
.pipe_nr
:
2069 rulenum
= (i
& 0xffff) | (do_set
<< 24);
2070 i
= setsockopt(s
, IPPROTO_IP
, IP_FW_DEL
, &rulenum
,
2073 exitval
= EX_UNAVAILABLE
;
2074 warn("rule %u: setsockopt(IP_FW_DEL)",
2079 if (exitval
!= EX_OK
)
2085 * fill the interface structure. We do not check the name as we can
2086 * create interfaces dynamically, so checking them at insert time
2087 * makes relatively little sense.
2088 * Interface names containing '*', '?', or '[' are assumed to be shell
2089 * patterns which match interfaces.
2092 fill_iface(ipfw_insn_if
*cmd
, char *arg
)
2094 cmd
->name
[0] = '\0';
2095 cmd
->o
.len
|= F_INSN_SIZE(ipfw_insn_if
);
2097 /* Parse the interface or address */
2098 if (!strcmp(arg
, "any"))
2099 cmd
->o
.len
= 0; /* effectively ignore this command */
2100 else if (!isdigit(*arg
)) {
2101 strlcpy(cmd
->name
, arg
, sizeof(cmd
->name
));
2102 cmd
->p
.glob
= strpbrk(arg
, "*?[") != NULL
? 1 : 0;
2103 } else if (!inet_aton(arg
, &cmd
->p
.ip
))
2104 errx(EX_DATAERR
, "bad ip address ``%s''", arg
);
2107 static unsigned long
2108 getbw(const char *str
, u_short
*flags
, int kb
)
2114 val
= strtoul(str
, &end
, 0);
2115 if (*end
== 'k' || *end
== 'K') {
2118 } else if (*end
== 'm' || *end
== 'M') {
2124 * Deal with bits or bytes or b(bits) or B(bytes). If there is no
2125 * trailer assume bits.
2127 if (strncasecmp(end
, "bit", 3) == 0) {
2129 } else if (strncasecmp(end
, "byte", 4) == 0) {
2131 } else if (*end
== 'b') {
2133 } else if (*end
== 'B') {
2138 * Return in bits if flags is NULL, else flag bits
2139 * or bytes in flags and return the unconverted value.
2141 if (inbytes
&& flags
)
2142 *flags
|= DN_QSIZE_IS_BYTES
;
2143 else if (inbytes
&& flags
== NULL
)
2149 * the following macro returns an error message if we run out of
2152 #define NEED1(msg) {if (!ac) errx(EX_USAGE, msg);}
2155 config_pipe(int ac
, char **av
)
2157 struct dn_ioc_pipe pipe
;
2162 memset(&pipe
, 0, sizeof pipe
);
2166 if (ac
&& isdigit(**av
)) {
2167 i
= atoi(*av
); av
++; ac
--;
2175 int tok
= match_token(dummynet_params
, *av
);
2180 pipe
.fs
.flags_fs
|= DN_NOERROR
;
2184 NEED1("plr needs argument 0..1\n");
2185 d
= strtod(av
[0], NULL
);
2190 pipe
.fs
.plr
= (int)(d
*0x7fffffff);
2195 NEED1("queue needs queue size\n");
2197 pipe
.fs
.qsize
= getbw(av
[0], &pipe
.fs
.flags_fs
, 1024);
2202 NEED1("buckets needs argument\n");
2203 pipe
.fs
.rq_size
= strtoul(av
[0], NULL
, 0);
2208 NEED1("mask needs mask specifier\n");
2210 * per-flow queue, mask is dst_ip, dst_port,
2211 * src_ip, src_port, proto measured in bits
2214 pipe
.fs
.flow_mask
.type
= ETHERTYPE_IP
;
2215 pipe
.fs
.flow_mask
.u
.ip
.dst_ip
= 0;
2216 pipe
.fs
.flow_mask
.u
.ip
.src_ip
= 0;
2217 pipe
.fs
.flow_mask
.u
.ip
.dst_port
= 0;
2218 pipe
.fs
.flow_mask
.u
.ip
.src_port
= 0;
2219 pipe
.fs
.flow_mask
.u
.ip
.proto
= 0;
2223 u_int32_t
*p32
= NULL
;
2224 u_int16_t
*p16
= NULL
;
2226 tok
= match_token(dummynet_params
, *av
);
2231 * special case, all bits significant
2233 pipe
.fs
.flow_mask
.u
.ip
.dst_ip
= ~0;
2234 pipe
.fs
.flow_mask
.u
.ip
.src_ip
= ~0;
2235 pipe
.fs
.flow_mask
.u
.ip
.dst_port
= ~0;
2236 pipe
.fs
.flow_mask
.u
.ip
.src_port
= ~0;
2237 pipe
.fs
.flow_mask
.u
.ip
.proto
= ~0;
2238 pipe
.fs
.flags_fs
|= DN_HAVE_FLOW_MASK
;
2242 p32
= &pipe
.fs
.flow_mask
.u
.ip
.dst_ip
;
2246 p32
= &pipe
.fs
.flow_mask
.u
.ip
.src_ip
;
2250 p16
= &pipe
.fs
.flow_mask
.u
.ip
.dst_port
;
2254 p16
= &pipe
.fs
.flow_mask
.u
.ip
.src_port
;
2261 ac
++; av
--; /* backtrack */
2265 errx(EX_USAGE
, "mask: value missing");
2266 if (*av
[0] == '/') {
2267 a
= strtoul(av
[0]+1, &end
, 0);
2268 a
= (a
== 32) ? ~0 : (1 << a
) - 1;
2270 a
= strtoul(av
[0], &end
, 0);
2273 else if (p16
!= NULL
) {
2276 "mask: must be 16 bit");
2277 *p16
= (u_int16_t
)a
;
2281 "mask: must be 8 bit");
2282 pipe
.fs
.flow_mask
.u
.ip
.proto
= (uint8_t)a
;
2285 pipe
.fs
.flags_fs
|= DN_HAVE_FLOW_MASK
;
2287 } /* end while, config masks */
2293 NEED1("red/gred needs w_q/min_th/max_th/max_p\n");
2294 pipe
.fs
.flags_fs
|= DN_IS_RED
;
2295 if (tok
== TOK_GRED
)
2296 pipe
.fs
.flags_fs
|= DN_IS_GENTLE_RED
;
2298 * the format for parameters is w_q/min_th/max_th/max_p
2300 if ((end
= strsep(&av
[0], "/"))) {
2301 double w_q
= strtod(end
, NULL
);
2302 if (w_q
> 1 || w_q
<= 0)
2303 errx(EX_DATAERR
, "0 < w_q <= 1");
2304 pipe
.fs
.w_q
= (int) (w_q
* (1 << SCALE_RED
));
2306 if ((end
= strsep(&av
[0], "/"))) {
2307 pipe
.fs
.min_th
= strtoul(end
, &end
, 0);
2308 if (*end
== 'K' || *end
== 'k')
2309 pipe
.fs
.min_th
*= 1024;
2311 if ((end
= strsep(&av
[0], "/"))) {
2312 pipe
.fs
.max_th
= strtoul(end
, &end
, 0);
2313 if (*end
== 'K' || *end
== 'k')
2314 pipe
.fs
.max_th
*= 1024;
2316 if ((end
= strsep(&av
[0], "/"))) {
2317 double max_p
= strtod(end
, NULL
);
2318 if (max_p
> 1 || max_p
<= 0)
2319 errx(EX_DATAERR
, "0 < max_p <= 1");
2320 pipe
.fs
.max_p
= (int)(max_p
* (1 << SCALE_RED
));
2326 pipe
.fs
.flags_fs
&= ~(DN_IS_RED
|DN_IS_GENTLE_RED
);
2330 NEED1("bw needs bandwidth\n");
2332 errx(EX_DATAERR
, "bandwidth only valid for pipes");
2334 * set bandwidth value
2336 pipe
.bandwidth
= getbw(av
[0], NULL
, 1000);
2337 if (pipe
.bandwidth
< 0)
2338 errx(EX_DATAERR
, "bandwidth too large");
2344 errx(EX_DATAERR
, "delay only valid for pipes");
2345 NEED1("delay needs argument 0..10000ms\n");
2346 pipe
.delay
= strtoul(av
[0], NULL
, 0);
2352 errx(EX_DATAERR
,"weight only valid for queues");
2353 NEED1("weight needs argument 0..100\n");
2354 pipe
.fs
.weight
= strtoul(av
[0], &end
, 0);
2360 errx(EX_DATAERR
,"pipe only valid for queues");
2361 NEED1("pipe needs pipe_number\n");
2362 pipe
.fs
.parent_nr
= strtoul(av
[0], &end
, 0);
2367 errx(EX_DATAERR
, "unrecognised option ``%s''", *av
);
2371 if (pipe
.pipe_nr
== 0)
2372 errx(EX_DATAERR
, "pipe_nr must be > 0");
2373 if (pipe
.delay
> 10000)
2374 errx(EX_DATAERR
, "delay must be < 10000");
2375 } else { /* do_pipe == 2, queue */
2376 if (pipe
.fs
.parent_nr
== 0)
2377 errx(EX_DATAERR
, "pipe must be > 0");
2378 if (pipe
.fs
.weight
>100)
2379 errx(EX_DATAERR
, "weight must be <= 100");
2381 if (pipe
.fs
.flags_fs
& DN_QSIZE_IS_BYTES
) {
2382 if (pipe
.fs
.qsize
> 1024*1024)
2383 errx(EX_DATAERR
, "queue size must be < 1MB");
2385 if (pipe
.fs
.qsize
> 100)
2386 errx(EX_DATAERR
, "2 <= queue size <= 100");
2388 if (pipe
.fs
.flags_fs
& DN_IS_RED
) {
2390 int lookup_depth
, avg_pkt_size
;
2391 double step
, idle
, weight
, w_q
;
2395 if (pipe
.fs
.min_th
>= pipe
.fs
.max_th
)
2396 errx(EX_DATAERR
, "min_th %d must be < than max_th %d",
2397 pipe
.fs
.min_th
, pipe
.fs
.max_th
);
2398 if (pipe
.fs
.max_th
== 0)
2399 errx(EX_DATAERR
, "max_th must be > 0");
2402 if (sysctlbyname("net.inet.ip.dummynet.red_lookup_depth",
2403 &lookup_depth
, &len
, NULL
, 0) == -1)
2405 errx(1, "sysctlbyname(\"%s\")",
2406 "net.inet.ip.dummynet.red_lookup_depth");
2407 if (lookup_depth
== 0)
2408 errx(EX_DATAERR
, "net.inet.ip.dummynet.red_lookup_depth"
2409 " must be greater than zero");
2412 if (sysctlbyname("net.inet.ip.dummynet.red_avg_pkt_size",
2413 &avg_pkt_size
, &len
, NULL
, 0) == -1)
2415 errx(1, "sysctlbyname(\"%s\")",
2416 "net.inet.ip.dummynet.red_avg_pkt_size");
2417 if (avg_pkt_size
== 0)
2419 "net.inet.ip.dummynet.red_avg_pkt_size must"
2420 " be greater than zero");
2422 len
= sizeof(clock_hz
);
2423 if (sysctlbyname("net.inet.ip.dummynet.hz", &clock_hz
, &len
,
2425 errx(1, "sysctlbyname(\"%s\")",
2426 "net.inet.ip.dummynet.hz");
2430 * Ticks needed for sending a medium-sized packet.
2431 * Unfortunately, when we are configuring a WF2Q+ queue, we
2432 * do not have bandwidth information, because that is stored
2433 * in the parent pipe, and also we have multiple queues
2434 * competing for it. So we set step=0, which is not very
2435 * correct. But on the other hand, why do we want RED with
2438 if (pipe
.bandwidth
==0) /* this is a WF2Q+ queue */
2441 step
= clock_hz
* avg_pkt_size
* 8 / pipe
.bandwidth
;
2444 * max idle time (in ticks) before avg queue size becomes 0.
2445 * NOTA: (3/w_q) is approx the value x so that
2446 * (1-w_q)^x < 10^-3.
2448 w_q
= ((double)pipe
.fs
.w_q
) / (1 << SCALE_RED
);
2449 idle
= step
* 3. / w_q
;
2450 pipe
.fs
.lookup_step
= (int)idle
/ lookup_depth
;
2451 if (!pipe
.fs
.lookup_step
)
2452 pipe
.fs
.lookup_step
= 1;
2454 for (t
= pipe
.fs
.lookup_step
; t
> 0; --t
)
2456 pipe
.fs
.lookup_weight
= (int)(weight
* (1 << SCALE_RED
));
2458 i
= setsockopt(s
, IPPROTO_IP
, IP_DUMMYNET_CONFIGURE
, &pipe
,
2461 err(1, "setsockopt(%s)", "IP_DUMMYNET_CONFIGURE");
2465 get_mac_addr_mask(char *p
, u_char
*addr
, u_char
*mask
)
2470 addr
[i
] = mask
[i
] = 0;
2471 if (!strcmp(p
, "any"))
2474 for (i
=0; *p
&& i
<6;i
++, p
++) {
2475 addr
[i
] = strtol(p
, &p
, 16);
2476 if (*p
!= ':') /* we start with the mask */
2479 if (*p
== '/') { /* mask len */
2480 l
= strtol(p
+1, &p
, 0);
2481 for (i
=0; l
>0; l
-=8, i
++)
2482 mask
[i
] = (l
>=8) ? 0xff : (~0U) << (8-l
);
2483 } else if (*p
== '&') { /* mask */
2484 for (i
=0, p
++; *p
&& i
<6;i
++, p
++) {
2485 mask
[i
] = strtol(p
, &p
, 16);
2489 } else if (*p
== '\0') {
2498 * helper function, updates the pointer to cmd with the length
2499 * of the current command, and also cleans up the first word of
2500 * the new command in case it has been clobbered before.
2503 next_cmd(ipfw_insn
*cmd
)
2506 bzero(cmd
, sizeof(*cmd
));
2511 * A function to fill simple commands of size 1.
2512 * Existing flags are preserved.
2515 fill_cmd(ipfw_insn
*cmd
, enum ipfw_opcodes opcode
, int flags
, u_int16_t arg
)
2517 cmd
->opcode
= opcode
;
2518 cmd
->len
= ((cmd
->len
| flags
) & (F_NOT
| F_OR
)) | 1;
2523 * Fetch and add the MAC address and type, with masks. This generates one or
2524 * two microinstructions, and returns the pointer to the last one.
2527 add_mac(ipfw_insn
*cmd
, int ac
, char *av
[])
2532 errx(EX_DATAERR
, "MAC dst src");
2534 cmd
->opcode
= O_MACADDR2
;
2535 cmd
->len
= (cmd
->len
& (F_NOT
| F_OR
)) | F_INSN_SIZE(ipfw_insn_mac
);
2537 mac
= (ipfw_insn_mac
*)cmd
;
2538 get_mac_addr_mask(av
[0], mac
->addr
, mac
->mask
); /* dst */
2539 get_mac_addr_mask(av
[1], &(mac
->addr
[6]), &(mac
->mask
[6])); /* src */
2544 add_mactype(ipfw_insn
*cmd
, int ac
, char *av
)
2547 errx(EX_DATAERR
, "missing MAC type");
2548 if (strcmp(av
, "any") != 0) { /* we have a non-null type */
2549 fill_newports((ipfw_insn_u16
*)cmd
, av
, IPPROTO_ETHERTYPE
);
2550 cmd
->opcode
= O_MAC_TYPE
;
2557 add_proto(ipfw_insn
*cmd
, char *av
)
2559 struct protoent
*pe
;
2562 if (!strncmp(av
, "all", strlen(av
)))
2563 ; /* same as "ip" */
2564 else if ((proto
= atoi(av
)) > 0)
2566 else if ((pe
= getprotobyname(av
)) != NULL
)
2567 proto
= pe
->p_proto
;
2570 if (proto
!= IPPROTO_IP
)
2571 fill_cmd(cmd
, O_PROTO
, 0, proto
);
2576 add_srcip(ipfw_insn
*cmd
, char *av
)
2578 fill_ip((ipfw_insn_ip
*)cmd
, av
);
2579 if (cmd
->opcode
== O_IP_DST_SET
) /* set */
2580 cmd
->opcode
= O_IP_SRC_SET
;
2581 else if (cmd
->opcode
== O_IP_DST_TABLE
) /* table */
2582 cmd
->opcode
= O_IP_SRC_TABLE
;
2583 else if (cmd
->opcode
== O_IP_DST_IFIP
) /* iface's IP */
2584 cmd
->opcode
= O_IP_SRC_IFIP
;
2585 else if (F_LEN(cmd
) == F_INSN_SIZE(ipfw_insn
)) /* me */
2586 cmd
->opcode
= O_IP_SRC_ME
;
2587 else if (F_LEN(cmd
) == F_INSN_SIZE(ipfw_insn_u32
)) /* one IP */
2588 cmd
->opcode
= O_IP_SRC
;
2589 else if (F_LEN(cmd
) == F_INSN_SIZE(ipfw_insn_ip
)) /* addr/mask */
2590 cmd
->opcode
= O_IP_SRC_MASK
;
2595 add_dstip(ipfw_insn
*cmd
, char *av
)
2597 fill_ip((ipfw_insn_ip
*)cmd
, av
);
2598 if (cmd
->opcode
== O_IP_DST_SET
) /* set */
2600 else if (cmd
->opcode
== O_IP_DST_TABLE
) /* table */
2602 else if (cmd
->opcode
== O_IP_DST_IFIP
) /* iface's IP */
2604 else if (F_LEN(cmd
) == F_INSN_SIZE(ipfw_insn
)) /* me */
2605 cmd
->opcode
= O_IP_DST_ME
;
2606 else if (F_LEN(cmd
) == F_INSN_SIZE(ipfw_insn_u32
)) /* one IP */
2607 cmd
->opcode
= O_IP_DST
;
2608 else if (F_LEN(cmd
) == F_INSN_SIZE(ipfw_insn_ip
)) /* addr/mask */
2609 cmd
->opcode
= O_IP_DST_MASK
;
2614 add_ports(ipfw_insn
*cmd
, char *av
, u_char proto
, int opcode
)
2616 if (!strncmp(av
, "any", strlen(av
))) {
2618 } else if (fill_newports((ipfw_insn_u16
*)cmd
, av
, proto
)) {
2619 /* XXX todo: check that we have a protocol with ports */
2620 cmd
->opcode
= opcode
;
2627 fill_rdr(ipfw_insn
*cmd
, char *av
)
2629 ipfw_insn_rdr
*c
= (ipfw_insn_rdr
*)cmd
;
2632 cmd
->opcode
= O_REDIRECT
;
2633 cmd
->len
= F_INSN_SIZE(ipfw_insn_rdr
);
2635 c
->addr
.s_addr
= INADDR_ANY
;
2637 c
->set
= UINT16_MAX
;
2639 p
= strchr(av
, ',');
2641 p
= strchr(av
, ':');
2644 lookup_host(av
, &c
->addr
);
2646 if (p
!= NULL
&& *(p
+ 1) != '\0') {
2649 c
->port
= strtoul(p
+ 1, &ep
, 0);
2651 errx(EX_DATAERR
, "illegal port %s", p
+ 1);
2652 c
->port
= htons(c
->port
);
2657 * Parse arguments and assemble the microinstructions which make up a rule.
2658 * Rules are added into the 'rulebuf' and then copied in the correct order
2659 * into the actual rule.
2661 * The syntax for a rule starts with the action, followed by an
2662 * optional log action, and the various match patterns.
2663 * In the assembled microcode, the first opcode must be a O_PROBE_STATE
2664 * (generated if the rule includes a keep-state option), then the
2665 * various match patterns, the "log" action, and the actual action.
2669 add(int ac
, char *av
[])
2672 * rules are added into the 'rulebuf' and then copied in
2673 * the correct order into the actual rule.
2674 * Some things that need to go out of order (prob, action etc.)
2677 static uint32_t rulebuf
[IPFW_RULE_SIZE_MAX
];
2678 static uint32_t actbuf
[IPFW_RULE_SIZE_MAX
];
2679 static uint32_t cmdbuf
[IPFW_RULE_SIZE_MAX
];
2681 ipfw_insn
*src
, *dst
, *cmd
, *action
, *prev
= NULL
;
2682 ipfw_insn
*first_cmd
; /* first match pattern */
2684 struct ipfw_ioc_rule
*rule
;
2687 * various flags used to record that we entered some fields.
2689 ipfw_insn
*have_state
= NULL
; /* check-state or keep-state */
2693 int open_par
= 0; /* open parenthesis ( */
2695 int has_dstport
= 0;
2698 /* proto is here because it is used to fetch ports */
2699 u_char proto
= IPPROTO_IP
; /* default protocol */
2701 double match_prob
= 1; /* match probability, default is always match */
2703 bzero(actbuf
, sizeof(actbuf
)); /* actions go here */
2704 bzero(cmdbuf
, sizeof(cmdbuf
));
2705 bzero(rulebuf
, sizeof(rulebuf
));
2707 rule
= (struct ipfw_ioc_rule
*)rulebuf
;
2708 cmd
= (ipfw_insn
*)cmdbuf
;
2709 action
= (ipfw_insn
*)actbuf
;
2713 /* [rule N] -- Rule number optional */
2714 if (ac
&& isdigit(**av
)) {
2715 rule
->rulenum
= atoi(*av
);
2720 /* [set N] -- set number (0..30), optional */
2721 if (ac
> 1 && !strncmp(*av
, "set", strlen(*av
))) {
2722 int set
= strtoul(av
[1], NULL
, 10);
2723 if (set
< 0 || set
> 30)
2724 errx(EX_DATAERR
, "illegal set %s", av
[1]);
2729 /* [prob D] -- match probability, optional */
2730 if (ac
> 1 && !strncmp(*av
, "prob", strlen(*av
))) {
2731 match_prob
= strtod(av
[1], NULL
);
2733 if (match_prob
<= 0 || match_prob
> 1)
2734 errx(EX_DATAERR
, "illegal match prob. %s", av
[1]);
2738 /* action -- mandatory */
2739 NEED1("missing action");
2740 i
= match_token(rule_actions
, *av
);
2742 action
->len
= 1; /* default */
2744 case TOK_CHECKSTATE
:
2745 have_state
= action
;
2746 action
->opcode
= O_CHECK_STATE
;
2750 action
->opcode
= O_ACCEPT
;
2754 action
->opcode
= O_DEFRAG
;
2759 action
->opcode
= O_DENY
;
2764 action
->opcode
= O_REJECT
;
2765 action
->arg1
= ICMP_UNREACH_HOST
;
2769 action
->opcode
= O_REJECT
;
2770 action
->arg1
= ICMP_REJECT_RST
;
2774 action
->opcode
= O_REJECT
;
2775 NEED1("missing reject code");
2776 fill_reject_code(&action
->arg1
, *av
);
2781 action
->opcode
= O_COUNT
;
2786 action
->len
= F_INSN_SIZE(ipfw_insn_pipe
);
2790 action
->opcode
= O_QUEUE
;
2791 else if (i
== TOK_PIPE
)
2792 action
->opcode
= O_PIPE
;
2793 else if (i
== TOK_SKIPTO
)
2794 action
->opcode
= O_SKIPTO
;
2795 NEED1("missing skipto/pipe/queue number");
2796 action
->arg1
= strtoul(*av
, NULL
, 10);
2802 action
->opcode
= (i
== TOK_DIVERT
) ? O_DIVERT
: O_TEE
;
2803 NEED1("missing divert/tee port");
2804 action
->arg1
= strtoul(*av
, NULL
, 0);
2805 if (action
->arg1
== 0) {
2806 struct servent
*serv
;
2808 serv
= getservbyname(av
[0], "divert");
2810 action
->arg1
= ntohs(serv
->s_port
);
2812 errx(EX_DATAERR
, "illegal divert/tee port");
2818 ipfw_insn_sa
*p
= (ipfw_insn_sa
*)action
;
2821 NEED1("missing forward address[:port]");
2823 action
->opcode
= O_FORWARD_IP
;
2824 action
->len
= F_INSN_SIZE(ipfw_insn_sa
);
2826 p
->sa
.sin_len
= sizeof(struct sockaddr_in
);
2827 p
->sa
.sin_family
= AF_INET
;
2830 * locate the address-port separator (':' or ',')
2832 st
= strchr(*av
, ':');
2834 st
= strchr(*av
, ',');
2837 i
= strtoport(st
, &end
, 0 /* base */, 0 /* proto */);
2840 "illegal forwarding port ``%s''", st
);
2841 p
->sa
.sin_port
= (u_short
)i
;
2843 lookup_host(*av
, &(p
->sa
.sin_addr
));
2849 errx(EX_DATAERR
, "invalid action %s\n", av
[-1]);
2851 action
= next_cmd(action
);
2854 * [log [logamount N]] -- log, optional
2856 * If exists, it goes first in the cmdbuf, but then it is
2857 * skipped in the copy section to the end of the buffer.
2859 if (ac
&& !strncmp(*av
, "log", strlen(*av
))) {
2860 ipfw_insn_log
*c
= (ipfw_insn_log
*)cmd
;
2862 cmd
->len
= F_INSN_SIZE(ipfw_insn_log
);
2863 cmd
->opcode
= O_LOG
;
2865 if (ac
&& !strncmp(*av
, "logamount", strlen(*av
))) {
2867 NEED1("logamount requires argument");
2868 c
->max_log
= atoi(*av
);
2871 cmd
= next_cmd(cmd
);
2874 if (have_state
) /* must be a check-state, we are done */
2877 #define OR_START(target) \
2878 if (ac && (*av[0] == '(' || *av[0] == '{')) { \
2880 errx(EX_USAGE, "nested \"(\" not allowed\n"); \
2883 if ( (av[0])[1] == '\0') { \
2894 !strncmp(*av, ")", strlen(*av)) || \
2895 !strncmp(*av, "}", strlen(*av)) )) { \
2900 errx(EX_USAGE, "missing \")\"\n"); \
2904 if (ac && !strncmp(*av, "not", strlen(*av))) { \
2905 if (cmd->len & F_NOT) \
2906 errx(EX_USAGE, "double \"not\" not allowed\n"); \
2907 cmd->len |= F_NOT; \
2911 #define OR_BLOCK(target) \
2912 if (ac && !strncmp(*av, "or", strlen(*av))) { \
2913 if (prev == NULL || open_par == 0) \
2914 errx(EX_DATAERR, "invalid OR block"); \
2915 prev->len |= F_OR; \
2925 * MAC addresses, optional.
2926 * If we have this, we skip the part "proto from src to dst"
2927 * and jump straight to the option parsing.
2930 NEED1("missing protocol");
2931 if (!strncmp(*av
, "MAC", strlen(*av
)) ||
2932 !strncmp(*av
, "mac", strlen(*av
))) {
2933 ac
--; av
++; /* the "MAC" keyword */
2934 add_mac(cmd
, ac
, av
); /* exits in case of errors */
2935 cmd
= next_cmd(cmd
);
2936 ac
-= 2; av
+= 2; /* dst-mac and src-mac */
2938 NEED1("missing mac type");
2939 if (add_mactype(cmd
, ac
, av
[0]))
2940 cmd
= next_cmd(cmd
);
2941 ac
--; av
++; /* any or mac-type */
2947 * protocol, mandatory
2949 OR_START(get_proto
);
2951 NEED1("missing protocol");
2952 if (add_proto(cmd
, *av
)) {
2954 if (F_LEN(cmd
) == 0) /* plain IP */
2959 cmd
= next_cmd(cmd
);
2961 } else if (first_cmd
!= cmd
) {
2962 errx(EX_DATAERR
, "invalid protocol ``%s''", *av
);
2965 OR_BLOCK(get_proto
);
2970 if (!ac
|| strncmp(*av
, "from", strlen(*av
)))
2971 errx(EX_USAGE
, "missing ``from''");
2975 * source IP, mandatory
2977 OR_START(source_ip
);
2978 NOT_BLOCK
; /* optional "not" */
2979 NEED1("missing source address");
2980 if (add_srcip(cmd
, *av
)) {
2982 if (F_LEN(cmd
) != 0) { /* ! any */
2984 cmd
= next_cmd(cmd
);
2987 OR_BLOCK(source_ip
);
2990 * source ports, optional
2992 NOT_BLOCK
; /* optional "not" */
2994 if (!strncmp(*av
, "any", strlen(*av
)) ||
2995 add_ports(cmd
, *av
, proto
, O_IP_SRCPORT
)) {
2997 if (F_LEN(cmd
) != 0)
2998 cmd
= next_cmd(cmd
);
3005 if (!ac
|| strncmp(*av
, "to", strlen(*av
)))
3006 errx(EX_USAGE
, "missing ``to''");
3010 * destination, mandatory
3013 NOT_BLOCK
; /* optional "not" */
3014 NEED1("missing dst address");
3015 if (add_dstip(cmd
, *av
)) {
3017 if (F_LEN(cmd
) != 0) { /* ! any */
3019 cmd
= next_cmd(cmd
);
3025 * dest. ports, optional
3027 NOT_BLOCK
; /* optional "not" */
3029 if (!strncmp(*av
, "any", strlen(*av
)) ||
3030 add_ports(cmd
, *av
, proto
, O_IP_DSTPORT
)) {
3032 if (F_LEN(cmd
) != 0) {
3034 cmd
= next_cmd(cmd
);
3040 if (ac
&& first_cmd
== cmd
) {
3042 * nothing specified so far, store in the rule to ease
3045 rule
->usr_flags
= IPFW_USR_F_NORULE
;
3050 ipfw_insn_u32
*cmd32
; /* alias for cmd */
3053 cmd32
= (ipfw_insn_u32
*)cmd
;
3055 if (*s1
== '!') { /* alternate syntax for NOT */
3056 if (cmd
->len
& F_NOT
)
3057 errx(EX_USAGE
, "double \"not\" not allowed\n");
3061 i
= match_token(rule_options
, s1
);
3065 if (cmd
->len
& F_NOT
)
3066 errx(EX_USAGE
, "double \"not\" not allowed\n");
3071 if (open_par
== 0 || prev
== NULL
)
3072 errx(EX_USAGE
, "invalid \"or\" block\n");
3076 case TOK_STARTBRACE
:
3078 errx(EX_USAGE
, "+nested \"(\" not allowed\n");
3084 errx(EX_USAGE
, "+missing \")\"\n");
3090 fill_cmd(cmd
, O_IN
, 0, 0);
3094 cmd
->len
^= F_NOT
; /* toggle F_NOT */
3095 fill_cmd(cmd
, O_IN
, 0, 0);
3099 fill_cmd(cmd
, O_FRAG
, 0, 0);
3103 fill_cmd(cmd
, O_IPFRAG
, 0, 0);
3107 fill_cmd(cmd
, O_LAYER2
, 0, 0);
3113 NEED1("recv, xmit, via require interface name"
3115 fill_iface((ipfw_insn_if
*)cmd
, av
[0]);
3117 if (F_LEN(cmd
) == 0) /* not a valid address */
3120 cmd
->opcode
= O_XMIT
;
3121 else if (i
== TOK_RECV
) {
3122 cmd
->opcode
= O_RECV
;
3124 } else if (i
== TOK_VIA
)
3125 cmd
->opcode
= O_VIA
;
3129 NEED1("icmpcodes requires list of codes");
3130 fill_icmp(O_ICMPCODE
, (ipfw_insn_u32
*)cmd
, *av
);
3135 NEED1("icmptypes requires list of types");
3136 fill_icmp(O_ICMPTYPE
, (ipfw_insn_u32
*)cmd
, *av
);
3141 NEED1("ipttl requires TTL");
3142 fill_cmd(cmd
, O_IPTTL
, 0, strtoul(*av
, NULL
, 0));
3147 NEED1("ipid requires length");
3148 fill_cmd(cmd
, O_IPID
, 0, strtoul(*av
, NULL
, 0));
3153 NEED1("iplen requires length");
3154 fill_cmd(cmd
, O_IPLEN
, 0, strtoul(*av
, NULL
, 0));
3159 NEED1("ipver requires version");
3160 fill_cmd(cmd
, O_IPVER
, 0, strtoul(*av
, NULL
, 0));
3164 case TOK_IPPRECEDENCE
:
3165 NEED1("ipprecedence requires value");
3166 fill_cmd(cmd
, O_IPPRECEDENCE
, 0,
3167 (strtoul(*av
, NULL
, 0) & 7) << 5);
3172 NEED1("missing argument for ipoptions");
3173 fill_flags(cmd
, O_IPOPT
, f_ipopts
, *av
);
3178 NEED1("missing argument for iptos");
3179 fill_flags(cmd
, O_IPTOS
, f_iptos
, *av
);
3184 NEED1("uid requires argument");
3190 cmd
->opcode
= O_UID
;
3191 uid
= strtoul(*av
, &end
, 0);
3192 pwd
= (*end
== '\0') ? getpwuid(uid
) : getpwnam(*av
);
3194 errx(EX_DATAERR
, "uid \"%s\" nonexistent", *av
);
3195 cmd32
->d
[0] = pwd
->pw_uid
;
3196 cmd
->len
= F_INSN_SIZE(ipfw_insn_u32
);
3202 NEED1("gid requires argument");
3208 cmd
->opcode
= O_GID
;
3209 gid
= strtoul(*av
, &end
, 0);
3210 grp
= (*end
== '\0') ? getgrgid(gid
) : getgrnam(*av
);
3212 errx(EX_DATAERR
, "gid \"%s\" nonexistent", *av
);
3213 cmd32
->d
[0] = grp
->gr_gid
;
3214 cmd
->len
= F_INSN_SIZE(ipfw_insn_u32
);
3220 fill_cmd(cmd
, O_ESTAB
, 0, 0);
3224 fill_cmd(cmd
, O_TCPFLAGS
, 0,
3225 (TH_SYN
) | ( (TH_ACK
) & 0xff) <<8 );
3229 NEED1("missing argument for tcpoptions");
3230 fill_flags(cmd
, O_TCPOPTS
, f_tcpopts
, *av
);
3236 NEED1("tcpseq/tcpack requires argument");
3237 cmd
->len
= F_INSN_SIZE(ipfw_insn_u32
);
3238 cmd
->opcode
= (i
== TOK_TCPSEQ
) ? O_TCPSEQ
: O_TCPACK
;
3239 cmd32
->d
[0] = htonl(strtoul(*av
, NULL
, 0));
3244 NEED1("tcpwin requires length");
3245 fill_cmd(cmd
, O_TCPWIN
, 0,
3246 htons(strtoul(*av
, NULL
, 0)));
3251 NEED1("missing argument for tcpflags");
3252 cmd
->opcode
= O_TCPFLAGS
;
3253 fill_flags(cmd
, O_TCPFLAGS
, f_tcpflags
, *av
);
3259 errx(EX_USAGE
, "rdr cannot be part "
3262 errx(EX_USAGE
, "only one of rdr, keep-state "
3263 "and limit is allowed");
3266 NEED1("rdr needs address and port");
3273 errx(EX_USAGE
, "keep-state cannot be part "
3276 errx(EX_USAGE
, "only one of rdr, keep-state "
3277 "and limit is allowed");
3280 fill_cmd(cmd
, O_KEEP_STATE
, 0, 0);
3285 errx(EX_USAGE
, "limit cannot be part "
3288 errx(EX_USAGE
, "only one of rdr, keep-state "
3289 "and limit is allowed");
3291 NEED1("limit needs mask and # of connections");
3294 ipfw_insn_limit
*c
= (ipfw_insn_limit
*)cmd
;
3296 cmd
->len
= F_INSN_SIZE(ipfw_insn_limit
);
3297 cmd
->opcode
= O_LIMIT
;
3303 val
= match_token(limit_masks
, *av
);
3306 c
->limit_mask
|= val
;
3309 c
->conn_limit
= atoi(*av
);
3310 if (c
->conn_limit
== 0)
3311 errx(EX_USAGE
, "limit: limit must be >0");
3312 if (c
->limit_mask
== 0)
3313 errx(EX_USAGE
, "missing limit mask");
3319 NEED1("missing protocol");
3320 if (add_proto(cmd
, *av
)) {
3324 errx(EX_DATAERR
, "invalid protocol ``%s''", *av
);
3328 NEED1("missing source IP");
3329 if (add_srcip(cmd
, *av
)) {
3335 NEED1("missing destination IP");
3336 if (add_dstip(cmd
, *av
)) {
3342 NEED1("missing source port");
3343 if (!strncmp(*av
, "any", strlen(*av
)) ||
3344 add_ports(cmd
, *av
, proto
, O_IP_SRCPORT
)) {
3347 errx(EX_DATAERR
, "invalid source port %s", *av
);
3351 NEED1("missing destination port");
3352 if (!strncmp(*av
, "any", strlen(*av
)) ||
3353 add_ports(cmd
, *av
, proto
, O_IP_DSTPORT
)) {
3354 if (F_LEN(cmd
) != 0)
3358 errx(EX_DATAERR
, "invalid destination port %s",
3364 errx(EX_USAGE
, "MAC dst-mac src-mac");
3365 if (add_mac(cmd
, ac
, av
)) {
3371 NEED1("missing mac type");
3372 if (!add_mactype(cmd
, ac
, *av
))
3373 errx(EX_DATAERR
, "invalid mac type %s", *av
);
3378 errx(EX_USAGE
, "unrecognised option [%d] %s\n", i
, s1
);
3380 if (F_LEN(cmd
) > 0) { /* prepare to advance */
3382 cmd
= next_cmd(cmd
);
3388 * Now copy stuff into the rule.
3389 * If we have a keep-state option, the first instruction
3390 * must be a PROBE_STATE (which is generated here).
3391 * If we have a LOG option, it was stored as the first command,
3392 * and now must be moved to the top of the action part.
3394 dst
= (ipfw_insn
*)rule
->cmd
;
3397 * First thing to write into the command stream is the match probability.
3399 if (match_prob
!= 1) { /* 1 means always match */
3400 dst
->opcode
= O_PROB
;
3402 *((int32_t *)(dst
+1)) = (int32_t)(match_prob
* 0x7fffffff);
3407 * generate O_PROBE_STATE if necessary
3409 if (have_state
&& have_state
->opcode
!= O_CHECK_STATE
) {
3410 fill_cmd(dst
, O_PROBE_STATE
, 0, 0);
3411 dst
= next_cmd(dst
);
3414 * copy all commands but O_LOG, O_KEEP_STATE, O_LIMIT, O_REDIRECT
3416 for (src
= (ipfw_insn
*)cmdbuf
; src
!= cmd
; src
+= i
) {
3419 switch (src
->opcode
) {
3426 bcopy(src
, dst
, i
* sizeof(u_int32_t
));
3432 * put back the have_state command as last opcode
3434 if (have_state
&& have_state
->opcode
!= O_CHECK_STATE
) {
3435 i
= F_LEN(have_state
);
3436 bcopy(have_state
, dst
, i
* sizeof(u_int32_t
));
3439 if (have_state
->opcode
== O_REDIRECT
&&
3440 (!has_dstport
|| !has_recv
))
3441 errx(EX_USAGE
, "missing \'dst-port\' or \'recv\'");
3444 * start action section
3446 rule
->act_ofs
= dst
- rule
->cmd
;
3449 * put back O_LOG if necessary
3451 src
= (ipfw_insn
*)cmdbuf
;
3452 if ( src
->opcode
== O_LOG
) {
3454 bcopy(src
, dst
, i
* sizeof(u_int32_t
));
3458 * copy all other actions
3460 for (src
= (ipfw_insn
*)actbuf
; src
!= action
; src
+= i
) {
3462 bcopy(src
, dst
, i
* sizeof(u_int32_t
));
3466 rule
->cmd_len
= (u_int32_t
*)dst
- (u_int32_t
*)(rule
->cmd
);
3467 i
= (uint8_t *)dst
- (uint8_t *)rule
;
3468 if (getsockopt(s
, IPPROTO_IP
, IP_FW_ADD
, rule
, &i
) == -1)
3469 err(EX_UNAVAILABLE
, "getsockopt(%s)", "IP_FW_ADD");
3471 show_ipfw(rule
, 10, 10);
3475 zero(int ac
, char *av
[])
3483 /* clear all entries */
3484 if (setsockopt(s
, IPPROTO_IP
, IP_FW_ZERO
, NULL
, 0) < 0)
3485 err(EX_UNAVAILABLE
, "setsockopt(%s)", "IP_FW_ZERO");
3487 printf("Accounting cleared.\n");
3494 if (isdigit(**av
)) {
3495 rulenum
= atoi(*av
);
3498 if (setsockopt(s
, IPPROTO_IP
,
3499 IP_FW_ZERO
, &rulenum
, sizeof rulenum
)) {
3500 warn("rule %u: setsockopt(IP_FW_ZERO)",
3502 failed
= EX_UNAVAILABLE
;
3503 } else if (!do_quiet
)
3504 printf("Entry %d cleared\n", rulenum
);
3506 errx(EX_USAGE
, "invalid rule number ``%s''", *av
);
3509 if (failed
!= EX_OK
)
3514 resetlog(int ac
, char *av
[])
3522 /* clear all entries */
3523 if (setsockopt(s
, IPPROTO_IP
, IP_FW_RESETLOG
, NULL
, 0) < 0)
3524 err(EX_UNAVAILABLE
, "setsockopt(IP_FW_RESETLOG)");
3526 printf("Logging counts reset.\n");
3533 if (isdigit(**av
)) {
3534 rulenum
= atoi(*av
);
3537 if (setsockopt(s
, IPPROTO_IP
,
3538 IP_FW_RESETLOG
, &rulenum
, sizeof rulenum
)) {
3539 warn("rule %u: setsockopt(IP_FW_RESETLOG)",
3541 failed
= EX_UNAVAILABLE
;
3542 } else if (!do_quiet
)
3543 printf("Entry %d logging count reset\n",
3546 errx(EX_DATAERR
, "invalid rule number ``%s''", *av
);
3549 if (failed
!= EX_OK
)
3556 int cmd
= do_pipe
? IP_DUMMYNET_FLUSH
: IP_FW_FLUSH
;
3558 if (!do_force
&& !do_quiet
) { /* need to ask user */
3561 printf("Are you sure? [yn] ");
3564 c
= toupper(getc(stdin
));
3565 while (c
!= '\n' && getc(stdin
) != '\n')
3567 return; /* and do not flush */
3568 } while (c
!= 'Y' && c
!= 'N');
3570 if (c
== 'N') /* user said no */
3573 if (setsockopt(s
, IPPROTO_IP
, cmd
, NULL
, 0) < 0)
3574 err(EX_UNAVAILABLE
, "setsockopt(IP_%s_FLUSH)",
3575 do_pipe
? "DUMMYNET" : "FW");
3577 printf("Flushed all %s.\n", do_pipe
? "pipes" : "rules");
3581 table_create(int ac
, char **av
)
3583 struct ipfw_ioc_table tbl
;
3590 errx(EX_DATAERR
, "missing table id");
3592 memset(&tbl
, 0, sizeof(tbl
));
3593 tbl
.tableid
= strtoul(*av
, &eptr
, 0);
3595 errx(EX_DATAERR
, "invalid table id %s", *av
);
3596 if (setsockopt(s
, IPPROTO_IP
, IP_FW_TBL_CREATE
, &tbl
, sizeof(tbl
)) < 0)
3597 err(EX_UNAVAILABLE
, "setsockopt(IP_FW_TBL_CREATE)");
3599 printf("Created table %d\n", tbl
.tableid
);
3603 table_flush(int ac
, char **av
, int opt
)
3605 struct ipfw_ioc_table tbl
;
3611 memset(&tbl
, 0, sizeof(tbl
));
3614 if (opt
== IP_FW_TBL_FLUSH
) {
3615 /* Flush all tables */
3619 errx(EX_DATAERR
, "missing table id");
3622 tbl
.tableid
= strtoul(*av
, &eptr
, 0);
3624 errx(EX_DATAERR
, "invalid table id %s", *av
);
3627 if (!do_force
&& !do_quiet
) { /* need to ask user */
3630 printf("Are you sure? [yn] ");
3633 c
= toupper(getc(stdin
));
3634 while (c
!= '\n' && getc(stdin
) != '\n')
3636 return; /* and do not flush */
3637 } while (c
!= 'Y' && c
!= 'N');
3639 if (c
== 'N') /* user said no */
3643 if (setsockopt(s
, IPPROTO_IP
, opt
, &tbl
, sizeof(tbl
)) < 0) {
3644 err(EX_UNAVAILABLE
, "setsockopt(IP_FW_TBL_%s)",
3645 opt
== IP_FW_TBL_FLUSH
? "FLUSH" : "DESTROY");
3648 if (tbl
.tableid
>= 0) {
3649 printf("%sed table %d\n",
3650 opt
== IP_FW_TBL_FLUSH
? "Flush" : "Destroy",
3653 printf("Flushed all tables\n");
3661 struct ipfw_ioc_tbllist
*list
;
3666 len
= sizeof(table_max
);
3667 if (sysctlbyname("net.inet.ip.fw.table_max", &table_max
, &len
,
3669 err(EX_UNAVAILABLE
, "sysctl net.inet.ip.fw.table_max failed");
3671 len1
= __offsetof(struct ipfw_ioc_tbllist
, tables
[table_max
]);
3672 list
= malloc(len1
);
3675 if (getsockopt(s
, IPPROTO_IP
, IP_FW_TBL_GET
, list
, &len1
) < 0)
3676 err(EX_UNAVAILABLE
, "getsockopt(IP_FW_TBL_GET)");
3678 for (i
= 0; i
< list
->tablecnt
; ++i
)
3679 printf("%u\n", list
->tables
[i
]);
3682 /* XXX copied from route(8) */
3684 inet_makenetandmask(in_addr_t net
, struct sockaddr_in
*in
,
3685 struct sockaddr_in
*in_mask
, int bits
)
3687 in_addr_t addr
, mask
= 0;
3691 * XXX: This approach unable to handle 0.0.0.1/32 correctly
3692 * as inet_network() converts 0.0.0.1 and 1 equally.
3695 addr
= net
<< IN_CLASSA_NSHIFT
;
3696 else if (net
<= 0xffff)
3697 addr
= net
<< IN_CLASSB_NSHIFT
;
3698 else if (net
<= 0xffffff)
3699 addr
= net
<< IN_CLASSC_NSHIFT
;
3704 mask
= 0xffffffff << (32 - bits
);
3707 else if (IN_CLASSA(addr
))
3708 mask
= IN_CLASSA_NET
;
3709 else if (IN_CLASSB(addr
))
3710 mask
= IN_CLASSB_NET
;
3711 else if (IN_CLASSC(addr
))
3712 mask
= IN_CLASSC_NET
;
3713 else if (IN_MULTICAST(addr
))
3714 mask
= IN_CLASSD_NET
;
3718 in
->sin_family
= AF_INET
;
3719 in
->sin_len
= sizeof(struct sockaddr_in
);
3720 in
->sin_addr
.s_addr
= htonl(addr
);
3722 if (mask
!= 0xffffffff) {
3723 in_mask
->sin_addr
.s_addr
= htonl(mask
);
3724 cp
= (char *)(&in_mask
->sin_addr
+ 1);
3725 while (*--cp
== 0 && cp
> (char *)in_mask
)
3727 in_mask
->sin_len
= 1 + cp
- (char *)in_mask
;
3732 table_alt(int ac
, char **av
, int opt
)
3734 struct ipfw_ioc_tblcont ent
;
3735 struct ipfw_ioc_tblent
*te
;
3741 errx(EX_DATAERR
, "missing table id");
3743 memset(&ent
, 0, sizeof(ent
));
3744 ent
.tableid
= strtoul(*av
, &eptr
, 0);
3748 errx(EX_DATAERR
, "invalid table id %s", *av
);
3753 errx(EX_DATAERR
, "missing addresses");
3758 q
= strchr(*av
, '/');
3764 val
= inet_network(*av
);
3766 if (val
== INADDR_NONE
) {
3768 errx(EX_DATAERR
, "invalid address %s", *av
);
3771 bits
= strtoul(q
+ 1, &eptr
, 0);
3772 if (*eptr
!= '\0') {
3774 errx(EX_DATAERR
, "invalid address %s", *av
);
3776 inet_makenetandmask(val
, &te
->key
, &te
->netmask
, bits
);
3780 n
= inet_pton(AF_INET
, *av
, &te
->key
.sin_addr
);
3783 errx(EX_DATAERR
, "invalid address %s", *av
);
3786 err(EX_UNAVAILABLE
, "inet_pton failed");
3788 te
->key
.sin_family
= AF_INET
;
3789 te
->key
.sin_len
= sizeof(struct sockaddr_in
);
3792 if (setsockopt(s
, IPPROTO_IP
, opt
, &ent
, sizeof(ent
)) < 0) {
3793 if (opt
== IP_FW_TBL_ADD
&& errno
== EEXIST
) {
3794 printf("Failed to add %s to table %d\n",
3796 } else if (opt
== IP_FW_TBL_DEL
&& errno
== ESRCH
) {
3797 printf("Failed to delete %s from table %d\n",
3801 err(EX_UNAVAILABLE
, "setsockopt(IP_FW_TBL_%s)",
3802 opt
== IP_FW_TBL_ADD
? "ADD" : "DEL");
3804 } else if (!do_quiet
) {
3805 printf("%sed %s %s table %d\n",
3806 opt
== IP_FW_TBL_ADD
? "Add" : "Delet", *av
,
3807 opt
== IP_FW_TBL_ADD
? "to" : "from", ent
.tableid
);
3816 table_show(int ac
, char **av
)
3818 struct ipfw_ioc_tblcont
*cont
= NULL
;
3819 int tableid
, count
= 128, i
, uwidth
= 0, lwidth
= 0;
3825 errx(EX_DATAERR
, "missing table id");
3827 tableid
= strtoul(*av
, &eptr
, 0);
3829 errx(EX_DATAERR
, "invalid table id %s", *av
);
3834 len
= __offsetof(struct ipfw_ioc_tblcont
, ent
[count
]);
3835 cont
= reallocf(cont
, len
);
3836 cont
->tableid
= tableid
;
3838 if (getsockopt(s
, IPPROTO_IP
, IP_FW_TBL_GET
, cont
, &len
) < 0) {
3839 if (errno
== E2BIG
) {
3843 err(EX_UNAVAILABLE
, "getsockopt(IP_FW_TBL_GET)");
3847 if (cont
->entcnt
== 0)
3851 for (i
= 0; i
< cont
->entcnt
; ++i
) {
3854 width
= snprintf(NULL
, 0, "%ju",
3855 (uintmax_t)cont
->ent
[i
].use
);
3861 for (i
= 0; i
< cont
->entcnt
; ++i
) {
3862 const struct ipfw_ioc_tblent
*te
= &cont
->ent
[i
];
3863 char addr
[INET_ADDRSTRLEN
];
3866 printf("%*ju ", uwidth
, (uintmax_t)te
->use
);
3873 strcpy(timestr
, ctime(&t0
));
3874 *strchr(timestr
, '\n') = '\0';
3875 lwidth
= strlen(timestr
);
3877 if (te
->last_used
) {
3878 time_t t
= _long_to_time(te
->last_used
);
3880 strcpy(timestr
, ctime(&t
));
3881 *strchr(timestr
, '\n') = '\0';
3882 printf("%s ", timestr
);
3884 printf("%*s ", lwidth
, " ");
3888 if (te
->netmask
.sin_len
== 0) {
3889 printf("%s\n", inet_ntop(AF_INET
,
3890 &te
->key
.sin_addr
, addr
, sizeof(addr
)));
3892 struct sockaddr_in mask
;
3895 memset(&mask
, 0, sizeof(mask
));
3896 memcpy(&mask
, &te
->netmask
,
3897 te
->netmask
.sin_len
);
3898 b
= ffs(ntohl(te
->netmask
.sin_addr
.s_addr
));
3901 printf("%s/%d\n", inet_ntop(AF_INET
,
3902 &te
->key
.sin_addr
, addr
, sizeof(addr
)), b
);
3908 table_zero(int ac
, char **av
)
3910 struct ipfw_ioc_table tbl
;
3915 memset(&tbl
, 0, sizeof(tbl
));
3921 tbl
.tableid
= strtoul(*av
, &eptr
, 0);
3923 errx(EX_DATAERR
, "invalid table id %s", *av
);
3926 if (setsockopt(s
, IPPROTO_IP
, IP_FW_TBL_ZERO
, &tbl
, sizeof(tbl
)) < 0)
3927 err(EX_UNAVAILABLE
, "setsockopt(IP_FW_TBL_ZERO)");
3929 printf("Accounting cleared\n");
3933 table_expire(int ac
, char **av
)
3935 struct ipfw_ioc_tblexp tbl
;
3942 memset(&tbl
, 0, sizeof(tbl
));
3944 errx(EX_DATAERR
, "missing expire time");
3945 } else if (ac
== 1) {
3948 tbl
.tableid
= strtoul(*av
, &eptr
, 0);
3950 errx(EX_DATAERR
, "invalid table id %s", *av
);
3955 tbl
.expire
= strtoul(*av
, &eptr
, 0);
3957 errx(EX_DATAERR
, "invalid expire timeout %s", *av
);
3959 if (!do_force
&& !do_quiet
) { /* need to ask user */
3962 printf("Are you sure? [yn] ");
3965 c
= toupper(getc(stdin
));
3966 while (c
!= '\n' && getc(stdin
) != '\n')
3968 return; /* and do not flush */
3969 } while (c
!= 'Y' && c
!= 'N');
3971 if (c
== 'N') /* user said no */
3976 if (getsockopt(s
, IPPROTO_IP
, IP_FW_TBL_EXPIRE
, &tbl
, &len
) < 0)
3977 err(EX_UNAVAILABLE
, "getsockopt(IP_FW_TBL_EXPIRE)");
3979 printf("Expired %d address%s\n", tbl
.expcnt
,
3980 (tbl
.expcnt
== 0 || tbl
.expcnt
> 1) ? "es" : "");
3985 ipfw_main(int ac
, char **av
)
3992 /* Set the force flag for non-interactive processes */
3993 do_force
= !isatty(STDIN_FILENO
);
3995 optind
= optreset
= 1;
3996 while ((ch
= getopt(ac
, av
, "hs:acdefNqStv")) != -1)
3998 case 'h': /* help */
4000 break; /* NOTREACHED */
4002 case 's': /* sort */
4003 do_sort
= atoi(optarg
);
4032 case 'v': /* verbose */
4041 NEED1("bad arguments, for usage summary ``ipfw''");
4044 * Reset do_pipe and do_table.
4050 * optional: pipe, queue or table
4052 if (!strncmp(*av
, "pipe", strlen(*av
))) {
4056 } else if (!strncmp(*av
, "queue", strlen(*av
))) {
4060 } else if (!strncmp(*av
, "table", strlen(*av
))) {
4065 NEED1("missing command");
4068 * for pipes, queues and table we normally say 'pipe NN config'
4069 * but the code is easier to parse as 'pipe config NN' so we
4070 * swap the two arguments.
4072 if ((do_pipe
> 0 || do_table
> 0) && ac
> 1 &&
4073 *av
[0] >= '0' && *av
[0] <= '9') {
4079 if (!strncmp(*av
, "create", strlen(*av
)))
4080 table_create(ac
, av
);
4081 else if (!strncmp(*av
, "destroy", strlen(*av
)))
4082 table_flush(ac
, av
, IP_FW_TBL_DESTROY
);
4083 else if (!strncmp(*av
, "list", strlen(*av
)))
4085 else if (!strncmp(*av
, "add", strlen(*av
)))
4086 table_alt(ac
, av
, IP_FW_TBL_ADD
);
4087 else if (!strncmp(*av
, "delete", strlen(*av
)))
4088 table_alt(ac
, av
, IP_FW_TBL_DEL
);
4089 else if (!strncmp(*av
, "flush", strlen(*av
)))
4090 table_flush(ac
, av
, IP_FW_TBL_FLUSH
);
4091 else if (!strncmp(*av
, "print", strlen(*av
)))
4093 else if (!strncmp(*av
, "show", strlen(*av
))) {
4096 } else if (!strncmp(*av
, "zero", strlen(*av
)))
4098 else if (!strncmp(*av
, "expire", strlen(*av
)))
4099 table_expire(ac
, av
);
4101 errx(EX_USAGE
, "bad command `%s'", *av
);
4104 if (!strncmp(*av
, "add", strlen(*av
)))
4106 else if (do_pipe
&& !strncmp(*av
, "config", strlen(*av
)))
4107 config_pipe(ac
, av
);
4108 else if (!strncmp(*av
, "delete", strlen(*av
)))
4110 else if (!strncmp(*av
, "flush", strlen(*av
)))
4112 else if (!strncmp(*av
, "zero", strlen(*av
)))
4114 else if (!strncmp(*av
, "resetlog", strlen(*av
)))
4116 else if (!strncmp(*av
, "print", strlen(*av
)) ||
4117 !strncmp(*av
, "list", strlen(*av
)))
4119 else if (!strncmp(*av
, "enable", strlen(*av
)))
4120 sysctl_handler(ac
, av
, 1);
4121 else if (!strncmp(*av
, "disable", strlen(*av
)))
4122 sysctl_handler(ac
, av
, 0);
4123 else if (!strncmp(*av
, "set", strlen(*av
)))
4124 sets_handler(ac
, av
);
4125 else if (!strncmp(*av
, "show", strlen(*av
))) {
4129 errx(EX_USAGE
, "bad command `%s'", *av
);
4135 ipfw_readfile(int ac
, char *av
[])
4138 #define WHITESP " \t\f\v\n\r"
4140 char *a
, *p
, *args
[MAX_ARGS
], *cmd
= NULL
;
4142 int i
=0, lineno
=0, qflag
=0, pflag
=0, status
;
4147 while ((c
= getopt(ac
, av
, "D:U:p:q")) != -1)
4151 errx(EX_USAGE
, "-D requires -p");
4152 if (i
> MAX_ARGS
- 2)
4154 "too many -D or -U options");
4155 args
[i
++] = __DECONST(char *, "-D");
4161 errx(EX_USAGE
, "-U requires -p");
4162 if (i
> MAX_ARGS
- 2)
4164 "too many -D or -U options");
4165 args
[i
++] = __DECONST(char *, "-U");
4181 errx(EX_USAGE
, "bad arguments, for usage"
4182 " summary ``ipfw''");
4188 errx(EX_USAGE
, "extraneous filename arguments");
4190 if ((f
= fopen(av
[0], "r")) == NULL
)
4191 err(EX_UNAVAILABLE
, "fopen: %s", av
[0]);
4194 /* pipe through preprocessor (cpp or m4) */
4199 if (pipe(pipedes
) == -1)
4200 err(EX_OSERR
, "cannot create pipe");
4202 switch((preproc
= fork())) {
4204 err(EX_OSERR
, "cannot fork");
4208 if (dup2(fileno(f
), 0) == -1
4209 || dup2(pipedes
[1], 1) == -1)
4210 err(EX_OSERR
, "dup2()");
4215 err(EX_OSERR
, "execvp(%s) failed", cmd
);
4221 if ((f
= fdopen(pipedes
[0], "r")) == NULL
) {
4222 int savederrno
= errno
;
4224 kill(preproc
, SIGTERM
);
4226 err(EX_OSERR
, "fdopen()");
4231 while (fgets(buf
, BUFSIZ
, f
)) {
4233 snprintf(linename
, sizeof(linename
), "Line %d", lineno
);
4238 if ((p
= strchr(buf
, '#')) != NULL
)
4242 args
[i
++] = __DECONST(char *, "-q");
4243 for (a
= strtok(buf
, WHITESP
);
4244 a
&& i
< MAX_ARGS
; a
= strtok(NULL
, WHITESP
), i
++)
4246 if (i
== (qflag
? 2: 1))
4249 errx(EX_USAGE
, "%s: too many arguments",
4257 if (waitpid(preproc
, &status
, 0) == -1)
4258 errx(EX_OSERR
, "waitpid()");
4259 if (WIFEXITED(status
) && WEXITSTATUS(status
) != EX_OK
)
4260 errx(EX_UNAVAILABLE
,
4261 "preprocessor exited with status %d",
4262 WEXITSTATUS(status
));
4263 else if (WIFSIGNALED(status
))
4264 errx(EX_UNAVAILABLE
,
4265 "preprocessor exited with signal %d",
4271 main(int ac
, char *av
[])
4273 s
= socket(AF_INET
, SOCK_RAW
, IPPROTO_RAW
);
4275 err(EX_UNAVAILABLE
, "socket");
4278 * If the last argument is an absolute pathname, interpret it
4279 * as a file to be preprocessed.
4282 if (ac
> 1 && av
[ac
- 1][0] == '/' && access(av
[ac
- 1], R_OK
) == 0)
4283 ipfw_readfile(ac
, av
);