2 * Copyright (c) 2004-2016 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
30 * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
32 * Redistribution and use in source and binary forms, with or without
33 * modification, are permitted provided that the following conditions
35 * 1. Redistributions of source code must retain the above copyright
36 * notice, this list of conditions and the following disclaimer.
37 * 2. Redistributions in binary form must reproduce the above copyright
38 * notice, this list of conditions and the following disclaimer in the
39 * documentation and/or other materials provided with the distribution.
41 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53 * $FreeBSD: src/sys/netinet/ip_fw2.c,v 1.6.2.18 2003/10/17 11:01:03 scottl Exp $
60 * Implement IP packet firewall (new version)
64 #error IPFIREWALL requires INET.
68 #include <machine/spl.h>
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/malloc.h>
74 #include <sys/mcache.h>
75 #include <sys/kernel.h>
77 #include <sys/socket.h>
78 #include <sys/socketvar.h>
79 #include <sys/sysctl.h>
80 #include <sys/syslog.h>
81 #include <sys/ucred.h>
82 #include <sys/kern_event.h>
83 #include <sys/kauth.h>
86 #include <net/net_kev.h>
87 #include <net/route.h>
88 #include <netinet/in.h>
89 #include <netinet/in_systm.h>
90 #include <netinet/in_var.h>
91 #include <netinet/in_pcb.h>
92 #include <netinet/ip.h>
93 #include <netinet/ip_var.h>
94 #include <netinet/ip_icmp.h>
95 #include <netinet/ip_fw.h>
96 #include <netinet/ip_divert.h>
99 #include <netinet/ip_dummynet.h>
100 #endif /* DUMMYNET */
102 #include <netinet/tcp.h>
103 #include <netinet/tcp_timer.h>
104 #include <netinet/tcp_var.h>
105 #include <netinet/tcpip.h>
106 #include <netinet/udp.h>
107 #include <netinet/udp_var.h>
110 #include <netinet6/ipsec.h>
113 #include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
115 #include "ip_fw2_compat.h"
117 #include <sys/kern_event.h>
121 #include <machine/in_cksum.h>
122 */ /* XXX for in_cksum */
125 * XXX This one should go in sys/mbuf.h. It is used to avoid that
126 * a firewall-generated packet loops forever through the firewall.
128 #ifndef M_SKIP_FIREWALL
129 #define M_SKIP_FIREWALL 0x4000
133 * set_disable contains one bit per set value (0..31).
134 * If the bit is set, all rules with the corresponding set
135 * are disabled. Set RESVD_SET(31) is reserved for the default rule
136 * and rules that are not deleted by the flush command,
137 * and CANNOT be disabled.
138 * Rules in set RESVD_SET can only be deleted explicitly.
140 static u_int32_t set_disable
;
143 static int verbose_limit
;
144 extern int fw_bypass
;
146 #define IPFW_RULE_INACTIVE 1
149 * list of rules for layer 3
151 static struct ip_fw
*layer3_chain
;
153 MALLOC_DEFINE(M_IPFW
, "IpFw/IpAcct", "IpFw/IpAcct chain's");
155 static int fw_debug
= 0;
156 static int autoinc_step
= 100; /* bounded to 1..1000 in add_rule() */
158 static void ipfw_kev_post_msg(u_int32_t
);
160 static int Get32static_len(void);
161 static int Get64static_len(void);
165 static int ipfw_sysctl SYSCTL_HANDLER_ARGS
;
167 SYSCTL_NODE(_net_inet_ip
, OID_AUTO
, fw
, CTLFLAG_RW
|CTLFLAG_LOCKED
, 0, "Firewall");
168 SYSCTL_PROC(_net_inet_ip_fw
, OID_AUTO
, enable
,
169 CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
,
170 &fw_enable
, 0, ipfw_sysctl
, "I", "Enable ipfw");
171 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, autoinc_step
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
172 &autoinc_step
, 0, "Rule number autincrement step");
173 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, one_pass
,
174 CTLFLAG_RW
| CTLFLAG_LOCKED
,
176 "Only do a single pass through ipfw when using dummynet(4)");
177 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, debug
,
178 CTLFLAG_RW
| CTLFLAG_LOCKED
,
179 &fw_debug
, 0, "Enable printing of debug ip_fw statements");
180 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, verbose
,
181 CTLFLAG_RW
| CTLFLAG_LOCKED
,
182 &fw_verbose
, 0, "Log matches to ipfw rules");
183 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, verbose_limit
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
184 &verbose_limit
, 0, "Set upper limit of matches of ipfw rules logged");
187 * IP FW Stealth Logging:
189 typedef enum ipfw_stealth_stats_type
{
190 IPFW_STEALTH_STATS_UDP
,
191 IPFW_STEALTH_STATS_TCP
,
192 IPFW_STEALTH_STATS_UDPv6
,
193 IPFW_STEALTH_STATS_TCPv6
,
194 IPFW_STEALTH_STATS_MAX
,
195 } ipfw_stealth_stats_type_t
;
197 #define IPFW_STEALTH_TIMEOUT_SEC 30
199 #define DYN_KEEPALIVE_LEEWAY 15
201 // Piggybagging Stealth stats with ipfw_tick().
202 #define IPFW_STEALTH_TIMEOUT_FREQUENCY (30 / dyn_keepalive_period)
204 static const char* ipfw_stealth_stats_str
[IPFW_STEALTH_STATS_MAX
] = {
205 "UDP", "TCP", "UDP v6", "TCP v6",
208 static uint32_t ipfw_stealth_stats_needs_flush
= FALSE
;
209 static uint32_t ipfw_stealth_stats
[IPFW_STEALTH_STATS_MAX
];
211 static void ipfw_stealth_flush_stats(void);
212 void ipfw_stealth_stats_incr_udp(void);
213 void ipfw_stealth_stats_incr_tcp(void);
214 void ipfw_stealth_stats_incr_udpv6(void);
215 void ipfw_stealth_stats_incr_tcpv6(void);
218 * Description of dynamic rules.
220 * Dynamic rules are stored in lists accessed through a hash table
221 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
222 * be modified through the sysctl variable dyn_buckets which is
223 * updated when the table becomes empty.
225 * XXX currently there is only one list, ipfw_dyn.
227 * When a packet is received, its address fields are first masked
228 * with the mask defined for the rule, then hashed, then matched
229 * against the entries in the corresponding list.
230 * Dynamic rules can be used for different purposes:
232 * + enforcing limits on the number of sessions;
233 * + in-kernel NAT (not implemented yet)
235 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
236 * measured in seconds and depending on the flags.
238 * The total number of dynamic rules is stored in dyn_count.
239 * The max number of dynamic rules is dyn_max. When we reach
240 * the maximum number of rules we do not create anymore. This is
241 * done to avoid consuming too much memory, but also too much
242 * time when searching on each packet (ideally, we should try instead
243 * to put a limit on the length of the list on each bucket...).
245 * Each dynamic rule holds a pointer to the parent ipfw rule so
246 * we know what action to perform. Dynamic rules are removed when
247 * the parent rule is deleted. XXX we should make them survive.
249 * There are some limitations with dynamic rules -- we do not
250 * obey the 'randomized match', and we do not do multiple
251 * passes through the firewall. XXX check the latter!!!
253 static ipfw_dyn_rule
**ipfw_dyn_v
= NULL
;
254 static u_int32_t dyn_buckets
= 256; /* must be power of 2 */
255 static u_int32_t curr_dyn_buckets
= 256; /* must be power of 2 */
258 * Timeouts for various events in handing dynamic rules.
260 static u_int32_t dyn_ack_lifetime
= 300;
261 static u_int32_t dyn_syn_lifetime
= 20;
262 static u_int32_t dyn_fin_lifetime
= 1;
263 static u_int32_t dyn_rst_lifetime
= 1;
264 static u_int32_t dyn_udp_lifetime
= 10;
265 static u_int32_t dyn_short_lifetime
= 5;
268 * Keepalives are sent if dyn_keepalive is set. They are sent every
269 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
270 * seconds of lifetime of a rule.
271 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
272 * than dyn_keepalive_period.
275 static u_int32_t dyn_keepalive_interval
= 25;
276 static u_int32_t dyn_keepalive_period
= 5;
277 static u_int32_t dyn_keepalive
= 1; /* do send keepalives */
279 static u_int32_t static_count
; /* # of static rules */
280 static u_int32_t static_len
; /* size in bytes of static rules */
281 static u_int32_t static_len_32
; /* size in bytes of static rules for 32 bit client */
282 static u_int32_t static_len_64
; /* size in bytes of static rules for 64 bit client */
283 static u_int32_t dyn_count
; /* # of dynamic rules */
284 static u_int32_t dyn_max
= 4096; /* max # of dynamic rules */
286 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_buckets
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
287 &dyn_buckets
, 0, "Number of dyn. buckets");
288 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, curr_dyn_buckets
, CTLFLAG_RD
| CTLFLAG_LOCKED
,
289 &curr_dyn_buckets
, 0, "Current Number of dyn. buckets");
290 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_count
, CTLFLAG_RD
| CTLFLAG_LOCKED
,
291 &dyn_count
, 0, "Number of dyn. rules");
292 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_max
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
293 &dyn_max
, 0, "Max number of dyn. rules");
294 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, static_count
, CTLFLAG_RD
| CTLFLAG_LOCKED
,
295 &static_count
, 0, "Number of static rules");
296 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_ack_lifetime
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
297 &dyn_ack_lifetime
, 0, "Lifetime of dyn. rules for acks");
298 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_syn_lifetime
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
299 &dyn_syn_lifetime
, 0, "Lifetime of dyn. rules for syn");
300 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_fin_lifetime
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
301 &dyn_fin_lifetime
, 0, "Lifetime of dyn. rules for fin");
302 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_rst_lifetime
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
303 &dyn_rst_lifetime
, 0, "Lifetime of dyn. rules for rst");
304 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_udp_lifetime
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
305 &dyn_udp_lifetime
, 0, "Lifetime of dyn. rules for UDP");
306 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_short_lifetime
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
307 &dyn_short_lifetime
, 0, "Lifetime of dyn. rules for other situations");
308 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_keepalive
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
309 &dyn_keepalive
, 0, "Enable keepalives for dyn. rules");
313 ipfw_sysctl SYSCTL_HANDLER_ARGS
315 #pragma unused(arg1, arg2)
318 error
= sysctl_handle_int(oidp
, oidp
->oid_arg1
, oidp
->oid_arg2
, req
);
319 if (error
|| !req
->newptr
)
322 ipfw_kev_post_msg(KEV_IPFW_ENABLE
);
327 #endif /* SYSCTL_NODE */
330 static ip_fw_chk_t ipfw_chk
;
333 lck_grp_t
*ipfw_mutex_grp
;
334 lck_grp_attr_t
*ipfw_mutex_grp_attr
;
335 lck_attr_t
*ipfw_mutex_attr
;
336 decl_lck_mtx_data(,ipfw_mutex_data
);
337 lck_mtx_t
*ipfw_mutex
= &ipfw_mutex_data
;
339 extern void ipfwsyslog( int level
, const char *format
,...);
341 #define ipfwstring "ipfw:"
342 static size_t ipfwstringlen
;
344 #define dolog( a ) { \
345 if ( fw_verbose == 2 ) /* Apple logging, log to ipfw.log */ \
350 #define RULESIZE64(rule) (sizeof(struct ip_fw_64) + \
351 ((struct ip_fw *)(rule))->cmd_len * 4 - 4)
353 #define RULESIZE32(rule) (sizeof(struct ip_fw_32) + \
354 ((struct ip_fw *)(rule))->cmd_len * 4 - 4)
356 void ipfwsyslog( int level
, const char *format
,...)
360 struct kev_msg ev_msg
;
362 char msgBuf
[msgsize
];
367 bzero(msgBuf
, msgsize
);
368 bzero(&ev_msg
, sizeof(struct kev_msg
));
369 va_start( ap
, format
);
370 loglen
= vsnprintf(msgBuf
, msgsize
, format
, ap
);
373 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
374 ev_msg
.kev_class
= KEV_NETWORK_CLASS
;
375 ev_msg
.kev_subclass
= KEV_LOG_SUBCLASS
;
376 ev_msg
.event_code
= IPFWLOGEVENT
;
378 /* get rid of the trailing \n */
379 if (loglen
< msgsize
)
384 pri
= LOG_PRI(level
);
386 /* remove "ipfw:" prefix if logging to ipfw log */
387 if ( !(strncmp( ipfwstring
, msgBuf
, ipfwstringlen
))){
388 dptr
= msgBuf
+ipfwstringlen
;
391 ev_msg
.dv
[0].data_ptr
= &pri
;
392 ev_msg
.dv
[0].data_length
= 1;
393 ev_msg
.dv
[1].data_ptr
= dptr
;
394 ev_msg
.dv
[1].data_length
= 100; /* bug in kern_post_msg, it can't handle size > 256-msghdr */
395 ev_msg
.dv
[2].data_length
= 0;
397 kev_post_msg(&ev_msg
);
400 static inline void ipfw_stealth_stats_incr(uint32_t type
)
402 if (type
>= IPFW_STEALTH_STATS_MAX
)
405 ipfw_stealth_stats
[type
]++;
407 if (!ipfw_stealth_stats_needs_flush
) {
408 ipfw_stealth_stats_needs_flush
= TRUE
;
412 void ipfw_stealth_stats_incr_udp(void)
414 ipfw_stealth_stats_incr(IPFW_STEALTH_STATS_UDP
);
417 void ipfw_stealth_stats_incr_tcp(void)
419 ipfw_stealth_stats_incr(IPFW_STEALTH_STATS_TCP
);
422 void ipfw_stealth_stats_incr_udpv6(void)
424 ipfw_stealth_stats_incr(IPFW_STEALTH_STATS_UDPv6
);
427 void ipfw_stealth_stats_incr_tcpv6(void)
429 ipfw_stealth_stats_incr(IPFW_STEALTH_STATS_TCPv6
);
432 static void ipfw_stealth_flush_stats(void)
436 for (i
= 0; i
< IPFW_STEALTH_STATS_MAX
; i
++) {
437 if (ipfw_stealth_stats
[i
]) {
438 ipfwsyslog (LOG_INFO
, "Stealth Mode connection attempt to %s %d times",
439 ipfw_stealth_stats_str
[i
], ipfw_stealth_stats
[i
]);
440 ipfw_stealth_stats
[i
] = 0;
443 ipfw_stealth_stats_needs_flush
= FALSE
;
447 * This macro maps an ip pointer into a layer3 header pointer of type T
449 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
452 icmptype_match(struct ip
*ip
, ipfw_insn_u32
*cmd
)
454 int type
= L3HDR(struct icmp
,ip
)->icmp_type
;
456 return (type
<= ICMP_MAXTYPE
&& (cmd
->d
[0] & (1<<type
)) );
459 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
460 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
463 is_icmp_query(struct ip
*ip
)
465 int type
= L3HDR(struct icmp
, ip
)->icmp_type
;
466 return (type
<= ICMP_MAXTYPE
&& (TT
& (1<<type
)) );
471 Get32static_len(void)
474 int len
= static_len_32
;
478 for (rule
= layer3_chain
; rule
; rule
= rule
->next
) {
479 if (rule
->reserved_1
== IPFW_RULE_INACTIVE
) {
482 if ( rule
->act_ofs
){
483 useraction
= (char*)ACTION_PTR( rule
);
484 if ( ((ipfw_insn
*)useraction
)->opcode
== O_QUEUE
|| ((ipfw_insn
*)useraction
)->opcode
== O_PIPE
){
485 diff
= sizeof(ipfw_insn_pipe
) - sizeof(ipfw_insn_pipe_32
);
495 Get64static_len(void)
498 int len
= static_len_64
;
502 for (rule
= layer3_chain
; rule
; rule
= rule
->next
) {
503 if (rule
->reserved_1
== IPFW_RULE_INACTIVE
) {
506 if ( rule
->act_ofs
){
507 useraction
= (char *)ACTION_PTR( rule
);
508 if ( ((ipfw_insn
*)useraction
)->opcode
== O_QUEUE
|| ((ipfw_insn
*)useraction
)->opcode
== O_PIPE
){
509 diff
= sizeof(ipfw_insn_pipe_64
) - sizeof(ipfw_insn_pipe
);
519 copyto32fw_insn( struct ip_fw_32
*fw32
, struct ip_fw
*user_ip_fw
, int cmdsize
)
528 end
= ((char*)user_ip_fw
->cmd
) + cmdsize
;
529 useraction
= (char*)ACTION_PTR( user_ip_fw
);
530 fw32action
= (char*)fw32
->cmd
+ (user_ip_fw
->act_ofs
* sizeof(uint32_t));
531 if ( ( justcmdsize
= ( fw32action
- (char*)fw32
->cmd
)))
532 bcopy( user_ip_fw
->cmd
, fw32
->cmd
, justcmdsize
);
533 while ( useraction
< end
){
534 if ( ((ipfw_insn
*)useraction
)->opcode
== O_QUEUE
|| ((ipfw_insn
*)useraction
)->opcode
== O_PIPE
){
535 actioncopysize
= sizeof(ipfw_insn_pipe_32
);
536 ((ipfw_insn
*)fw32action
)->opcode
= ((ipfw_insn
*)useraction
)->opcode
;
537 ((ipfw_insn
*)fw32action
)->arg1
= ((ipfw_insn
*)useraction
)->arg1
;
538 ((ipfw_insn
*)fw32action
)->len
= F_INSN_SIZE(ipfw_insn_pipe_32
);
539 diff
= ((ipfw_insn
*)useraction
)->len
- ((ipfw_insn
*)fw32action
)->len
;
541 fw32
->cmd_len
-= diff
;
544 actioncopysize
= (F_LEN((ipfw_insn
*)useraction
) ? (F_LEN((ipfw_insn
*)useraction
)) : 1 ) * sizeof(uint32_t);
545 bcopy( useraction
, fw32action
, actioncopysize
);
547 useraction
+= (F_LEN((ipfw_insn
*)useraction
) ? (F_LEN((ipfw_insn
*)useraction
)) : 1 ) * sizeof(uint32_t);
548 fw32action
+= actioncopysize
;
553 copyto64fw_insn( struct ip_fw_64
*fw64
, struct ip_fw
*user_ip_fw
, int cmdsize
)
562 end
= ((char *)user_ip_fw
->cmd
) + cmdsize
;
563 useraction
= (char*)ACTION_PTR( user_ip_fw
);
564 if ( (justcmdsize
= (useraction
- (char*)user_ip_fw
->cmd
)))
565 bcopy( user_ip_fw
->cmd
, fw64
->cmd
, justcmdsize
);
566 fw64action
= (char*)fw64
->cmd
+ justcmdsize
;
567 while ( useraction
< end
){
568 if ( ((ipfw_insn
*)user_ip_fw
)->opcode
== O_QUEUE
|| ((ipfw_insn
*)user_ip_fw
)->opcode
== O_PIPE
){
569 actioncopysize
= sizeof(ipfw_insn_pipe_64
);
570 ((ipfw_insn
*)fw64action
)->opcode
= ((ipfw_insn
*)useraction
)->opcode
;
571 ((ipfw_insn
*)fw64action
)->arg1
= ((ipfw_insn
*)useraction
)->arg1
;
572 ((ipfw_insn
*)fw64action
)->len
= F_INSN_SIZE(ipfw_insn_pipe_64
);
573 diff
= ((ipfw_insn
*)fw64action
)->len
- ((ipfw_insn
*)useraction
)->len
;
575 fw64
->cmd_len
+= diff
;
578 actioncopysize
= (F_LEN((ipfw_insn
*)useraction
) ? (F_LEN((ipfw_insn
*)useraction
)) : 1 ) * sizeof(uint32_t);
579 bcopy( useraction
, fw64action
, actioncopysize
);
581 useraction
+= (F_LEN((ipfw_insn
*)useraction
) ? (F_LEN((ipfw_insn
*)useraction
)) : 1 ) * sizeof(uint32_t);
582 fw64action
+= actioncopysize
;
587 copyto32fw( struct ip_fw
*user_ip_fw
, struct ip_fw_32
*fw32
, __unused
size_t copysize
)
589 size_t rulesize
, cmdsize
;
591 fw32
->version
= user_ip_fw
->version
;
592 fw32
->context
= CAST_DOWN_EXPLICIT( user32_addr_t
, user_ip_fw
->context
);
593 fw32
->next
= CAST_DOWN_EXPLICIT(user32_addr_t
, user_ip_fw
->next
);
594 fw32
->next_rule
= CAST_DOWN_EXPLICIT(user32_addr_t
, user_ip_fw
->next_rule
);
595 fw32
->act_ofs
= user_ip_fw
->act_ofs
;
596 fw32
->cmd_len
= user_ip_fw
->cmd_len
;
597 fw32
->rulenum
= user_ip_fw
->rulenum
;
598 fw32
->set
= user_ip_fw
->set
;
599 fw32
->set_masks
[0] = user_ip_fw
->set_masks
[0];
600 fw32
->set_masks
[1] = user_ip_fw
->set_masks
[1];
601 fw32
->pcnt
= user_ip_fw
->pcnt
;
602 fw32
->bcnt
= user_ip_fw
->bcnt
;
603 fw32
->timestamp
= user_ip_fw
->timestamp
;
604 fw32
->reserved_1
= user_ip_fw
->reserved_1
;
605 fw32
->reserved_2
= user_ip_fw
->reserved_2
;
606 rulesize
= sizeof(struct ip_fw_32
) + (user_ip_fw
->cmd_len
* sizeof(ipfw_insn
) - 4);
607 cmdsize
= user_ip_fw
->cmd_len
* sizeof(u_int32_t
);
608 copyto32fw_insn( fw32
, user_ip_fw
, cmdsize
);
612 copyto64fw( struct ip_fw
*user_ip_fw
, struct ip_fw_64
*fw64
, size_t copysize
)
614 size_t rulesize
, cmdsize
;
616 fw64
->version
= user_ip_fw
->version
;
617 fw64
->context
= CAST_DOWN_EXPLICIT(__uint64_t
, user_ip_fw
->context
);
618 fw64
->next
= CAST_DOWN_EXPLICIT(user64_addr_t
, user_ip_fw
->next
);
619 fw64
->next_rule
= CAST_DOWN_EXPLICIT(user64_addr_t
, user_ip_fw
->next_rule
);
620 fw64
->act_ofs
= user_ip_fw
->act_ofs
;
621 fw64
->cmd_len
= user_ip_fw
->cmd_len
;
622 fw64
->rulenum
= user_ip_fw
->rulenum
;
623 fw64
->set
= user_ip_fw
->set
;
624 fw64
->set_masks
[0] = user_ip_fw
->set_masks
[0];
625 fw64
->set_masks
[1] = user_ip_fw
->set_masks
[1];
626 fw64
->pcnt
= user_ip_fw
->pcnt
;
627 fw64
->bcnt
= user_ip_fw
->bcnt
;
628 fw64
->timestamp
= user_ip_fw
->timestamp
;
629 fw64
->reserved_1
= user_ip_fw
->reserved_1
;
630 fw64
->reserved_2
= user_ip_fw
->reserved_2
;
631 rulesize
= sizeof(struct ip_fw_64
) + (user_ip_fw
->cmd_len
* sizeof(ipfw_insn
) - 4);
632 if (rulesize
> copysize
)
633 cmdsize
= copysize
- sizeof(struct ip_fw_64
) + 4;
635 cmdsize
= user_ip_fw
->cmd_len
* sizeof(u_int32_t
);
636 copyto64fw_insn( fw64
, user_ip_fw
, cmdsize
);
640 copyfrom32fw_insn( struct ip_fw_32
*fw32
, struct ip_fw
*user_ip_fw
, int cmdsize
)
649 end
= ((char*)fw32
->cmd
) + cmdsize
;
650 fw32action
= (char*)ACTION_PTR( fw32
);
651 if ((justcmdsize
= (fw32action
- (char*)fw32
->cmd
)))
652 bcopy( fw32
->cmd
, user_ip_fw
->cmd
, justcmdsize
);
653 useraction
= (char*)user_ip_fw
->cmd
+ justcmdsize
;
654 while ( fw32action
< end
){
655 if ( ((ipfw_insn
*)fw32action
)->opcode
== O_QUEUE
|| ((ipfw_insn
*)fw32action
)->opcode
== O_PIPE
){
656 actioncopysize
= sizeof(ipfw_insn_pipe
);
657 ((ipfw_insn
*)useraction
)->opcode
= ((ipfw_insn
*)fw32action
)->opcode
;
658 ((ipfw_insn
*)useraction
)->arg1
= ((ipfw_insn
*)fw32action
)->arg1
;
659 ((ipfw_insn
*)useraction
)->len
= F_INSN_SIZE(ipfw_insn_pipe
);
660 diff
= ((ipfw_insn
*)useraction
)->len
- ((ipfw_insn
*)fw32action
)->len
;
662 /* readjust the cmd_len */
663 user_ip_fw
->cmd_len
+= diff
;
666 actioncopysize
= (F_LEN((ipfw_insn
*)fw32action
) ? (F_LEN((ipfw_insn
*)fw32action
)) : 1 ) * sizeof(uint32_t);
667 bcopy( fw32action
, useraction
, actioncopysize
);
669 fw32action
+= (F_LEN((ipfw_insn
*)fw32action
) ? (F_LEN((ipfw_insn
*)fw32action
)) : 1 ) * sizeof(uint32_t);
670 useraction
+= actioncopysize
;
673 return( useraction
- (char*)user_ip_fw
->cmd
);
677 copyfrom64fw_insn( struct ip_fw_64
*fw64
, struct ip_fw
*user_ip_fw
, int cmdsize
)
686 end
= ((char *)fw64
->cmd
) + cmdsize
;
687 fw64action
= (char*)ACTION_PTR( fw64
);
688 if ( (justcmdsize
= (fw64action
- (char*)fw64
->cmd
)))
689 bcopy( fw64
->cmd
, user_ip_fw
->cmd
, justcmdsize
);
690 useraction
= (char*)user_ip_fw
->cmd
+ justcmdsize
;
691 while ( fw64action
< end
){
692 if ( ((ipfw_insn
*)fw64action
)->opcode
== O_QUEUE
|| ((ipfw_insn
*)fw64action
)->opcode
== O_PIPE
){
693 actioncopysize
= sizeof(ipfw_insn_pipe
);
694 ((ipfw_insn
*)useraction
)->opcode
= ((ipfw_insn
*)fw64action
)->opcode
;
695 ((ipfw_insn
*)useraction
)->arg1
= ((ipfw_insn
*)fw64action
)->arg1
;
696 ((ipfw_insn
*)useraction
)->len
= F_INSN_SIZE(ipfw_insn_pipe
);
697 diff
= ((ipfw_insn
*)fw64action
)->len
- ((ipfw_insn
*)useraction
)->len
;
699 /* readjust the cmd_len */
700 user_ip_fw
->cmd_len
-= diff
;
703 actioncopysize
= (F_LEN((ipfw_insn
*)fw64action
) ? (F_LEN((ipfw_insn
*)fw64action
)) : 1 ) * sizeof(uint32_t);
704 bcopy( fw64action
, useraction
, actioncopysize
);
706 fw64action
+= (F_LEN((ipfw_insn
*)fw64action
) ? (F_LEN((ipfw_insn
*)fw64action
)) : 1 ) * sizeof(uint32_t);
707 useraction
+= actioncopysize
;
709 return( useraction
- (char*)user_ip_fw
->cmd
);
713 copyfrom32fw( struct ip_fw_32
*fw32
, struct ip_fw
*user_ip_fw
, size_t copysize
)
715 size_t rulesize
, cmdsize
;
717 user_ip_fw
->version
= fw32
->version
;
718 user_ip_fw
->context
= CAST_DOWN(void *, fw32
->context
);
719 user_ip_fw
->next
= CAST_DOWN(struct ip_fw
*, fw32
->next
);
720 user_ip_fw
->next_rule
= CAST_DOWN_EXPLICIT(struct ip_fw
*, fw32
->next_rule
);
721 user_ip_fw
->act_ofs
= fw32
->act_ofs
;
722 user_ip_fw
->cmd_len
= fw32
->cmd_len
;
723 user_ip_fw
->rulenum
= fw32
->rulenum
;
724 user_ip_fw
->set
= fw32
->set
;
725 user_ip_fw
->set_masks
[0] = fw32
->set_masks
[0];
726 user_ip_fw
->set_masks
[1] = fw32
->set_masks
[1];
727 user_ip_fw
->pcnt
= fw32
->pcnt
;
728 user_ip_fw
->bcnt
= fw32
->bcnt
;
729 user_ip_fw
->timestamp
= fw32
->timestamp
;
730 user_ip_fw
->reserved_1
= fw32
->reserved_1
;
731 user_ip_fw
->reserved_2
= fw32
->reserved_2
;
732 rulesize
= sizeof(struct ip_fw_32
) + (fw32
->cmd_len
* sizeof(ipfw_insn
) - 4);
733 if ( rulesize
> copysize
)
734 cmdsize
= copysize
- sizeof(struct ip_fw_32
)-4;
736 cmdsize
= fw32
->cmd_len
* sizeof(ipfw_insn
);
737 cmdsize
= copyfrom32fw_insn( fw32
, user_ip_fw
, cmdsize
);
738 return( sizeof(struct ip_fw
) + cmdsize
- 4);
742 copyfrom64fw( struct ip_fw_64
*fw64
, struct ip_fw
*user_ip_fw
, size_t copysize
)
744 size_t rulesize
, cmdsize
;
746 user_ip_fw
->version
= fw64
->version
;
747 user_ip_fw
->context
= CAST_DOWN_EXPLICIT( void *, fw64
->context
);
748 user_ip_fw
->next
= CAST_DOWN_EXPLICIT(struct ip_fw
*, fw64
->next
);
749 user_ip_fw
->next_rule
= CAST_DOWN_EXPLICIT(struct ip_fw
*, fw64
->next_rule
);
750 user_ip_fw
->act_ofs
= fw64
->act_ofs
;
751 user_ip_fw
->cmd_len
= fw64
->cmd_len
;
752 user_ip_fw
->rulenum
= fw64
->rulenum
;
753 user_ip_fw
->set
= fw64
->set
;
754 user_ip_fw
->set_masks
[0] = fw64
->set_masks
[0];
755 user_ip_fw
->set_masks
[1] = fw64
->set_masks
[1];
756 user_ip_fw
->pcnt
= fw64
->pcnt
;
757 user_ip_fw
->bcnt
= fw64
->bcnt
;
758 user_ip_fw
->timestamp
= fw64
->timestamp
;
759 user_ip_fw
->reserved_1
= fw64
->reserved_1
;
760 user_ip_fw
->reserved_2
= fw64
->reserved_2
;
761 //bcopy( fw64->cmd, user_ip_fw->cmd, fw64->cmd_len * sizeof(ipfw_insn));
762 rulesize
= sizeof(struct ip_fw_64
) + (fw64
->cmd_len
* sizeof(ipfw_insn
) - 4);
763 if ( rulesize
> copysize
)
764 cmdsize
= copysize
- sizeof(struct ip_fw_64
)-4;
766 cmdsize
= fw64
->cmd_len
* sizeof(ipfw_insn
);
767 cmdsize
= copyfrom64fw_insn( fw64
, user_ip_fw
, cmdsize
);
768 return( sizeof(struct ip_fw
) + cmdsize
- 4);
772 externalize_flow_id(struct ipfw_flow_id
*dst
, struct ip_flow_id
*src
);
774 externalize_flow_id(struct ipfw_flow_id
*dst
, struct ip_flow_id
*src
)
776 dst
->dst_ip
= src
->dst_ip
;
777 dst
->src_ip
= src
->src_ip
;
778 dst
->dst_port
= src
->dst_port
;
779 dst
->src_port
= src
->src_port
;
780 dst
->proto
= src
->proto
;
781 dst
->flags
= src
->flags
;
785 void cp_dyn_to_comp_32( struct ipfw_dyn_rule_compat_32
*dyn_rule_vers1
, int *len
)
787 struct ipfw_dyn_rule_compat_32
*dyn_last
=NULL
;
792 for (i
= 0; i
< curr_dyn_buckets
; i
++) {
793 for ( p
= ipfw_dyn_v
[i
] ; p
!= NULL
; p
= p
->next
) {
794 dyn_rule_vers1
->chain
= (user32_addr_t
)(p
->rule
->rulenum
);
795 externalize_flow_id(&dyn_rule_vers1
->id
, &p
->id
);
796 externalize_flow_id(&dyn_rule_vers1
->mask
, &p
->id
);
797 dyn_rule_vers1
->type
= p
->dyn_type
;
798 dyn_rule_vers1
->expire
= p
->expire
;
799 dyn_rule_vers1
->pcnt
= p
->pcnt
;
800 dyn_rule_vers1
->bcnt
= p
->bcnt
;
801 dyn_rule_vers1
->bucket
= p
->bucket
;
802 dyn_rule_vers1
->state
= p
->state
;
804 dyn_rule_vers1
->next
= CAST_DOWN_EXPLICIT( user32_addr_t
, p
->next
);
805 dyn_last
= dyn_rule_vers1
;
807 *len
+= sizeof(*dyn_rule_vers1
);
812 if (dyn_last
!= NULL
) {
813 dyn_last
->next
= ((user32_addr_t
)0);
820 void cp_dyn_to_comp_64( struct ipfw_dyn_rule_compat_64
*dyn_rule_vers1
, int *len
)
822 struct ipfw_dyn_rule_compat_64
*dyn_last
=NULL
;
827 for (i
= 0; i
< curr_dyn_buckets
; i
++) {
828 for ( p
= ipfw_dyn_v
[i
] ; p
!= NULL
; p
= p
->next
) {
829 dyn_rule_vers1
->chain
= (user64_addr_t
) p
->rule
->rulenum
;
830 externalize_flow_id(&dyn_rule_vers1
->id
, &p
->id
);
831 externalize_flow_id(&dyn_rule_vers1
->mask
, &p
->id
);
832 dyn_rule_vers1
->type
= p
->dyn_type
;
833 dyn_rule_vers1
->expire
= p
->expire
;
834 dyn_rule_vers1
->pcnt
= p
->pcnt
;
835 dyn_rule_vers1
->bcnt
= p
->bcnt
;
836 dyn_rule_vers1
->bucket
= p
->bucket
;
837 dyn_rule_vers1
->state
= p
->state
;
839 dyn_rule_vers1
->next
= CAST_DOWN(user64_addr_t
, p
->next
);
840 dyn_last
= dyn_rule_vers1
;
842 *len
+= sizeof(*dyn_rule_vers1
);
847 if (dyn_last
!= NULL
) {
848 dyn_last
->next
= CAST_DOWN(user64_addr_t
, NULL
);
854 sooptcopyin_fw( struct sockopt
*sopt
, struct ip_fw
*user_ip_fw
, size_t *size
)
856 size_t valsize
, copyinsize
= 0;
859 valsize
= sopt
->sopt_valsize
;
862 if (proc_is64bit(sopt
->sopt_p
)) {
863 struct ip_fw_64
*fw64
=NULL
;
865 if ( valsize
< sizeof(struct ip_fw_64
) ) {
869 copyinsize
= sizeof(struct ip_fw_64
);
870 if ( valsize
> copyinsize
)
871 sopt
->sopt_valsize
= valsize
= copyinsize
;
873 if ( sopt
->sopt_p
!= 0) {
874 fw64
= _MALLOC(copyinsize
, M_TEMP
, M_WAITOK
);
877 if ((error
= copyin(sopt
->sopt_val
, fw64
, valsize
)) != 0){
883 bcopy(CAST_DOWN(caddr_t
, sopt
->sopt_val
), fw64
, valsize
);
885 valsize
= copyfrom64fw( fw64
, user_ip_fw
, valsize
);
886 _FREE( fw64
, M_TEMP
);
888 struct ip_fw_32
*fw32
=NULL
;
890 if ( valsize
< sizeof(struct ip_fw_32
) ) {
894 copyinsize
= sizeof(struct ip_fw_32
);
895 if ( valsize
> copyinsize
)
896 sopt
->sopt_valsize
= valsize
= copyinsize
;
898 if ( sopt
->sopt_p
!= 0) {
899 fw32
= _MALLOC(copyinsize
, M_TEMP
, M_WAITOK
);
902 if ( (error
= copyin(sopt
->sopt_val
, fw32
, valsize
)) != 0){
903 _FREE( fw32
, M_TEMP
);
908 bcopy(CAST_DOWN(caddr_t
, sopt
->sopt_val
), fw32
, valsize
);
910 valsize
= copyfrom32fw( fw32
, user_ip_fw
, valsize
);
911 _FREE( fw32
, M_TEMP
);
919 * The following checks use two arrays of 8 or 16 bits to store the
920 * bits that we want set or clear, respectively. They are in the
921 * low and high half of cmd->arg1 or cmd->d[0].
923 * We scan options and store the bits we find set. We succeed if
925 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
927 * The code is sometimes optimized not to store additional variables.
931 flags_match(ipfw_insn
*cmd
, u_int8_t bits
)
936 if ( ((cmd
->arg1
& 0xff) & bits
) != 0)
937 return 0; /* some bits we want set were clear */
938 want_clear
= (cmd
->arg1
>> 8) & 0xff;
939 if ( (want_clear
& bits
) != want_clear
)
940 return 0; /* some bits we want clear were set */
945 ipopts_match(struct ip
*ip
, ipfw_insn
*cmd
)
947 int optlen
, bits
= 0;
948 u_char
*cp
= (u_char
*)(ip
+ 1);
949 int x
= (ip
->ip_hl
<< 2) - sizeof (struct ip
);
951 for (; x
> 0; x
-= optlen
, cp
+= optlen
) {
952 int opt
= cp
[IPOPT_OPTVAL
];
954 if (opt
== IPOPT_EOL
)
956 if (opt
== IPOPT_NOP
)
959 optlen
= cp
[IPOPT_OLEN
];
960 if (optlen
<= 0 || optlen
> x
)
961 return 0; /* invalid or truncated */
969 bits
|= IP_FW_IPOPT_LSRR
;
973 bits
|= IP_FW_IPOPT_SSRR
;
977 bits
|= IP_FW_IPOPT_RR
;
981 bits
|= IP_FW_IPOPT_TS
;
985 return (flags_match(cmd
, bits
));
989 tcpopts_match(struct ip
*ip
, ipfw_insn
*cmd
)
991 int optlen
, bits
= 0;
992 struct tcphdr
*tcp
= L3HDR(struct tcphdr
,ip
);
993 u_char
*cp
= (u_char
*)(tcp
+ 1);
994 int x
= (tcp
->th_off
<< 2) - sizeof(struct tcphdr
);
996 for (; x
> 0; x
-= optlen
, cp
+= optlen
) {
998 if (opt
== TCPOPT_EOL
)
1000 if (opt
== TCPOPT_NOP
)
1014 bits
|= IP_FW_TCPOPT_MSS
;
1018 bits
|= IP_FW_TCPOPT_WINDOW
;
1021 case TCPOPT_SACK_PERMITTED
:
1023 bits
|= IP_FW_TCPOPT_SACK
;
1026 case TCPOPT_TIMESTAMP
:
1027 bits
|= IP_FW_TCPOPT_TS
;
1033 bits
|= IP_FW_TCPOPT_CC
;
1037 return (flags_match(cmd
, bits
));
1041 iface_match(struct ifnet
*ifp
, ipfw_insn_if
*cmd
)
1043 if (ifp
== NULL
) /* no iface with this packet, match fails */
1045 /* Check by name or by IP address */
1046 if (cmd
->name
[0] != '\0') { /* match by name */
1047 /* Check unit number (-1 is wildcard) */
1048 if (cmd
->p
.unit
!= -1 && cmd
->p
.unit
!= ifp
->if_unit
)
1051 if (!strncmp(ifp
->if_name
, cmd
->name
, IFNAMSIZ
))
1056 ifnet_lock_shared(ifp
);
1057 TAILQ_FOREACH(ia
, &ifp
->if_addrhead
, ifa_link
) {
1059 if (ia
->ifa_addr
->sa_family
!= AF_INET
) {
1063 if (cmd
->p
.ip
.s_addr
== ((struct sockaddr_in
*)
1064 (ia
->ifa_addr
))->sin_addr
.s_addr
) {
1066 ifnet_lock_done(ifp
);
1067 return(1); /* match */
1071 ifnet_lock_done(ifp
);
1073 return(0); /* no match, fail ... */
1077 * The 'verrevpath' option checks that the interface that an IP packet
1078 * arrives on is the same interface that traffic destined for the
1079 * packet's source address would be routed out of. This is a measure
1080 * to block forged packets. This is also commonly known as "anti-spoofing"
1081 * or Unicast Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The
1082 * name of the knob is purposely reminisent of the Cisco IOS command,
1084 * ip verify unicast reverse-path
1086 * which implements the same functionality. But note that syntax is
1087 * misleading. The check may be performed on all IP packets whether unicast,
1088 * multicast, or broadcast.
1091 verify_rev_path(struct in_addr src
, struct ifnet
*ifp
)
1093 static struct route ro
;
1094 struct sockaddr_in
*dst
;
1096 bzero(&ro
, sizeof (ro
));
1097 dst
= (struct sockaddr_in
*)&(ro
.ro_dst
);
1099 /* Check if we've cached the route from the previous call. */
1100 if (src
.s_addr
!= dst
->sin_addr
.s_addr
) {
1101 dst
->sin_family
= AF_INET
;
1102 dst
->sin_len
= sizeof(*dst
);
1103 dst
->sin_addr
= src
;
1105 rtalloc_ign(&ro
, RTF_CLONING
|RTF_PRCLONING
, false);
1107 if (ro
.ro_rt
!= NULL
) {
1108 RT_LOCK_SPIN(ro
.ro_rt
);
1111 return 0; /* No route */
1113 if ((ifp
== NULL
) ||
1114 (ro
.ro_rt
->rt_ifp
->if_index
!= ifp
->if_index
)) {
1115 RT_UNLOCK(ro
.ro_rt
);
1119 RT_UNLOCK(ro
.ro_rt
);
1125 static u_int64_t norule_counter
; /* counter for ipfw_log(NULL...) */
1127 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
1128 #define SNP(buf) buf, sizeof(buf)
1131 * We enter here when we have a rule with O_LOG.
1132 * XXX this function alone takes about 2Kbytes of code!
1135 ipfw_log(struct ip_fw
*f
, u_int hlen
, struct ether_header
*eh
,
1136 struct mbuf
*m
, struct ifnet
*oif
)
1139 int limit_reached
= 0;
1140 char ipv4str
[MAX_IPv4_STR_LEN
];
1141 char action2
[40], proto
[48], fragment
[28];
1146 if (f
== NULL
) { /* bogus pkt */
1147 if (verbose_limit
!= 0 && norule_counter
>= verbose_limit
)
1150 if (norule_counter
== verbose_limit
)
1151 limit_reached
= verbose_limit
;
1153 } else { /* O_LOG is the first action, find the real one */
1154 ipfw_insn
*cmd
= ACTION_PTR(f
);
1155 ipfw_insn_log
*l
= (ipfw_insn_log
*)cmd
;
1157 if (l
->max_log
!= 0 && l
->log_left
== 0)
1160 if (l
->log_left
== 0)
1161 limit_reached
= l
->max_log
;
1162 cmd
+= F_LEN(cmd
); /* point to first action */
1163 if (cmd
->opcode
== O_PROB
)
1167 switch (cmd
->opcode
) {
1173 if (cmd
->arg1
==ICMP_REJECT_RST
)
1175 else if (cmd
->arg1
==ICMP_UNREACH_HOST
)
1178 snprintf(SNPARGS(action2
, 0), "Unreach %d",
1189 snprintf(SNPARGS(action2
, 0), "Divert %d",
1193 snprintf(SNPARGS(action2
, 0), "Tee %d",
1197 snprintf(SNPARGS(action2
, 0), "SkipTo %d",
1201 snprintf(SNPARGS(action2
, 0), "Pipe %d",
1205 snprintf(SNPARGS(action2
, 0), "Queue %d",
1208 case O_FORWARD_IP
: {
1209 ipfw_insn_sa
*sa
= (ipfw_insn_sa
*)cmd
;
1212 if (f
->reserved_1
== IPFW_RULE_INACTIVE
) {
1215 len
= snprintf(SNPARGS(action2
, 0), "Forward to %s",
1216 inet_ntop(AF_INET
, &sa
->sa
.sin_addr
, ipv4str
, sizeof(ipv4str
)));
1217 if (sa
->sa
.sin_port
)
1218 snprintf(SNPARGS(action2
, len
), ":%d",
1228 if (hlen
== 0) { /* non-ip */
1229 snprintf(SNPARGS(proto
, 0), "MAC");
1231 struct ip
*ip
= mtod(m
, struct ip
*);
1232 /* these three are all aliases to the same thing */
1233 struct icmp
*const icmp
= L3HDR(struct icmp
, ip
);
1234 struct tcphdr
*const tcp
= (struct tcphdr
*)icmp
;
1235 struct udphdr
*const udp
= (struct udphdr
*)icmp
;
1237 int ip_off
, offset
, ip_len
;
1241 if (eh
!= NULL
) { /* layer 2 packets are as on the wire */
1242 ip_off
= ntohs(ip
->ip_off
);
1243 ip_len
= ntohs(ip
->ip_len
);
1245 ip_off
= ip
->ip_off
;
1246 ip_len
= ip
->ip_len
;
1248 offset
= ip_off
& IP_OFFMASK
;
1251 len
= snprintf(SNPARGS(proto
, 0), "TCP %s",
1252 inet_ntop(AF_INET
, &ip
->ip_src
, ipv4str
, sizeof(ipv4str
)));
1254 snprintf(SNPARGS(proto
, len
), ":%d %s:%d",
1255 ntohs(tcp
->th_sport
),
1256 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)),
1257 ntohs(tcp
->th_dport
));
1259 snprintf(SNPARGS(proto
, len
), " %s",
1260 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)));
1264 len
= snprintf(SNPARGS(proto
, 0), "UDP %s",
1265 inet_ntop(AF_INET
, &ip
->ip_src
, ipv4str
, sizeof(ipv4str
)));
1267 snprintf(SNPARGS(proto
, len
), ":%d %s:%d",
1268 ntohs(udp
->uh_sport
),
1269 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)),
1270 ntohs(udp
->uh_dport
));
1272 snprintf(SNPARGS(proto
, len
), " %s",
1273 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)));
1278 len
= snprintf(SNPARGS(proto
, 0),
1280 icmp
->icmp_type
, icmp
->icmp_code
);
1282 len
= snprintf(SNPARGS(proto
, 0), "ICMP ");
1283 len
+= snprintf(SNPARGS(proto
, len
), "%s",
1284 inet_ntop(AF_INET
, &ip
->ip_src
, ipv4str
, sizeof(ipv4str
)));
1285 snprintf(SNPARGS(proto
, len
), " %s",
1286 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)));
1290 len
= snprintf(SNPARGS(proto
, 0), "P:%d %s", ip
->ip_p
,
1291 inet_ntop(AF_INET
, &ip
->ip_src
, ipv4str
, sizeof(ipv4str
)));
1292 snprintf(SNPARGS(proto
, len
), " %s",
1293 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)));
1297 if (ip_off
& (IP_MF
| IP_OFFMASK
))
1298 snprintf(SNPARGS(fragment
, 0), " (frag %d:%d@%d%s)",
1299 ntohs(ip
->ip_id
), ip_len
- (ip
->ip_hl
<< 2),
1301 (ip_off
& IP_MF
) ? "+" : "");
1303 if (oif
|| m
->m_pkthdr
.rcvif
)
1305 dolog((LOG_AUTHPRIV
| LOG_INFO
,
1306 "ipfw: %d %s %s %s via %s%d%s\n",
1307 f
? f
->rulenum
: -1,
1308 action
, proto
, oif
? "out" : "in",
1309 oif
? oif
->if_name
: m
->m_pkthdr
.rcvif
->if_name
,
1310 oif
? oif
->if_unit
: m
->m_pkthdr
.rcvif
->if_unit
,
1314 dolog((LOG_AUTHPRIV
| LOG_INFO
,
1315 "ipfw: %d %s %s [no if info]%s\n",
1316 f
? f
->rulenum
: -1,
1317 action
, proto
, fragment
));
1320 dolog((LOG_AUTHPRIV
| LOG_NOTICE
,
1321 "ipfw: limit %d reached on entry %d\n",
1322 limit_reached
, f
? f
->rulenum
: -1));
1327 * IMPORTANT: the hash function for dynamic rules must be commutative
1328 * in source and destination (ip,port), because rules are bidirectional
1329 * and we want to find both in the same bucket.
1332 hash_packet(struct ip_flow_id
*id
)
1336 i
= (id
->dst_ip
) ^ (id
->src_ip
) ^ (id
->dst_port
) ^ (id
->src_port
);
1337 i
&= (curr_dyn_buckets
- 1);
1342 * unlink a dynamic rule from a chain. prev is a pointer to
1343 * the previous one, q is a pointer to the rule to delete,
1344 * head is a pointer to the head of the queue.
1345 * Modifies q and potentially also head.
1347 #define UNLINK_DYN_RULE(prev, head, q) { \
1348 ipfw_dyn_rule *old_q = q; \
1350 /* remove a refcount to the parent */ \
1351 if (q->dyn_type == O_LIMIT) \
1352 q->parent->count--; \
1353 DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
1354 (q->id.src_ip), (q->id.src_port), \
1355 (q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); ) \
1357 prev->next = q = q->next; \
1359 head = q = q->next; \
1361 _FREE(old_q, M_IPFW); }
1363 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
1366 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
1368 * If keep_me == NULL, rules are deleted even if not expired,
1369 * otherwise only expired rules are removed.
1371 * The value of the second parameter is also used to point to identify
1372 * a rule we absolutely do not want to remove (e.g. because we are
1373 * holding a reference to it -- this is the case with O_LIMIT_PARENT
1374 * rules). The pointer is only used for comparison, so any non-null
1378 remove_dyn_rule(struct ip_fw
*rule
, ipfw_dyn_rule
*keep_me
)
1380 static u_int32_t last_remove
= 0;
1382 #define FORCE (keep_me == NULL)
1384 ipfw_dyn_rule
*prev
, *q
;
1385 int i
, pass
= 0, max_pass
= 0;
1386 struct timeval timenow
;
1388 getmicrotime(&timenow
);
1390 if (ipfw_dyn_v
== NULL
|| dyn_count
== 0)
1392 /* do not expire more than once per second, it is useless */
1393 if (!FORCE
&& last_remove
== timenow
.tv_sec
)
1395 last_remove
= timenow
.tv_sec
;
1398 * because O_LIMIT refer to parent rules, during the first pass only
1399 * remove child and mark any pending LIMIT_PARENT, and remove
1400 * them in a second pass.
1403 for (i
= 0 ; i
< curr_dyn_buckets
; i
++) {
1404 for (prev
=NULL
, q
= ipfw_dyn_v
[i
] ; q
; ) {
1406 * Logic can become complex here, so we split tests.
1410 if (rule
!= NULL
&& rule
!= q
->rule
)
1411 goto next
; /* not the one we are looking for */
1412 if (q
->dyn_type
== O_LIMIT_PARENT
) {
1414 * handle parent in the second pass,
1415 * record we need one.
1420 if (FORCE
&& q
->count
!= 0 ) {
1421 /* XXX should not happen! */
1422 printf("ipfw: OUCH! cannot remove rule,"
1423 " count %d\n", q
->count
);
1427 !TIME_LEQ( q
->expire
, timenow
.tv_sec
))
1430 if (q
->dyn_type
!= O_LIMIT_PARENT
|| !q
->count
) {
1431 UNLINK_DYN_RULE(prev
, ipfw_dyn_v
[i
], q
);
1439 if (pass
++ < max_pass
)
1445 * lookup a dynamic rule.
1447 static ipfw_dyn_rule
*
1448 lookup_dyn_rule(struct ip_flow_id
*pkt
, int *match_direction
,
1452 * stateful ipfw extensions.
1453 * Lookup into dynamic session queue
1455 #define MATCH_REVERSE 0
1456 #define MATCH_FORWARD 1
1457 #define MATCH_NONE 2
1458 #define MATCH_UNKNOWN 3
1459 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
1460 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
1462 int i
, dir
= MATCH_NONE
;
1463 ipfw_dyn_rule
*prev
, *q
=NULL
;
1464 struct timeval timenow
;
1466 getmicrotime(&timenow
);
1468 if (ipfw_dyn_v
== NULL
)
1469 goto done
; /* not found */
1470 i
= hash_packet( pkt
);
1471 for (prev
=NULL
, q
= ipfw_dyn_v
[i
] ; q
!= NULL
; ) {
1472 if (q
->dyn_type
== O_LIMIT_PARENT
&& q
->count
)
1474 if (TIME_LEQ( q
->expire
, timenow
.tv_sec
)) { /* expire entry */
1477 /* check if entry is TCP */
1478 if ( q
->id
.proto
== IPPROTO_TCP
)
1480 /* do not delete an established TCP connection which hasn't been closed by both sides */
1481 if ( (q
->state
& (BOTH_SYN
| BOTH_FIN
)) != (BOTH_SYN
| BOTH_FIN
) )
1485 UNLINK_DYN_RULE(prev
, ipfw_dyn_v
[i
], q
);
1489 if (pkt
->proto
== q
->id
.proto
&&
1490 q
->dyn_type
!= O_LIMIT_PARENT
) {
1491 if (pkt
->src_ip
== q
->id
.src_ip
&&
1492 pkt
->dst_ip
== q
->id
.dst_ip
&&
1493 pkt
->src_port
== q
->id
.src_port
&&
1494 pkt
->dst_port
== q
->id
.dst_port
) {
1495 dir
= MATCH_FORWARD
;
1498 if (pkt
->src_ip
== q
->id
.dst_ip
&&
1499 pkt
->dst_ip
== q
->id
.src_ip
&&
1500 pkt
->src_port
== q
->id
.dst_port
&&
1501 pkt
->dst_port
== q
->id
.src_port
) {
1502 dir
= MATCH_REVERSE
;
1511 goto done
; /* q = NULL, not found */
1513 if ( prev
!= NULL
) { /* found and not in front */
1514 prev
->next
= q
->next
;
1515 q
->next
= ipfw_dyn_v
[i
];
1518 if (pkt
->proto
== IPPROTO_TCP
) { /* update state according to flags */
1519 u_char flags
= pkt
->flags
& (TH_FIN
|TH_SYN
|TH_RST
);
1521 q
->state
|= (dir
== MATCH_FORWARD
) ? flags
: (flags
<< 8);
1523 case TH_SYN
: /* opening */
1524 q
->expire
= timenow
.tv_sec
+ dyn_syn_lifetime
;
1527 case BOTH_SYN
: /* move to established */
1528 case BOTH_SYN
| TH_FIN
: /* one side tries to close */
1529 case BOTH_SYN
| (TH_FIN
<< 8) :
1531 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
1532 u_int32_t ack
= ntohl(tcp
->th_ack
);
1533 if (dir
== MATCH_FORWARD
) {
1534 if (q
->ack_fwd
== 0 || _SEQ_GE(ack
, q
->ack_fwd
))
1536 else { /* ignore out-of-sequence */
1540 if (q
->ack_rev
== 0 || _SEQ_GE(ack
, q
->ack_rev
))
1542 else { /* ignore out-of-sequence */
1547 q
->expire
= timenow
.tv_sec
+ dyn_ack_lifetime
;
1550 case BOTH_SYN
| BOTH_FIN
: /* both sides closed */
1551 if (dyn_fin_lifetime
>= dyn_keepalive_period
)
1552 dyn_fin_lifetime
= dyn_keepalive_period
- 1;
1553 q
->expire
= timenow
.tv_sec
+ dyn_fin_lifetime
;
1559 * reset or some invalid combination, but can also
1560 * occur if we use keep-state the wrong way.
1562 if ( (q
->state
& ((TH_RST
<< 8)|TH_RST
)) == 0)
1563 printf("invalid state: 0x%x\n", q
->state
);
1565 if (dyn_rst_lifetime
>= dyn_keepalive_period
)
1566 dyn_rst_lifetime
= dyn_keepalive_period
- 1;
1567 q
->expire
= timenow
.tv_sec
+ dyn_rst_lifetime
;
1570 } else if (pkt
->proto
== IPPROTO_UDP
) {
1571 q
->expire
= timenow
.tv_sec
+ dyn_udp_lifetime
;
1573 /* other protocols */
1574 q
->expire
= timenow
.tv_sec
+ dyn_short_lifetime
;
1577 if (match_direction
)
1578 *match_direction
= dir
;
1583 realloc_dynamic_table(void)
1586 * Try reallocation, make sure we have a power of 2 and do
1587 * not allow more than 64k entries. In case of overflow,
1591 if (dyn_buckets
> 65536)
1593 if ((dyn_buckets
& (dyn_buckets
-1)) != 0) { /* not a power of 2 */
1594 dyn_buckets
= curr_dyn_buckets
; /* reset */
1597 curr_dyn_buckets
= dyn_buckets
;
1598 if (ipfw_dyn_v
!= NULL
)
1599 _FREE(ipfw_dyn_v
, M_IPFW
);
1601 ipfw_dyn_v
= _MALLOC(curr_dyn_buckets
* sizeof(ipfw_dyn_rule
*),
1602 M_IPFW
, M_NOWAIT
| M_ZERO
);
1603 if (ipfw_dyn_v
!= NULL
|| curr_dyn_buckets
<= 2)
1605 curr_dyn_buckets
/= 2;
1610 * Install state of type 'type' for a dynamic session.
1611 * The hash table contains two type of rules:
1612 * - regular rules (O_KEEP_STATE)
1613 * - rules for sessions with limited number of sess per user
1614 * (O_LIMIT). When they are created, the parent is
1615 * increased by 1, and decreased on delete. In this case,
1616 * the third parameter is the parent rule and not the chain.
1617 * - "parent" rules for the above (O_LIMIT_PARENT).
1619 static ipfw_dyn_rule
*
1620 add_dyn_rule(struct ip_flow_id
*id
, u_int8_t dyn_type
, struct ip_fw
*rule
)
1624 struct timeval timenow
;
1626 getmicrotime(&timenow
);
1628 if (ipfw_dyn_v
== NULL
||
1629 (dyn_count
== 0 && dyn_buckets
!= curr_dyn_buckets
)) {
1630 realloc_dynamic_table();
1631 if (ipfw_dyn_v
== NULL
)
1632 return NULL
; /* failed ! */
1634 i
= hash_packet(id
);
1636 r
= _MALLOC(sizeof *r
, M_IPFW
, M_NOWAIT
| M_ZERO
);
1639 printf ("ipfw: sorry cannot allocate state\n");
1644 /* increase refcount on parent, and set pointer */
1645 if (dyn_type
== O_LIMIT
) {
1646 ipfw_dyn_rule
*parent
= (ipfw_dyn_rule
*)rule
;
1647 if ( parent
->dyn_type
!= O_LIMIT_PARENT
)
1648 panic("invalid parent");
1651 rule
= parent
->rule
;
1655 r
->expire
= timenow
.tv_sec
+ dyn_syn_lifetime
;
1657 r
->dyn_type
= dyn_type
;
1658 r
->pcnt
= r
->bcnt
= 0;
1662 r
->next
= ipfw_dyn_v
[i
];
1665 DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1667 (r
->id
.src_ip
), (r
->id
.src_port
),
1668 (r
->id
.dst_ip
), (r
->id
.dst_port
),
1674 * lookup dynamic parent rule using pkt and rule as search keys.
1675 * If the lookup fails, then install one.
1677 static ipfw_dyn_rule
*
1678 lookup_dyn_parent(struct ip_flow_id
*pkt
, struct ip_fw
*rule
)
1682 struct timeval timenow
;
1684 getmicrotime(&timenow
);
1687 i
= hash_packet( pkt
);
1688 for (q
= ipfw_dyn_v
[i
] ; q
!= NULL
; q
=q
->next
)
1689 if (q
->dyn_type
== O_LIMIT_PARENT
&&
1691 pkt
->proto
== q
->id
.proto
&&
1692 pkt
->src_ip
== q
->id
.src_ip
&&
1693 pkt
->dst_ip
== q
->id
.dst_ip
&&
1694 pkt
->src_port
== q
->id
.src_port
&&
1695 pkt
->dst_port
== q
->id
.dst_port
) {
1696 q
->expire
= timenow
.tv_sec
+ dyn_short_lifetime
;
1697 DEB(printf("ipfw: lookup_dyn_parent found "
1698 "0x%llx\n", (uint64_t)VM_KERNEL_ADDRPERM(q
));)
1702 return add_dyn_rule(pkt
, O_LIMIT_PARENT
, rule
);
1706 * Install dynamic state for rule type cmd->o.opcode
1708 * Returns 1 (failure) if state is not installed because of errors or because
1709 * session limitations are enforced.
1712 install_state(struct ip_fw
*rule
, ipfw_insn_limit
*cmd
,
1713 struct ip_fw_args
*args
)
1715 static int last_log
;
1716 struct timeval timenow
;
1719 getmicrotime(&timenow
);
1721 DEB(printf("ipfw: install state type %d 0x%08x %u -> 0x%08x %u\n",
1723 (args
->fwa_id
.src_ip
), (args
->fwa_id
.src_port
),
1724 (args
->fwa_id
.dst_ip
), (args
->fwa_id
.dst_port
) );)
1726 q
= lookup_dyn_rule(&args
->fwa_id
, NULL
, NULL
);
1728 if (q
!= NULL
) { /* should never occur */
1729 if (last_log
!= timenow
.tv_sec
) {
1730 last_log
= timenow
.tv_sec
;
1731 printf("ipfw: install_state: entry already present, done\n");
1736 if (dyn_count
>= dyn_max
)
1738 * Run out of slots, try to remove any expired rule.
1740 remove_dyn_rule(NULL
, (ipfw_dyn_rule
*)1);
1742 if (dyn_count
>= dyn_max
) {
1743 if (last_log
!= timenow
.tv_sec
) {
1744 last_log
= timenow
.tv_sec
;
1745 printf("ipfw: install_state: Too many dynamic rules\n");
1747 return 1; /* cannot install, notify caller */
1750 switch (cmd
->o
.opcode
) {
1751 case O_KEEP_STATE
: /* bidir rule */
1752 add_dyn_rule(&args
->fwa_id
, O_KEEP_STATE
, rule
);
1755 case O_LIMIT
: /* limit number of sessions */
1757 u_int16_t limit_mask
= cmd
->limit_mask
;
1758 struct ip_flow_id id
;
1759 ipfw_dyn_rule
*parent
;
1761 DEB(printf("ipfw: installing dyn-limit rule %d\n",
1764 id
.dst_ip
= id
.src_ip
= 0;
1765 id
.dst_port
= id
.src_port
= 0;
1766 id
.proto
= args
->fwa_id
.proto
;
1768 if (limit_mask
& DYN_SRC_ADDR
)
1769 id
.src_ip
= args
->fwa_id
.src_ip
;
1770 if (limit_mask
& DYN_DST_ADDR
)
1771 id
.dst_ip
= args
->fwa_id
.dst_ip
;
1772 if (limit_mask
& DYN_SRC_PORT
)
1773 id
.src_port
= args
->fwa_id
.src_port
;
1774 if (limit_mask
& DYN_DST_PORT
)
1775 id
.dst_port
= args
->fwa_id
.dst_port
;
1776 parent
= lookup_dyn_parent(&id
, rule
);
1777 if (parent
== NULL
) {
1778 printf("ipfw: add parent failed\n");
1781 if (parent
->count
>= cmd
->conn_limit
) {
1783 * See if we can remove some expired rule.
1785 remove_dyn_rule(rule
, parent
);
1786 if (parent
->count
>= cmd
->conn_limit
) {
1787 if (fw_verbose
&& last_log
!= timenow
.tv_sec
) {
1788 last_log
= timenow
.tv_sec
;
1789 dolog((LOG_AUTHPRIV
| LOG_DEBUG
,
1790 "drop session, too many entries\n"));
1795 add_dyn_rule(&args
->fwa_id
, O_LIMIT
, (struct ip_fw
*)parent
);
1799 printf("ipfw: unknown dynamic rule type %u\n", cmd
->o
.opcode
);
1802 lookup_dyn_rule(&args
->fwa_id
, NULL
, NULL
); /* XXX just set lifetime */
1807 * Generate a TCP packet, containing either a RST or a keepalive.
1808 * When flags & TH_RST, we are sending a RST packet, because of a
1809 * "reset" action matched the packet.
1810 * Otherwise we are sending a keepalive, and flags & TH_
1812 static struct mbuf
*
1813 send_pkt(struct ip_flow_id
*id
, u_int32_t seq
, u_int32_t ack
, int flags
)
1819 MGETHDR(m
, M_DONTWAIT
, MT_HEADER
); /* MAC-OK */
1822 m
->m_pkthdr
.rcvif
= (struct ifnet
*)0;
1823 m
->m_pkthdr
.len
= m
->m_len
= sizeof(struct ip
) + sizeof(struct tcphdr
);
1824 m
->m_data
+= max_linkhdr
;
1826 ip
= mtod(m
, struct ip
*);
1827 bzero(ip
, m
->m_len
);
1828 tcp
= (struct tcphdr
*)(ip
+ 1); /* no IP options */
1829 ip
->ip_p
= IPPROTO_TCP
;
1832 * Assume we are sending a RST (or a keepalive in the reverse
1833 * direction), swap src and destination addresses and ports.
1835 ip
->ip_src
.s_addr
= htonl(id
->dst_ip
);
1836 ip
->ip_dst
.s_addr
= htonl(id
->src_ip
);
1837 tcp
->th_sport
= htons(id
->dst_port
);
1838 tcp
->th_dport
= htons(id
->src_port
);
1839 if (flags
& TH_RST
) { /* we are sending a RST */
1840 if (flags
& TH_ACK
) {
1841 tcp
->th_seq
= htonl(ack
);
1842 tcp
->th_ack
= htonl(0);
1843 tcp
->th_flags
= TH_RST
;
1847 tcp
->th_seq
= htonl(0);
1848 tcp
->th_ack
= htonl(seq
);
1849 tcp
->th_flags
= TH_RST
| TH_ACK
;
1853 * We are sending a keepalive. flags & TH_SYN determines
1854 * the direction, forward if set, reverse if clear.
1855 * NOTE: seq and ack are always assumed to be correct
1856 * as set by the caller. This may be confusing...
1858 if (flags
& TH_SYN
) {
1860 * we have to rewrite the correct addresses!
1862 ip
->ip_dst
.s_addr
= htonl(id
->dst_ip
);
1863 ip
->ip_src
.s_addr
= htonl(id
->src_ip
);
1864 tcp
->th_dport
= htons(id
->dst_port
);
1865 tcp
->th_sport
= htons(id
->src_port
);
1867 tcp
->th_seq
= htonl(seq
);
1868 tcp
->th_ack
= htonl(ack
);
1869 tcp
->th_flags
= TH_ACK
;
1872 * set ip_len to the payload size so we can compute
1873 * the tcp checksum on the pseudoheader
1874 * XXX check this, could save a couple of words ?
1876 ip
->ip_len
= htons(sizeof(struct tcphdr
));
1877 tcp
->th_sum
= in_cksum(m
, m
->m_pkthdr
.len
);
1879 * now fill fields left out earlier
1881 ip
->ip_ttl
= ip_defttl
;
1882 ip
->ip_len
= m
->m_pkthdr
.len
;
1883 m
->m_flags
|= M_SKIP_FIREWALL
;
1889 * sends a reject message, consuming the mbuf passed as an argument.
1892 send_reject(struct ip_fw_args
*args
, int code
, int offset
, __unused
int ip_len
)
1895 if (code
!= ICMP_REJECT_RST
) { /* Send an ICMP unreach */
1896 /* We need the IP header in host order for icmp_error(). */
1897 if (args
->fwa_eh
!= NULL
) {
1898 struct ip
*ip
= mtod(args
->fwa_m
, struct ip
*);
1899 ip
->ip_len
= ntohs(ip
->ip_len
);
1900 ip
->ip_off
= ntohs(ip
->ip_off
);
1902 args
->fwa_m
->m_flags
|= M_SKIP_FIREWALL
;
1903 icmp_error(args
->fwa_m
, ICMP_UNREACH
, code
, 0L, 0);
1904 } else if (offset
== 0 && args
->fwa_id
.proto
== IPPROTO_TCP
) {
1905 struct tcphdr
*const tcp
=
1906 L3HDR(struct tcphdr
, mtod(args
->fwa_m
, struct ip
*));
1907 if ( (tcp
->th_flags
& TH_RST
) == 0) {
1910 m
= send_pkt(&(args
->fwa_id
), ntohl(tcp
->th_seq
),
1912 tcp
->th_flags
| TH_RST
);
1914 struct route sro
; /* fake route */
1916 bzero (&sro
, sizeof (sro
));
1917 ip_output(m
, NULL
, &sro
, 0, NULL
, NULL
);
1918 ROUTE_RELEASE(&sro
);
1921 m_freem(args
->fwa_m
);
1923 m_freem(args
->fwa_m
);
1929 * Given an ip_fw *, lookup_next_rule will return a pointer
1930 * to the next rule, which can be either the jump
1931 * target (for skipto instructions) or the next one in the list (in
1932 * all other cases including a missing jump target).
1933 * The result is also written in the "next_rule" field of the rule.
1934 * Backward jumps are not allowed, so start looking from the next
1937 * This never returns NULL -- in case we do not have an exact match,
1938 * the next rule is returned. When the ruleset is changed,
1939 * pointers are flushed so we are always correct.
1942 static struct ip_fw
*
1943 lookup_next_rule(struct ip_fw
*me
)
1945 struct ip_fw
*rule
= NULL
;
1948 /* look for action, in case it is a skipto */
1949 cmd
= ACTION_PTR(me
);
1950 if (cmd
->opcode
== O_LOG
)
1952 if ( cmd
->opcode
== O_SKIPTO
)
1953 for (rule
= me
->next
; rule
; rule
= rule
->next
)
1954 if (rule
->rulenum
>= cmd
->arg1
)
1956 if (rule
== NULL
) /* failure or not a skipto */
1958 me
->next_rule
= rule
;
1963 * The main check routine for the firewall.
1965 * All arguments are in args so we can modify them and return them
1966 * back to the caller.
1970 * args->fwa_m (in/out) The packet; we set to NULL when/if we nuke it.
1971 * Starts with the IP header.
1972 * args->fwa_eh (in) Mac header if present, or NULL for layer3 packet.
1973 * args->fwa_oif Outgoing interface, or NULL if packet is incoming.
1974 * The incoming interface is in the mbuf. (in)
1975 * args->fwa_divert_rule (in/out)
1976 * Skip up to the first rule past this rule number;
1977 * upon return, non-zero port number for divert or tee.
1979 * args->fwa_ipfw_rule Pointer to the last matching rule (in/out)
1980 * args->fwa_next_hop Socket we are forwarding to (out).
1981 * args->fwa_id Addresses grabbed from the packet (out)
1985 * IP_FW_PORT_DENY_FLAG the packet must be dropped.
1986 * 0 The packet is to be accepted and routed normally OR
1987 * the packet was denied/rejected and has been dropped;
1988 * in the latter case, *m is equal to NULL upon return.
1989 * port Divert the packet to port, with these caveats:
1991 * - If IP_FW_PORT_TEE_FLAG is set, tee the packet instead
1992 * of diverting it (ie, 'ipfw tee').
1994 * - If IP_FW_PORT_DYNT_FLAG is set, interpret the lower
1995 * 16 bits as a dummynet pipe number instead of diverting
1999 ipfw_chk(struct ip_fw_args
*args
)
2002 * Local variables hold state during the processing of a packet.
2004 * IMPORTANT NOTE: to speed up the processing of rules, there
2005 * are some assumption on the values of the variables, which
2006 * are documented here. Should you change them, please check
2007 * the implementation of the various instructions to make sure
2008 * that they still work.
2010 * args->fwa_eh The MAC header. It is non-null for a layer2
2011 * packet, it is NULL for a layer-3 packet.
2013 * m | args->fwa_m Pointer to the mbuf, as received from the caller.
2014 * It may change if ipfw_chk() does an m_pullup, or if it
2015 * consumes the packet because it calls send_reject().
2016 * XXX This has to change, so that ipfw_chk() never modifies
2017 * or consumes the buffer.
2018 * ip is simply an alias of the value of m, and it is kept
2019 * in sync with it (the packet is supposed to start with
2022 struct mbuf
*m
= args
->fwa_m
;
2023 struct ip
*ip
= mtod(m
, struct ip
*);
2026 * oif | args->fwa_oif If NULL, ipfw_chk has been called on the
2027 * inbound path (ether_input, bdg_forward, ip_input).
2028 * If non-NULL, ipfw_chk has been called on the outbound path
2029 * (ether_output, ip_output).
2031 struct ifnet
*oif
= args
->fwa_oif
;
2033 struct ip_fw
*f
= NULL
; /* matching rule */
2037 * hlen The length of the IPv4 header.
2038 * hlen >0 means we have an IPv4 packet.
2040 u_int hlen
= 0; /* hlen >0 means we have an IP pkt */
2043 * offset The offset of a fragment. offset != 0 means that
2044 * we have a fragment at this offset of an IPv4 packet.
2045 * offset == 0 means that (if this is an IPv4 packet)
2046 * this is the first or only fragment.
2051 * Local copies of addresses. They are only valid if we have
2054 * proto The protocol. Set to 0 for non-ip packets,
2055 * or to the protocol read from the packet otherwise.
2056 * proto != 0 means that we have an IPv4 packet.
2058 * src_port, dst_port port numbers, in HOST format. Only
2059 * valid for TCP and UDP packets.
2061 * src_ip, dst_ip ip addresses, in NETWORK format.
2062 * Only valid for IPv4 packets.
2065 u_int16_t src_port
= 0, dst_port
= 0; /* NOTE: host format */
2066 struct in_addr src_ip
= { 0 } , dst_ip
= { 0 }; /* NOTE: network format */
2069 int dyn_dir
= MATCH_UNKNOWN
;
2070 ipfw_dyn_rule
*q
= NULL
;
2071 struct timeval timenow
;
2073 if (m
->m_flags
& M_SKIP_FIREWALL
|| fw_bypass
) {
2074 return 0; /* accept */
2078 * Clear packet chain if we find one here.
2081 if (m
->m_nextpkt
!= NULL
) {
2082 m_freem_list(m
->m_nextpkt
);
2083 m
->m_nextpkt
= NULL
;
2086 lck_mtx_lock(ipfw_mutex
);
2088 getmicrotime(&timenow
);
2090 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
2091 * MATCH_NONE when checked and not matched (q = NULL),
2092 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
2095 pktlen
= m
->m_pkthdr
.len
;
2096 if (args
->fwa_eh
== NULL
|| /* layer 3 packet */
2097 ( m
->m_pkthdr
.len
>= sizeof(struct ip
) &&
2098 ntohs(args
->fwa_eh
->ether_type
) == ETHERTYPE_IP
))
2099 hlen
= ip
->ip_hl
<< 2;
2102 * Collect parameters into local variables for faster matching.
2104 if (hlen
== 0) { /* do not grab addresses for non-ip pkts */
2105 proto
= args
->fwa_id
.proto
= 0; /* mark f_id invalid */
2106 goto after_ip_checks
;
2109 proto
= args
->fwa_id
.proto
= ip
->ip_p
;
2110 src_ip
= ip
->ip_src
;
2111 dst_ip
= ip
->ip_dst
;
2112 if (args
->fwa_eh
!= NULL
) { /* layer 2 packets are as on the wire */
2113 offset
= ntohs(ip
->ip_off
) & IP_OFFMASK
;
2114 ip_len
= ntohs(ip
->ip_len
);
2116 offset
= ip
->ip_off
& IP_OFFMASK
;
2117 ip_len
= ip
->ip_len
;
2119 pktlen
= ip_len
< pktlen
? ip_len
: pktlen
;
2121 #define PULLUP_TO(len) \
2123 if ((m)->m_len < (len)) { \
2124 args->fwa_m = m = m_pullup(m, (len)); \
2126 goto pullup_failed; \
2127 ip = mtod(m, struct ip *); \
2137 PULLUP_TO(hlen
+ sizeof(struct tcphdr
));
2138 tcp
= L3HDR(struct tcphdr
, ip
);
2139 dst_port
= tcp
->th_dport
;
2140 src_port
= tcp
->th_sport
;
2141 args
->fwa_id
.flags
= tcp
->th_flags
;
2149 PULLUP_TO(hlen
+ sizeof(struct udphdr
));
2150 udp
= L3HDR(struct udphdr
, ip
);
2151 dst_port
= udp
->uh_dport
;
2152 src_port
= udp
->uh_sport
;
2157 PULLUP_TO(hlen
+ 4); /* type, code and checksum. */
2158 args
->fwa_id
.flags
= L3HDR(struct icmp
, ip
)->icmp_type
;
2167 args
->fwa_id
.src_ip
= ntohl(src_ip
.s_addr
);
2168 args
->fwa_id
.dst_ip
= ntohl(dst_ip
.s_addr
);
2169 args
->fwa_id
.src_port
= src_port
= ntohs(src_port
);
2170 args
->fwa_id
.dst_port
= dst_port
= ntohs(dst_port
);
2173 if (args
->fwa_ipfw_rule
) {
2175 * Packet has already been tagged. Look for the next rule
2176 * to restart processing.
2178 * If fw_one_pass != 0 then just accept it.
2179 * XXX should not happen here, but optimized out in
2183 lck_mtx_unlock(ipfw_mutex
);
2187 f
= args
->fwa_ipfw_rule
->next_rule
;
2189 f
= lookup_next_rule(args
->fwa_ipfw_rule
);
2192 * Find the starting rule. It can be either the first
2193 * one, or the one after divert_rule if asked so.
2195 int skipto
= args
->fwa_divert_rule
;
2198 if (args
->fwa_eh
== NULL
&& skipto
!= 0) {
2199 if (skipto
>= IPFW_DEFAULT_RULE
) {
2200 lck_mtx_unlock(ipfw_mutex
);
2201 return(IP_FW_PORT_DENY_FLAG
); /* invalid */
2203 while (f
&& f
->rulenum
<= skipto
)
2205 if (f
== NULL
) { /* drop packet */
2206 lck_mtx_unlock(ipfw_mutex
);
2207 return(IP_FW_PORT_DENY_FLAG
);
2211 args
->fwa_divert_rule
= 0; /* reset to avoid confusion later */
2214 * Now scan the rules, and parse microinstructions for each rule.
2216 for (; f
; f
= f
->next
) {
2219 int skip_or
; /* skip rest of OR block */
2222 if (f
->reserved_1
== IPFW_RULE_INACTIVE
) {
2226 if (set_disable
& (1 << f
->set
) )
2230 for (l
= f
->cmd_len
, cmd
= f
->cmd
; l
> 0 ;
2231 l
-= cmdlen
, cmd
+= cmdlen
) {
2235 * check_body is a jump target used when we find a
2236 * CHECK_STATE, and need to jump to the body of
2241 cmdlen
= F_LEN(cmd
);
2243 * An OR block (insn_1 || .. || insn_n) has the
2244 * F_OR bit set in all but the last instruction.
2245 * The first match will set "skip_or", and cause
2246 * the following instructions to be skipped until
2247 * past the one with the F_OR bit clear.
2249 if (skip_or
) { /* skip this instruction */
2250 if ((cmd
->len
& F_OR
) == 0)
2251 skip_or
= 0; /* next one is good */
2254 match
= 0; /* set to 1 if we succeed */
2256 switch (cmd
->opcode
) {
2258 * The first set of opcodes compares the packet's
2259 * fields with some pattern, setting 'match' if a
2260 * match is found. At the end of the loop there is
2261 * logic to deal with F_NOT and F_OR flags associated
2269 printf("ipfw: opcode %d unimplemented\n",
2278 * We only check offset == 0 && proto != 0,
2279 * as this ensures that we have an IPv4
2280 * packet with the ports info.
2286 struct inpcbinfo
*pi
;
2290 if (proto
== IPPROTO_TCP
) {
2293 } else if (proto
== IPPROTO_UDP
) {
2300 in_pcblookup_hash(pi
,
2301 dst_ip
, htons(dst_port
),
2302 src_ip
, htons(src_port
),
2304 in_pcblookup_hash(pi
,
2305 src_ip
, htons(src_port
),
2306 dst_ip
, htons(dst_port
),
2309 if (pcb
== NULL
|| pcb
->inp_socket
== NULL
)
2311 #if __FreeBSD_version < 500034
2312 #define socheckuid(a,b) (kauth_cred_getuid((a)->so_cred) != (b))
2314 if (cmd
->opcode
== O_UID
) {
2317 (kauth_cred_getuid(pcb
->inp_socket
->so_cred
) == (uid_t
)((ipfw_insn_u32
*)cmd
)->d
[0]);
2319 !socheckuid(pcb
->inp_socket
,
2320 (uid_t
)((ipfw_insn_u32
*)cmd
)->d
[0]);
2326 kauth_cred_ismember_gid(pcb
->inp_socket
->so_cred
,
2327 (gid_t
)((ipfw_insn_u32
*)cmd
)->d
[0], &match
);
2330 /* release reference on pcb */
2331 in_pcb_checkstate(pcb
, WNT_RELEASE
, 0);
2337 match
= iface_match(m
->m_pkthdr
.rcvif
,
2338 (ipfw_insn_if
*)cmd
);
2342 match
= iface_match(oif
, (ipfw_insn_if
*)cmd
);
2346 match
= iface_match(oif
? oif
:
2347 m
->m_pkthdr
.rcvif
, (ipfw_insn_if
*)cmd
);
2351 if (args
->fwa_eh
!= NULL
) { /* have MAC header */
2352 u_int32_t
*want
= (u_int32_t
*)
2353 ((ipfw_insn_mac
*)cmd
)->addr
;
2354 u_int32_t
*mask
= (u_int32_t
*)
2355 ((ipfw_insn_mac
*)cmd
)->mask
;
2356 u_int32_t
*hdr
= (u_int32_t
*)args
->fwa_eh
;
2359 ( want
[0] == (hdr
[0] & mask
[0]) &&
2360 want
[1] == (hdr
[1] & mask
[1]) &&
2361 want
[2] == (hdr
[2] & mask
[2]) );
2366 if (args
->fwa_eh
!= NULL
) {
2368 ntohs(args
->fwa_eh
->ether_type
);
2370 ((ipfw_insn_u16
*)cmd
)->ports
;
2373 for (i
= cmdlen
- 1; !match
&& i
>0;
2375 match
= (t
>=p
[0] && t
<=p
[1]);
2380 match
= (hlen
> 0 && offset
!= 0);
2383 case O_IN
: /* "out" is "not in" */
2384 match
= (oif
== NULL
);
2388 match
= (args
->fwa_eh
!= NULL
);
2393 * We do not allow an arg of 0 so the
2394 * check of "proto" only suffices.
2396 match
= (proto
== cmd
->arg1
);
2400 match
= (hlen
> 0 &&
2401 ((ipfw_insn_ip
*)cmd
)->addr
.s_addr
==
2409 (cmd
->opcode
== O_IP_DST_MASK
) ?
2410 dst_ip
.s_addr
: src_ip
.s_addr
;
2411 uint32_t *p
= ((ipfw_insn_u32
*)cmd
)->d
;
2414 for (; !match
&& i
>0; i
-= 2, p
+= 2)
2415 match
= (p
[0] == (a
& p
[1]));
2423 INADDR_TO_IFP(src_ip
, tif
);
2424 match
= (tif
!= NULL
);
2431 u_int32_t
*d
= (u_int32_t
*)(cmd
+1);
2433 cmd
->opcode
== O_IP_DST_SET
?
2434 args
->fwa_id
.dst_ip
:
2435 args
->fwa_id
.src_ip
;
2439 addr
-= d
[0]; /* subtract base */
2440 match
= (addr
< cmd
->arg1
) &&
2441 ( d
[ 1 + (addr
>>5)] &
2442 (1<<(addr
& 0x1f)) );
2447 match
= (hlen
> 0 &&
2448 ((ipfw_insn_ip
*)cmd
)->addr
.s_addr
==
2456 INADDR_TO_IFP(dst_ip
, tif
);
2457 match
= (tif
!= NULL
);
2464 * offset == 0 && proto != 0 is enough
2465 * to guarantee that we have an IPv4
2466 * packet with port info.
2468 if ((proto
==IPPROTO_UDP
|| proto
==IPPROTO_TCP
)
2471 (cmd
->opcode
== O_IP_SRCPORT
) ?
2472 src_port
: dst_port
;
2474 ((ipfw_insn_u16
*)cmd
)->ports
;
2477 for (i
= cmdlen
- 1; !match
&& i
>0;
2479 match
= (x
>=p
[0] && x
<=p
[1]);
2484 match
= (offset
== 0 && proto
==IPPROTO_ICMP
&&
2485 icmptype_match(ip
, (ipfw_insn_u32
*)cmd
) );
2489 match
= (hlen
> 0 && ipopts_match(ip
, cmd
) );
2493 match
= (hlen
> 0 && cmd
->arg1
== ip
->ip_v
);
2499 if (hlen
> 0) { /* only for IP packets */
2504 if (cmd
->opcode
== O_IPLEN
)
2506 else if (cmd
->opcode
== O_IPTTL
)
2508 else /* must be IPID */
2509 x
= ntohs(ip
->ip_id
);
2511 match
= (cmd
->arg1
== x
);
2514 /* otherwise we have ranges */
2515 p
= ((ipfw_insn_u16
*)cmd
)->ports
;
2517 for (; !match
&& i
>0; i
--, p
+= 2)
2518 match
= (x
>= p
[0] && x
<= p
[1]);
2522 case O_IPPRECEDENCE
:
2523 match
= (hlen
> 0 &&
2524 (cmd
->arg1
== (ip
->ip_tos
& 0xe0)) );
2528 match
= (hlen
> 0 &&
2529 flags_match(cmd
, ip
->ip_tos
));
2533 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
2535 L3HDR(struct tcphdr
,ip
)->th_flags
));
2539 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
2540 tcpopts_match(ip
, cmd
));
2544 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
2545 ((ipfw_insn_u32
*)cmd
)->d
[0] ==
2546 L3HDR(struct tcphdr
,ip
)->th_seq
);
2550 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
2551 ((ipfw_insn_u32
*)cmd
)->d
[0] ==
2552 L3HDR(struct tcphdr
,ip
)->th_ack
);
2556 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
2558 L3HDR(struct tcphdr
,ip
)->th_win
);
2562 /* reject packets which have SYN only */
2563 /* XXX should i also check for TH_ACK ? */
2564 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
2565 (L3HDR(struct tcphdr
,ip
)->th_flags
&
2566 (TH_RST
| TH_ACK
| TH_SYN
)) != TH_SYN
);
2571 ipfw_log(f
, hlen
, args
->fwa_eh
, m
, oif
);
2576 match
= (random()<((ipfw_insn_u32
*)cmd
)->d
[0]);
2580 /* Outgoing packets automatically pass/match */
2581 match
= ((oif
!= NULL
) ||
2582 (m
->m_pkthdr
.rcvif
== NULL
) ||
2583 verify_rev_path(src_ip
, m
->m_pkthdr
.rcvif
));
2588 match
= (m_tag_find(m
,
2589 PACKET_TAG_IPSEC_IN_DONE
, NULL
) != NULL
);
2592 match
= (ipsec_gethist(m
, NULL
) != NULL
);
2594 /* otherwise no match */
2598 * The second set of opcodes represents 'actions',
2599 * i.e. the terminal part of a rule once the packet
2600 * matches all previous patterns.
2601 * Typically there is only one action for each rule,
2602 * and the opcode is stored at the end of the rule
2603 * (but there are exceptions -- see below).
2605 * In general, here we set retval and terminate the
2606 * outer loop (would be a 'break 3' in some language,
2607 * but we need to do a 'goto done').
2610 * O_COUNT and O_SKIPTO actions:
2611 * instead of terminating, we jump to the next rule
2612 * ('goto next_rule', equivalent to a 'break 2'),
2613 * or to the SKIPTO target ('goto again' after
2614 * having set f, cmd and l), respectively.
2616 * O_LIMIT and O_KEEP_STATE: these opcodes are
2617 * not real 'actions', and are stored right
2618 * before the 'action' part of the rule.
2619 * These opcodes try to install an entry in the
2620 * state tables; if successful, we continue with
2621 * the next opcode (match=1; break;), otherwise
2622 * the packet * must be dropped
2623 * ('goto done' after setting retval);
2625 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2626 * cause a lookup of the state table, and a jump
2627 * to the 'action' part of the parent rule
2628 * ('goto check_body') if an entry is found, or
2629 * (CHECK_STATE only) a jump to the next rule if
2630 * the entry is not found ('goto next_rule').
2631 * The result of the lookup is cached to make
2632 * further instances of these opcodes are
2637 if (install_state(f
,
2638 (ipfw_insn_limit
*)cmd
, args
)) {
2639 retval
= IP_FW_PORT_DENY_FLAG
;
2640 goto done
; /* error/limit violation */
2648 * dynamic rules are checked at the first
2649 * keep-state or check-state occurrence,
2650 * with the result being stored in dyn_dir.
2651 * The compiler introduces a PROBE_STATE
2652 * instruction for us when we have a
2653 * KEEP_STATE (because PROBE_STATE needs
2656 if (dyn_dir
== MATCH_UNKNOWN
&&
2657 (q
= lookup_dyn_rule(&args
->fwa_id
,
2658 &dyn_dir
, proto
== IPPROTO_TCP
?
2659 L3HDR(struct tcphdr
, ip
) : NULL
))
2662 * Found dynamic entry, update stats
2663 * and jump to the 'action' part of
2669 cmd
= ACTION_PTR(f
);
2670 l
= f
->cmd_len
- f
->act_ofs
;
2674 * Dynamic entry not found. If CHECK_STATE,
2675 * skip to next rule, if PROBE_STATE just
2676 * ignore and continue with next opcode.
2678 if (cmd
->opcode
== O_CHECK_STATE
)
2684 retval
= 0; /* accept */
2689 args
->fwa_ipfw_rule
= f
; /* report matching rule */
2690 retval
= cmd
->arg1
| IP_FW_PORT_DYNT_FLAG
;
2695 if (args
->fwa_eh
) /* not on layer 2 */
2697 args
->fwa_divert_rule
= f
->rulenum
;
2698 retval
= (cmd
->opcode
== O_DIVERT
) ?
2700 cmd
->arg1
| IP_FW_PORT_TEE_FLAG
;
2705 f
->pcnt
++; /* update stats */
2707 f
->timestamp
= timenow
.tv_sec
;
2708 if (cmd
->opcode
== O_COUNT
)
2711 if (f
->next_rule
== NULL
)
2712 lookup_next_rule(f
);
2718 * Drop the packet and send a reject notice
2719 * if the packet is not ICMP (or is an ICMP
2720 * query), and it is not multicast/broadcast.
2722 if (hlen
> 0 && offset
== 0 &&
2723 (proto
!= IPPROTO_ICMP
||
2724 is_icmp_query(ip
)) &&
2725 !(m
->m_flags
& (M_BCAST
|M_MCAST
)) &&
2726 !IN_MULTICAST(dst_ip
.s_addr
)) {
2727 send_reject(args
, cmd
->arg1
,
2733 retval
= IP_FW_PORT_DENY_FLAG
;
2737 if (args
->fwa_eh
) /* not valid on layer2 pkts */
2739 if (!q
|| dyn_dir
== MATCH_FORWARD
)
2740 args
->fwa_next_hop
=
2741 &((ipfw_insn_sa
*)cmd
)->sa
;
2746 panic("-- unknown opcode %d\n", cmd
->opcode
);
2747 } /* end of switch() on opcodes */
2749 if (cmd
->len
& F_NOT
)
2753 if (cmd
->len
& F_OR
)
2756 if (!(cmd
->len
& F_OR
)) /* not an OR block, */
2757 break; /* try next rule */
2760 } /* end of inner for, scan opcodes */
2762 next_rule
:; /* try next rule */
2764 } /* end of outer for, scan rules */
2765 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
2766 lck_mtx_unlock(ipfw_mutex
);
2767 return(IP_FW_PORT_DENY_FLAG
);
2770 /* Update statistics */
2773 f
->timestamp
= timenow
.tv_sec
;
2774 lck_mtx_unlock(ipfw_mutex
);
2779 printf("ipfw: pullup failed\n");
2780 lck_mtx_unlock(ipfw_mutex
);
2781 return(IP_FW_PORT_DENY_FLAG
);
2785 * When a rule is added/deleted, clear the next_rule pointers in all rules.
2786 * These will be reconstructed on the fly as packets are matched.
2787 * Must be called at splimp().
2790 flush_rule_ptrs(void)
2794 for (rule
= layer3_chain
; rule
; rule
= rule
->next
)
2795 rule
->next_rule
= NULL
;
2799 * When pipes/queues are deleted, clear the "pipe_ptr" pointer to a given
2800 * pipe/queue, or to all of them (match == NULL).
2801 * Must be called at splimp().
2804 flush_pipe_ptrs(struct dn_flow_set
*match
)
2808 for (rule
= layer3_chain
; rule
; rule
= rule
->next
) {
2809 ipfw_insn_pipe
*cmd
= (ipfw_insn_pipe
*)ACTION_PTR(rule
);
2811 if (cmd
->o
.opcode
!= O_PIPE
&& cmd
->o
.opcode
!= O_QUEUE
)
2814 * XXX Use bcmp/bzero to handle pipe_ptr to overcome
2815 * possible alignment problems on 64-bit architectures.
2816 * This code is seldom used so we do not worry too
2817 * much about efficiency.
2819 if (match
== NULL
||
2820 !bcmp(&cmd
->pipe_ptr
, &match
, sizeof(match
)) )
2821 bzero(&cmd
->pipe_ptr
, sizeof(cmd
->pipe_ptr
));
2826 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
2827 * possibly create a rule number and add the rule to the list.
2828 * Update the rule_number in the input struct so the caller knows it as well.
2831 add_rule(struct ip_fw
**head
, struct ip_fw
*input_rule
)
2833 struct ip_fw
*rule
, *f
, *prev
;
2834 int l
= RULESIZE(input_rule
);
2836 if (*head
== NULL
&& input_rule
->rulenum
!= IPFW_DEFAULT_RULE
)
2839 rule
= _MALLOC(l
, M_IPFW
, M_WAIT
| M_ZERO
);
2841 printf("ipfw2: add_rule MALLOC failed\n");
2845 bcopy(input_rule
, rule
, l
);
2848 rule
->next_rule
= NULL
;
2852 rule
->timestamp
= 0;
2854 if (*head
== NULL
) { /* default rule */
2860 * If rulenum is 0, find highest numbered rule before the
2861 * default rule, and add autoinc_step
2863 if (autoinc_step
< 1)
2865 else if (autoinc_step
> 1000)
2866 autoinc_step
= 1000;
2867 if (rule
->rulenum
== 0) {
2869 * locate the highest numbered rule before default
2871 for (f
= *head
; f
; f
= f
->next
) {
2872 if (f
->rulenum
== IPFW_DEFAULT_RULE
)
2874 rule
->rulenum
= f
->rulenum
;
2876 if (rule
->rulenum
< IPFW_DEFAULT_RULE
- autoinc_step
)
2877 rule
->rulenum
+= autoinc_step
;
2878 input_rule
->rulenum
= rule
->rulenum
;
2882 * Now insert the new rule in the right place in the sorted list.
2884 for (prev
= NULL
, f
= *head
; f
; prev
= f
, f
= f
->next
) {
2885 if (f
->rulenum
> rule
->rulenum
) { /* found the location */
2889 } else { /* head insert */
2900 static_len_32
+= RULESIZE32(input_rule
);
2901 static_len_64
+= RULESIZE64(input_rule
);
2902 DEB(printf("ipfw: installed rule %d, static count now %d\n",
2903 rule
->rulenum
, static_count
);)
2908 * Free storage associated with a static rule (including derived
2910 * The caller is in charge of clearing rule pointers to avoid
2911 * dangling pointers.
2912 * @return a pointer to the next entry.
2913 * Arguments are not checked, so they better be correct.
2914 * Must be called at splimp().
2916 static struct ip_fw
*
2917 delete_rule(struct ip_fw
**head
, struct ip_fw
*prev
, struct ip_fw
*rule
)
2920 int l
= RULESIZE(rule
);
2923 remove_dyn_rule(rule
, NULL
/* force removal */);
2930 static_len_32
-= RULESIZE32(rule
);
2931 static_len_64
-= RULESIZE64(rule
);
2934 if (DUMMYNET_LOADED
)
2935 dn_ipfw_rule_delete(rule
);
2936 #endif /* DUMMYNET */
2937 _FREE(rule
, M_IPFW
);
2941 #if DEBUG_INACTIVE_RULES
2943 print_chain(struct ip_fw
**chain
)
2945 struct ip_fw
*rule
= *chain
;
2947 for (; rule
; rule
= rule
->next
) {
2948 ipfw_insn
*cmd
= ACTION_PTR(rule
);
2950 printf("ipfw: rule->rulenum = %d\n", rule
->rulenum
);
2952 if (rule
->reserved_1
== IPFW_RULE_INACTIVE
) {
2953 printf("ipfw: rule->reserved = IPFW_RULE_INACTIVE\n");
2956 switch (cmd
->opcode
) {
2958 printf("ipfw: ACTION: Deny\n");
2962 if (cmd
->arg1
==ICMP_REJECT_RST
)
2963 printf("ipfw: ACTION: Reset\n");
2964 else if (cmd
->arg1
==ICMP_UNREACH_HOST
)
2965 printf("ipfw: ACTION: Reject\n");
2969 printf("ipfw: ACTION: Accept\n");
2972 printf("ipfw: ACTION: Count\n");
2975 printf("ipfw: ACTION: Divert\n");
2978 printf("ipfw: ACTION: Tee\n");
2981 printf("ipfw: ACTION: SkipTo\n");
2984 printf("ipfw: ACTION: Pipe\n");
2987 printf("ipfw: ACTION: Queue\n");
2990 printf("ipfw: ACTION: Forward\n");
2993 printf("ipfw: invalid action! %d\n", cmd
->opcode
);
2997 #endif /* DEBUG_INACTIVE_RULES */
3000 flush_inactive(void *param
)
3002 struct ip_fw
*inactive_rule
= (struct ip_fw
*)param
;
3003 struct ip_fw
*rule
, *prev
;
3005 lck_mtx_lock(ipfw_mutex
);
3007 for (rule
= layer3_chain
, prev
= NULL
; rule
; ) {
3008 if (rule
== inactive_rule
&& rule
->reserved_1
== IPFW_RULE_INACTIVE
) {
3009 struct ip_fw
*n
= rule
;
3012 layer3_chain
= rule
->next
;
3015 prev
->next
= rule
->next
;
3026 #if DEBUG_INACTIVE_RULES
3027 print_chain(&layer3_chain
);
3029 lck_mtx_unlock(ipfw_mutex
);
3033 mark_inactive(struct ip_fw
**prev
, struct ip_fw
**rule
)
3035 int l
= RULESIZE(*rule
);
3037 if ((*rule
)->reserved_1
!= IPFW_RULE_INACTIVE
) {
3038 (*rule
)->reserved_1
= IPFW_RULE_INACTIVE
;
3041 static_len_32
-= RULESIZE32(*rule
);
3042 static_len_64
-= RULESIZE64(*rule
);
3044 timeout(flush_inactive
, *rule
, 30*hz
); /* 30 sec. */
3048 *rule
= (*rule
)->next
;
3052 * Deletes all rules from a chain (except rules in set RESVD_SET
3053 * unless kill_default = 1).
3054 * Must be called at splimp().
3057 free_chain(struct ip_fw
**chain
, int kill_default
)
3059 struct ip_fw
*prev
, *rule
;
3061 flush_rule_ptrs(); /* more efficient to do outside the loop */
3062 for (prev
= NULL
, rule
= *chain
; rule
; )
3063 if (kill_default
|| rule
->set
!= RESVD_SET
) {
3064 ipfw_insn
*cmd
= ACTION_PTR(rule
);
3066 /* skip over forwarding rules so struct isn't
3067 * deleted while pointer is still in use elsewhere
3069 if (cmd
->opcode
== O_FORWARD_IP
) {
3070 mark_inactive(&prev
, &rule
);
3073 rule
= delete_rule(chain
, prev
, rule
);
3083 * Remove all rules with given number, and also do set manipulation.
3084 * Assumes chain != NULL && *chain != NULL.
3086 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
3087 * the next 8 bits are the new set, the top 8 bits are the command:
3089 * 0 delete rules with given number
3090 * 1 delete rules with given set number
3091 * 2 move rules with given number to new set
3092 * 3 move rules with given set number to new set
3093 * 4 swap sets with given numbers
3096 del_entry(struct ip_fw
**chain
, u_int32_t arg
)
3098 struct ip_fw
*prev
= NULL
, *rule
= *chain
;
3099 u_int16_t rulenum
; /* rule or old_set */
3100 u_int8_t cmd
, new_set
;
3102 rulenum
= arg
& 0xffff;
3103 cmd
= (arg
>> 24) & 0xff;
3104 new_set
= (arg
>> 16) & 0xff;
3108 if (new_set
> RESVD_SET
)
3110 if (cmd
== 0 || cmd
== 2) {
3111 if (rulenum
>= IPFW_DEFAULT_RULE
)
3114 if (rulenum
> RESVD_SET
) /* old_set */
3119 case 0: /* delete rules with given number */
3121 * locate first rule to delete
3123 for (; rule
->rulenum
< rulenum
; prev
= rule
, rule
= rule
->next
)
3125 if (rule
->rulenum
!= rulenum
)
3129 * flush pointers outside the loop, then delete all matching
3130 * rules. prev remains the same throughout the cycle.
3133 while (rule
->rulenum
== rulenum
) {
3134 ipfw_insn
*insn
= ACTION_PTR(rule
);
3136 /* keep forwarding rules around so struct isn't
3137 * deleted while pointer is still in use elsewhere
3139 if (insn
->opcode
== O_FORWARD_IP
) {
3140 mark_inactive(&prev
, &rule
);
3143 rule
= delete_rule(chain
, prev
, rule
);
3148 case 1: /* delete all rules with given set number */
3150 while (rule
->rulenum
< IPFW_DEFAULT_RULE
) {
3151 if (rule
->set
== rulenum
) {
3152 ipfw_insn
*insn
= ACTION_PTR(rule
);
3154 /* keep forwarding rules around so struct isn't
3155 * deleted while pointer is still in use elsewhere
3157 if (insn
->opcode
== O_FORWARD_IP
) {
3158 mark_inactive(&prev
, &rule
);
3161 rule
= delete_rule(chain
, prev
, rule
);
3171 case 2: /* move rules with given number to new set */
3172 for (; rule
->rulenum
< IPFW_DEFAULT_RULE
; rule
= rule
->next
)
3173 if (rule
->rulenum
== rulenum
)
3174 rule
->set
= new_set
;
3177 case 3: /* move rules with given set number to new set */
3178 for (; rule
->rulenum
< IPFW_DEFAULT_RULE
; rule
= rule
->next
)
3179 if (rule
->set
== rulenum
)
3180 rule
->set
= new_set
;
3183 case 4: /* swap two sets */
3184 for (; rule
->rulenum
< IPFW_DEFAULT_RULE
; rule
= rule
->next
)
3185 if (rule
->set
== rulenum
)
3186 rule
->set
= new_set
;
3187 else if (rule
->set
== new_set
)
3188 rule
->set
= rulenum
;
3195 * Clear counters for a specific rule.
3198 clear_counters(struct ip_fw
*rule
, int log_only
)
3200 ipfw_insn_log
*l
= (ipfw_insn_log
*)ACTION_PTR(rule
);
3202 if (log_only
== 0) {
3203 rule
->bcnt
= rule
->pcnt
= 0;
3204 rule
->timestamp
= 0;
3206 if (l
->o
.opcode
== O_LOG
)
3207 l
->log_left
= l
->max_log
;
3211 * Reset some or all counters on firewall rules.
3212 * @arg frwl is null to clear all entries, or contains a specific
3214 * @arg log_only is 1 if we only want to reset logs, zero otherwise.
3217 zero_entry(int rulenum
, int log_only
)
3224 for (rule
= layer3_chain
; rule
; rule
= rule
->next
)
3225 clear_counters(rule
, log_only
);
3226 msg
= log_only
? "ipfw: All logging counts reset.\n" :
3227 "ipfw: Accounting cleared.\n";
3231 * We can have multiple rules with the same number, so we
3232 * need to clear them all.
3234 for (rule
= layer3_chain
; rule
; rule
= rule
->next
)
3235 if (rule
->rulenum
== rulenum
) {
3236 while (rule
&& rule
->rulenum
== rulenum
) {
3237 clear_counters(rule
, log_only
);
3243 if (!cleared
) /* we did not find any matching rules */
3245 msg
= log_only
? "ipfw: Entry %d logging count reset.\n" :
3246 "ipfw: Entry %d cleared.\n";
3250 dolog((LOG_AUTHPRIV
| LOG_NOTICE
, msg
, rulenum
));
3256 * Check validity of the structure before insert.
3257 * Fortunately rules are simple, so this mostly need to check rule sizes.
3260 check_ipfw_struct(struct ip_fw
*rule
, int size
)
3266 if (size
< sizeof(*rule
)) {
3267 printf("ipfw: rule too short\n");
3270 /* first, check for valid size */
3273 printf("ipfw: size mismatch (have %d want %d)\n", size
, l
);
3277 * Now go for the individual checks. Very simple ones, basically only
3278 * instruction sizes.
3280 for (l
= rule
->cmd_len
, cmd
= rule
->cmd
;
3281 l
> 0 ; l
-= cmdlen
, cmd
+= cmdlen
) {
3282 cmdlen
= F_LEN(cmd
);
3284 printf("ipfw: opcode %d size truncated\n",
3288 DEB(printf("ipfw: opcode %d\n", cmd
->opcode
);)
3289 switch (cmd
->opcode
) {
3300 case O_IPPRECEDENCE
:
3308 if (cmdlen
!= F_INSN_SIZE(ipfw_insn
))
3314 #endif /* __APPLE__ */
3321 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_u32
))
3326 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_limit
))
3331 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_log
))
3334 /* enforce logging limit */
3336 ((ipfw_insn_log
*)cmd
)->max_log
== 0 && verbose_limit
!= 0) {
3337 ((ipfw_insn_log
*)cmd
)->max_log
= verbose_limit
;
3340 ((ipfw_insn_log
*)cmd
)->log_left
=
3341 ((ipfw_insn_log
*)cmd
)->max_log
;
3347 /* only odd command lengths */
3348 if ( !(cmdlen
& 1) || cmdlen
> 31)
3354 if (cmd
->arg1
== 0 || cmd
->arg1
> 256) {
3355 printf("ipfw: invalid set size %d\n",
3359 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_u32
) +
3365 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_mac
))
3373 if (cmdlen
< 1 || cmdlen
> 31)
3379 case O_IP_DSTPORT
: /* XXX artificial limit, 30 port pairs */
3380 if (cmdlen
< 2 || cmdlen
> 31)
3387 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_if
))
3393 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_pipe
))
3398 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_sa
))
3402 case O_FORWARD_MAC
: /* XXX not implemented yet */
3411 if (cmdlen
!= F_INSN_SIZE(ipfw_insn
))
3415 printf("ipfw: opcode %d, multiple actions"
3422 printf("ipfw: opcode %d, action must be"
3429 printf("ipfw: opcode %d, unknown opcode\n",
3434 if (have_action
== 0) {
3435 printf("ipfw: missing action\n");
3441 printf("ipfw: opcode %d size %d wrong\n",
3442 cmd
->opcode
, cmdlen
);
3448 ipfw_kev_post_msg(u_int32_t event_code
)
3450 struct kev_msg ev_msg
;
3452 bzero(&ev_msg
, sizeof(struct kev_msg
));
3454 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
3455 ev_msg
.kev_class
= KEV_FIREWALL_CLASS
;
3456 ev_msg
.kev_subclass
= KEV_IPFW_SUBCLASS
;
3457 ev_msg
.event_code
= event_code
;
3459 kev_post_msg(&ev_msg
);
3464 * {set|get}sockopt parser.
3467 ipfw_ctl(struct sockopt
*sopt
)
3469 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
3470 u_int32_t api_version
;
3474 size_t rulesize
= RULE_MAXSIZE
;
3475 struct ip_fw
*bp
, *buf
, *rule
;
3478 /* copy of orig sopt to send to ipfw_get_command_and_version() */
3479 struct sockopt tmp_sopt
= *sopt
;
3480 struct timeval timenow
;
3482 getmicrotime(&timenow
);
3485 * Disallow modifications in really-really secure mode, but still allow
3486 * the logging counters to be reset.
3488 if (sopt
->sopt_name
== IP_FW_ADD
||
3489 (sopt
->sopt_dir
== SOPT_SET
&& sopt
->sopt_name
!= IP_FW_RESETLOG
)) {
3490 #if __FreeBSD_version >= 500034
3491 error
= securelevel_ge(sopt
->sopt_td
->td_ucred
, 3);
3494 #else /* FreeBSD 4.x */
3495 if (securelevel
>= 3)
3500 /* first get the command and version, then do conversion as necessary */
3501 error
= ipfw_get_command_and_version(&tmp_sopt
, &command
, &api_version
);
3503 /* error getting the version */
3507 if (proc_is64bit(sopt
->sopt_p
))
3515 * pass up a copy of the current rules. Static rules
3516 * come first (the last of which has number IPFW_DEFAULT_RULE),
3517 * followed by a possibly empty list of dynamic rule.
3518 * The last dynamic rule has NULL in the "next" field.
3520 lck_mtx_lock(ipfw_mutex
);
3523 size
= Get64static_len();
3524 dynrulesize
= sizeof(ipfw_dyn_rule_64
);
3526 size
+= (dyn_count
* dynrulesize
);
3528 size
= Get32static_len();
3529 dynrulesize
= sizeof(ipfw_dyn_rule_32
);
3531 size
+= (dyn_count
* dynrulesize
);
3535 * XXX todo: if the user passes a short length just to know
3536 * how much room is needed, do not bother filling up the
3537 * buffer, just jump to the sooptcopyout.
3539 buf
= _MALLOC(size
, M_TEMP
, M_WAITOK
| M_ZERO
);
3541 lck_mtx_unlock(ipfw_mutex
);
3547 for (rule
= layer3_chain
; rule
; rule
= rule
->next
) {
3549 if (rule
->reserved_1
== IPFW_RULE_INACTIVE
) {
3556 copyto64fw( rule
, (struct ip_fw_64
*)bp
, size
);
3557 bcopy(&set_disable
, &(( (struct ip_fw_64
*)bp
)->next_rule
), sizeof(set_disable
));
3558 /* do not use macro RULESIZE64 since we want RULESIZE for ip_fw_64 */
3559 rulesize_64
= sizeof(struct ip_fw_64
) + ((struct ip_fw_64
*)(bp
))->cmd_len
* 4 - 4;
3560 bp
= (struct ip_fw
*)((char *)bp
+ rulesize_64
);
3564 copyto32fw( rule
, (struct ip_fw_32
*)bp
, size
);
3565 bcopy(&set_disable
, &(( (struct ip_fw_32
*)bp
)->next_rule
), sizeof(set_disable
));
3566 /* do not use macro RULESIZE32 since we want RULESIZE for ip_fw_32 */
3567 rulesize_32
= sizeof(struct ip_fw_32
) + ((struct ip_fw_32
*)(bp
))->cmd_len
* 4 - 4;
3568 bp
= (struct ip_fw
*)((char *)bp
+ rulesize_32
);
3574 char *dst
, *last
= NULL
;
3577 for (i
= 0 ; i
< curr_dyn_buckets
; i
++ )
3578 for ( p
= ipfw_dyn_v
[i
] ; p
!= NULL
;
3579 p
= p
->next
, dst
+= dynrulesize
) {
3581 ipfw_dyn_rule_64
*ipfw_dyn_dst
;
3583 ipfw_dyn_dst
= (ipfw_dyn_rule_64
*)dst
;
3585 * store a non-null value in "next".
3586 * The userland code will interpret a
3587 * NULL here as a marker
3588 * for the last dynamic rule.
3590 ipfw_dyn_dst
->next
= CAST_DOWN_EXPLICIT(user64_addr_t
, dst
);
3591 ipfw_dyn_dst
->rule
= p
->rule
->rulenum
;
3592 ipfw_dyn_dst
->parent
= CAST_DOWN(user64_addr_t
, p
->parent
);
3593 ipfw_dyn_dst
->pcnt
= p
->pcnt
;
3594 ipfw_dyn_dst
->bcnt
= p
->bcnt
;
3595 externalize_flow_id(&ipfw_dyn_dst
->id
, &p
->id
);
3596 ipfw_dyn_dst
->expire
=
3597 TIME_LEQ(p
->expire
, timenow
.tv_sec
) ?
3598 0 : p
->expire
- timenow
.tv_sec
;
3599 ipfw_dyn_dst
->bucket
= p
->bucket
;
3600 ipfw_dyn_dst
->state
= p
->state
;
3601 ipfw_dyn_dst
->ack_fwd
= p
->ack_fwd
;
3602 ipfw_dyn_dst
->ack_rev
= p
->ack_rev
;
3603 ipfw_dyn_dst
->dyn_type
= p
->dyn_type
;
3604 ipfw_dyn_dst
->count
= p
->count
;
3605 last
= (char*)ipfw_dyn_dst
;
3607 ipfw_dyn_rule_32
*ipfw_dyn_dst
;
3609 ipfw_dyn_dst
= (ipfw_dyn_rule_32
*)dst
;
3611 * store a non-null value in "next".
3612 * The userland code will interpret a
3613 * NULL here as a marker
3614 * for the last dynamic rule.
3616 ipfw_dyn_dst
->next
= CAST_DOWN_EXPLICIT(user32_addr_t
, dst
);
3617 ipfw_dyn_dst
->rule
= p
->rule
->rulenum
;
3618 ipfw_dyn_dst
->parent
= CAST_DOWN_EXPLICIT(user32_addr_t
, p
->parent
);
3619 ipfw_dyn_dst
->pcnt
= p
->pcnt
;
3620 ipfw_dyn_dst
->bcnt
= p
->bcnt
;
3621 externalize_flow_id(&ipfw_dyn_dst
->id
, &p
->id
);
3622 ipfw_dyn_dst
->expire
=
3623 TIME_LEQ(p
->expire
, timenow
.tv_sec
) ?
3624 0 : p
->expire
- timenow
.tv_sec
;
3625 ipfw_dyn_dst
->bucket
= p
->bucket
;
3626 ipfw_dyn_dst
->state
= p
->state
;
3627 ipfw_dyn_dst
->ack_fwd
= p
->ack_fwd
;
3628 ipfw_dyn_dst
->ack_rev
= p
->ack_rev
;
3629 ipfw_dyn_dst
->dyn_type
= p
->dyn_type
;
3630 ipfw_dyn_dst
->count
= p
->count
;
3631 last
= (char*)ipfw_dyn_dst
;
3634 /* mark last dynamic rule */
3637 ((ipfw_dyn_rule_64
*)last
)->next
= 0;
3639 ((ipfw_dyn_rule_32
*)last
)->next
= 0;
3642 lck_mtx_unlock(ipfw_mutex
);
3644 /* convert back if necessary and copyout */
3645 if (api_version
== IP_FW_VERSION_0
) {
3647 struct ip_old_fw
*buf2
, *rule_vers0
;
3649 lck_mtx_lock(ipfw_mutex
);
3650 buf2
= _MALLOC(static_count
* sizeof(struct ip_old_fw
), M_TEMP
, M_WAITOK
);
3652 lck_mtx_unlock(ipfw_mutex
);
3660 for (i
= 0; i
< static_count
; i
++) {
3661 /* static rules have different sizes */
3662 int j
= RULESIZE(bp
);
3663 ipfw_convert_from_latest(bp
, rule_vers0
, api_version
, is64user
);
3664 bp
= (struct ip_fw
*)((char *)bp
+ j
);
3665 len
+= sizeof(*rule_vers0
);
3668 lck_mtx_unlock(ipfw_mutex
);
3669 error
= sooptcopyout(sopt
, buf2
, len
);
3670 _FREE(buf2
, M_TEMP
);
3672 } else if (api_version
== IP_FW_VERSION_1
) {
3673 int i
, len
= 0, buf_size
;
3674 struct ip_fw_compat
*buf2
;
3675 size_t ipfwcompsize
;
3676 size_t ipfwdyncompsize
;
3679 lck_mtx_lock(ipfw_mutex
);
3681 ipfwcompsize
= sizeof(struct ip_fw_compat_64
);
3682 ipfwdyncompsize
= sizeof(struct ipfw_dyn_rule_compat_64
);
3684 ipfwcompsize
= sizeof(struct ip_fw_compat_32
);
3685 ipfwdyncompsize
= sizeof(struct ipfw_dyn_rule_compat_32
);
3688 buf_size
= static_count
* ipfwcompsize
+
3689 dyn_count
* ipfwdyncompsize
;
3691 buf2
= _MALLOC(buf_size
, M_TEMP
, M_WAITOK
);
3693 lck_mtx_unlock(ipfw_mutex
);
3698 rule_vers1
= (char*)buf2
;
3700 /* first do static rules */
3701 for (i
= 0; i
< static_count
; i
++) {
3702 /* static rules have different sizes */
3705 ipfw_convert_from_latest(bp
, (void *)rule_vers1
, api_version
, is64user
);
3706 rulesize_64
= sizeof(struct ip_fw_64
) + ((struct ip_fw_64
*)(bp
))->cmd_len
* 4 - 4;
3707 bp
= (struct ip_fw
*)((char *)bp
+ rulesize_64
);
3710 ipfw_convert_from_latest(bp
, (void *)rule_vers1
, api_version
, is64user
);
3711 rulesize_32
= sizeof(struct ip_fw_32
) + ((struct ip_fw_32
*)(bp
))->cmd_len
* 4 - 4;
3712 bp
= (struct ip_fw
*)((char *)bp
+ rulesize_32
);
3714 len
+= ipfwcompsize
;
3715 rule_vers1
+= ipfwcompsize
;
3717 /* now do dynamic rules */
3719 cp_dyn_to_comp_64( (struct ipfw_dyn_rule_compat_64
*)rule_vers1
, &len
);
3721 cp_dyn_to_comp_32( (struct ipfw_dyn_rule_compat_32
*)rule_vers1
, &len
);
3723 lck_mtx_unlock(ipfw_mutex
);
3724 error
= sooptcopyout(sopt
, buf2
, len
);
3725 _FREE(buf2
, M_TEMP
);
3728 error
= sooptcopyout(sopt
, buf
, size
);
3737 * Normally we cannot release the lock on each iteration.
3738 * We could do it here only because we start from the head all
3739 * the times so there is no risk of missing some entries.
3740 * On the other hand, the risk is that we end up with
3741 * a very inconsistent ruleset, so better keep the lock
3742 * around the whole cycle.
3744 * XXX this code can be improved by resetting the head of
3745 * the list to point to the default rule, and then freeing
3746 * the old list without the need for a lock.
3749 lck_mtx_lock(ipfw_mutex
);
3750 free_chain(&layer3_chain
, 0 /* keep default rule */);
3752 #if DEBUG_INACTIVE_RULES
3753 print_chain(&layer3_chain
);
3755 lck_mtx_unlock(ipfw_mutex
);
3760 size_t savedsopt_valsize
=0;
3761 rule
= _MALLOC(RULE_MAXSIZE
, M_TEMP
, M_WAITOK
| M_ZERO
);
3767 if (api_version
!= IP_FW_CURRENT_API_VERSION
) {
3768 error
= ipfw_convert_to_latest(sopt
, rule
, api_version
, is64user
);
3771 savedsopt_valsize
= sopt
->sopt_valsize
; /* it might get modified in sooptcopyin_fw */
3772 error
= sooptcopyin_fw( sopt
, rule
, &rulesize
);
3777 if ((api_version
== IP_FW_VERSION_0
) || (api_version
== IP_FW_VERSION_1
)) {
3778 /* the rule has already been checked so just
3779 * adjust sopt_valsize to match what would be expected.
3781 sopt
->sopt_valsize
= RULESIZE(rule
);
3782 rulesize
= RULESIZE(rule
);
3784 error
= check_ipfw_struct(rule
, rulesize
);
3786 lck_mtx_lock(ipfw_mutex
);
3787 error
= add_rule(&layer3_chain
, rule
);
3788 if (!error
&& fw_bypass
)
3790 lck_mtx_unlock(ipfw_mutex
);
3792 size
= RULESIZE(rule
);
3793 if (!error
&& sopt
->sopt_dir
== SOPT_GET
) {
3794 /* convert back if necessary and copyout */
3795 if (api_version
== IP_FW_VERSION_0
) {
3796 struct ip_old_fw rule_vers0
;
3798 ipfw_convert_from_latest(rule
, &rule_vers0
, api_version
, is64user
);
3799 sopt
->sopt_valsize
= sizeof(struct ip_old_fw
);
3801 error
= sooptcopyout(sopt
, &rule_vers0
, sizeof(struct ip_old_fw
));
3802 } else if (api_version
== IP_FW_VERSION_1
) {
3803 struct ip_fw_compat rule_vers1
;
3804 ipfw_convert_from_latest(rule
, &rule_vers1
, api_version
, is64user
);
3805 sopt
->sopt_valsize
= sizeof(struct ip_fw_compat
);
3807 error
= sooptcopyout(sopt
, &rule_vers1
, sizeof(struct ip_fw_compat
));
3810 userrule
= _MALLOC(savedsopt_valsize
, M_TEMP
, M_WAITOK
);
3811 if ( userrule
== NULL
)
3812 userrule
= (char*)rule
;
3813 if (proc_is64bit(sopt
->sopt_p
)){
3814 copyto64fw( rule
, (struct ip_fw_64
*)userrule
, savedsopt_valsize
);
3817 copyto32fw( rule
, (struct ip_fw_32
*)userrule
, savedsopt_valsize
);
3819 error
= sooptcopyout(sopt
, userrule
, savedsopt_valsize
);
3821 _FREE(userrule
, M_TEMP
);
3827 _FREE(rule
, M_TEMP
);
3833 * IP_FW_DEL is used for deleting single rules or sets,
3834 * and (ab)used to atomically manipulate sets.
3835 * rule->rulenum != 0 indicates single rule delete
3836 * rule->set_masks used to manipulate sets
3837 * rule->set_masks[0] contains info on sets to be
3838 * disabled, swapped, or moved
3839 * rule->set_masks[1] contains sets to be enabled.
3842 /* there is only a simple rule passed in
3843 * (no cmds), so use a temp struct to copy
3845 struct ip_fw temp_rule
;
3849 bzero(&temp_rule
, sizeof(struct ip_fw
));
3850 if (api_version
!= IP_FW_CURRENT_API_VERSION
) {
3851 error
= ipfw_convert_to_latest(sopt
, &temp_rule
, api_version
, is64user
);
3854 error
= sooptcopyin_fw(sopt
, &temp_rule
, 0 );
3858 /* set_masks is used to distinguish between deleting
3859 * single rules or atomically manipulating sets
3861 lck_mtx_lock(ipfw_mutex
);
3863 arg
= temp_rule
.set_masks
[0];
3864 cmd
= (arg
>> 24) & 0xff;
3866 if (temp_rule
.rulenum
) {
3868 error
= del_entry(&layer3_chain
, temp_rule
.rulenum
);
3869 #if DEBUG_INACTIVE_RULES
3870 print_chain(&layer3_chain
);
3874 /* set reassignment - see comment above del_entry() for details */
3875 error
= del_entry(&layer3_chain
, temp_rule
.set_masks
[0]);
3876 #if DEBUG_INACTIVE_RULES
3877 print_chain(&layer3_chain
);
3880 else if (temp_rule
.set_masks
[0] != 0 ||
3881 temp_rule
.set_masks
[1] != 0) {
3882 /* set enable/disable */
3884 (set_disable
| temp_rule
.set_masks
[0]) & ~temp_rule
.set_masks
[1] &
3885 ~(1<<RESVD_SET
); /* set RESVD_SET always enabled */
3888 if (!layer3_chain
->next
)
3890 lck_mtx_unlock(ipfw_mutex
);
3895 case IP_FW_RESETLOG
: /* using rule->rulenum */
3897 /* there is only a simple rule passed in
3898 * (no cmds), so use a temp struct to copy
3900 struct ip_fw temp_rule
;
3902 bzero(&temp_rule
, sizeof(struct ip_fw
));
3904 if (api_version
!= IP_FW_CURRENT_API_VERSION
) {
3905 error
= ipfw_convert_to_latest(sopt
, &temp_rule
, api_version
, is64user
);
3908 if (sopt
->sopt_val
!= 0) {
3909 error
= sooptcopyin_fw( sopt
, &temp_rule
, 0);
3914 lck_mtx_lock(ipfw_mutex
);
3915 error
= zero_entry(temp_rule
.rulenum
, sopt
->sopt_name
== IP_FW_RESETLOG
);
3916 lck_mtx_unlock(ipfw_mutex
);
3921 printf("ipfw: ipfw_ctl invalid option %d\n", sopt
->sopt_name
);
3925 if (error
!= EINVAL
) {
3929 ipfw_kev_post_msg(KEV_IPFW_ADD
);
3933 ipfw_kev_post_msg(KEV_IPFW_DEL
);
3936 case IP_OLD_FW_FLUSH
:
3937 ipfw_kev_post_msg(KEV_IPFW_FLUSH
);
3949 * dummynet needs a reference to the default rule, because rules can be
3950 * deleted while packets hold a reference to them. When this happens,
3951 * dummynet changes the reference to the default rule (it could well be a
3952 * NULL pointer, but this way we do not need to check for the special
3953 * case, plus here he have info on the default behaviour).
3955 struct ip_fw
*ip_fw_default_rule
;
3958 * This procedure is only used to handle keepalives. It is invoked
3959 * every dyn_keepalive_period
3962 ipfw_tick(__unused
void * unused
)
3964 struct mbuf
*m0
, *m
, *mnext
, **mtailp
;
3967 struct timeval timenow
;
3968 static int stealth_cnt
= 0;
3970 if (ipfw_stealth_stats_needs_flush
) {
3972 if (!(stealth_cnt
% IPFW_STEALTH_TIMEOUT_FREQUENCY
)) {
3973 ipfw_stealth_flush_stats();
3977 if (dyn_keepalive
== 0 || ipfw_dyn_v
== NULL
|| dyn_count
== 0)
3980 getmicrotime(&timenow
);
3983 * We make a chain of packets to go out here -- not deferring
3984 * until after we drop the ipfw lock would result
3985 * in a lock order reversal with the normal packet input -> ipfw
3991 lck_mtx_lock(ipfw_mutex
);
3992 for (i
= 0 ; i
< curr_dyn_buckets
; i
++) {
3993 for (q
= ipfw_dyn_v
[i
] ; q
; q
= q
->next
) {
3994 if (q
->dyn_type
== O_LIMIT_PARENT
)
3996 if (q
->id
.proto
!= IPPROTO_TCP
)
3998 if ( (q
->state
& BOTH_SYN
) != BOTH_SYN
)
4000 if (TIME_LEQ( timenow
.tv_sec
+dyn_keepalive_interval
,
4002 continue; /* too early */
4003 if (TIME_LEQ(q
->expire
, timenow
.tv_sec
))
4004 continue; /* too late, rule expired */
4006 *mtailp
= send_pkt(&(q
->id
), q
->ack_rev
- 1, q
->ack_fwd
, TH_SYN
);
4007 if (*mtailp
!= NULL
)
4008 mtailp
= &(*mtailp
)->m_nextpkt
;
4010 *mtailp
= send_pkt(&(q
->id
), q
->ack_fwd
- 1, q
->ack_rev
, 0);
4011 if (*mtailp
!= NULL
)
4012 mtailp
= &(*mtailp
)->m_nextpkt
;
4015 lck_mtx_unlock(ipfw_mutex
);
4017 for (m
= mnext
= m0
; m
!= NULL
; m
= mnext
) {
4018 struct route sro
; /* fake route */
4020 mnext
= m
->m_nextpkt
;
4021 m
->m_nextpkt
= NULL
;
4022 bzero (&sro
, sizeof (sro
));
4023 ip_output(m
, NULL
, &sro
, 0, NULL
, NULL
);
4024 ROUTE_RELEASE(&sro
);
4027 timeout_with_leeway(ipfw_tick
, NULL
, dyn_keepalive_period
*hz
,
4028 DYN_KEEPALIVE_LEEWAY
*hz
);
4034 struct ip_fw default_rule
;
4037 ipfw_mutex_grp_attr
= lck_grp_attr_alloc_init();
4038 ipfw_mutex_grp
= lck_grp_alloc_init("ipfw", ipfw_mutex_grp_attr
);
4039 ipfw_mutex_attr
= lck_attr_alloc_init();
4040 lck_mtx_init(ipfw_mutex
, ipfw_mutex_grp
, ipfw_mutex_attr
);
4042 layer3_chain
= NULL
;
4044 bzero(&default_rule
, sizeof default_rule
);
4046 default_rule
.act_ofs
= 0;
4047 default_rule
.rulenum
= IPFW_DEFAULT_RULE
;
4048 default_rule
.cmd_len
= 1;
4049 default_rule
.set
= RESVD_SET
;
4051 default_rule
.cmd
[0].len
= 1;
4052 default_rule
.cmd
[0].opcode
=
4053 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4058 if (add_rule(&layer3_chain
, &default_rule
)) {
4059 printf("ipfw2: add_rule failed adding default rule\n");
4060 printf("ipfw2 failed initialization!!\n");
4064 ip_fw_default_rule
= layer3_chain
;
4066 #ifdef IPFIREWALL_VERBOSE
4069 #ifdef IPFIREWALL_VERBOSE_LIMIT
4070 verbose_limit
= IPFIREWALL_VERBOSE_LIMIT
;
4074 printf("ipfw2 verbose logging enabled: unlimited logging by default\n");
4076 printf("ipfw2 verbose logging enabled: limited to %d packets/entry by default\n",
4081 ip_fw_chk_ptr
= ipfw_chk
;
4082 ip_fw_ctl_ptr
= ipfw_ctl
;
4084 ipfwstringlen
= strlen( ipfwstring
);
4086 timeout(ipfw_tick
, NULL
, hz
);