2 * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25 * $FreeBSD: src/sys/netinet/ip_fw2.c,v 1.6.2.18 2003/10/17 11:01:03 scottl Exp $
32 * Implement IP packet firewall (new version)
36 #error IPFIREWALL requires INET.
40 #include <machine/spl.h>
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/malloc.h>
46 #include <sys/kernel.h>
48 #include <sys/socket.h>
49 #include <sys/socketvar.h>
50 #include <sys/sysctl.h>
51 #include <sys/syslog.h>
52 #include <sys/ucred.h>
53 #include <sys/kern_event.h>
56 #include <net/route.h>
57 #include <netinet/in.h>
58 #include <netinet/in_systm.h>
59 #include <netinet/in_var.h>
60 #include <netinet/in_pcb.h>
61 #include <netinet/ip.h>
62 #include <netinet/ip_var.h>
63 #include <netinet/ip_icmp.h>
64 #include <netinet/ip_fw.h>
65 #include <netinet/ip_divert.h>
68 #include <netinet/ip_dummynet.h>
71 #include <netinet/tcp.h>
72 #include <netinet/tcp_timer.h>
73 #include <netinet/tcp_var.h>
74 #include <netinet/tcpip.h>
75 #include <netinet/udp.h>
76 #include <netinet/udp_var.h>
79 #include <netinet6/ipsec.h>
82 #include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
84 #include "ip_fw2_compat.h"
86 #include <sys/kern_event.h>
90 #include <machine/in_cksum.h>
91 */ /* XXX for in_cksum */
94 * XXX This one should go in sys/mbuf.h. It is used to avoid that
95 * a firewall-generated packet loops forever through the firewall.
97 #ifndef M_SKIP_FIREWALL
98 #define M_SKIP_FIREWALL 0x4000
102 * set_disable contains one bit per set value (0..31).
103 * If the bit is set, all rules with the corresponding set
104 * are disabled. Set RESVD_SET(31) is reserved for the default rule
105 * and rules that are not deleted by the flush command,
106 * and CANNOT be disabled.
107 * Rules in set RESVD_SET can only be deleted explicitly.
109 static u_int32_t set_disable
;
112 static int verbose_limit
;
113 extern int fw_bypass
;
115 #define IPFW_DEFAULT_RULE 65535
117 #define IPFW_RULE_INACTIVE 1
120 * list of rules for layer 3
122 static struct ip_fw
*layer3_chain
;
124 MALLOC_DEFINE(M_IPFW
, "IpFw/IpAcct", "IpFw/IpAcct chain's");
126 static int fw_debug
= 0;
127 static int autoinc_step
= 100; /* bounded to 1..1000 in add_rule() */
129 static void ipfw_kev_post_msg(u_int32_t
);
133 static int ipfw_sysctl SYSCTL_HANDLER_ARGS
;
135 SYSCTL_NODE(_net_inet_ip
, OID_AUTO
, fw
, CTLFLAG_RW
|CTLFLAG_LOCKED
, 0, "Firewall");
136 SYSCTL_PROC(_net_inet_ip_fw
, OID_AUTO
, enable
,
137 CTLTYPE_INT
| CTLFLAG_RW
,
138 &fw_enable
, 0, ipfw_sysctl
, "I", "Enable ipfw");
139 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, autoinc_step
, CTLFLAG_RW
,
140 &autoinc_step
, 0, "Rule number autincrement step");
141 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, one_pass
,
144 "Only do a single pass through ipfw when using dummynet(4)");
145 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, debug
,
147 &fw_debug
, 0, "Enable printing of debug ip_fw statements");
148 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, verbose
,
150 &fw_verbose
, 0, "Log matches to ipfw rules");
151 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, verbose_limit
, CTLFLAG_RW
,
152 &verbose_limit
, 0, "Set upper limit of matches of ipfw rules logged");
155 * Description of dynamic rules.
157 * Dynamic rules are stored in lists accessed through a hash table
158 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
159 * be modified through the sysctl variable dyn_buckets which is
160 * updated when the table becomes empty.
162 * XXX currently there is only one list, ipfw_dyn.
164 * When a packet is received, its address fields are first masked
165 * with the mask defined for the rule, then hashed, then matched
166 * against the entries in the corresponding list.
167 * Dynamic rules can be used for different purposes:
169 * + enforcing limits on the number of sessions;
170 * + in-kernel NAT (not implemented yet)
172 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
173 * measured in seconds and depending on the flags.
175 * The total number of dynamic rules is stored in dyn_count.
176 * The max number of dynamic rules is dyn_max. When we reach
177 * the maximum number of rules we do not create anymore. This is
178 * done to avoid consuming too much memory, but also too much
179 * time when searching on each packet (ideally, we should try instead
180 * to put a limit on the length of the list on each bucket...).
182 * Each dynamic rule holds a pointer to the parent ipfw rule so
183 * we know what action to perform. Dynamic rules are removed when
184 * the parent rule is deleted. XXX we should make them survive.
186 * There are some limitations with dynamic rules -- we do not
187 * obey the 'randomized match', and we do not do multiple
188 * passes through the firewall. XXX check the latter!!!
190 static ipfw_dyn_rule
**ipfw_dyn_v
= NULL
;
191 static u_int32_t dyn_buckets
= 256; /* must be power of 2 */
192 static u_int32_t curr_dyn_buckets
= 256; /* must be power of 2 */
195 * Timeouts for various events in handing dynamic rules.
197 static u_int32_t dyn_ack_lifetime
= 300;
198 static u_int32_t dyn_syn_lifetime
= 20;
199 static u_int32_t dyn_fin_lifetime
= 1;
200 static u_int32_t dyn_rst_lifetime
= 1;
201 static u_int32_t dyn_udp_lifetime
= 10;
202 static u_int32_t dyn_short_lifetime
= 5;
205 * Keepalives are sent if dyn_keepalive is set. They are sent every
206 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
207 * seconds of lifetime of a rule.
208 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
209 * than dyn_keepalive_period.
212 static u_int32_t dyn_keepalive_interval
= 20;
213 static u_int32_t dyn_keepalive_period
= 5;
214 static u_int32_t dyn_keepalive
= 1; /* do send keepalives */
216 static u_int32_t static_count
; /* # of static rules */
217 static u_int32_t static_len
; /* size in bytes of static rules */
218 static u_int32_t dyn_count
; /* # of dynamic rules */
219 static u_int32_t dyn_max
= 4096; /* max # of dynamic rules */
221 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_buckets
, CTLFLAG_RW
,
222 &dyn_buckets
, 0, "Number of dyn. buckets");
223 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, curr_dyn_buckets
, CTLFLAG_RD
,
224 &curr_dyn_buckets
, 0, "Current Number of dyn. buckets");
225 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_count
, CTLFLAG_RD
,
226 &dyn_count
, 0, "Number of dyn. rules");
227 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_max
, CTLFLAG_RW
,
228 &dyn_max
, 0, "Max number of dyn. rules");
229 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, static_count
, CTLFLAG_RD
,
230 &static_count
, 0, "Number of static rules");
231 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_ack_lifetime
, CTLFLAG_RW
,
232 &dyn_ack_lifetime
, 0, "Lifetime of dyn. rules for acks");
233 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_syn_lifetime
, CTLFLAG_RW
,
234 &dyn_syn_lifetime
, 0, "Lifetime of dyn. rules for syn");
235 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_fin_lifetime
, CTLFLAG_RW
,
236 &dyn_fin_lifetime
, 0, "Lifetime of dyn. rules for fin");
237 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_rst_lifetime
, CTLFLAG_RW
,
238 &dyn_rst_lifetime
, 0, "Lifetime of dyn. rules for rst");
239 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_udp_lifetime
, CTLFLAG_RW
,
240 &dyn_udp_lifetime
, 0, "Lifetime of dyn. rules for UDP");
241 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_short_lifetime
, CTLFLAG_RW
,
242 &dyn_short_lifetime
, 0, "Lifetime of dyn. rules for other situations");
243 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_keepalive
, CTLFLAG_RW
,
244 &dyn_keepalive
, 0, "Enable keepalives for dyn. rules");
247 ipfw_sysctl SYSCTL_HANDLER_ARGS
249 #pragma unused(arg1, arg2)
252 error
= sysctl_handle_int(oidp
, oidp
->oid_arg1
, oidp
->oid_arg2
, req
);
253 if (error
|| !req
->newptr
)
256 ipfw_kev_post_msg(KEV_IPFW_ENABLE
);
261 #endif /* SYSCTL_NODE */
264 static ip_fw_chk_t ipfw_chk
;
267 lck_grp_t
*ipfw_mutex_grp
;
268 lck_grp_attr_t
*ipfw_mutex_grp_attr
;
269 lck_attr_t
*ipfw_mutex_attr
;
270 lck_mtx_t
*ipfw_mutex
;
272 extern void ipfwsyslog( int level
, const char *format
,...);
275 ip_dn_ruledel_t
*ip_dn_ruledel_ptr
= NULL
; /* hook into dummynet */
276 #endif /* DUMMYNET */
278 #define KEV_LOG_SUBCLASS 10
279 #define IPFWLOGEVENT 0
281 #define ipfwstring "ipfw:"
282 static size_t ipfwstringlen
;
284 #define dolog( a ) { \
285 if ( fw_verbose == 2 ) /* Apple logging, log to ipfw.log */ \
290 void ipfwsyslog( int level
, const char *format
,...)
294 struct kev_msg ev_msg
;
296 char msgBuf
[msgsize
];
301 va_start( ap
, format
);
302 loglen
= vsnprintf(msgBuf
, msgsize
, format
, ap
);
305 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
306 ev_msg
.kev_class
= KEV_NETWORK_CLASS
;
307 ev_msg
.kev_subclass
= KEV_LOG_SUBCLASS
;
308 ev_msg
.event_code
= IPFWLOGEVENT
;
310 /* get rid of the trailing \n */
313 pri
= LOG_PRI(level
);
315 /* remove "ipfw:" prefix if logging to ipfw log */
316 if ( !(strncmp( ipfwstring
, msgBuf
, ipfwstringlen
))){
317 dptr
= msgBuf
+ipfwstringlen
;
320 ev_msg
.dv
[0].data_ptr
= &pri
;
321 ev_msg
.dv
[0].data_length
= 1;
322 ev_msg
.dv
[1].data_ptr
= dptr
;
323 ev_msg
.dv
[1].data_length
= 100; /* bug in kern_post_msg, it can't handle size > 256-msghdr */
324 ev_msg
.dv
[2].data_length
= 0;
326 kev_post_msg(&ev_msg
);
330 * This macro maps an ip pointer into a layer3 header pointer of type T
332 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
335 icmptype_match(struct ip
*ip
, ipfw_insn_u32
*cmd
)
337 int type
= L3HDR(struct icmp
,ip
)->icmp_type
;
339 return (type
<= ICMP_MAXTYPE
&& (cmd
->d
[0] & (1<<type
)) );
342 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
343 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
346 is_icmp_query(struct ip
*ip
)
348 int type
= L3HDR(struct icmp
, ip
)->icmp_type
;
349 return (type
<= ICMP_MAXTYPE
&& (TT
& (1<<type
)) );
354 * The following checks use two arrays of 8 or 16 bits to store the
355 * bits that we want set or clear, respectively. They are in the
356 * low and high half of cmd->arg1 or cmd->d[0].
358 * We scan options and store the bits we find set. We succeed if
360 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
362 * The code is sometimes optimized not to store additional variables.
366 flags_match(ipfw_insn
*cmd
, u_int8_t bits
)
371 if ( ((cmd
->arg1
& 0xff) & bits
) != 0)
372 return 0; /* some bits we want set were clear */
373 want_clear
= (cmd
->arg1
>> 8) & 0xff;
374 if ( (want_clear
& bits
) != want_clear
)
375 return 0; /* some bits we want clear were set */
380 ipopts_match(struct ip
*ip
, ipfw_insn
*cmd
)
382 int optlen
, bits
= 0;
383 u_char
*cp
= (u_char
*)(ip
+ 1);
384 int x
= (ip
->ip_hl
<< 2) - sizeof (struct ip
);
386 for (; x
> 0; x
-= optlen
, cp
+= optlen
) {
387 int opt
= cp
[IPOPT_OPTVAL
];
389 if (opt
== IPOPT_EOL
)
391 if (opt
== IPOPT_NOP
)
394 optlen
= cp
[IPOPT_OLEN
];
395 if (optlen
<= 0 || optlen
> x
)
396 return 0; /* invalid or truncated */
404 bits
|= IP_FW_IPOPT_LSRR
;
408 bits
|= IP_FW_IPOPT_SSRR
;
412 bits
|= IP_FW_IPOPT_RR
;
416 bits
|= IP_FW_IPOPT_TS
;
420 return (flags_match(cmd
, bits
));
424 tcpopts_match(struct ip
*ip
, ipfw_insn
*cmd
)
426 int optlen
, bits
= 0;
427 struct tcphdr
*tcp
= L3HDR(struct tcphdr
,ip
);
428 u_char
*cp
= (u_char
*)(tcp
+ 1);
429 int x
= (tcp
->th_off
<< 2) - sizeof(struct tcphdr
);
431 for (; x
> 0; x
-= optlen
, cp
+= optlen
) {
433 if (opt
== TCPOPT_EOL
)
435 if (opt
== TCPOPT_NOP
)
449 bits
|= IP_FW_TCPOPT_MSS
;
453 bits
|= IP_FW_TCPOPT_WINDOW
;
456 case TCPOPT_SACK_PERMITTED
:
458 bits
|= IP_FW_TCPOPT_SACK
;
461 case TCPOPT_TIMESTAMP
:
462 bits
|= IP_FW_TCPOPT_TS
;
468 bits
|= IP_FW_TCPOPT_CC
;
472 return (flags_match(cmd
, bits
));
476 iface_match(struct ifnet
*ifp
, ipfw_insn_if
*cmd
)
478 if (ifp
== NULL
) /* no iface with this packet, match fails */
480 /* Check by name or by IP address */
481 if (cmd
->name
[0] != '\0') { /* match by name */
482 /* Check unit number (-1 is wildcard) */
483 if (cmd
->p
.unit
!= -1 && cmd
->p
.unit
!= ifp
->if_unit
)
486 if (!strncmp(ifp
->if_name
, cmd
->name
, IFNAMSIZ
))
491 ifnet_lock_shared(ifp
);
492 TAILQ_FOREACH(ia
, &ifp
->if_addrhead
, ifa_link
) {
493 if (ia
->ifa_addr
== NULL
)
495 if (ia
->ifa_addr
->sa_family
!= AF_INET
)
497 if (cmd
->p
.ip
.s_addr
== ((struct sockaddr_in
*)
498 (ia
->ifa_addr
))->sin_addr
.s_addr
) {
499 ifnet_lock_done(ifp
);
500 return(1); /* match */
503 ifnet_lock_done(ifp
);
505 return(0); /* no match, fail ... */
509 * The 'verrevpath' option checks that the interface that an IP packet
510 * arrives on is the same interface that traffic destined for the
511 * packet's source address would be routed out of. This is a measure
512 * to block forged packets. This is also commonly known as "anti-spoofing"
513 * or Unicast Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The
514 * name of the knob is purposely reminisent of the Cisco IOS command,
516 * ip verify unicast reverse-path
518 * which implements the same functionality. But note that syntax is
519 * misleading. The check may be performed on all IP packets whether unicast,
520 * multicast, or broadcast.
523 verify_rev_path(struct in_addr src
, struct ifnet
*ifp
)
525 static struct route ro
;
526 struct sockaddr_in
*dst
;
528 dst
= (struct sockaddr_in
*)&(ro
.ro_dst
);
530 /* Check if we've cached the route from the previous call. */
531 if (src
.s_addr
!= dst
->sin_addr
.s_addr
) {
534 bzero(dst
, sizeof(*dst
));
535 dst
->sin_family
= AF_INET
;
536 dst
->sin_len
= sizeof(*dst
);
539 rtalloc_ign(&ro
, RTF_CLONING
|RTF_PRCLONING
);
542 if ((ro
.ro_rt
== NULL
) || (ifp
== NULL
) ||
543 (ro
.ro_rt
->rt_ifp
->if_index
!= ifp
->if_index
))
550 static u_int64_t norule_counter
; /* counter for ipfw_log(NULL...) */
552 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
553 #define SNP(buf) buf, sizeof(buf)
556 * We enter here when we have a rule with O_LOG.
557 * XXX this function alone takes about 2Kbytes of code!
560 ipfw_log(struct ip_fw
*f
, u_int hlen
, struct ether_header
*eh
,
561 struct mbuf
*m
, struct ifnet
*oif
)
564 int limit_reached
= 0;
565 char ipv4str
[MAX_IPv4_STR_LEN
];
566 char action2
[40], proto
[48], fragment
[28];
571 if (f
== NULL
) { /* bogus pkt */
572 if (verbose_limit
!= 0 && norule_counter
>= verbose_limit
)
575 if (norule_counter
== verbose_limit
)
576 limit_reached
= verbose_limit
;
578 } else { /* O_LOG is the first action, find the real one */
579 ipfw_insn
*cmd
= ACTION_PTR(f
);
580 ipfw_insn_log
*l
= (ipfw_insn_log
*)cmd
;
582 if (l
->max_log
!= 0 && l
->log_left
== 0)
585 if (l
->log_left
== 0)
586 limit_reached
= l
->max_log
;
587 cmd
+= F_LEN(cmd
); /* point to first action */
588 if (cmd
->opcode
== O_PROB
)
592 switch (cmd
->opcode
) {
598 if (cmd
->arg1
==ICMP_REJECT_RST
)
600 else if (cmd
->arg1
==ICMP_UNREACH_HOST
)
603 snprintf(SNPARGS(action2
, 0), "Unreach %d",
614 snprintf(SNPARGS(action2
, 0), "Divert %d",
618 snprintf(SNPARGS(action2
, 0), "Tee %d",
622 snprintf(SNPARGS(action2
, 0), "SkipTo %d",
626 snprintf(SNPARGS(action2
, 0), "Pipe %d",
630 snprintf(SNPARGS(action2
, 0), "Queue %d",
634 ipfw_insn_sa
*sa
= (ipfw_insn_sa
*)cmd
;
637 if (f
->reserved_1
== IPFW_RULE_INACTIVE
) {
640 len
= snprintf(SNPARGS(action2
, 0), "Forward to %s",
641 inet_ntop(AF_INET
, &sa
->sa
.sin_addr
, ipv4str
, sizeof(ipv4str
)));
643 snprintf(SNPARGS(action2
, len
), ":%d",
653 if (hlen
== 0) { /* non-ip */
654 snprintf(SNPARGS(proto
, 0), "MAC");
656 struct ip
*ip
= mtod(m
, struct ip
*);
657 /* these three are all aliases to the same thing */
658 struct icmp
*const icmp
= L3HDR(struct icmp
, ip
);
659 struct tcphdr
*const tcp
= (struct tcphdr
*)icmp
;
660 struct udphdr
*const udp
= (struct udphdr
*)icmp
;
662 int ip_off
, offset
, ip_len
;
666 if (eh
!= NULL
) { /* layer 2 packets are as on the wire */
667 ip_off
= ntohs(ip
->ip_off
);
668 ip_len
= ntohs(ip
->ip_len
);
673 offset
= ip_off
& IP_OFFMASK
;
676 len
= snprintf(SNPARGS(proto
, 0), "TCP %s",
677 inet_ntop(AF_INET
, &ip
->ip_src
, ipv4str
, sizeof(ipv4str
)));
679 snprintf(SNPARGS(proto
, len
), ":%d %s:%d",
680 ntohs(tcp
->th_sport
),
681 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)),
682 ntohs(tcp
->th_dport
));
684 snprintf(SNPARGS(proto
, len
), " %s",
685 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)));
689 len
= snprintf(SNPARGS(proto
, 0), "UDP %s",
690 inet_ntop(AF_INET
, &ip
->ip_src
, ipv4str
, sizeof(ipv4str
)));
692 snprintf(SNPARGS(proto
, len
), ":%d %s:%d",
693 ntohs(udp
->uh_sport
),
694 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)),
695 ntohs(udp
->uh_dport
));
697 snprintf(SNPARGS(proto
, len
), " %s",
698 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)));
703 len
= snprintf(SNPARGS(proto
, 0),
705 icmp
->icmp_type
, icmp
->icmp_code
);
707 len
= snprintf(SNPARGS(proto
, 0), "ICMP ");
708 len
+= snprintf(SNPARGS(proto
, len
), "%s",
709 inet_ntop(AF_INET
, &ip
->ip_src
, ipv4str
, sizeof(ipv4str
)));
710 snprintf(SNPARGS(proto
, len
), " %s",
711 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)));
715 len
= snprintf(SNPARGS(proto
, 0), "P:%d %s", ip
->ip_p
,
716 inet_ntop(AF_INET
, &ip
->ip_src
, ipv4str
, sizeof(ipv4str
)));
717 snprintf(SNPARGS(proto
, len
), " %s",
718 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)));
722 if (ip_off
& (IP_MF
| IP_OFFMASK
))
723 snprintf(SNPARGS(fragment
, 0), " (frag %d:%d@%d%s)",
724 ntohs(ip
->ip_id
), ip_len
- (ip
->ip_hl
<< 2),
726 (ip_off
& IP_MF
) ? "+" : "");
728 if (oif
|| m
->m_pkthdr
.rcvif
)
730 dolog((LOG_AUTHPRIV
| LOG_INFO
,
731 "ipfw: %d %s %s %s via %s%d%s\n",
733 action
, proto
, oif
? "out" : "in",
734 oif
? oif
->if_name
: m
->m_pkthdr
.rcvif
->if_name
,
735 oif
? oif
->if_unit
: m
->m_pkthdr
.rcvif
->if_unit
,
739 dolog((LOG_AUTHPRIV
| LOG_INFO
,
740 "ipfw: %d %s %s [no if info]%s\n",
742 action
, proto
, fragment
));
745 dolog((LOG_AUTHPRIV
| LOG_NOTICE
,
746 "ipfw: limit %d reached on entry %d\n",
747 limit_reached
, f
? f
->rulenum
: -1));
752 * IMPORTANT: the hash function for dynamic rules must be commutative
753 * in source and destination (ip,port), because rules are bidirectional
754 * and we want to find both in the same bucket.
757 hash_packet(struct ipfw_flow_id
*id
)
761 i
= (id
->dst_ip
) ^ (id
->src_ip
) ^ (id
->dst_port
) ^ (id
->src_port
);
762 i
&= (curr_dyn_buckets
- 1);
767 * unlink a dynamic rule from a chain. prev is a pointer to
768 * the previous one, q is a pointer to the rule to delete,
769 * head is a pointer to the head of the queue.
770 * Modifies q and potentially also head.
772 #define UNLINK_DYN_RULE(prev, head, q) { \
773 ipfw_dyn_rule *old_q = q; \
775 /* remove a refcount to the parent */ \
776 if (q->dyn_type == O_LIMIT) \
777 q->parent->count--; \
778 DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
779 (q->id.src_ip), (q->id.src_port), \
780 (q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); ) \
782 prev->next = q = q->next; \
784 head = q = q->next; \
786 _FREE(old_q, M_IPFW); }
788 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
791 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
793 * If keep_me == NULL, rules are deleted even if not expired,
794 * otherwise only expired rules are removed.
796 * The value of the second parameter is also used to point to identify
797 * a rule we absolutely do not want to remove (e.g. because we are
798 * holding a reference to it -- this is the case with O_LIMIT_PARENT
799 * rules). The pointer is only used for comparison, so any non-null
803 remove_dyn_rule(struct ip_fw
*rule
, ipfw_dyn_rule
*keep_me
)
805 static u_int32_t last_remove
= 0;
807 #define FORCE (keep_me == NULL)
809 ipfw_dyn_rule
*prev
, *q
;
810 int i
, pass
= 0, max_pass
= 0;
811 struct timeval timenow
;
813 getmicrotime(&timenow
);
815 if (ipfw_dyn_v
== NULL
|| dyn_count
== 0)
817 /* do not expire more than once per second, it is useless */
818 if (!FORCE
&& last_remove
== timenow
.tv_sec
)
820 last_remove
= timenow
.tv_sec
;
823 * because O_LIMIT refer to parent rules, during the first pass only
824 * remove child and mark any pending LIMIT_PARENT, and remove
825 * them in a second pass.
828 for (i
= 0 ; i
< curr_dyn_buckets
; i
++) {
829 for (prev
=NULL
, q
= ipfw_dyn_v
[i
] ; q
; ) {
831 * Logic can become complex here, so we split tests.
835 if (rule
!= NULL
&& rule
!= q
->rule
)
836 goto next
; /* not the one we are looking for */
837 if (q
->dyn_type
== O_LIMIT_PARENT
) {
839 * handle parent in the second pass,
840 * record we need one.
845 if (FORCE
&& q
->count
!= 0 ) {
846 /* XXX should not happen! */
847 printf("ipfw: OUCH! cannot remove rule,"
848 " count %d\n", q
->count
);
852 !TIME_LEQ( q
->expire
, timenow
.tv_sec
))
855 if (q
->dyn_type
!= O_LIMIT_PARENT
|| !q
->count
) {
856 UNLINK_DYN_RULE(prev
, ipfw_dyn_v
[i
], q
);
864 if (pass
++ < max_pass
)
870 * lookup a dynamic rule.
872 static ipfw_dyn_rule
*
873 lookup_dyn_rule(struct ipfw_flow_id
*pkt
, int *match_direction
,
877 * stateful ipfw extensions.
878 * Lookup into dynamic session queue
880 #define MATCH_REVERSE 0
881 #define MATCH_FORWARD 1
883 #define MATCH_UNKNOWN 3
884 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
885 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
887 int i
, dir
= MATCH_NONE
;
888 ipfw_dyn_rule
*prev
, *q
=NULL
;
889 struct timeval timenow
;
891 getmicrotime(&timenow
);
893 if (ipfw_dyn_v
== NULL
)
894 goto done
; /* not found */
895 i
= hash_packet( pkt
);
896 for (prev
=NULL
, q
= ipfw_dyn_v
[i
] ; q
!= NULL
; ) {
897 if (q
->dyn_type
== O_LIMIT_PARENT
&& q
->count
)
899 if (TIME_LEQ( q
->expire
, timenow
.tv_sec
)) { /* expire entry */
902 /* check if entry is TCP */
903 if ( q
->id
.proto
== IPPROTO_TCP
)
905 /* do not delete an established TCP connection which hasn't been closed by both sides */
906 if ( (q
->state
& (BOTH_SYN
| BOTH_FIN
)) != (BOTH_SYN
| BOTH_FIN
) )
910 UNLINK_DYN_RULE(prev
, ipfw_dyn_v
[i
], q
);
914 if (pkt
->proto
== q
->id
.proto
&&
915 q
->dyn_type
!= O_LIMIT_PARENT
) {
916 if (pkt
->src_ip
== q
->id
.src_ip
&&
917 pkt
->dst_ip
== q
->id
.dst_ip
&&
918 pkt
->src_port
== q
->id
.src_port
&&
919 pkt
->dst_port
== q
->id
.dst_port
) {
923 if (pkt
->src_ip
== q
->id
.dst_ip
&&
924 pkt
->dst_ip
== q
->id
.src_ip
&&
925 pkt
->src_port
== q
->id
.dst_port
&&
926 pkt
->dst_port
== q
->id
.src_port
) {
936 goto done
; /* q = NULL, not found */
938 if ( prev
!= NULL
) { /* found and not in front */
939 prev
->next
= q
->next
;
940 q
->next
= ipfw_dyn_v
[i
];
943 if (pkt
->proto
== IPPROTO_TCP
) { /* update state according to flags */
944 u_char flags
= pkt
->flags
& (TH_FIN
|TH_SYN
|TH_RST
);
946 q
->state
|= (dir
== MATCH_FORWARD
) ? flags
: (flags
<< 8);
948 case TH_SYN
: /* opening */
949 q
->expire
= timenow
.tv_sec
+ dyn_syn_lifetime
;
952 case BOTH_SYN
: /* move to established */
953 case BOTH_SYN
| TH_FIN
: /* one side tries to close */
954 case BOTH_SYN
| (TH_FIN
<< 8) :
956 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
957 u_int32_t ack
= ntohl(tcp
->th_ack
);
958 if (dir
== MATCH_FORWARD
) {
959 if (q
->ack_fwd
== 0 || _SEQ_GE(ack
, q
->ack_fwd
))
961 else { /* ignore out-of-sequence */
965 if (q
->ack_rev
== 0 || _SEQ_GE(ack
, q
->ack_rev
))
967 else { /* ignore out-of-sequence */
972 q
->expire
= timenow
.tv_sec
+ dyn_ack_lifetime
;
975 case BOTH_SYN
| BOTH_FIN
: /* both sides closed */
976 if (dyn_fin_lifetime
>= dyn_keepalive_period
)
977 dyn_fin_lifetime
= dyn_keepalive_period
- 1;
978 q
->expire
= timenow
.tv_sec
+ dyn_fin_lifetime
;
984 * reset or some invalid combination, but can also
985 * occur if we use keep-state the wrong way.
987 if ( (q
->state
& ((TH_RST
<< 8)|TH_RST
)) == 0)
988 printf("invalid state: 0x%x\n", q
->state
);
990 if (dyn_rst_lifetime
>= dyn_keepalive_period
)
991 dyn_rst_lifetime
= dyn_keepalive_period
- 1;
992 q
->expire
= timenow
.tv_sec
+ dyn_rst_lifetime
;
995 } else if (pkt
->proto
== IPPROTO_UDP
) {
996 q
->expire
= timenow
.tv_sec
+ dyn_udp_lifetime
;
998 /* other protocols */
999 q
->expire
= timenow
.tv_sec
+ dyn_short_lifetime
;
1002 if (match_direction
)
1003 *match_direction
= dir
;
1008 realloc_dynamic_table(void)
1011 * Try reallocation, make sure we have a power of 2 and do
1012 * not allow more than 64k entries. In case of overflow,
1016 if (dyn_buckets
> 65536)
1018 if ((dyn_buckets
& (dyn_buckets
-1)) != 0) { /* not a power of 2 */
1019 dyn_buckets
= curr_dyn_buckets
; /* reset */
1022 curr_dyn_buckets
= dyn_buckets
;
1023 if (ipfw_dyn_v
!= NULL
)
1024 _FREE(ipfw_dyn_v
, M_IPFW
);
1026 ipfw_dyn_v
= _MALLOC(curr_dyn_buckets
* sizeof(ipfw_dyn_rule
*),
1027 M_IPFW
, M_NOWAIT
| M_ZERO
);
1028 if (ipfw_dyn_v
!= NULL
|| curr_dyn_buckets
<= 2)
1030 curr_dyn_buckets
/= 2;
1035 * Install state of type 'type' for a dynamic session.
1036 * The hash table contains two type of rules:
1037 * - regular rules (O_KEEP_STATE)
1038 * - rules for sessions with limited number of sess per user
1039 * (O_LIMIT). When they are created, the parent is
1040 * increased by 1, and decreased on delete. In this case,
1041 * the third parameter is the parent rule and not the chain.
1042 * - "parent" rules for the above (O_LIMIT_PARENT).
1044 static ipfw_dyn_rule
*
1045 add_dyn_rule(struct ipfw_flow_id
*id
, u_int8_t dyn_type
, struct ip_fw
*rule
)
1049 struct timeval timenow
;
1051 getmicrotime(&timenow
);
1053 if (ipfw_dyn_v
== NULL
||
1054 (dyn_count
== 0 && dyn_buckets
!= curr_dyn_buckets
)) {
1055 realloc_dynamic_table();
1056 if (ipfw_dyn_v
== NULL
)
1057 return NULL
; /* failed ! */
1059 i
= hash_packet(id
);
1061 r
= _MALLOC(sizeof *r
, M_IPFW
, M_NOWAIT
| M_ZERO
);
1064 printf ("ipfw: sorry cannot allocate state\n");
1069 /* increase refcount on parent, and set pointer */
1070 if (dyn_type
== O_LIMIT
) {
1071 ipfw_dyn_rule
*parent
= (ipfw_dyn_rule
*)rule
;
1072 if ( parent
->dyn_type
!= O_LIMIT_PARENT
)
1073 panic("invalid parent");
1076 rule
= parent
->rule
;
1080 r
->expire
= timenow
.tv_sec
+ dyn_syn_lifetime
;
1082 r
->dyn_type
= dyn_type
;
1083 r
->pcnt
= r
->bcnt
= 0;
1087 r
->next
= ipfw_dyn_v
[i
];
1090 DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1092 (r
->id
.src_ip
), (r
->id
.src_port
),
1093 (r
->id
.dst_ip
), (r
->id
.dst_port
),
1099 * lookup dynamic parent rule using pkt and rule as search keys.
1100 * If the lookup fails, then install one.
1102 static ipfw_dyn_rule
*
1103 lookup_dyn_parent(struct ipfw_flow_id
*pkt
, struct ip_fw
*rule
)
1107 struct timeval timenow
;
1109 getmicrotime(&timenow
);
1112 i
= hash_packet( pkt
);
1113 for (q
= ipfw_dyn_v
[i
] ; q
!= NULL
; q
=q
->next
)
1114 if (q
->dyn_type
== O_LIMIT_PARENT
&&
1116 pkt
->proto
== q
->id
.proto
&&
1117 pkt
->src_ip
== q
->id
.src_ip
&&
1118 pkt
->dst_ip
== q
->id
.dst_ip
&&
1119 pkt
->src_port
== q
->id
.src_port
&&
1120 pkt
->dst_port
== q
->id
.dst_port
) {
1121 q
->expire
= timenow
.tv_sec
+ dyn_short_lifetime
;
1122 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q
);)
1126 return add_dyn_rule(pkt
, O_LIMIT_PARENT
, rule
);
1130 * Install dynamic state for rule type cmd->o.opcode
1132 * Returns 1 (failure) if state is not installed because of errors or because
1133 * session limitations are enforced.
1136 install_state(struct ip_fw
*rule
, ipfw_insn_limit
*cmd
,
1137 struct ip_fw_args
*args
)
1139 static int last_log
;
1140 struct timeval timenow
;
1143 getmicrotime(&timenow
);
1145 DEB(printf("ipfw: install state type %d 0x%08x %u -> 0x%08x %u\n",
1147 (args
->f_id
.src_ip
), (args
->f_id
.src_port
),
1148 (args
->f_id
.dst_ip
), (args
->f_id
.dst_port
) );)
1150 q
= lookup_dyn_rule(&args
->f_id
, NULL
, NULL
);
1152 if (q
!= NULL
) { /* should never occur */
1153 if (last_log
!= timenow
.tv_sec
) {
1154 last_log
= timenow
.tv_sec
;
1155 printf("ipfw: install_state: entry already present, done\n");
1160 if (dyn_count
>= dyn_max
)
1162 * Run out of slots, try to remove any expired rule.
1164 remove_dyn_rule(NULL
, (ipfw_dyn_rule
*)1);
1166 if (dyn_count
>= dyn_max
) {
1167 if (last_log
!= timenow
.tv_sec
) {
1168 last_log
= timenow
.tv_sec
;
1169 printf("ipfw: install_state: Too many dynamic rules\n");
1171 return 1; /* cannot install, notify caller */
1174 switch (cmd
->o
.opcode
) {
1175 case O_KEEP_STATE
: /* bidir rule */
1176 add_dyn_rule(&args
->f_id
, O_KEEP_STATE
, rule
);
1179 case O_LIMIT
: /* limit number of sessions */
1181 u_int16_t limit_mask
= cmd
->limit_mask
;
1182 struct ipfw_flow_id id
;
1183 ipfw_dyn_rule
*parent
;
1185 DEB(printf("ipfw: installing dyn-limit rule %d\n",
1188 id
.dst_ip
= id
.src_ip
= 0;
1189 id
.dst_port
= id
.src_port
= 0;
1190 id
.proto
= args
->f_id
.proto
;
1192 if (limit_mask
& DYN_SRC_ADDR
)
1193 id
.src_ip
= args
->f_id
.src_ip
;
1194 if (limit_mask
& DYN_DST_ADDR
)
1195 id
.dst_ip
= args
->f_id
.dst_ip
;
1196 if (limit_mask
& DYN_SRC_PORT
)
1197 id
.src_port
= args
->f_id
.src_port
;
1198 if (limit_mask
& DYN_DST_PORT
)
1199 id
.dst_port
= args
->f_id
.dst_port
;
1200 parent
= lookup_dyn_parent(&id
, rule
);
1201 if (parent
== NULL
) {
1202 printf("ipfw: add parent failed\n");
1205 if (parent
->count
>= cmd
->conn_limit
) {
1207 * See if we can remove some expired rule.
1209 remove_dyn_rule(rule
, parent
);
1210 if (parent
->count
>= cmd
->conn_limit
) {
1211 if (fw_verbose
&& last_log
!= timenow
.tv_sec
) {
1212 last_log
= timenow
.tv_sec
;
1213 dolog((LOG_AUTHPRIV
| LOG_DEBUG
,
1214 "drop session, too many entries\n"));
1219 add_dyn_rule(&args
->f_id
, O_LIMIT
, (struct ip_fw
*)parent
);
1223 printf("ipfw: unknown dynamic rule type %u\n", cmd
->o
.opcode
);
1226 lookup_dyn_rule(&args
->f_id
, NULL
, NULL
); /* XXX just set lifetime */
1231 * Transmit a TCP packet, containing either a RST or a keepalive.
1232 * When flags & TH_RST, we are sending a RST packet, because of a
1233 * "reset" action matched the packet.
1234 * Otherwise we are sending a keepalive, and flags & TH_
1237 send_pkt(struct ipfw_flow_id
*id
, u_int32_t seq
, u_int32_t ack
, int flags
)
1242 struct route sro
; /* fake route */
1244 MGETHDR(m
, M_DONTWAIT
, MT_HEADER
); /* MAC-OK */
1247 m
->m_pkthdr
.rcvif
= (struct ifnet
*)0;
1248 m
->m_pkthdr
.len
= m
->m_len
= sizeof(struct ip
) + sizeof(struct tcphdr
);
1249 m
->m_data
+= max_linkhdr
;
1251 ip
= mtod(m
, struct ip
*);
1252 bzero(ip
, m
->m_len
);
1253 tcp
= (struct tcphdr
*)(ip
+ 1); /* no IP options */
1254 ip
->ip_p
= IPPROTO_TCP
;
1257 * Assume we are sending a RST (or a keepalive in the reverse
1258 * direction), swap src and destination addresses and ports.
1260 ip
->ip_src
.s_addr
= htonl(id
->dst_ip
);
1261 ip
->ip_dst
.s_addr
= htonl(id
->src_ip
);
1262 tcp
->th_sport
= htons(id
->dst_port
);
1263 tcp
->th_dport
= htons(id
->src_port
);
1264 if (flags
& TH_RST
) { /* we are sending a RST */
1265 if (flags
& TH_ACK
) {
1266 tcp
->th_seq
= htonl(ack
);
1267 tcp
->th_ack
= htonl(0);
1268 tcp
->th_flags
= TH_RST
;
1272 tcp
->th_seq
= htonl(0);
1273 tcp
->th_ack
= htonl(seq
);
1274 tcp
->th_flags
= TH_RST
| TH_ACK
;
1278 * We are sending a keepalive. flags & TH_SYN determines
1279 * the direction, forward if set, reverse if clear.
1280 * NOTE: seq and ack are always assumed to be correct
1281 * as set by the caller. This may be confusing...
1283 if (flags
& TH_SYN
) {
1285 * we have to rewrite the correct addresses!
1287 ip
->ip_dst
.s_addr
= htonl(id
->dst_ip
);
1288 ip
->ip_src
.s_addr
= htonl(id
->src_ip
);
1289 tcp
->th_dport
= htons(id
->dst_port
);
1290 tcp
->th_sport
= htons(id
->src_port
);
1292 tcp
->th_seq
= htonl(seq
);
1293 tcp
->th_ack
= htonl(ack
);
1294 tcp
->th_flags
= TH_ACK
;
1297 * set ip_len to the payload size so we can compute
1298 * the tcp checksum on the pseudoheader
1299 * XXX check this, could save a couple of words ?
1301 ip
->ip_len
= htons(sizeof(struct tcphdr
));
1302 tcp
->th_sum
= in_cksum(m
, m
->m_pkthdr
.len
);
1304 * now fill fields left out earlier
1306 ip
->ip_ttl
= ip_defttl
;
1307 ip
->ip_len
= m
->m_pkthdr
.len
;
1308 bzero (&sro
, sizeof (sro
));
1309 ip_rtaddr(ip
->ip_dst
, &sro
);
1310 m
->m_flags
|= M_SKIP_FIREWALL
;
1311 ip_output_list(m
, 0, NULL
, &sro
, 0, NULL
, NULL
);
1317 * sends a reject message, consuming the mbuf passed as an argument.
1320 send_reject(struct ip_fw_args
*args
, int code
, int offset
, __unused
int ip_len
)
1323 if (code
!= ICMP_REJECT_RST
) { /* Send an ICMP unreach */
1324 /* We need the IP header in host order for icmp_error(). */
1325 if (args
->eh
!= NULL
) {
1326 struct ip
*ip
= mtod(args
->m
, struct ip
*);
1327 ip
->ip_len
= ntohs(ip
->ip_len
);
1328 ip
->ip_off
= ntohs(ip
->ip_off
);
1330 args
->m
->m_flags
|= M_SKIP_FIREWALL
;
1331 icmp_error(args
->m
, ICMP_UNREACH
, code
, 0L, 0);
1332 } else if (offset
== 0 && args
->f_id
.proto
== IPPROTO_TCP
) {
1333 struct tcphdr
*const tcp
=
1334 L3HDR(struct tcphdr
, mtod(args
->m
, struct ip
*));
1335 if ( (tcp
->th_flags
& TH_RST
) == 0) {
1336 send_pkt(&(args
->f_id
), ntohl(tcp
->th_seq
),
1338 tcp
->th_flags
| TH_RST
);
1348 * Given an ip_fw *, lookup_next_rule will return a pointer
1349 * to the next rule, which can be either the jump
1350 * target (for skipto instructions) or the next one in the list (in
1351 * all other cases including a missing jump target).
1352 * The result is also written in the "next_rule" field of the rule.
1353 * Backward jumps are not allowed, so start looking from the next
1356 * This never returns NULL -- in case we do not have an exact match,
1357 * the next rule is returned. When the ruleset is changed,
1358 * pointers are flushed so we are always correct.
1361 static struct ip_fw
*
1362 lookup_next_rule(struct ip_fw
*me
)
1364 struct ip_fw
*rule
= NULL
;
1367 /* look for action, in case it is a skipto */
1368 cmd
= ACTION_PTR(me
);
1369 if (cmd
->opcode
== O_LOG
)
1371 if ( cmd
->opcode
== O_SKIPTO
)
1372 for (rule
= me
->next
; rule
; rule
= rule
->next
)
1373 if (rule
->rulenum
>= cmd
->arg1
)
1375 if (rule
== NULL
) /* failure or not a skipto */
1377 me
->next_rule
= rule
;
1382 * The main check routine for the firewall.
1384 * All arguments are in args so we can modify them and return them
1385 * back to the caller.
1389 * args->m (in/out) The packet; we set to NULL when/if we nuke it.
1390 * Starts with the IP header.
1391 * args->eh (in) Mac header if present, or NULL for layer3 packet.
1392 * args->oif Outgoing interface, or NULL if packet is incoming.
1393 * The incoming interface is in the mbuf. (in)
1394 * args->divert_rule (in/out)
1395 * Skip up to the first rule past this rule number;
1396 * upon return, non-zero port number for divert or tee.
1398 * args->rule Pointer to the last matching rule (in/out)
1399 * args->next_hop Socket we are forwarding to (out).
1400 * args->f_id Addresses grabbed from the packet (out)
1404 * IP_FW_PORT_DENY_FLAG the packet must be dropped.
1405 * 0 The packet is to be accepted and routed normally OR
1406 * the packet was denied/rejected and has been dropped;
1407 * in the latter case, *m is equal to NULL upon return.
1408 * port Divert the packet to port, with these caveats:
1410 * - If IP_FW_PORT_TEE_FLAG is set, tee the packet instead
1411 * of diverting it (ie, 'ipfw tee').
1413 * - If IP_FW_PORT_DYNT_FLAG is set, interpret the lower
1414 * 16 bits as a dummynet pipe number instead of diverting
1418 ipfw_chk(struct ip_fw_args
*args
)
1421 * Local variables hold state during the processing of a packet.
1423 * IMPORTANT NOTE: to speed up the processing of rules, there
1424 * are some assumption on the values of the variables, which
1425 * are documented here. Should you change them, please check
1426 * the implementation of the various instructions to make sure
1427 * that they still work.
1429 * args->eh The MAC header. It is non-null for a layer2
1430 * packet, it is NULL for a layer-3 packet.
1432 * m | args->m Pointer to the mbuf, as received from the caller.
1433 * It may change if ipfw_chk() does an m_pullup, or if it
1434 * consumes the packet because it calls send_reject().
1435 * XXX This has to change, so that ipfw_chk() never modifies
1436 * or consumes the buffer.
1437 * ip is simply an alias of the value of m, and it is kept
1438 * in sync with it (the packet is supposed to start with
1441 struct mbuf
*m
= args
->m
;
1442 struct ip
*ip
= mtod(m
, struct ip
*);
1445 * oif | args->oif If NULL, ipfw_chk has been called on the
1446 * inbound path (ether_input, bdg_forward, ip_input).
1447 * If non-NULL, ipfw_chk has been called on the outbound path
1448 * (ether_output, ip_output).
1450 struct ifnet
*oif
= args
->oif
;
1452 struct ip_fw
*f
= NULL
; /* matching rule */
1456 * hlen The length of the IPv4 header.
1457 * hlen >0 means we have an IPv4 packet.
1459 u_int hlen
= 0; /* hlen >0 means we have an IP pkt */
1462 * offset The offset of a fragment. offset != 0 means that
1463 * we have a fragment at this offset of an IPv4 packet.
1464 * offset == 0 means that (if this is an IPv4 packet)
1465 * this is the first or only fragment.
1470 * Local copies of addresses. They are only valid if we have
1473 * proto The protocol. Set to 0 for non-ip packets,
1474 * or to the protocol read from the packet otherwise.
1475 * proto != 0 means that we have an IPv4 packet.
1477 * src_port, dst_port port numbers, in HOST format. Only
1478 * valid for TCP and UDP packets.
1480 * src_ip, dst_ip ip addresses, in NETWORK format.
1481 * Only valid for IPv4 packets.
1484 u_int16_t src_port
= 0, dst_port
= 0; /* NOTE: host format */
1485 struct in_addr src_ip
= { 0 } , dst_ip
= { 0 }; /* NOTE: network format */
1488 int dyn_dir
= MATCH_UNKNOWN
;
1489 ipfw_dyn_rule
*q
= NULL
;
1490 struct timeval timenow
;
1492 if (m
->m_flags
& M_SKIP_FIREWALL
|| fw_bypass
) {
1493 return 0; /* accept */
1497 * Clear packet chain if we find one here.
1500 if (m
->m_nextpkt
!= NULL
) {
1501 m_freem_list(m
->m_nextpkt
);
1502 m
->m_nextpkt
= NULL
;
1505 lck_mtx_lock(ipfw_mutex
);
1507 getmicrotime(&timenow
);
1509 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
1510 * MATCH_NONE when checked and not matched (q = NULL),
1511 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
1514 pktlen
= m
->m_pkthdr
.len
;
1515 if (args
->eh
== NULL
|| /* layer 3 packet */
1516 ( m
->m_pkthdr
.len
>= sizeof(struct ip
) &&
1517 ntohs(args
->eh
->ether_type
) == ETHERTYPE_IP
))
1518 hlen
= ip
->ip_hl
<< 2;
1521 * Collect parameters into local variables for faster matching.
1523 if (hlen
== 0) { /* do not grab addresses for non-ip pkts */
1524 proto
= args
->f_id
.proto
= 0; /* mark f_id invalid */
1525 goto after_ip_checks
;
1528 proto
= args
->f_id
.proto
= ip
->ip_p
;
1529 src_ip
= ip
->ip_src
;
1530 dst_ip
= ip
->ip_dst
;
1531 if (args
->eh
!= NULL
) { /* layer 2 packets are as on the wire */
1532 offset
= ntohs(ip
->ip_off
) & IP_OFFMASK
;
1533 ip_len
= ntohs(ip
->ip_len
);
1535 offset
= ip
->ip_off
& IP_OFFMASK
;
1536 ip_len
= ip
->ip_len
;
1538 pktlen
= ip_len
< pktlen
? ip_len
: pktlen
;
1540 #define PULLUP_TO(len) \
1542 if ((m)->m_len < (len)) { \
1543 args->m = m = m_pullup(m, (len)); \
1545 goto pullup_failed; \
1546 ip = mtod(m, struct ip *); \
1556 PULLUP_TO(hlen
+ sizeof(struct tcphdr
));
1557 tcp
= L3HDR(struct tcphdr
, ip
);
1558 dst_port
= tcp
->th_dport
;
1559 src_port
= tcp
->th_sport
;
1560 args
->f_id
.flags
= tcp
->th_flags
;
1568 PULLUP_TO(hlen
+ sizeof(struct udphdr
));
1569 udp
= L3HDR(struct udphdr
, ip
);
1570 dst_port
= udp
->uh_dport
;
1571 src_port
= udp
->uh_sport
;
1576 PULLUP_TO(hlen
+ 4); /* type, code and checksum. */
1577 args
->f_id
.flags
= L3HDR(struct icmp
, ip
)->icmp_type
;
1586 args
->f_id
.src_ip
= ntohl(src_ip
.s_addr
);
1587 args
->f_id
.dst_ip
= ntohl(dst_ip
.s_addr
);
1588 args
->f_id
.src_port
= src_port
= ntohs(src_port
);
1589 args
->f_id
.dst_port
= dst_port
= ntohs(dst_port
);
1594 * Packet has already been tagged. Look for the next rule
1595 * to restart processing.
1597 * If fw_one_pass != 0 then just accept it.
1598 * XXX should not happen here, but optimized out in
1602 lck_mtx_unlock(ipfw_mutex
);
1606 f
= args
->rule
->next_rule
;
1608 f
= lookup_next_rule(args
->rule
);
1611 * Find the starting rule. It can be either the first
1612 * one, or the one after divert_rule if asked so.
1614 int skipto
= args
->divert_rule
;
1617 if (args
->eh
== NULL
&& skipto
!= 0) {
1618 if (skipto
>= IPFW_DEFAULT_RULE
) {
1619 lck_mtx_unlock(ipfw_mutex
);
1620 return(IP_FW_PORT_DENY_FLAG
); /* invalid */
1622 while (f
&& f
->rulenum
<= skipto
)
1624 if (f
== NULL
) { /* drop packet */
1625 lck_mtx_unlock(ipfw_mutex
);
1626 return(IP_FW_PORT_DENY_FLAG
);
1630 args
->divert_rule
= 0; /* reset to avoid confusion later */
1633 * Now scan the rules, and parse microinstructions for each rule.
1635 for (; f
; f
= f
->next
) {
1638 int skip_or
; /* skip rest of OR block */
1641 if (f
->reserved_1
== IPFW_RULE_INACTIVE
) {
1645 if (set_disable
& (1 << f
->set
) )
1649 for (l
= f
->cmd_len
, cmd
= f
->cmd
; l
> 0 ;
1650 l
-= cmdlen
, cmd
+= cmdlen
) {
1654 * check_body is a jump target used when we find a
1655 * CHECK_STATE, and need to jump to the body of
1660 cmdlen
= F_LEN(cmd
);
1662 * An OR block (insn_1 || .. || insn_n) has the
1663 * F_OR bit set in all but the last instruction.
1664 * The first match will set "skip_or", and cause
1665 * the following instructions to be skipped until
1666 * past the one with the F_OR bit clear.
1668 if (skip_or
) { /* skip this instruction */
1669 if ((cmd
->len
& F_OR
) == 0)
1670 skip_or
= 0; /* next one is good */
1673 match
= 0; /* set to 1 if we succeed */
1675 switch (cmd
->opcode
) {
1677 * The first set of opcodes compares the packet's
1678 * fields with some pattern, setting 'match' if a
1679 * match is found. At the end of the loop there is
1680 * logic to deal with F_NOT and F_OR flags associated
1688 printf("ipfw: opcode %d unimplemented\n",
1697 * We only check offset == 0 && proto != 0,
1698 * as this ensures that we have an IPv4
1699 * packet with the ports info.
1705 struct inpcbinfo
*pi
;
1709 if (proto
== IPPROTO_TCP
) {
1712 } else if (proto
== IPPROTO_UDP
) {
1719 in_pcblookup_hash(pi
,
1720 dst_ip
, htons(dst_port
),
1721 src_ip
, htons(src_port
),
1723 in_pcblookup_hash(pi
,
1724 src_ip
, htons(src_port
),
1725 dst_ip
, htons(dst_port
),
1728 if (pcb
== NULL
|| pcb
->inp_socket
== NULL
)
1730 #if __FreeBSD_version < 500034
1731 #define socheckuid(a,b) (kauth_cred_getuid((a)->so_cred) != (b))
1733 if (cmd
->opcode
== O_UID
) {
1736 (pcb
->inp_socket
->so_uid
== (uid_t
)((ipfw_insn_u32
*)cmd
)->d
[0]);
1738 !socheckuid(pcb
->inp_socket
,
1739 (uid_t
)((ipfw_insn_u32
*)cmd
)->d
[0]);
1745 kauth_cred_ismember_gid(pcb
->inp_socket
->so_cred
,
1746 (gid_t
)((ipfw_insn_u32
*)cmd
)->d
[0], &match
);
1754 match
= iface_match(m
->m_pkthdr
.rcvif
,
1755 (ipfw_insn_if
*)cmd
);
1759 match
= iface_match(oif
, (ipfw_insn_if
*)cmd
);
1763 match
= iface_match(oif
? oif
:
1764 m
->m_pkthdr
.rcvif
, (ipfw_insn_if
*)cmd
);
1768 if (args
->eh
!= NULL
) { /* have MAC header */
1769 u_int32_t
*want
= (u_int32_t
*)
1770 ((ipfw_insn_mac
*)cmd
)->addr
;
1771 u_int32_t
*mask
= (u_int32_t
*)
1772 ((ipfw_insn_mac
*)cmd
)->mask
;
1773 u_int32_t
*hdr
= (u_int32_t
*)args
->eh
;
1776 ( want
[0] == (hdr
[0] & mask
[0]) &&
1777 want
[1] == (hdr
[1] & mask
[1]) &&
1778 want
[2] == (hdr
[2] & mask
[2]) );
1783 if (args
->eh
!= NULL
) {
1785 ntohs(args
->eh
->ether_type
);
1787 ((ipfw_insn_u16
*)cmd
)->ports
;
1790 for (i
= cmdlen
- 1; !match
&& i
>0;
1792 match
= (t
>=p
[0] && t
<=p
[1]);
1797 match
= (hlen
> 0 && offset
!= 0);
1800 case O_IN
: /* "out" is "not in" */
1801 match
= (oif
== NULL
);
1805 match
= (args
->eh
!= NULL
);
1810 * We do not allow an arg of 0 so the
1811 * check of "proto" only suffices.
1813 match
= (proto
== cmd
->arg1
);
1817 match
= (hlen
> 0 &&
1818 ((ipfw_insn_ip
*)cmd
)->addr
.s_addr
==
1826 (cmd
->opcode
== O_IP_DST_MASK
) ?
1827 dst_ip
.s_addr
: src_ip
.s_addr
;
1828 uint32_t *p
= ((ipfw_insn_u32
*)cmd
)->d
;
1831 for (; !match
&& i
>0; i
-= 2, p
+= 2)
1832 match
= (p
[0] == (a
& p
[1]));
1840 INADDR_TO_IFP(src_ip
, tif
);
1841 match
= (tif
!= NULL
);
1848 u_int32_t
*d
= (u_int32_t
*)(cmd
+1);
1850 cmd
->opcode
== O_IP_DST_SET
?
1856 addr
-= d
[0]; /* subtract base */
1857 match
= (addr
< cmd
->arg1
) &&
1858 ( d
[ 1 + (addr
>>5)] &
1859 (1<<(addr
& 0x1f)) );
1864 match
= (hlen
> 0 &&
1865 ((ipfw_insn_ip
*)cmd
)->addr
.s_addr
==
1873 INADDR_TO_IFP(dst_ip
, tif
);
1874 match
= (tif
!= NULL
);
1881 * offset == 0 && proto != 0 is enough
1882 * to guarantee that we have an IPv4
1883 * packet with port info.
1885 if ((proto
==IPPROTO_UDP
|| proto
==IPPROTO_TCP
)
1888 (cmd
->opcode
== O_IP_SRCPORT
) ?
1889 src_port
: dst_port
;
1891 ((ipfw_insn_u16
*)cmd
)->ports
;
1894 for (i
= cmdlen
- 1; !match
&& i
>0;
1896 match
= (x
>=p
[0] && x
<=p
[1]);
1901 match
= (offset
== 0 && proto
==IPPROTO_ICMP
&&
1902 icmptype_match(ip
, (ipfw_insn_u32
*)cmd
) );
1906 match
= (hlen
> 0 && ipopts_match(ip
, cmd
) );
1910 match
= (hlen
> 0 && cmd
->arg1
== ip
->ip_v
);
1916 if (hlen
> 0) { /* only for IP packets */
1921 if (cmd
->opcode
== O_IPLEN
)
1923 else if (cmd
->opcode
== O_IPTTL
)
1925 else /* must be IPID */
1926 x
= ntohs(ip
->ip_id
);
1928 match
= (cmd
->arg1
== x
);
1931 /* otherwise we have ranges */
1932 p
= ((ipfw_insn_u16
*)cmd
)->ports
;
1934 for (; !match
&& i
>0; i
--, p
+= 2)
1935 match
= (x
>= p
[0] && x
<= p
[1]);
1939 case O_IPPRECEDENCE
:
1940 match
= (hlen
> 0 &&
1941 (cmd
->arg1
== (ip
->ip_tos
& 0xe0)) );
1945 match
= (hlen
> 0 &&
1946 flags_match(cmd
, ip
->ip_tos
));
1950 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
1952 L3HDR(struct tcphdr
,ip
)->th_flags
));
1956 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
1957 tcpopts_match(ip
, cmd
));
1961 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
1962 ((ipfw_insn_u32
*)cmd
)->d
[0] ==
1963 L3HDR(struct tcphdr
,ip
)->th_seq
);
1967 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
1968 ((ipfw_insn_u32
*)cmd
)->d
[0] ==
1969 L3HDR(struct tcphdr
,ip
)->th_ack
);
1973 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
1975 L3HDR(struct tcphdr
,ip
)->th_win
);
1979 /* reject packets which have SYN only */
1980 /* XXX should i also check for TH_ACK ? */
1981 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
1982 (L3HDR(struct tcphdr
,ip
)->th_flags
&
1983 (TH_RST
| TH_ACK
| TH_SYN
)) != TH_SYN
);
1988 ipfw_log(f
, hlen
, args
->eh
, m
, oif
);
1993 match
= (random()<((ipfw_insn_u32
*)cmd
)->d
[0]);
1997 /* Outgoing packets automatically pass/match */
1998 match
= ((oif
!= NULL
) ||
1999 (m
->m_pkthdr
.rcvif
== NULL
) ||
2000 verify_rev_path(src_ip
, m
->m_pkthdr
.rcvif
));
2005 match
= (m_tag_find(m
,
2006 PACKET_TAG_IPSEC_IN_DONE
, NULL
) != NULL
);
2009 match
= (ipsec_gethist(m
, NULL
) != NULL
);
2011 /* otherwise no match */
2015 * The second set of opcodes represents 'actions',
2016 * i.e. the terminal part of a rule once the packet
2017 * matches all previous patterns.
2018 * Typically there is only one action for each rule,
2019 * and the opcode is stored at the end of the rule
2020 * (but there are exceptions -- see below).
2022 * In general, here we set retval and terminate the
2023 * outer loop (would be a 'break 3' in some language,
2024 * but we need to do a 'goto done').
2027 * O_COUNT and O_SKIPTO actions:
2028 * instead of terminating, we jump to the next rule
2029 * ('goto next_rule', equivalent to a 'break 2'),
2030 * or to the SKIPTO target ('goto again' after
2031 * having set f, cmd and l), respectively.
2033 * O_LIMIT and O_KEEP_STATE: these opcodes are
2034 * not real 'actions', and are stored right
2035 * before the 'action' part of the rule.
2036 * These opcodes try to install an entry in the
2037 * state tables; if successful, we continue with
2038 * the next opcode (match=1; break;), otherwise
2039 * the packet * must be dropped
2040 * ('goto done' after setting retval);
2042 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2043 * cause a lookup of the state table, and a jump
2044 * to the 'action' part of the parent rule
2045 * ('goto check_body') if an entry is found, or
2046 * (CHECK_STATE only) a jump to the next rule if
2047 * the entry is not found ('goto next_rule').
2048 * The result of the lookup is cached to make
2049 * further instances of these opcodes are
2054 if (install_state(f
,
2055 (ipfw_insn_limit
*)cmd
, args
)) {
2056 retval
= IP_FW_PORT_DENY_FLAG
;
2057 goto done
; /* error/limit violation */
2065 * dynamic rules are checked at the first
2066 * keep-state or check-state occurrence,
2067 * with the result being stored in dyn_dir.
2068 * The compiler introduces a PROBE_STATE
2069 * instruction for us when we have a
2070 * KEEP_STATE (because PROBE_STATE needs
2073 if (dyn_dir
== MATCH_UNKNOWN
&&
2074 (q
= lookup_dyn_rule(&args
->f_id
,
2075 &dyn_dir
, proto
== IPPROTO_TCP
?
2076 L3HDR(struct tcphdr
, ip
) : NULL
))
2079 * Found dynamic entry, update stats
2080 * and jump to the 'action' part of
2086 cmd
= ACTION_PTR(f
);
2087 l
= f
->cmd_len
- f
->act_ofs
;
2091 * Dynamic entry not found. If CHECK_STATE,
2092 * skip to next rule, if PROBE_STATE just
2093 * ignore and continue with next opcode.
2095 if (cmd
->opcode
== O_CHECK_STATE
)
2101 retval
= 0; /* accept */
2106 args
->rule
= f
; /* report matching rule */
2107 retval
= cmd
->arg1
| IP_FW_PORT_DYNT_FLAG
;
2112 if (args
->eh
) /* not on layer 2 */
2114 args
->divert_rule
= f
->rulenum
;
2115 retval
= (cmd
->opcode
== O_DIVERT
) ?
2117 cmd
->arg1
| IP_FW_PORT_TEE_FLAG
;
2122 f
->pcnt
++; /* update stats */
2124 f
->timestamp
= timenow
.tv_sec
;
2125 if (cmd
->opcode
== O_COUNT
)
2128 if (f
->next_rule
== NULL
)
2129 lookup_next_rule(f
);
2135 * Drop the packet and send a reject notice
2136 * if the packet is not ICMP (or is an ICMP
2137 * query), and it is not multicast/broadcast.
2139 if (hlen
> 0 && offset
== 0 &&
2140 (proto
!= IPPROTO_ICMP
||
2141 is_icmp_query(ip
)) &&
2142 !(m
->m_flags
& (M_BCAST
|M_MCAST
)) &&
2143 !IN_MULTICAST(dst_ip
.s_addr
)) {
2144 send_reject(args
, cmd
->arg1
,
2150 retval
= IP_FW_PORT_DENY_FLAG
;
2154 if (args
->eh
) /* not valid on layer2 pkts */
2156 if (!q
|| dyn_dir
== MATCH_FORWARD
)
2158 &((ipfw_insn_sa
*)cmd
)->sa
;
2163 panic("-- unknown opcode %d\n", cmd
->opcode
);
2164 } /* end of switch() on opcodes */
2166 if (cmd
->len
& F_NOT
)
2170 if (cmd
->len
& F_OR
)
2173 if (!(cmd
->len
& F_OR
)) /* not an OR block, */
2174 break; /* try next rule */
2177 } /* end of inner for, scan opcodes */
2179 next_rule
:; /* try next rule */
2181 } /* end of outer for, scan rules */
2182 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
2183 lck_mtx_unlock(ipfw_mutex
);
2184 return(IP_FW_PORT_DENY_FLAG
);
2187 /* Update statistics */
2190 f
->timestamp
= timenow
.tv_sec
;
2191 lck_mtx_unlock(ipfw_mutex
);
2196 printf("ipfw: pullup failed\n");
2197 lck_mtx_unlock(ipfw_mutex
);
2198 return(IP_FW_PORT_DENY_FLAG
);
2202 * When a rule is added/deleted, clear the next_rule pointers in all rules.
2203 * These will be reconstructed on the fly as packets are matched.
2204 * Must be called at splimp().
2207 flush_rule_ptrs(void)
2211 for (rule
= layer3_chain
; rule
; rule
= rule
->next
)
2212 rule
->next_rule
= NULL
;
2216 * When pipes/queues are deleted, clear the "pipe_ptr" pointer to a given
2217 * pipe/queue, or to all of them (match == NULL).
2218 * Must be called at splimp().
2221 flush_pipe_ptrs(struct dn_flow_set
*match
)
2225 for (rule
= layer3_chain
; rule
; rule
= rule
->next
) {
2226 ipfw_insn_pipe
*cmd
= (ipfw_insn_pipe
*)ACTION_PTR(rule
);
2228 if (cmd
->o
.opcode
!= O_PIPE
&& cmd
->o
.opcode
!= O_QUEUE
)
2231 * XXX Use bcmp/bzero to handle pipe_ptr to overcome
2232 * possible alignment problems on 64-bit architectures.
2233 * This code is seldom used so we do not worry too
2234 * much about efficiency.
2236 if (match
== NULL
||
2237 !bcmp(&cmd
->pipe_ptr
, &match
, sizeof(match
)) )
2238 bzero(&cmd
->pipe_ptr
, sizeof(cmd
->pipe_ptr
));
2243 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
2244 * possibly create a rule number and add the rule to the list.
2245 * Update the rule_number in the input struct so the caller knows it as well.
2248 add_rule(struct ip_fw
**head
, struct ip_fw
*input_rule
)
2250 struct ip_fw
*rule
, *f
, *prev
;
2251 int l
= RULESIZE(input_rule
);
2253 if (*head
== NULL
&& input_rule
->rulenum
!= IPFW_DEFAULT_RULE
)
2256 rule
= _MALLOC(l
, M_IPFW
, M_WAIT
);
2258 printf("ipfw2: add_rule MALLOC failed\n");
2263 bcopy(input_rule
, rule
, l
);
2266 rule
->next_rule
= NULL
;
2270 rule
->timestamp
= 0;
2272 if (*head
== NULL
) { /* default rule */
2278 * If rulenum is 0, find highest numbered rule before the
2279 * default rule, and add autoinc_step
2281 if (autoinc_step
< 1)
2283 else if (autoinc_step
> 1000)
2284 autoinc_step
= 1000;
2285 if (rule
->rulenum
== 0) {
2287 * locate the highest numbered rule before default
2289 for (f
= *head
; f
; f
= f
->next
) {
2290 if (f
->rulenum
== IPFW_DEFAULT_RULE
)
2292 rule
->rulenum
= f
->rulenum
;
2294 if (rule
->rulenum
< IPFW_DEFAULT_RULE
- autoinc_step
)
2295 rule
->rulenum
+= autoinc_step
;
2296 input_rule
->rulenum
= rule
->rulenum
;
2300 * Now insert the new rule in the right place in the sorted list.
2302 for (prev
= NULL
, f
= *head
; f
; prev
= f
, f
= f
->next
) {
2303 if (f
->rulenum
> rule
->rulenum
) { /* found the location */
2307 } else { /* head insert */
2318 DEB(printf("ipfw: installed rule %d, static count now %d\n",
2319 rule
->rulenum
, static_count
);)
2324 * Free storage associated with a static rule (including derived
2326 * The caller is in charge of clearing rule pointers to avoid
2327 * dangling pointers.
2328 * @return a pointer to the next entry.
2329 * Arguments are not checked, so they better be correct.
2330 * Must be called at splimp().
2332 static struct ip_fw
*
2333 delete_rule(struct ip_fw
**head
, struct ip_fw
*prev
, struct ip_fw
*rule
)
2336 int l
= RULESIZE(rule
);
2339 remove_dyn_rule(rule
, NULL
/* force removal */);
2348 if (DUMMYNET_LOADED
)
2349 ip_dn_ruledel_ptr(rule
);
2350 #endif /* DUMMYNET */
2351 _FREE(rule
, M_IPFW
);
2355 #if DEBUG_INACTIVE_RULES
2357 print_chain(struct ip_fw
**chain
)
2359 struct ip_fw
*rule
= *chain
;
2361 for (; rule
; rule
= rule
->next
) {
2362 ipfw_insn
*cmd
= ACTION_PTR(rule
);
2364 printf("ipfw: rule->rulenum = %d\n", rule
->rulenum
);
2366 if (rule
->reserved_1
== IPFW_RULE_INACTIVE
) {
2367 printf("ipfw: rule->reserved = IPFW_RULE_INACTIVE\n");
2370 switch (cmd
->opcode
) {
2372 printf("ipfw: ACTION: Deny\n");
2376 if (cmd
->arg1
==ICMP_REJECT_RST
)
2377 printf("ipfw: ACTION: Reset\n");
2378 else if (cmd
->arg1
==ICMP_UNREACH_HOST
)
2379 printf("ipfw: ACTION: Reject\n");
2383 printf("ipfw: ACTION: Accept\n");
2386 printf("ipfw: ACTION: Count\n");
2389 printf("ipfw: ACTION: Divert\n");
2392 printf("ipfw: ACTION: Tee\n");
2395 printf("ipfw: ACTION: SkipTo\n");
2398 printf("ipfw: ACTION: Pipe\n");
2401 printf("ipfw: ACTION: Queue\n");
2404 printf("ipfw: ACTION: Forward\n");
2407 printf("ipfw: invalid action! %d\n", cmd
->opcode
);
2411 #endif /* DEBUG_INACTIVE_RULES */
2414 flush_inactive(void *param
)
2416 struct ip_fw
*inactive_rule
= (struct ip_fw
*)param
;
2417 struct ip_fw
*rule
, *prev
;
2419 lck_mtx_lock(ipfw_mutex
);
2421 for (rule
= layer3_chain
, prev
= NULL
; rule
; ) {
2422 if (rule
== inactive_rule
&& rule
->reserved_1
== IPFW_RULE_INACTIVE
) {
2423 struct ip_fw
*n
= rule
;
2426 layer3_chain
= rule
->next
;
2429 prev
->next
= rule
->next
;
2440 #if DEBUG_INACTIVE_RULES
2441 print_chain(&layer3_chain
);
2443 lck_mtx_unlock(ipfw_mutex
);
2447 mark_inactive(struct ip_fw
**prev
, struct ip_fw
**rule
)
2449 int l
= RULESIZE(*rule
);
2451 if ((*rule
)->reserved_1
!= IPFW_RULE_INACTIVE
) {
2452 (*rule
)->reserved_1
= IPFW_RULE_INACTIVE
;
2456 timeout(flush_inactive
, *rule
, 30*hz
); /* 30 sec. */
2460 *rule
= (*rule
)->next
;
2464 * Deletes all rules from a chain (except rules in set RESVD_SET
2465 * unless kill_default = 1).
2466 * Must be called at splimp().
2469 free_chain(struct ip_fw
**chain
, int kill_default
)
2471 struct ip_fw
*prev
, *rule
;
2473 flush_rule_ptrs(); /* more efficient to do outside the loop */
2474 for (prev
= NULL
, rule
= *chain
; rule
; )
2475 if (kill_default
|| rule
->set
!= RESVD_SET
) {
2476 ipfw_insn
*cmd
= ACTION_PTR(rule
);
2478 /* skip over forwarding rules so struct isn't
2479 * deleted while pointer is still in use elsewhere
2481 if (cmd
->opcode
== O_FORWARD_IP
) {
2482 mark_inactive(&prev
, &rule
);
2485 rule
= delete_rule(chain
, prev
, rule
);
2495 * Remove all rules with given number, and also do set manipulation.
2496 * Assumes chain != NULL && *chain != NULL.
2498 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
2499 * the next 8 bits are the new set, the top 8 bits are the command:
2501 * 0 delete rules with given number
2502 * 1 delete rules with given set number
2503 * 2 move rules with given number to new set
2504 * 3 move rules with given set number to new set
2505 * 4 swap sets with given numbers
2508 del_entry(struct ip_fw
**chain
, u_int32_t arg
)
2510 struct ip_fw
*prev
= NULL
, *rule
= *chain
;
2511 u_int16_t rulenum
; /* rule or old_set */
2512 u_int8_t cmd
, new_set
;
2514 rulenum
= arg
& 0xffff;
2515 cmd
= (arg
>> 24) & 0xff;
2516 new_set
= (arg
>> 16) & 0xff;
2520 if (new_set
> RESVD_SET
)
2522 if (cmd
== 0 || cmd
== 2) {
2523 if (rulenum
>= IPFW_DEFAULT_RULE
)
2526 if (rulenum
> RESVD_SET
) /* old_set */
2531 case 0: /* delete rules with given number */
2533 * locate first rule to delete
2535 for (; rule
->rulenum
< rulenum
; prev
= rule
, rule
= rule
->next
)
2537 if (rule
->rulenum
!= rulenum
)
2541 * flush pointers outside the loop, then delete all matching
2542 * rules. prev remains the same throughout the cycle.
2545 while (rule
->rulenum
== rulenum
) {
2546 ipfw_insn
*insn
= ACTION_PTR(rule
);
2548 /* keep forwarding rules around so struct isn't
2549 * deleted while pointer is still in use elsewhere
2551 if (insn
->opcode
== O_FORWARD_IP
) {
2552 mark_inactive(&prev
, &rule
);
2555 rule
= delete_rule(chain
, prev
, rule
);
2560 case 1: /* delete all rules with given set number */
2562 while (rule
->rulenum
< IPFW_DEFAULT_RULE
) {
2563 if (rule
->set
== rulenum
) {
2564 ipfw_insn
*insn
= ACTION_PTR(rule
);
2566 /* keep forwarding rules around so struct isn't
2567 * deleted while pointer is still in use elsewhere
2569 if (insn
->opcode
== O_FORWARD_IP
) {
2570 mark_inactive(&prev
, &rule
);
2573 rule
= delete_rule(chain
, prev
, rule
);
2583 case 2: /* move rules with given number to new set */
2584 for (; rule
->rulenum
< IPFW_DEFAULT_RULE
; rule
= rule
->next
)
2585 if (rule
->rulenum
== rulenum
)
2586 rule
->set
= new_set
;
2589 case 3: /* move rules with given set number to new set */
2590 for (; rule
->rulenum
< IPFW_DEFAULT_RULE
; rule
= rule
->next
)
2591 if (rule
->set
== rulenum
)
2592 rule
->set
= new_set
;
2595 case 4: /* swap two sets */
2596 for (; rule
->rulenum
< IPFW_DEFAULT_RULE
; rule
= rule
->next
)
2597 if (rule
->set
== rulenum
)
2598 rule
->set
= new_set
;
2599 else if (rule
->set
== new_set
)
2600 rule
->set
= rulenum
;
2607 * Clear counters for a specific rule.
2610 clear_counters(struct ip_fw
*rule
, int log_only
)
2612 ipfw_insn_log
*l
= (ipfw_insn_log
*)ACTION_PTR(rule
);
2614 if (log_only
== 0) {
2615 rule
->bcnt
= rule
->pcnt
= 0;
2616 rule
->timestamp
= 0;
2618 if (l
->o
.opcode
== O_LOG
)
2619 l
->log_left
= l
->max_log
;
2623 * Reset some or all counters on firewall rules.
2624 * @arg frwl is null to clear all entries, or contains a specific
2626 * @arg log_only is 1 if we only want to reset logs, zero otherwise.
2629 zero_entry(int rulenum
, int log_only
)
2636 for (rule
= layer3_chain
; rule
; rule
= rule
->next
)
2637 clear_counters(rule
, log_only
);
2638 msg
= log_only
? "ipfw: All logging counts reset.\n" :
2639 "ipfw: Accounting cleared.\n";
2643 * We can have multiple rules with the same number, so we
2644 * need to clear them all.
2646 for (rule
= layer3_chain
; rule
; rule
= rule
->next
)
2647 if (rule
->rulenum
== rulenum
) {
2648 while (rule
&& rule
->rulenum
== rulenum
) {
2649 clear_counters(rule
, log_only
);
2655 if (!cleared
) /* we did not find any matching rules */
2657 msg
= log_only
? "ipfw: Entry %d logging count reset.\n" :
2658 "ipfw: Entry %d cleared.\n";
2662 dolog((LOG_AUTHPRIV
| LOG_NOTICE
, msg
, rulenum
));
2668 * Check validity of the structure before insert.
2669 * Fortunately rules are simple, so this mostly need to check rule sizes.
2672 check_ipfw_struct(struct ip_fw
*rule
, int size
)
2678 if (size
< sizeof(*rule
)) {
2679 printf("ipfw: rule too short\n");
2682 /* first, check for valid size */
2685 printf("ipfw: size mismatch (have %d want %d)\n", size
, l
);
2689 * Now go for the individual checks. Very simple ones, basically only
2690 * instruction sizes.
2692 for (l
= rule
->cmd_len
, cmd
= rule
->cmd
;
2693 l
> 0 ; l
-= cmdlen
, cmd
+= cmdlen
) {
2694 cmdlen
= F_LEN(cmd
);
2696 printf("ipfw: opcode %d size truncated\n",
2700 DEB(printf("ipfw: opcode %d\n", cmd
->opcode
);)
2701 switch (cmd
->opcode
) {
2712 case O_IPPRECEDENCE
:
2720 if (cmdlen
!= F_INSN_SIZE(ipfw_insn
))
2726 #endif /* __APPLE__ */
2733 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_u32
))
2738 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_limit
))
2743 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_log
))
2746 /* enforce logging limit */
2748 ((ipfw_insn_log
*)cmd
)->max_log
== 0 && verbose_limit
!= 0) {
2749 ((ipfw_insn_log
*)cmd
)->max_log
= verbose_limit
;
2752 ((ipfw_insn_log
*)cmd
)->log_left
=
2753 ((ipfw_insn_log
*)cmd
)->max_log
;
2759 /* only odd command lengths */
2760 if ( !(cmdlen
& 1) || cmdlen
> 31)
2766 if (cmd
->arg1
== 0 || cmd
->arg1
> 256) {
2767 printf("ipfw: invalid set size %d\n",
2771 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_u32
) +
2777 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_mac
))
2785 if (cmdlen
< 1 || cmdlen
> 31)
2791 case O_IP_DSTPORT
: /* XXX artificial limit, 30 port pairs */
2792 if (cmdlen
< 2 || cmdlen
> 31)
2799 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_if
))
2805 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_pipe
))
2810 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_sa
))
2814 case O_FORWARD_MAC
: /* XXX not implemented yet */
2823 if (cmdlen
!= F_INSN_SIZE(ipfw_insn
))
2827 printf("ipfw: opcode %d, multiple actions"
2834 printf("ipfw: opcode %d, action must be"
2841 printf("ipfw: opcode %d, unknown opcode\n",
2846 if (have_action
== 0) {
2847 printf("ipfw: missing action\n");
2853 printf("ipfw: opcode %d size %d wrong\n",
2854 cmd
->opcode
, cmdlen
);
2860 ipfw_kev_post_msg(u_int32_t event_code
)
2862 struct kev_msg ev_msg
;
2864 bzero(&ev_msg
, sizeof(struct kev_msg
));
2866 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
2867 ev_msg
.kev_class
= KEV_FIREWALL_CLASS
;
2868 ev_msg
.kev_subclass
= KEV_IPFW_SUBCLASS
;
2869 ev_msg
.event_code
= event_code
;
2871 kev_post_msg(&ev_msg
);
2876 * {set|get}sockopt parser.
2879 ipfw_ctl(struct sockopt
*sopt
)
2881 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
2882 u_int32_t api_version
;
2886 struct ip_fw
*bp
, *buf
, *rule
;
2888 /* copy of orig sopt to send to ipfw_get_command_and_version() */
2889 struct sockopt tmp_sopt
= *sopt
;
2890 struct timeval timenow
;
2892 getmicrotime(&timenow
);
2895 * Disallow modifications in really-really secure mode, but still allow
2896 * the logging counters to be reset.
2898 if (sopt
->sopt_name
== IP_FW_ADD
||
2899 (sopt
->sopt_dir
== SOPT_SET
&& sopt
->sopt_name
!= IP_FW_RESETLOG
)) {
2900 #if __FreeBSD_version >= 500034
2901 error
= securelevel_ge(sopt
->sopt_td
->td_ucred
, 3);
2904 #else /* FreeBSD 4.x */
2905 if (securelevel
>= 3)
2910 /* first get the command and version, then do conversion as necessary */
2911 error
= ipfw_get_command_and_version(&tmp_sopt
, &command
, &api_version
);
2914 /* error getting the version */
2921 * pass up a copy of the current rules. Static rules
2922 * come first (the last of which has number IPFW_DEFAULT_RULE),
2923 * followed by a possibly empty list of dynamic rule.
2924 * The last dynamic rule has NULL in the "next" field.
2926 lck_mtx_lock(ipfw_mutex
);
2927 size
= static_len
; /* size of static rules */
2928 if (ipfw_dyn_v
) /* add size of dyn.rules */
2929 size
+= (dyn_count
* sizeof(ipfw_dyn_rule
));
2932 * XXX todo: if the user passes a short length just to know
2933 * how much room is needed, do not bother filling up the
2934 * buffer, just jump to the sooptcopyout.
2936 buf
= _MALLOC(size
, M_TEMP
, M_WAITOK
);
2938 lck_mtx_unlock(ipfw_mutex
);
2946 for (rule
= layer3_chain
; rule
; rule
= rule
->next
) {
2947 int i
= RULESIZE(rule
);
2949 if (rule
->reserved_1
== IPFW_RULE_INACTIVE
) {
2953 bcopy(&set_disable
, &(bp
->next_rule
),
2954 sizeof(set_disable
));
2955 bp
= (struct ip_fw
*)((char *)bp
+ i
);
2959 ipfw_dyn_rule
*p
, *dst
, *last
= NULL
;
2961 dst
= (ipfw_dyn_rule
*)bp
;
2962 for (i
= 0 ; i
< curr_dyn_buckets
; i
++ )
2963 for ( p
= ipfw_dyn_v
[i
] ; p
!= NULL
;
2964 p
= p
->next
, dst
++ ) {
2965 bcopy(p
, dst
, sizeof *p
);
2966 bcopy(&(p
->rule
->rulenum
), &(dst
->rule
),
2967 sizeof(p
->rule
->rulenum
));
2969 * store a non-null value in "next".
2970 * The userland code will interpret a
2971 * NULL here as a marker
2972 * for the last dynamic rule.
2974 bcopy(&dst
, &dst
->next
, sizeof(dst
));
2977 TIME_LEQ(dst
->expire
, timenow
.tv_sec
) ?
2978 0 : dst
->expire
- timenow
.tv_sec
;
2980 if (last
!= NULL
) /* mark last dynamic rule */
2981 bzero(&last
->next
, sizeof(last
));
2983 lck_mtx_unlock(ipfw_mutex
);
2985 /* convert back if necessary and copyout */
2986 if (api_version
== IP_FW_VERSION_0
) {
2988 struct ip_old_fw
*buf2
, *rule_vers0
;
2990 lck_mtx_lock(ipfw_mutex
);
2991 buf2
= _MALLOC(static_count
* sizeof(struct ip_old_fw
), M_TEMP
, M_WAITOK
);
2993 lck_mtx_unlock(ipfw_mutex
);
3001 for (i
= 0; i
< static_count
; i
++) {
3002 /* static rules have different sizes */
3003 int j
= RULESIZE(bp
);
3004 ipfw_convert_from_latest(bp
, rule_vers0
, api_version
);
3005 bp
= (struct ip_fw
*)((char *)bp
+ j
);
3006 len
+= sizeof(*rule_vers0
);
3009 lck_mtx_unlock(ipfw_mutex
);
3010 error
= sooptcopyout(sopt
, buf2
, len
);
3011 _FREE(buf2
, M_TEMP
);
3013 } else if (api_version
== IP_FW_VERSION_1
) {
3014 int i
, len
= 0, buf_size
;
3015 struct ip_fw_compat
*buf2
, *rule_vers1
;
3016 struct ipfw_dyn_rule_compat
*dyn_rule_vers1
, *dyn_last
= NULL
;
3019 lck_mtx_lock(ipfw_mutex
);
3020 buf_size
= static_count
* sizeof(struct ip_fw_compat
) +
3021 dyn_count
* sizeof(struct ipfw_dyn_rule_compat
);
3023 buf2
= _MALLOC(buf_size
, M_TEMP
, M_WAITOK
);
3025 lck_mtx_unlock(ipfw_mutex
);
3033 /* first do static rules */
3034 for (i
= 0; i
< static_count
; i
++) {
3035 /* static rules have different sizes */
3036 int j
= RULESIZE(bp
);
3037 ipfw_convert_from_latest(bp
, rule_vers1
, api_version
);
3038 bp
= (struct ip_fw
*)((char *)bp
+ j
);
3039 len
+= sizeof(*rule_vers1
);
3043 /* now do dynamic rules */
3044 dyn_rule_vers1
= (struct ipfw_dyn_rule_compat
*)rule_vers1
;
3046 for (i
= 0; i
< curr_dyn_buckets
; i
++) {
3047 for ( p
= ipfw_dyn_v
[i
] ; p
!= NULL
; p
= p
->next
) {
3048 dyn_rule_vers1
->chain
= p
->rule
->rulenum
;
3049 dyn_rule_vers1
->id
= p
->id
;
3050 dyn_rule_vers1
->mask
= p
->id
;
3051 dyn_rule_vers1
->type
= p
->dyn_type
;
3052 dyn_rule_vers1
->expire
= p
->expire
;
3053 dyn_rule_vers1
->pcnt
= p
->pcnt
;
3054 dyn_rule_vers1
->bcnt
= p
->bcnt
;
3055 dyn_rule_vers1
->bucket
= p
->bucket
;
3056 dyn_rule_vers1
->state
= p
->state
;
3058 dyn_rule_vers1
->next
= (struct ipfw_dyn_rule
*) dyn_rule_vers1
;
3059 dyn_last
= dyn_rule_vers1
;
3061 len
+= sizeof(*dyn_rule_vers1
);
3066 if (dyn_last
!= NULL
) {
3067 dyn_last
->next
= NULL
;
3070 lck_mtx_unlock(ipfw_mutex
);
3072 error
= sooptcopyout(sopt
, buf2
, len
);
3073 _FREE(buf2
, M_TEMP
);
3076 error
= sooptcopyout(sopt
, buf
, size
);
3084 * Normally we cannot release the lock on each iteration.
3085 * We could do it here only because we start from the head all
3086 * the times so there is no risk of missing some entries.
3087 * On the other hand, the risk is that we end up with
3088 * a very inconsistent ruleset, so better keep the lock
3089 * around the whole cycle.
3091 * XXX this code can be improved by resetting the head of
3092 * the list to point to the default rule, and then freeing
3093 * the old list without the need for a lock.
3096 lck_mtx_lock(ipfw_mutex
);
3097 free_chain(&layer3_chain
, 0 /* keep default rule */);
3099 #if DEBUG_INACTIVE_RULES
3100 print_chain(&layer3_chain
);
3102 lck_mtx_unlock(ipfw_mutex
);
3106 rule
= _MALLOC(RULE_MAXSIZE
, M_TEMP
, M_WAITOK
);
3112 bzero(rule
, RULE_MAXSIZE
);
3114 if (api_version
!= IP_FW_CURRENT_API_VERSION
) {
3115 error
= ipfw_convert_to_latest(sopt
, rule
, api_version
);
3118 error
= sooptcopyin(sopt
, rule
, RULE_MAXSIZE
,
3119 sizeof(struct ip_fw
) );
3123 if ((api_version
== IP_FW_VERSION_0
) || (api_version
== IP_FW_VERSION_1
)) {
3124 /* the rule has already been checked so just
3125 * adjust sopt_valsize to match what would be expected.
3127 sopt
->sopt_valsize
= RULESIZE(rule
);
3129 error
= check_ipfw_struct(rule
, sopt
->sopt_valsize
);
3131 lck_mtx_lock(ipfw_mutex
);
3132 error
= add_rule(&layer3_chain
, rule
);
3133 if (!error
&& fw_bypass
)
3135 lck_mtx_unlock(ipfw_mutex
);
3137 size
= RULESIZE(rule
);
3138 if (!error
&& sopt
->sopt_dir
== SOPT_GET
) {
3139 /* convert back if necessary and copyout */
3140 if (api_version
== IP_FW_VERSION_0
) {
3141 struct ip_old_fw rule_vers0
;
3143 ipfw_convert_from_latest(rule
, &rule_vers0
, api_version
);
3144 sopt
->sopt_valsize
= sizeof(struct ip_old_fw
);
3146 error
= sooptcopyout(sopt
, &rule_vers0
, sizeof(struct ip_old_fw
));
3147 } else if (api_version
== IP_FW_VERSION_1
) {
3148 struct ip_fw_compat rule_vers1
;
3150 ipfw_convert_from_latest(rule
, &rule_vers1
, api_version
);
3151 sopt
->sopt_valsize
= sizeof(struct ip_fw_compat
);
3153 error
= sooptcopyout(sopt
, &rule_vers1
, sizeof(struct ip_fw_compat
));
3155 error
= sooptcopyout(sopt
, rule
, size
);
3161 _FREE(rule
, M_TEMP
);
3167 * IP_FW_DEL is used for deleting single rules or sets,
3168 * and (ab)used to atomically manipulate sets.
3169 * rule->rulenum != 0 indicates single rule delete
3170 * rule->set_masks used to manipulate sets
3171 * rule->set_masks[0] contains info on sets to be
3172 * disabled, swapped, or moved
3173 * rule->set_masks[1] contains sets to be enabled.
3176 /* there is only a simple rule passed in
3177 * (no cmds), so use a temp struct to copy
3179 struct ip_fw temp_rule
;
3183 bzero(&temp_rule
, sizeof(struct ip_fw
));
3184 if (api_version
!= IP_FW_CURRENT_API_VERSION
) {
3185 error
= ipfw_convert_to_latest(sopt
, &temp_rule
, api_version
);
3188 error
= sooptcopyin(sopt
, &temp_rule
, sizeof(struct ip_fw
),
3189 sizeof(struct ip_fw
) );
3193 /* set_masks is used to distinguish between deleting
3194 * single rules or atomically manipulating sets
3196 lck_mtx_lock(ipfw_mutex
);
3198 arg
= temp_rule
.set_masks
[0];
3199 cmd
= (arg
>> 24) & 0xff;
3201 if (temp_rule
.rulenum
) {
3203 error
= del_entry(&layer3_chain
, temp_rule
.rulenum
);
3204 #if DEBUG_INACTIVE_RULES
3205 print_chain(&layer3_chain
);
3209 /* set reassignment - see comment above del_entry() for details */
3210 error
= del_entry(&layer3_chain
, temp_rule
.set_masks
[0]);
3211 #if DEBUG_INACTIVE_RULES
3212 print_chain(&layer3_chain
);
3215 else if (temp_rule
.set_masks
[0] != 0 ||
3216 temp_rule
.set_masks
[1] != 0) {
3217 /* set enable/disable */
3219 (set_disable
| temp_rule
.set_masks
[0]) & ~temp_rule
.set_masks
[1] &
3220 ~(1<<RESVD_SET
); /* set RESVD_SET always enabled */
3223 if (!layer3_chain
->next
)
3225 lck_mtx_unlock(ipfw_mutex
);
3230 case IP_FW_RESETLOG
: /* using rule->rulenum */
3232 /* there is only a simple rule passed in
3233 * (no cmds), so use a temp struct to copy
3235 struct ip_fw temp_rule
;
3237 bzero(&temp_rule
, sizeof(struct ip_fw
));
3239 if (api_version
!= IP_FW_CURRENT_API_VERSION
) {
3240 error
= ipfw_convert_to_latest(sopt
, &temp_rule
, api_version
);
3243 if (sopt
->sopt_val
!= 0) {
3244 error
= sooptcopyin(sopt
, &temp_rule
, sizeof(struct ip_fw
),
3245 sizeof(struct ip_fw
) );
3250 lck_mtx_lock(ipfw_mutex
);
3251 error
= zero_entry(temp_rule
.rulenum
, sopt
->sopt_name
== IP_FW_RESETLOG
);
3252 lck_mtx_unlock(ipfw_mutex
);
3257 printf("ipfw: ipfw_ctl invalid option %d\n", sopt
->sopt_name
);
3261 if (error
!= EINVAL
) {
3265 ipfw_kev_post_msg(KEV_IPFW_ADD
);
3269 ipfw_kev_post_msg(KEV_IPFW_DEL
);
3272 case IP_OLD_FW_FLUSH
:
3273 ipfw_kev_post_msg(KEV_IPFW_FLUSH
);
3285 * dummynet needs a reference to the default rule, because rules can be
3286 * deleted while packets hold a reference to them. When this happens,
3287 * dummynet changes the reference to the default rule (it could well be a
3288 * NULL pointer, but this way we do not need to check for the special
3289 * case, plus here he have info on the default behaviour).
3291 struct ip_fw
*ip_fw_default_rule
;
3294 * This procedure is only used to handle keepalives. It is invoked
3295 * every dyn_keepalive_period
3298 ipfw_tick(__unused
void * unused
)
3302 struct timeval timenow
;
3305 if (dyn_keepalive
== 0 || ipfw_dyn_v
== NULL
|| dyn_count
== 0)
3308 getmicrotime(&timenow
);
3310 lck_mtx_lock(ipfw_mutex
);
3311 for (i
= 0 ; i
< curr_dyn_buckets
; i
++) {
3312 for (q
= ipfw_dyn_v
[i
] ; q
; q
= q
->next
) {
3313 if (q
->dyn_type
== O_LIMIT_PARENT
)
3315 if (q
->id
.proto
!= IPPROTO_TCP
)
3317 if ( (q
->state
& BOTH_SYN
) != BOTH_SYN
)
3319 if (TIME_LEQ( timenow
.tv_sec
+dyn_keepalive_interval
,
3321 continue; /* too early */
3322 if (TIME_LEQ(q
->expire
, timenow
.tv_sec
))
3323 continue; /* too late, rule expired */
3325 send_pkt(&(q
->id
), q
->ack_rev
- 1, q
->ack_fwd
, TH_SYN
);
3326 send_pkt(&(q
->id
), q
->ack_fwd
- 1, q
->ack_rev
, 0);
3329 lck_mtx_unlock(ipfw_mutex
);
3331 timeout(ipfw_tick
, NULL
, dyn_keepalive_period
*hz
);
3337 struct ip_fw default_rule
;
3340 ipfw_mutex_grp_attr
= lck_grp_attr_alloc_init();
3341 ipfw_mutex_grp
= lck_grp_alloc_init("ipfw", ipfw_mutex_grp_attr
);
3342 ipfw_mutex_attr
= lck_attr_alloc_init();
3344 if ((ipfw_mutex
= lck_mtx_alloc_init(ipfw_mutex_grp
, ipfw_mutex_attr
)) == NULL
) {
3345 printf("ipfw_init: can't alloc ipfw_mutex\n");
3349 layer3_chain
= NULL
;
3351 bzero(&default_rule
, sizeof default_rule
);
3353 default_rule
.act_ofs
= 0;
3354 default_rule
.rulenum
= IPFW_DEFAULT_RULE
;
3355 default_rule
.cmd_len
= 1;
3356 default_rule
.set
= RESVD_SET
;
3358 default_rule
.cmd
[0].len
= 1;
3359 default_rule
.cmd
[0].opcode
=
3360 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
3365 if (add_rule(&layer3_chain
, &default_rule
)) {
3366 printf("ipfw2: add_rule failed adding default rule\n");
3367 printf("ipfw2 failed initialization!!\n");
3371 ip_fw_default_rule
= layer3_chain
;
3373 #ifdef IPFIREWALL_VERBOSE
3376 #ifdef IPFIREWALL_VERBOSE_LIMIT
3377 verbose_limit
= IPFIREWALL_VERBOSE_LIMIT
;
3381 printf("ipfw2 verbose logging enabled: unlimited logging by default\n");
3383 printf("ipfw2 verbose logging enabled: limited to %d packets/entry by default\n",
3388 ip_fw_chk_ptr
= ipfw_chk
;
3389 ip_fw_ctl_ptr
= ipfw_ctl
;
3391 ipfwstringlen
= strlen( ipfwstring
);
3393 timeout(ipfw_tick
, NULL
, hz
);