2 * Copyright (c) 2004-2013 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/route.h>
87 #include <netinet/in.h>
88 #include <netinet/in_systm.h>
89 #include <netinet/in_var.h>
90 #include <netinet/in_pcb.h>
91 #include <netinet/ip.h>
92 #include <netinet/ip_var.h>
93 #include <netinet/ip_icmp.h>
94 #include <netinet/ip_fw.h>
95 #include <netinet/ip_divert.h>
98 #include <netinet/ip_dummynet.h>
101 #include <netinet/tcp.h>
102 #include <netinet/tcp_timer.h>
103 #include <netinet/tcp_var.h>
104 #include <netinet/tcpip.h>
105 #include <netinet/udp.h>
106 #include <netinet/udp_var.h>
109 #include <netinet6/ipsec.h>
112 #include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
114 #include "ip_fw2_compat.h"
116 #include <sys/kern_event.h>
120 #include <machine/in_cksum.h>
121 */ /* XXX for in_cksum */
124 * XXX This one should go in sys/mbuf.h. It is used to avoid that
125 * a firewall-generated packet loops forever through the firewall.
127 #ifndef M_SKIP_FIREWALL
128 #define M_SKIP_FIREWALL 0x4000
132 * set_disable contains one bit per set value (0..31).
133 * If the bit is set, all rules with the corresponding set
134 * are disabled. Set RESVD_SET(31) is reserved for the default rule
135 * and rules that are not deleted by the flush command,
136 * and CANNOT be disabled.
137 * Rules in set RESVD_SET can only be deleted explicitly.
139 static u_int32_t set_disable
;
142 static int verbose_limit
;
143 extern int fw_bypass
;
145 #define IPFW_RULE_INACTIVE 1
148 * list of rules for layer 3
150 static struct ip_fw
*layer3_chain
;
152 MALLOC_DEFINE(M_IPFW
, "IpFw/IpAcct", "IpFw/IpAcct chain's");
154 static int fw_debug
= 0;
155 static int autoinc_step
= 100; /* bounded to 1..1000 in add_rule() */
157 static void ipfw_kev_post_msg(u_int32_t
);
159 static int Get32static_len(void);
160 static int Get64static_len(void);
164 static int ipfw_sysctl SYSCTL_HANDLER_ARGS
;
166 SYSCTL_NODE(_net_inet_ip
, OID_AUTO
, fw
, CTLFLAG_RW
|CTLFLAG_LOCKED
, 0, "Firewall");
167 SYSCTL_PROC(_net_inet_ip_fw
, OID_AUTO
, enable
,
168 CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
,
169 &fw_enable
, 0, ipfw_sysctl
, "I", "Enable ipfw");
170 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, autoinc_step
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
171 &autoinc_step
, 0, "Rule number autincrement step");
172 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, one_pass
,
173 CTLFLAG_RW
| CTLFLAG_LOCKED
,
175 "Only do a single pass through ipfw when using dummynet(4)");
176 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, debug
,
177 CTLFLAG_RW
| CTLFLAG_LOCKED
,
178 &fw_debug
, 0, "Enable printing of debug ip_fw statements");
179 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, verbose
,
180 CTLFLAG_RW
| CTLFLAG_LOCKED
,
181 &fw_verbose
, 0, "Log matches to ipfw rules");
182 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, verbose_limit
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
183 &verbose_limit
, 0, "Set upper limit of matches of ipfw rules logged");
186 * IP FW Stealth Logging:
188 typedef enum ipfw_stealth_stats_type
{
189 IPFW_STEALTH_STATS_UDP
,
190 IPFW_STEALTH_STATS_TCP
,
191 IPFW_STEALTH_STATS_UDPv6
,
192 IPFW_STEALTH_STATS_TCPv6
,
193 IPFW_STEALTH_STATS_MAX
,
194 } ipfw_stealth_stats_type_t
;
196 #define IPFW_STEALTH_TIMEOUT_SEC 30
198 #define DYN_KEEPALIVE_LEEWAY 15
200 // Piggybagging Stealth stats with ipfw_tick().
201 #define IPFW_STEALTH_TIMEOUT_FREQUENCY (30 / dyn_keepalive_period)
203 static const char* ipfw_stealth_stats_str
[IPFW_STEALTH_STATS_MAX
] = {
204 "UDP", "TCP", "UDP v6", "TCP v6",
207 static uint32_t ipfw_stealth_stats_needs_flush
= FALSE
;
208 static uint32_t ipfw_stealth_stats
[IPFW_STEALTH_STATS_MAX
];
210 static void ipfw_stealth_flush_stats(void);
211 void ipfw_stealth_stats_incr_udp(void);
212 void ipfw_stealth_stats_incr_tcp(void);
213 void ipfw_stealth_stats_incr_udpv6(void);
214 void ipfw_stealth_stats_incr_tcpv6(void);
217 * Description of dynamic rules.
219 * Dynamic rules are stored in lists accessed through a hash table
220 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
221 * be modified through the sysctl variable dyn_buckets which is
222 * updated when the table becomes empty.
224 * XXX currently there is only one list, ipfw_dyn.
226 * When a packet is received, its address fields are first masked
227 * with the mask defined for the rule, then hashed, then matched
228 * against the entries in the corresponding list.
229 * Dynamic rules can be used for different purposes:
231 * + enforcing limits on the number of sessions;
232 * + in-kernel NAT (not implemented yet)
234 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
235 * measured in seconds and depending on the flags.
237 * The total number of dynamic rules is stored in dyn_count.
238 * The max number of dynamic rules is dyn_max. When we reach
239 * the maximum number of rules we do not create anymore. This is
240 * done to avoid consuming too much memory, but also too much
241 * time when searching on each packet (ideally, we should try instead
242 * to put a limit on the length of the list on each bucket...).
244 * Each dynamic rule holds a pointer to the parent ipfw rule so
245 * we know what action to perform. Dynamic rules are removed when
246 * the parent rule is deleted. XXX we should make them survive.
248 * There are some limitations with dynamic rules -- we do not
249 * obey the 'randomized match', and we do not do multiple
250 * passes through the firewall. XXX check the latter!!!
252 static ipfw_dyn_rule
**ipfw_dyn_v
= NULL
;
253 static u_int32_t dyn_buckets
= 256; /* must be power of 2 */
254 static u_int32_t curr_dyn_buckets
= 256; /* must be power of 2 */
257 * Timeouts for various events in handing dynamic rules.
259 static u_int32_t dyn_ack_lifetime
= 300;
260 static u_int32_t dyn_syn_lifetime
= 20;
261 static u_int32_t dyn_fin_lifetime
= 1;
262 static u_int32_t dyn_rst_lifetime
= 1;
263 static u_int32_t dyn_udp_lifetime
= 10;
264 static u_int32_t dyn_short_lifetime
= 5;
267 * Keepalives are sent if dyn_keepalive is set. They are sent every
268 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
269 * seconds of lifetime of a rule.
270 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
271 * than dyn_keepalive_period.
274 static u_int32_t dyn_keepalive_interval
= 25;
275 static u_int32_t dyn_keepalive_period
= 5;
276 static u_int32_t dyn_keepalive
= 1; /* do send keepalives */
278 static u_int32_t static_count
; /* # of static rules */
279 static u_int32_t static_len
; /* size in bytes of static rules */
280 static u_int32_t static_len_32
; /* size in bytes of static rules for 32 bit client */
281 static u_int32_t static_len_64
; /* size in bytes of static rules for 64 bit client */
282 static u_int32_t dyn_count
; /* # of dynamic rules */
283 static u_int32_t dyn_max
= 4096; /* max # of dynamic rules */
285 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_buckets
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
286 &dyn_buckets
, 0, "Number of dyn. buckets");
287 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, curr_dyn_buckets
, CTLFLAG_RD
| CTLFLAG_LOCKED
,
288 &curr_dyn_buckets
, 0, "Current Number of dyn. buckets");
289 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_count
, CTLFLAG_RD
| CTLFLAG_LOCKED
,
290 &dyn_count
, 0, "Number of dyn. rules");
291 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_max
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
292 &dyn_max
, 0, "Max number of dyn. rules");
293 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, static_count
, CTLFLAG_RD
| CTLFLAG_LOCKED
,
294 &static_count
, 0, "Number of static rules");
295 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_ack_lifetime
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
296 &dyn_ack_lifetime
, 0, "Lifetime of dyn. rules for acks");
297 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_syn_lifetime
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
298 &dyn_syn_lifetime
, 0, "Lifetime of dyn. rules for syn");
299 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_fin_lifetime
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
300 &dyn_fin_lifetime
, 0, "Lifetime of dyn. rules for fin");
301 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_rst_lifetime
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
302 &dyn_rst_lifetime
, 0, "Lifetime of dyn. rules for rst");
303 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_udp_lifetime
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
304 &dyn_udp_lifetime
, 0, "Lifetime of dyn. rules for UDP");
305 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_short_lifetime
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
306 &dyn_short_lifetime
, 0, "Lifetime of dyn. rules for other situations");
307 SYSCTL_INT(_net_inet_ip_fw
, OID_AUTO
, dyn_keepalive
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
308 &dyn_keepalive
, 0, "Enable keepalives for dyn. rules");
312 ipfw_sysctl SYSCTL_HANDLER_ARGS
314 #pragma unused(arg1, arg2)
317 error
= sysctl_handle_int(oidp
, oidp
->oid_arg1
, oidp
->oid_arg2
, req
);
318 if (error
|| !req
->newptr
)
321 ipfw_kev_post_msg(KEV_IPFW_ENABLE
);
326 #endif /* SYSCTL_NODE */
329 static ip_fw_chk_t ipfw_chk
;
332 lck_grp_t
*ipfw_mutex_grp
;
333 lck_grp_attr_t
*ipfw_mutex_grp_attr
;
334 lck_attr_t
*ipfw_mutex_attr
;
335 decl_lck_mtx_data(,ipfw_mutex_data
);
336 lck_mtx_t
*ipfw_mutex
= &ipfw_mutex_data
;
338 extern void ipfwsyslog( int level
, const char *format
,...);
340 #define KEV_LOG_SUBCLASS 10
341 #define IPFWLOGEVENT 0
343 #define ipfwstring "ipfw:"
344 static size_t ipfwstringlen
;
346 #define dolog( a ) { \
347 if ( fw_verbose == 2 ) /* Apple logging, log to ipfw.log */ \
352 #define RULESIZE64(rule) (sizeof(struct ip_fw_64) + \
353 ((struct ip_fw *)(rule))->cmd_len * 4 - 4)
355 #define RULESIZE32(rule) (sizeof(struct ip_fw_32) + \
356 ((struct ip_fw *)(rule))->cmd_len * 4 - 4)
358 void ipfwsyslog( int level
, const char *format
,...)
362 struct kev_msg ev_msg
;
364 char msgBuf
[msgsize
];
369 bzero(msgBuf
, msgsize
);
370 bzero(&ev_msg
, sizeof(struct kev_msg
));
371 va_start( ap
, format
);
372 loglen
= vsnprintf(msgBuf
, msgsize
, format
, ap
);
375 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
376 ev_msg
.kev_class
= KEV_NETWORK_CLASS
;
377 ev_msg
.kev_subclass
= KEV_LOG_SUBCLASS
;
378 ev_msg
.event_code
= IPFWLOGEVENT
;
380 /* get rid of the trailing \n */
381 if (loglen
< msgsize
)
386 pri
= LOG_PRI(level
);
388 /* remove "ipfw:" prefix if logging to ipfw log */
389 if ( !(strncmp( ipfwstring
, msgBuf
, ipfwstringlen
))){
390 dptr
= msgBuf
+ipfwstringlen
;
393 ev_msg
.dv
[0].data_ptr
= &pri
;
394 ev_msg
.dv
[0].data_length
= 1;
395 ev_msg
.dv
[1].data_ptr
= dptr
;
396 ev_msg
.dv
[1].data_length
= 100; /* bug in kern_post_msg, it can't handle size > 256-msghdr */
397 ev_msg
.dv
[2].data_length
= 0;
399 kev_post_msg(&ev_msg
);
402 static inline void ipfw_stealth_stats_incr(uint32_t type
)
404 if (type
>= IPFW_STEALTH_STATS_MAX
)
407 ipfw_stealth_stats
[type
]++;
409 if (!ipfw_stealth_stats_needs_flush
) {
410 ipfw_stealth_stats_needs_flush
= TRUE
;
414 void ipfw_stealth_stats_incr_udp(void)
416 ipfw_stealth_stats_incr(IPFW_STEALTH_STATS_UDP
);
419 void ipfw_stealth_stats_incr_tcp(void)
421 ipfw_stealth_stats_incr(IPFW_STEALTH_STATS_TCP
);
424 void ipfw_stealth_stats_incr_udpv6(void)
426 ipfw_stealth_stats_incr(IPFW_STEALTH_STATS_UDPv6
);
429 void ipfw_stealth_stats_incr_tcpv6(void)
431 ipfw_stealth_stats_incr(IPFW_STEALTH_STATS_TCPv6
);
434 static void ipfw_stealth_flush_stats(void)
438 for (i
= 0; i
< IPFW_STEALTH_STATS_MAX
; i
++) {
439 if (ipfw_stealth_stats
[i
]) {
440 ipfwsyslog (LOG_INFO
, "Stealth Mode connection attempt to %s %d times",
441 ipfw_stealth_stats_str
[i
], ipfw_stealth_stats
[i
]);
442 ipfw_stealth_stats
[i
] = 0;
445 ipfw_stealth_stats_needs_flush
= FALSE
;
449 * This macro maps an ip pointer into a layer3 header pointer of type T
451 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
454 icmptype_match(struct ip
*ip
, ipfw_insn_u32
*cmd
)
456 int type
= L3HDR(struct icmp
,ip
)->icmp_type
;
458 return (type
<= ICMP_MAXTYPE
&& (cmd
->d
[0] & (1<<type
)) );
461 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
462 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
465 is_icmp_query(struct ip
*ip
)
467 int type
= L3HDR(struct icmp
, ip
)->icmp_type
;
468 return (type
<= ICMP_MAXTYPE
&& (TT
& (1<<type
)) );
476 int len
= static_len_32
;
480 for (rule
= layer3_chain
; rule
; rule
= rule
->next
) {
481 if (rule
->reserved_1
== IPFW_RULE_INACTIVE
) {
484 if ( rule
->act_ofs
){
485 useraction
= (char*)ACTION_PTR( rule
);
486 if ( ((ipfw_insn
*)useraction
)->opcode
== O_QUEUE
|| ((ipfw_insn
*)useraction
)->opcode
== O_PIPE
){
487 diff
= sizeof(ipfw_insn_pipe
) - sizeof(ipfw_insn_pipe_32
);
500 int len
= static_len_64
;
504 for (rule
= layer3_chain
; rule
; rule
= rule
->next
) {
505 if (rule
->reserved_1
== IPFW_RULE_INACTIVE
) {
508 if ( rule
->act_ofs
){
509 useraction
= (char *)ACTION_PTR( rule
);
510 if ( ((ipfw_insn
*)useraction
)->opcode
== O_QUEUE
|| ((ipfw_insn
*)useraction
)->opcode
== O_PIPE
){
511 diff
= sizeof(ipfw_insn_pipe_64
) - sizeof(ipfw_insn_pipe
);
521 copyto32fw_insn( struct ip_fw_32
*fw32
, struct ip_fw
*user_ip_fw
, int cmdsize
)
530 end
= ((char*)user_ip_fw
->cmd
) + cmdsize
;
531 useraction
= (char*)ACTION_PTR( user_ip_fw
);
532 fw32action
= (char*)fw32
->cmd
+ (user_ip_fw
->act_ofs
* sizeof(uint32_t));
533 if ( ( justcmdsize
= ( fw32action
- (char*)fw32
->cmd
)))
534 bcopy( user_ip_fw
->cmd
, fw32
->cmd
, justcmdsize
);
535 while ( useraction
< end
){
536 if ( ((ipfw_insn
*)useraction
)->opcode
== O_QUEUE
|| ((ipfw_insn
*)useraction
)->opcode
== O_PIPE
){
537 actioncopysize
= sizeof(ipfw_insn_pipe_32
);
538 ((ipfw_insn
*)fw32action
)->opcode
= ((ipfw_insn
*)useraction
)->opcode
;
539 ((ipfw_insn
*)fw32action
)->arg1
= ((ipfw_insn
*)useraction
)->arg1
;
540 ((ipfw_insn
*)fw32action
)->len
= F_INSN_SIZE(ipfw_insn_pipe_32
);
541 diff
= ((ipfw_insn
*)useraction
)->len
- ((ipfw_insn
*)fw32action
)->len
;
543 fw32
->cmd_len
-= diff
;
546 actioncopysize
= (F_LEN((ipfw_insn
*)useraction
) ? (F_LEN((ipfw_insn
*)useraction
)) : 1 ) * sizeof(uint32_t);
547 bcopy( useraction
, fw32action
, actioncopysize
);
549 useraction
+= (F_LEN((ipfw_insn
*)useraction
) ? (F_LEN((ipfw_insn
*)useraction
)) : 1 ) * sizeof(uint32_t);
550 fw32action
+= actioncopysize
;
555 copyto64fw_insn( struct ip_fw_64
*fw64
, struct ip_fw
*user_ip_fw
, int cmdsize
)
564 end
= ((char *)user_ip_fw
->cmd
) + cmdsize
;
565 useraction
= (char*)ACTION_PTR( user_ip_fw
);
566 if ( (justcmdsize
= (useraction
- (char*)user_ip_fw
->cmd
)))
567 bcopy( user_ip_fw
->cmd
, fw64
->cmd
, justcmdsize
);
568 fw64action
= (char*)fw64
->cmd
+ justcmdsize
;
569 while ( useraction
< end
){
570 if ( ((ipfw_insn
*)user_ip_fw
)->opcode
== O_QUEUE
|| ((ipfw_insn
*)user_ip_fw
)->opcode
== O_PIPE
){
571 actioncopysize
= sizeof(ipfw_insn_pipe_64
);
572 ((ipfw_insn
*)fw64action
)->opcode
= ((ipfw_insn
*)useraction
)->opcode
;
573 ((ipfw_insn
*)fw64action
)->arg1
= ((ipfw_insn
*)useraction
)->arg1
;
574 ((ipfw_insn
*)fw64action
)->len
= F_INSN_SIZE(ipfw_insn_pipe_64
);
575 diff
= ((ipfw_insn
*)fw64action
)->len
- ((ipfw_insn
*)useraction
)->len
;
577 fw64
->cmd_len
+= diff
;
580 actioncopysize
= (F_LEN((ipfw_insn
*)useraction
) ? (F_LEN((ipfw_insn
*)useraction
)) : 1 ) * sizeof(uint32_t);
581 bcopy( useraction
, fw64action
, actioncopysize
);
583 useraction
+= (F_LEN((ipfw_insn
*)useraction
) ? (F_LEN((ipfw_insn
*)useraction
)) : 1 ) * sizeof(uint32_t);
584 fw64action
+= actioncopysize
;
589 copyto32fw( struct ip_fw
*user_ip_fw
, struct ip_fw_32
*fw32
, __unused
size_t copysize
)
591 size_t rulesize
, cmdsize
;
593 fw32
->version
= user_ip_fw
->version
;
594 fw32
->context
= CAST_DOWN_EXPLICIT( user32_addr_t
, user_ip_fw
->context
);
595 fw32
->next
= CAST_DOWN_EXPLICIT(user32_addr_t
, user_ip_fw
->next
);
596 fw32
->next_rule
= CAST_DOWN_EXPLICIT(user32_addr_t
, user_ip_fw
->next_rule
);
597 fw32
->act_ofs
= user_ip_fw
->act_ofs
;
598 fw32
->cmd_len
= user_ip_fw
->cmd_len
;
599 fw32
->rulenum
= user_ip_fw
->rulenum
;
600 fw32
->set
= user_ip_fw
->set
;
601 fw32
->set_masks
[0] = user_ip_fw
->set_masks
[0];
602 fw32
->set_masks
[1] = user_ip_fw
->set_masks
[1];
603 fw32
->pcnt
= user_ip_fw
->pcnt
;
604 fw32
->bcnt
= user_ip_fw
->bcnt
;
605 fw32
->timestamp
= user_ip_fw
->timestamp
;
606 fw32
->reserved_1
= user_ip_fw
->reserved_1
;
607 fw32
->reserved_2
= user_ip_fw
->reserved_2
;
608 rulesize
= sizeof(struct ip_fw_32
) + (user_ip_fw
->cmd_len
* sizeof(ipfw_insn
) - 4);
609 cmdsize
= user_ip_fw
->cmd_len
* sizeof(u_int32_t
);
610 copyto32fw_insn( fw32
, user_ip_fw
, cmdsize
);
614 copyto64fw( struct ip_fw
*user_ip_fw
, struct ip_fw_64
*fw64
, size_t copysize
)
616 size_t rulesize
, cmdsize
;
618 fw64
->version
= user_ip_fw
->version
;
619 fw64
->context
= CAST_DOWN_EXPLICIT(__uint64_t
, user_ip_fw
->context
);
620 fw64
->next
= CAST_DOWN_EXPLICIT(user64_addr_t
, user_ip_fw
->next
);
621 fw64
->next_rule
= CAST_DOWN_EXPLICIT(user64_addr_t
, user_ip_fw
->next_rule
);
622 fw64
->act_ofs
= user_ip_fw
->act_ofs
;
623 fw64
->cmd_len
= user_ip_fw
->cmd_len
;
624 fw64
->rulenum
= user_ip_fw
->rulenum
;
625 fw64
->set
= user_ip_fw
->set
;
626 fw64
->set_masks
[0] = user_ip_fw
->set_masks
[0];
627 fw64
->set_masks
[1] = user_ip_fw
->set_masks
[1];
628 fw64
->pcnt
= user_ip_fw
->pcnt
;
629 fw64
->bcnt
= user_ip_fw
->bcnt
;
630 fw64
->timestamp
= user_ip_fw
->timestamp
;
631 fw64
->reserved_1
= user_ip_fw
->reserved_1
;
632 fw64
->reserved_2
= user_ip_fw
->reserved_2
;
633 rulesize
= sizeof(struct ip_fw_64
) + (user_ip_fw
->cmd_len
* sizeof(ipfw_insn
) - 4);
634 if (rulesize
> copysize
)
635 cmdsize
= copysize
- sizeof(struct ip_fw_64
) + 4;
637 cmdsize
= user_ip_fw
->cmd_len
* sizeof(u_int32_t
);
638 copyto64fw_insn( fw64
, user_ip_fw
, cmdsize
);
642 copyfrom32fw_insn( struct ip_fw_32
*fw32
, struct ip_fw
*user_ip_fw
, int cmdsize
)
651 end
= ((char*)fw32
->cmd
) + cmdsize
;
652 fw32action
= (char*)ACTION_PTR( fw32
);
653 if ((justcmdsize
= (fw32action
- (char*)fw32
->cmd
)))
654 bcopy( fw32
->cmd
, user_ip_fw
->cmd
, justcmdsize
);
655 useraction
= (char*)user_ip_fw
->cmd
+ justcmdsize
;
656 while ( fw32action
< end
){
657 if ( ((ipfw_insn
*)fw32action
)->opcode
== O_QUEUE
|| ((ipfw_insn
*)fw32action
)->opcode
== O_PIPE
){
658 actioncopysize
= sizeof(ipfw_insn_pipe
);
659 ((ipfw_insn
*)useraction
)->opcode
= ((ipfw_insn
*)fw32action
)->opcode
;
660 ((ipfw_insn
*)useraction
)->arg1
= ((ipfw_insn
*)fw32action
)->arg1
;
661 ((ipfw_insn
*)useraction
)->len
= F_INSN_SIZE(ipfw_insn_pipe
);
662 diff
= ((ipfw_insn
*)useraction
)->len
- ((ipfw_insn
*)fw32action
)->len
;
664 /* readjust the cmd_len */
665 user_ip_fw
->cmd_len
+= diff
;
668 actioncopysize
= (F_LEN((ipfw_insn
*)fw32action
) ? (F_LEN((ipfw_insn
*)fw32action
)) : 1 ) * sizeof(uint32_t);
669 bcopy( fw32action
, useraction
, actioncopysize
);
671 fw32action
+= (F_LEN((ipfw_insn
*)fw32action
) ? (F_LEN((ipfw_insn
*)fw32action
)) : 1 ) * sizeof(uint32_t);
672 useraction
+= actioncopysize
;
675 return( useraction
- (char*)user_ip_fw
->cmd
);
679 copyfrom64fw_insn( struct ip_fw_64
*fw64
, struct ip_fw
*user_ip_fw
, int cmdsize
)
688 end
= ((char *)fw64
->cmd
) + cmdsize
;
689 fw64action
= (char*)ACTION_PTR( fw64
);
690 if ( (justcmdsize
= (fw64action
- (char*)fw64
->cmd
)))
691 bcopy( fw64
->cmd
, user_ip_fw
->cmd
, justcmdsize
);
692 useraction
= (char*)user_ip_fw
->cmd
+ justcmdsize
;
693 while ( fw64action
< end
){
694 if ( ((ipfw_insn
*)fw64action
)->opcode
== O_QUEUE
|| ((ipfw_insn
*)fw64action
)->opcode
== O_PIPE
){
695 actioncopysize
= sizeof(ipfw_insn_pipe
);
696 ((ipfw_insn
*)useraction
)->opcode
= ((ipfw_insn
*)fw64action
)->opcode
;
697 ((ipfw_insn
*)useraction
)->arg1
= ((ipfw_insn
*)fw64action
)->arg1
;
698 ((ipfw_insn
*)useraction
)->len
= F_INSN_SIZE(ipfw_insn_pipe
);
699 diff
= ((ipfw_insn
*)fw64action
)->len
- ((ipfw_insn
*)useraction
)->len
;
701 /* readjust the cmd_len */
702 user_ip_fw
->cmd_len
-= diff
;
705 actioncopysize
= (F_LEN((ipfw_insn
*)fw64action
) ? (F_LEN((ipfw_insn
*)fw64action
)) : 1 ) * sizeof(uint32_t);
706 bcopy( fw64action
, useraction
, actioncopysize
);
708 fw64action
+= (F_LEN((ipfw_insn
*)fw64action
) ? (F_LEN((ipfw_insn
*)fw64action
)) : 1 ) * sizeof(uint32_t);
709 useraction
+= actioncopysize
;
711 return( useraction
- (char*)user_ip_fw
->cmd
);
715 copyfrom32fw( struct ip_fw_32
*fw32
, struct ip_fw
*user_ip_fw
, size_t copysize
)
717 size_t rulesize
, cmdsize
;
719 user_ip_fw
->version
= fw32
->version
;
720 user_ip_fw
->context
= CAST_DOWN(void *, fw32
->context
);
721 user_ip_fw
->next
= CAST_DOWN(struct ip_fw
*, fw32
->next
);
722 user_ip_fw
->next_rule
= CAST_DOWN_EXPLICIT(struct ip_fw
*, fw32
->next_rule
);
723 user_ip_fw
->act_ofs
= fw32
->act_ofs
;
724 user_ip_fw
->cmd_len
= fw32
->cmd_len
;
725 user_ip_fw
->rulenum
= fw32
->rulenum
;
726 user_ip_fw
->set
= fw32
->set
;
727 user_ip_fw
->set_masks
[0] = fw32
->set_masks
[0];
728 user_ip_fw
->set_masks
[1] = fw32
->set_masks
[1];
729 user_ip_fw
->pcnt
= fw32
->pcnt
;
730 user_ip_fw
->bcnt
= fw32
->bcnt
;
731 user_ip_fw
->timestamp
= fw32
->timestamp
;
732 user_ip_fw
->reserved_1
= fw32
->reserved_1
;
733 user_ip_fw
->reserved_2
= fw32
->reserved_2
;
734 rulesize
= sizeof(struct ip_fw_32
) + (fw32
->cmd_len
* sizeof(ipfw_insn
) - 4);
735 if ( rulesize
> copysize
)
736 cmdsize
= copysize
- sizeof(struct ip_fw_32
)-4;
738 cmdsize
= fw32
->cmd_len
* sizeof(ipfw_insn
);
739 cmdsize
= copyfrom32fw_insn( fw32
, user_ip_fw
, cmdsize
);
740 return( sizeof(struct ip_fw
) + cmdsize
- 4);
744 copyfrom64fw( struct ip_fw_64
*fw64
, struct ip_fw
*user_ip_fw
, size_t copysize
)
746 size_t rulesize
, cmdsize
;
748 user_ip_fw
->version
= fw64
->version
;
749 user_ip_fw
->context
= CAST_DOWN_EXPLICIT( void *, fw64
->context
);
750 user_ip_fw
->next
= CAST_DOWN_EXPLICIT(struct ip_fw
*, fw64
->next
);
751 user_ip_fw
->next_rule
= CAST_DOWN_EXPLICIT(struct ip_fw
*, fw64
->next_rule
);
752 user_ip_fw
->act_ofs
= fw64
->act_ofs
;
753 user_ip_fw
->cmd_len
= fw64
->cmd_len
;
754 user_ip_fw
->rulenum
= fw64
->rulenum
;
755 user_ip_fw
->set
= fw64
->set
;
756 user_ip_fw
->set_masks
[0] = fw64
->set_masks
[0];
757 user_ip_fw
->set_masks
[1] = fw64
->set_masks
[1];
758 user_ip_fw
->pcnt
= fw64
->pcnt
;
759 user_ip_fw
->bcnt
= fw64
->bcnt
;
760 user_ip_fw
->timestamp
= fw64
->timestamp
;
761 user_ip_fw
->reserved_1
= fw64
->reserved_1
;
762 user_ip_fw
->reserved_2
= fw64
->reserved_2
;
763 //bcopy( fw64->cmd, user_ip_fw->cmd, fw64->cmd_len * sizeof(ipfw_insn));
764 rulesize
= sizeof(struct ip_fw_64
) + (fw64
->cmd_len
* sizeof(ipfw_insn
) - 4);
765 if ( rulesize
> copysize
)
766 cmdsize
= copysize
- sizeof(struct ip_fw_64
)-4;
768 cmdsize
= fw64
->cmd_len
* sizeof(ipfw_insn
);
769 cmdsize
= copyfrom64fw_insn( fw64
, user_ip_fw
, cmdsize
);
770 return( sizeof(struct ip_fw
) + cmdsize
- 4);
774 externalize_flow_id(struct ipfw_flow_id
*dst
, struct ip_flow_id
*src
);
776 externalize_flow_id(struct ipfw_flow_id
*dst
, struct ip_flow_id
*src
)
778 dst
->dst_ip
= src
->dst_ip
;
779 dst
->src_ip
= src
->src_ip
;
780 dst
->dst_port
= src
->dst_port
;
781 dst
->src_port
= src
->src_port
;
782 dst
->proto
= src
->proto
;
783 dst
->flags
= src
->flags
;
787 void cp_dyn_to_comp_32( struct ipfw_dyn_rule_compat_32
*dyn_rule_vers1
, int *len
)
789 struct ipfw_dyn_rule_compat_32
*dyn_last
=NULL
;
794 for (i
= 0; i
< curr_dyn_buckets
; i
++) {
795 for ( p
= ipfw_dyn_v
[i
] ; p
!= NULL
; p
= p
->next
) {
796 dyn_rule_vers1
->chain
= (user32_addr_t
)(p
->rule
->rulenum
);
797 externalize_flow_id(&dyn_rule_vers1
->id
, &p
->id
);
798 externalize_flow_id(&dyn_rule_vers1
->mask
, &p
->id
);
799 dyn_rule_vers1
->type
= p
->dyn_type
;
800 dyn_rule_vers1
->expire
= p
->expire
;
801 dyn_rule_vers1
->pcnt
= p
->pcnt
;
802 dyn_rule_vers1
->bcnt
= p
->bcnt
;
803 dyn_rule_vers1
->bucket
= p
->bucket
;
804 dyn_rule_vers1
->state
= p
->state
;
806 dyn_rule_vers1
->next
= CAST_DOWN_EXPLICIT( user32_addr_t
, p
->next
);
807 dyn_last
= dyn_rule_vers1
;
809 *len
+= sizeof(*dyn_rule_vers1
);
814 if (dyn_last
!= NULL
) {
815 dyn_last
->next
= ((user32_addr_t
)0);
822 void cp_dyn_to_comp_64( struct ipfw_dyn_rule_compat_64
*dyn_rule_vers1
, int *len
)
824 struct ipfw_dyn_rule_compat_64
*dyn_last
=NULL
;
829 for (i
= 0; i
< curr_dyn_buckets
; i
++) {
830 for ( p
= ipfw_dyn_v
[i
] ; p
!= NULL
; p
= p
->next
) {
831 dyn_rule_vers1
->chain
= (user64_addr_t
) p
->rule
->rulenum
;
832 externalize_flow_id(&dyn_rule_vers1
->id
, &p
->id
);
833 externalize_flow_id(&dyn_rule_vers1
->mask
, &p
->id
);
834 dyn_rule_vers1
->type
= p
->dyn_type
;
835 dyn_rule_vers1
->expire
= p
->expire
;
836 dyn_rule_vers1
->pcnt
= p
->pcnt
;
837 dyn_rule_vers1
->bcnt
= p
->bcnt
;
838 dyn_rule_vers1
->bucket
= p
->bucket
;
839 dyn_rule_vers1
->state
= p
->state
;
841 dyn_rule_vers1
->next
= CAST_DOWN(user64_addr_t
, p
->next
);
842 dyn_last
= dyn_rule_vers1
;
844 *len
+= sizeof(*dyn_rule_vers1
);
849 if (dyn_last
!= NULL
) {
850 dyn_last
->next
= CAST_DOWN(user64_addr_t
, NULL
);
856 sooptcopyin_fw( struct sockopt
*sopt
, struct ip_fw
*user_ip_fw
, size_t *size
)
858 size_t valsize
, copyinsize
= 0;
861 valsize
= sopt
->sopt_valsize
;
864 if (proc_is64bit(sopt
->sopt_p
)) {
865 struct ip_fw_64
*fw64
=NULL
;
867 if ( valsize
< sizeof(struct ip_fw_64
) ) {
871 copyinsize
= sizeof(struct ip_fw_64
);
872 if ( valsize
> copyinsize
)
873 sopt
->sopt_valsize
= valsize
= copyinsize
;
875 if ( sopt
->sopt_p
!= 0) {
876 fw64
= _MALLOC(copyinsize
, M_TEMP
, M_WAITOK
);
879 if ((error
= copyin(sopt
->sopt_val
, fw64
, valsize
)) != 0){
885 bcopy(CAST_DOWN(caddr_t
, sopt
->sopt_val
), fw64
, valsize
);
887 valsize
= copyfrom64fw( fw64
, user_ip_fw
, valsize
);
888 _FREE( fw64
, M_TEMP
);
890 struct ip_fw_32
*fw32
=NULL
;
892 if ( valsize
< sizeof(struct ip_fw_32
) ) {
896 copyinsize
= sizeof(struct ip_fw_32
);
897 if ( valsize
> copyinsize
)
898 sopt
->sopt_valsize
= valsize
= copyinsize
;
900 if ( sopt
->sopt_p
!= 0) {
901 fw32
= _MALLOC(copyinsize
, M_TEMP
, M_WAITOK
);
904 if ( (error
= copyin(sopt
->sopt_val
, fw32
, valsize
)) != 0){
905 _FREE( fw32
, M_TEMP
);
910 bcopy(CAST_DOWN(caddr_t
, sopt
->sopt_val
), fw32
, valsize
);
912 valsize
= copyfrom32fw( fw32
, user_ip_fw
, valsize
);
913 _FREE( fw32
, M_TEMP
);
921 * The following checks use two arrays of 8 or 16 bits to store the
922 * bits that we want set or clear, respectively. They are in the
923 * low and high half of cmd->arg1 or cmd->d[0].
925 * We scan options and store the bits we find set. We succeed if
927 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
929 * The code is sometimes optimized not to store additional variables.
933 flags_match(ipfw_insn
*cmd
, u_int8_t bits
)
938 if ( ((cmd
->arg1
& 0xff) & bits
) != 0)
939 return 0; /* some bits we want set were clear */
940 want_clear
= (cmd
->arg1
>> 8) & 0xff;
941 if ( (want_clear
& bits
) != want_clear
)
942 return 0; /* some bits we want clear were set */
947 ipopts_match(struct ip
*ip
, ipfw_insn
*cmd
)
949 int optlen
, bits
= 0;
950 u_char
*cp
= (u_char
*)(ip
+ 1);
951 int x
= (ip
->ip_hl
<< 2) - sizeof (struct ip
);
953 for (; x
> 0; x
-= optlen
, cp
+= optlen
) {
954 int opt
= cp
[IPOPT_OPTVAL
];
956 if (opt
== IPOPT_EOL
)
958 if (opt
== IPOPT_NOP
)
961 optlen
= cp
[IPOPT_OLEN
];
962 if (optlen
<= 0 || optlen
> x
)
963 return 0; /* invalid or truncated */
971 bits
|= IP_FW_IPOPT_LSRR
;
975 bits
|= IP_FW_IPOPT_SSRR
;
979 bits
|= IP_FW_IPOPT_RR
;
983 bits
|= IP_FW_IPOPT_TS
;
987 return (flags_match(cmd
, bits
));
991 tcpopts_match(struct ip
*ip
, ipfw_insn
*cmd
)
993 int optlen
, bits
= 0;
994 struct tcphdr
*tcp
= L3HDR(struct tcphdr
,ip
);
995 u_char
*cp
= (u_char
*)(tcp
+ 1);
996 int x
= (tcp
->th_off
<< 2) - sizeof(struct tcphdr
);
998 for (; x
> 0; x
-= optlen
, cp
+= optlen
) {
1000 if (opt
== TCPOPT_EOL
)
1002 if (opt
== TCPOPT_NOP
)
1016 bits
|= IP_FW_TCPOPT_MSS
;
1020 bits
|= IP_FW_TCPOPT_WINDOW
;
1023 case TCPOPT_SACK_PERMITTED
:
1025 bits
|= IP_FW_TCPOPT_SACK
;
1028 case TCPOPT_TIMESTAMP
:
1029 bits
|= IP_FW_TCPOPT_TS
;
1035 bits
|= IP_FW_TCPOPT_CC
;
1039 return (flags_match(cmd
, bits
));
1043 iface_match(struct ifnet
*ifp
, ipfw_insn_if
*cmd
)
1045 if (ifp
== NULL
) /* no iface with this packet, match fails */
1047 /* Check by name or by IP address */
1048 if (cmd
->name
[0] != '\0') { /* match by name */
1049 /* Check unit number (-1 is wildcard) */
1050 if (cmd
->p
.unit
!= -1 && cmd
->p
.unit
!= ifp
->if_unit
)
1053 if (!strncmp(ifp
->if_name
, cmd
->name
, IFNAMSIZ
))
1058 ifnet_lock_shared(ifp
);
1059 TAILQ_FOREACH(ia
, &ifp
->if_addrhead
, ifa_link
) {
1061 if (ia
->ifa_addr
->sa_family
!= AF_INET
) {
1065 if (cmd
->p
.ip
.s_addr
== ((struct sockaddr_in
*)
1066 (ia
->ifa_addr
))->sin_addr
.s_addr
) {
1068 ifnet_lock_done(ifp
);
1069 return(1); /* match */
1073 ifnet_lock_done(ifp
);
1075 return(0); /* no match, fail ... */
1079 * The 'verrevpath' option checks that the interface that an IP packet
1080 * arrives on is the same interface that traffic destined for the
1081 * packet's source address would be routed out of. This is a measure
1082 * to block forged packets. This is also commonly known as "anti-spoofing"
1083 * or Unicast Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The
1084 * name of the knob is purposely reminisent of the Cisco IOS command,
1086 * ip verify unicast reverse-path
1088 * which implements the same functionality. But note that syntax is
1089 * misleading. The check may be performed on all IP packets whether unicast,
1090 * multicast, or broadcast.
1093 verify_rev_path(struct in_addr src
, struct ifnet
*ifp
)
1095 static struct route ro
;
1096 struct sockaddr_in
*dst
;
1098 bzero(&ro
, sizeof (ro
));
1099 dst
= (struct sockaddr_in
*)&(ro
.ro_dst
);
1101 /* Check if we've cached the route from the previous call. */
1102 if (src
.s_addr
!= dst
->sin_addr
.s_addr
) {
1103 dst
->sin_family
= AF_INET
;
1104 dst
->sin_len
= sizeof(*dst
);
1105 dst
->sin_addr
= src
;
1107 rtalloc_ign(&ro
, RTF_CLONING
|RTF_PRCLONING
);
1109 if (ro
.ro_rt
!= NULL
) {
1110 RT_LOCK_SPIN(ro
.ro_rt
);
1113 return 0; /* No route */
1115 if ((ifp
== NULL
) ||
1116 (ro
.ro_rt
->rt_ifp
->if_index
!= ifp
->if_index
)) {
1117 RT_UNLOCK(ro
.ro_rt
);
1121 RT_UNLOCK(ro
.ro_rt
);
1127 static u_int64_t norule_counter
; /* counter for ipfw_log(NULL...) */
1129 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
1130 #define SNP(buf) buf, sizeof(buf)
1133 * We enter here when we have a rule with O_LOG.
1134 * XXX this function alone takes about 2Kbytes of code!
1137 ipfw_log(struct ip_fw
*f
, u_int hlen
, struct ether_header
*eh
,
1138 struct mbuf
*m
, struct ifnet
*oif
)
1141 int limit_reached
= 0;
1142 char ipv4str
[MAX_IPv4_STR_LEN
];
1143 char action2
[40], proto
[48], fragment
[28];
1148 if (f
== NULL
) { /* bogus pkt */
1149 if (verbose_limit
!= 0 && norule_counter
>= verbose_limit
)
1152 if (norule_counter
== verbose_limit
)
1153 limit_reached
= verbose_limit
;
1155 } else { /* O_LOG is the first action, find the real one */
1156 ipfw_insn
*cmd
= ACTION_PTR(f
);
1157 ipfw_insn_log
*l
= (ipfw_insn_log
*)cmd
;
1159 if (l
->max_log
!= 0 && l
->log_left
== 0)
1162 if (l
->log_left
== 0)
1163 limit_reached
= l
->max_log
;
1164 cmd
+= F_LEN(cmd
); /* point to first action */
1165 if (cmd
->opcode
== O_PROB
)
1169 switch (cmd
->opcode
) {
1175 if (cmd
->arg1
==ICMP_REJECT_RST
)
1177 else if (cmd
->arg1
==ICMP_UNREACH_HOST
)
1180 snprintf(SNPARGS(action2
, 0), "Unreach %d",
1191 snprintf(SNPARGS(action2
, 0), "Divert %d",
1195 snprintf(SNPARGS(action2
, 0), "Tee %d",
1199 snprintf(SNPARGS(action2
, 0), "SkipTo %d",
1203 snprintf(SNPARGS(action2
, 0), "Pipe %d",
1207 snprintf(SNPARGS(action2
, 0), "Queue %d",
1210 case O_FORWARD_IP
: {
1211 ipfw_insn_sa
*sa
= (ipfw_insn_sa
*)cmd
;
1214 if (f
->reserved_1
== IPFW_RULE_INACTIVE
) {
1217 len
= snprintf(SNPARGS(action2
, 0), "Forward to %s",
1218 inet_ntop(AF_INET
, &sa
->sa
.sin_addr
, ipv4str
, sizeof(ipv4str
)));
1219 if (sa
->sa
.sin_port
)
1220 snprintf(SNPARGS(action2
, len
), ":%d",
1230 if (hlen
== 0) { /* non-ip */
1231 snprintf(SNPARGS(proto
, 0), "MAC");
1233 struct ip
*ip
= mtod(m
, struct ip
*);
1234 /* these three are all aliases to the same thing */
1235 struct icmp
*const icmp
= L3HDR(struct icmp
, ip
);
1236 struct tcphdr
*const tcp
= (struct tcphdr
*)icmp
;
1237 struct udphdr
*const udp
= (struct udphdr
*)icmp
;
1239 int ip_off
, offset
, ip_len
;
1243 if (eh
!= NULL
) { /* layer 2 packets are as on the wire */
1244 ip_off
= ntohs(ip
->ip_off
);
1245 ip_len
= ntohs(ip
->ip_len
);
1247 ip_off
= ip
->ip_off
;
1248 ip_len
= ip
->ip_len
;
1250 offset
= ip_off
& IP_OFFMASK
;
1253 len
= snprintf(SNPARGS(proto
, 0), "TCP %s",
1254 inet_ntop(AF_INET
, &ip
->ip_src
, ipv4str
, sizeof(ipv4str
)));
1256 snprintf(SNPARGS(proto
, len
), ":%d %s:%d",
1257 ntohs(tcp
->th_sport
),
1258 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)),
1259 ntohs(tcp
->th_dport
));
1261 snprintf(SNPARGS(proto
, len
), " %s",
1262 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)));
1266 len
= snprintf(SNPARGS(proto
, 0), "UDP %s",
1267 inet_ntop(AF_INET
, &ip
->ip_src
, ipv4str
, sizeof(ipv4str
)));
1269 snprintf(SNPARGS(proto
, len
), ":%d %s:%d",
1270 ntohs(udp
->uh_sport
),
1271 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)),
1272 ntohs(udp
->uh_dport
));
1274 snprintf(SNPARGS(proto
, len
), " %s",
1275 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)));
1280 len
= snprintf(SNPARGS(proto
, 0),
1282 icmp
->icmp_type
, icmp
->icmp_code
);
1284 len
= snprintf(SNPARGS(proto
, 0), "ICMP ");
1285 len
+= snprintf(SNPARGS(proto
, len
), "%s",
1286 inet_ntop(AF_INET
, &ip
->ip_src
, ipv4str
, sizeof(ipv4str
)));
1287 snprintf(SNPARGS(proto
, len
), " %s",
1288 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)));
1292 len
= snprintf(SNPARGS(proto
, 0), "P:%d %s", ip
->ip_p
,
1293 inet_ntop(AF_INET
, &ip
->ip_src
, ipv4str
, sizeof(ipv4str
)));
1294 snprintf(SNPARGS(proto
, len
), " %s",
1295 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)));
1299 if (ip_off
& (IP_MF
| IP_OFFMASK
))
1300 snprintf(SNPARGS(fragment
, 0), " (frag %d:%d@%d%s)",
1301 ntohs(ip
->ip_id
), ip_len
- (ip
->ip_hl
<< 2),
1303 (ip_off
& IP_MF
) ? "+" : "");
1305 if (oif
|| m
->m_pkthdr
.rcvif
)
1307 dolog((LOG_AUTHPRIV
| LOG_INFO
,
1308 "ipfw: %d %s %s %s via %s%d%s\n",
1309 f
? f
->rulenum
: -1,
1310 action
, proto
, oif
? "out" : "in",
1311 oif
? oif
->if_name
: m
->m_pkthdr
.rcvif
->if_name
,
1312 oif
? oif
->if_unit
: m
->m_pkthdr
.rcvif
->if_unit
,
1316 dolog((LOG_AUTHPRIV
| LOG_INFO
,
1317 "ipfw: %d %s %s [no if info]%s\n",
1318 f
? f
->rulenum
: -1,
1319 action
, proto
, fragment
));
1322 dolog((LOG_AUTHPRIV
| LOG_NOTICE
,
1323 "ipfw: limit %d reached on entry %d\n",
1324 limit_reached
, f
? f
->rulenum
: -1));
1329 * IMPORTANT: the hash function for dynamic rules must be commutative
1330 * in source and destination (ip,port), because rules are bidirectional
1331 * and we want to find both in the same bucket.
1334 hash_packet(struct ip_flow_id
*id
)
1338 i
= (id
->dst_ip
) ^ (id
->src_ip
) ^ (id
->dst_port
) ^ (id
->src_port
);
1339 i
&= (curr_dyn_buckets
- 1);
1344 * unlink a dynamic rule from a chain. prev is a pointer to
1345 * the previous one, q is a pointer to the rule to delete,
1346 * head is a pointer to the head of the queue.
1347 * Modifies q and potentially also head.
1349 #define UNLINK_DYN_RULE(prev, head, q) { \
1350 ipfw_dyn_rule *old_q = q; \
1352 /* remove a refcount to the parent */ \
1353 if (q->dyn_type == O_LIMIT) \
1354 q->parent->count--; \
1355 DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
1356 (q->id.src_ip), (q->id.src_port), \
1357 (q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); ) \
1359 prev->next = q = q->next; \
1361 head = q = q->next; \
1363 _FREE(old_q, M_IPFW); }
1365 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
1368 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
1370 * If keep_me == NULL, rules are deleted even if not expired,
1371 * otherwise only expired rules are removed.
1373 * The value of the second parameter is also used to point to identify
1374 * a rule we absolutely do not want to remove (e.g. because we are
1375 * holding a reference to it -- this is the case with O_LIMIT_PARENT
1376 * rules). The pointer is only used for comparison, so any non-null
1380 remove_dyn_rule(struct ip_fw
*rule
, ipfw_dyn_rule
*keep_me
)
1382 static u_int32_t last_remove
= 0;
1384 #define FORCE (keep_me == NULL)
1386 ipfw_dyn_rule
*prev
, *q
;
1387 int i
, pass
= 0, max_pass
= 0;
1388 struct timeval timenow
;
1390 getmicrotime(&timenow
);
1392 if (ipfw_dyn_v
== NULL
|| dyn_count
== 0)
1394 /* do not expire more than once per second, it is useless */
1395 if (!FORCE
&& last_remove
== timenow
.tv_sec
)
1397 last_remove
= timenow
.tv_sec
;
1400 * because O_LIMIT refer to parent rules, during the first pass only
1401 * remove child and mark any pending LIMIT_PARENT, and remove
1402 * them in a second pass.
1405 for (i
= 0 ; i
< curr_dyn_buckets
; i
++) {
1406 for (prev
=NULL
, q
= ipfw_dyn_v
[i
] ; q
; ) {
1408 * Logic can become complex here, so we split tests.
1412 if (rule
!= NULL
&& rule
!= q
->rule
)
1413 goto next
; /* not the one we are looking for */
1414 if (q
->dyn_type
== O_LIMIT_PARENT
) {
1416 * handle parent in the second pass,
1417 * record we need one.
1422 if (FORCE
&& q
->count
!= 0 ) {
1423 /* XXX should not happen! */
1424 printf("ipfw: OUCH! cannot remove rule,"
1425 " count %d\n", q
->count
);
1429 !TIME_LEQ( q
->expire
, timenow
.tv_sec
))
1432 if (q
->dyn_type
!= O_LIMIT_PARENT
|| !q
->count
) {
1433 UNLINK_DYN_RULE(prev
, ipfw_dyn_v
[i
], q
);
1441 if (pass
++ < max_pass
)
1447 * lookup a dynamic rule.
1449 static ipfw_dyn_rule
*
1450 lookup_dyn_rule(struct ip_flow_id
*pkt
, int *match_direction
,
1454 * stateful ipfw extensions.
1455 * Lookup into dynamic session queue
1457 #define MATCH_REVERSE 0
1458 #define MATCH_FORWARD 1
1459 #define MATCH_NONE 2
1460 #define MATCH_UNKNOWN 3
1461 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
1462 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
1464 int i
, dir
= MATCH_NONE
;
1465 ipfw_dyn_rule
*prev
, *q
=NULL
;
1466 struct timeval timenow
;
1468 getmicrotime(&timenow
);
1470 if (ipfw_dyn_v
== NULL
)
1471 goto done
; /* not found */
1472 i
= hash_packet( pkt
);
1473 for (prev
=NULL
, q
= ipfw_dyn_v
[i
] ; q
!= NULL
; ) {
1474 if (q
->dyn_type
== O_LIMIT_PARENT
&& q
->count
)
1476 if (TIME_LEQ( q
->expire
, timenow
.tv_sec
)) { /* expire entry */
1479 /* check if entry is TCP */
1480 if ( q
->id
.proto
== IPPROTO_TCP
)
1482 /* do not delete an established TCP connection which hasn't been closed by both sides */
1483 if ( (q
->state
& (BOTH_SYN
| BOTH_FIN
)) != (BOTH_SYN
| BOTH_FIN
) )
1487 UNLINK_DYN_RULE(prev
, ipfw_dyn_v
[i
], q
);
1491 if (pkt
->proto
== q
->id
.proto
&&
1492 q
->dyn_type
!= O_LIMIT_PARENT
) {
1493 if (pkt
->src_ip
== q
->id
.src_ip
&&
1494 pkt
->dst_ip
== q
->id
.dst_ip
&&
1495 pkt
->src_port
== q
->id
.src_port
&&
1496 pkt
->dst_port
== q
->id
.dst_port
) {
1497 dir
= MATCH_FORWARD
;
1500 if (pkt
->src_ip
== q
->id
.dst_ip
&&
1501 pkt
->dst_ip
== q
->id
.src_ip
&&
1502 pkt
->src_port
== q
->id
.dst_port
&&
1503 pkt
->dst_port
== q
->id
.src_port
) {
1504 dir
= MATCH_REVERSE
;
1513 goto done
; /* q = NULL, not found */
1515 if ( prev
!= NULL
) { /* found and not in front */
1516 prev
->next
= q
->next
;
1517 q
->next
= ipfw_dyn_v
[i
];
1520 if (pkt
->proto
== IPPROTO_TCP
) { /* update state according to flags */
1521 u_char flags
= pkt
->flags
& (TH_FIN
|TH_SYN
|TH_RST
);
1523 q
->state
|= (dir
== MATCH_FORWARD
) ? flags
: (flags
<< 8);
1525 case TH_SYN
: /* opening */
1526 q
->expire
= timenow
.tv_sec
+ dyn_syn_lifetime
;
1529 case BOTH_SYN
: /* move to established */
1530 case BOTH_SYN
| TH_FIN
: /* one side tries to close */
1531 case BOTH_SYN
| (TH_FIN
<< 8) :
1533 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
1534 u_int32_t ack
= ntohl(tcp
->th_ack
);
1535 if (dir
== MATCH_FORWARD
) {
1536 if (q
->ack_fwd
== 0 || _SEQ_GE(ack
, q
->ack_fwd
))
1538 else { /* ignore out-of-sequence */
1542 if (q
->ack_rev
== 0 || _SEQ_GE(ack
, q
->ack_rev
))
1544 else { /* ignore out-of-sequence */
1549 q
->expire
= timenow
.tv_sec
+ dyn_ack_lifetime
;
1552 case BOTH_SYN
| BOTH_FIN
: /* both sides closed */
1553 if (dyn_fin_lifetime
>= dyn_keepalive_period
)
1554 dyn_fin_lifetime
= dyn_keepalive_period
- 1;
1555 q
->expire
= timenow
.tv_sec
+ dyn_fin_lifetime
;
1561 * reset or some invalid combination, but can also
1562 * occur if we use keep-state the wrong way.
1564 if ( (q
->state
& ((TH_RST
<< 8)|TH_RST
)) == 0)
1565 printf("invalid state: 0x%x\n", q
->state
);
1567 if (dyn_rst_lifetime
>= dyn_keepalive_period
)
1568 dyn_rst_lifetime
= dyn_keepalive_period
- 1;
1569 q
->expire
= timenow
.tv_sec
+ dyn_rst_lifetime
;
1572 } else if (pkt
->proto
== IPPROTO_UDP
) {
1573 q
->expire
= timenow
.tv_sec
+ dyn_udp_lifetime
;
1575 /* other protocols */
1576 q
->expire
= timenow
.tv_sec
+ dyn_short_lifetime
;
1579 if (match_direction
)
1580 *match_direction
= dir
;
1585 realloc_dynamic_table(void)
1588 * Try reallocation, make sure we have a power of 2 and do
1589 * not allow more than 64k entries. In case of overflow,
1593 if (dyn_buckets
> 65536)
1595 if ((dyn_buckets
& (dyn_buckets
-1)) != 0) { /* not a power of 2 */
1596 dyn_buckets
= curr_dyn_buckets
; /* reset */
1599 curr_dyn_buckets
= dyn_buckets
;
1600 if (ipfw_dyn_v
!= NULL
)
1601 _FREE(ipfw_dyn_v
, M_IPFW
);
1603 ipfw_dyn_v
= _MALLOC(curr_dyn_buckets
* sizeof(ipfw_dyn_rule
*),
1604 M_IPFW
, M_NOWAIT
| M_ZERO
);
1605 if (ipfw_dyn_v
!= NULL
|| curr_dyn_buckets
<= 2)
1607 curr_dyn_buckets
/= 2;
1612 * Install state of type 'type' for a dynamic session.
1613 * The hash table contains two type of rules:
1614 * - regular rules (O_KEEP_STATE)
1615 * - rules for sessions with limited number of sess per user
1616 * (O_LIMIT). When they are created, the parent is
1617 * increased by 1, and decreased on delete. In this case,
1618 * the third parameter is the parent rule and not the chain.
1619 * - "parent" rules for the above (O_LIMIT_PARENT).
1621 static ipfw_dyn_rule
*
1622 add_dyn_rule(struct ip_flow_id
*id
, u_int8_t dyn_type
, struct ip_fw
*rule
)
1626 struct timeval timenow
;
1628 getmicrotime(&timenow
);
1630 if (ipfw_dyn_v
== NULL
||
1631 (dyn_count
== 0 && dyn_buckets
!= curr_dyn_buckets
)) {
1632 realloc_dynamic_table();
1633 if (ipfw_dyn_v
== NULL
)
1634 return NULL
; /* failed ! */
1636 i
= hash_packet(id
);
1638 r
= _MALLOC(sizeof *r
, M_IPFW
, M_NOWAIT
| M_ZERO
);
1641 printf ("ipfw: sorry cannot allocate state\n");
1646 /* increase refcount on parent, and set pointer */
1647 if (dyn_type
== O_LIMIT
) {
1648 ipfw_dyn_rule
*parent
= (ipfw_dyn_rule
*)rule
;
1649 if ( parent
->dyn_type
!= O_LIMIT_PARENT
)
1650 panic("invalid parent");
1653 rule
= parent
->rule
;
1657 r
->expire
= timenow
.tv_sec
+ dyn_syn_lifetime
;
1659 r
->dyn_type
= dyn_type
;
1660 r
->pcnt
= r
->bcnt
= 0;
1664 r
->next
= ipfw_dyn_v
[i
];
1667 DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1669 (r
->id
.src_ip
), (r
->id
.src_port
),
1670 (r
->id
.dst_ip
), (r
->id
.dst_port
),
1676 * lookup dynamic parent rule using pkt and rule as search keys.
1677 * If the lookup fails, then install one.
1679 static ipfw_dyn_rule
*
1680 lookup_dyn_parent(struct ip_flow_id
*pkt
, struct ip_fw
*rule
)
1684 struct timeval timenow
;
1686 getmicrotime(&timenow
);
1689 i
= hash_packet( pkt
);
1690 for (q
= ipfw_dyn_v
[i
] ; q
!= NULL
; q
=q
->next
)
1691 if (q
->dyn_type
== O_LIMIT_PARENT
&&
1693 pkt
->proto
== q
->id
.proto
&&
1694 pkt
->src_ip
== q
->id
.src_ip
&&
1695 pkt
->dst_ip
== q
->id
.dst_ip
&&
1696 pkt
->src_port
== q
->id
.src_port
&&
1697 pkt
->dst_port
== q
->id
.dst_port
) {
1698 q
->expire
= timenow
.tv_sec
+ dyn_short_lifetime
;
1699 DEB(printf("ipfw: lookup_dyn_parent found "
1700 "0x%llx\n", (uint64_t)VM_KERNEL_ADDRPERM(q
));)
1704 return add_dyn_rule(pkt
, O_LIMIT_PARENT
, rule
);
1708 * Install dynamic state for rule type cmd->o.opcode
1710 * Returns 1 (failure) if state is not installed because of errors or because
1711 * session limitations are enforced.
1714 install_state(struct ip_fw
*rule
, ipfw_insn_limit
*cmd
,
1715 struct ip_fw_args
*args
)
1717 static int last_log
;
1718 struct timeval timenow
;
1721 getmicrotime(&timenow
);
1723 DEB(printf("ipfw: install state type %d 0x%08x %u -> 0x%08x %u\n",
1725 (args
->fwa_id
.src_ip
), (args
->fwa_id
.src_port
),
1726 (args
->fwa_id
.dst_ip
), (args
->fwa_id
.dst_port
) );)
1728 q
= lookup_dyn_rule(&args
->fwa_id
, NULL
, NULL
);
1730 if (q
!= NULL
) { /* should never occur */
1731 if (last_log
!= timenow
.tv_sec
) {
1732 last_log
= timenow
.tv_sec
;
1733 printf("ipfw: install_state: entry already present, done\n");
1738 if (dyn_count
>= dyn_max
)
1740 * Run out of slots, try to remove any expired rule.
1742 remove_dyn_rule(NULL
, (ipfw_dyn_rule
*)1);
1744 if (dyn_count
>= dyn_max
) {
1745 if (last_log
!= timenow
.tv_sec
) {
1746 last_log
= timenow
.tv_sec
;
1747 printf("ipfw: install_state: Too many dynamic rules\n");
1749 return 1; /* cannot install, notify caller */
1752 switch (cmd
->o
.opcode
) {
1753 case O_KEEP_STATE
: /* bidir rule */
1754 add_dyn_rule(&args
->fwa_id
, O_KEEP_STATE
, rule
);
1757 case O_LIMIT
: /* limit number of sessions */
1759 u_int16_t limit_mask
= cmd
->limit_mask
;
1760 struct ip_flow_id id
;
1761 ipfw_dyn_rule
*parent
;
1763 DEB(printf("ipfw: installing dyn-limit rule %d\n",
1766 id
.dst_ip
= id
.src_ip
= 0;
1767 id
.dst_port
= id
.src_port
= 0;
1768 id
.proto
= args
->fwa_id
.proto
;
1770 if (limit_mask
& DYN_SRC_ADDR
)
1771 id
.src_ip
= args
->fwa_id
.src_ip
;
1772 if (limit_mask
& DYN_DST_ADDR
)
1773 id
.dst_ip
= args
->fwa_id
.dst_ip
;
1774 if (limit_mask
& DYN_SRC_PORT
)
1775 id
.src_port
= args
->fwa_id
.src_port
;
1776 if (limit_mask
& DYN_DST_PORT
)
1777 id
.dst_port
= args
->fwa_id
.dst_port
;
1778 parent
= lookup_dyn_parent(&id
, rule
);
1779 if (parent
== NULL
) {
1780 printf("ipfw: add parent failed\n");
1783 if (parent
->count
>= cmd
->conn_limit
) {
1785 * See if we can remove some expired rule.
1787 remove_dyn_rule(rule
, parent
);
1788 if (parent
->count
>= cmd
->conn_limit
) {
1789 if (fw_verbose
&& last_log
!= timenow
.tv_sec
) {
1790 last_log
= timenow
.tv_sec
;
1791 dolog((LOG_AUTHPRIV
| LOG_DEBUG
,
1792 "drop session, too many entries\n"));
1797 add_dyn_rule(&args
->fwa_id
, O_LIMIT
, (struct ip_fw
*)parent
);
1801 printf("ipfw: unknown dynamic rule type %u\n", cmd
->o
.opcode
);
1804 lookup_dyn_rule(&args
->fwa_id
, NULL
, NULL
); /* XXX just set lifetime */
1809 * Generate a TCP packet, containing either a RST or a keepalive.
1810 * When flags & TH_RST, we are sending a RST packet, because of a
1811 * "reset" action matched the packet.
1812 * Otherwise we are sending a keepalive, and flags & TH_
1814 static struct mbuf
*
1815 send_pkt(struct ip_flow_id
*id
, u_int32_t seq
, u_int32_t ack
, int flags
)
1821 MGETHDR(m
, M_DONTWAIT
, MT_HEADER
); /* MAC-OK */
1824 m
->m_pkthdr
.rcvif
= (struct ifnet
*)0;
1825 m
->m_pkthdr
.len
= m
->m_len
= sizeof(struct ip
) + sizeof(struct tcphdr
);
1826 m
->m_data
+= max_linkhdr
;
1828 ip
= mtod(m
, struct ip
*);
1829 bzero(ip
, m
->m_len
);
1830 tcp
= (struct tcphdr
*)(ip
+ 1); /* no IP options */
1831 ip
->ip_p
= IPPROTO_TCP
;
1834 * Assume we are sending a RST (or a keepalive in the reverse
1835 * direction), swap src and destination addresses and ports.
1837 ip
->ip_src
.s_addr
= htonl(id
->dst_ip
);
1838 ip
->ip_dst
.s_addr
= htonl(id
->src_ip
);
1839 tcp
->th_sport
= htons(id
->dst_port
);
1840 tcp
->th_dport
= htons(id
->src_port
);
1841 if (flags
& TH_RST
) { /* we are sending a RST */
1842 if (flags
& TH_ACK
) {
1843 tcp
->th_seq
= htonl(ack
);
1844 tcp
->th_ack
= htonl(0);
1845 tcp
->th_flags
= TH_RST
;
1849 tcp
->th_seq
= htonl(0);
1850 tcp
->th_ack
= htonl(seq
);
1851 tcp
->th_flags
= TH_RST
| TH_ACK
;
1855 * We are sending a keepalive. flags & TH_SYN determines
1856 * the direction, forward if set, reverse if clear.
1857 * NOTE: seq and ack are always assumed to be correct
1858 * as set by the caller. This may be confusing...
1860 if (flags
& TH_SYN
) {
1862 * we have to rewrite the correct addresses!
1864 ip
->ip_dst
.s_addr
= htonl(id
->dst_ip
);
1865 ip
->ip_src
.s_addr
= htonl(id
->src_ip
);
1866 tcp
->th_dport
= htons(id
->dst_port
);
1867 tcp
->th_sport
= htons(id
->src_port
);
1869 tcp
->th_seq
= htonl(seq
);
1870 tcp
->th_ack
= htonl(ack
);
1871 tcp
->th_flags
= TH_ACK
;
1874 * set ip_len to the payload size so we can compute
1875 * the tcp checksum on the pseudoheader
1876 * XXX check this, could save a couple of words ?
1878 ip
->ip_len
= htons(sizeof(struct tcphdr
));
1879 tcp
->th_sum
= in_cksum(m
, m
->m_pkthdr
.len
);
1881 * now fill fields left out earlier
1883 ip
->ip_ttl
= ip_defttl
;
1884 ip
->ip_len
= m
->m_pkthdr
.len
;
1885 m
->m_flags
|= M_SKIP_FIREWALL
;
1891 * sends a reject message, consuming the mbuf passed as an argument.
1894 send_reject(struct ip_fw_args
*args
, int code
, int offset
, __unused
int ip_len
)
1897 if (code
!= ICMP_REJECT_RST
) { /* Send an ICMP unreach */
1898 /* We need the IP header in host order for icmp_error(). */
1899 if (args
->fwa_eh
!= NULL
) {
1900 struct ip
*ip
= mtod(args
->fwa_m
, struct ip
*);
1901 ip
->ip_len
= ntohs(ip
->ip_len
);
1902 ip
->ip_off
= ntohs(ip
->ip_off
);
1904 args
->fwa_m
->m_flags
|= M_SKIP_FIREWALL
;
1905 icmp_error(args
->fwa_m
, ICMP_UNREACH
, code
, 0L, 0);
1906 } else if (offset
== 0 && args
->fwa_id
.proto
== IPPROTO_TCP
) {
1907 struct tcphdr
*const tcp
=
1908 L3HDR(struct tcphdr
, mtod(args
->fwa_m
, struct ip
*));
1909 if ( (tcp
->th_flags
& TH_RST
) == 0) {
1912 m
= send_pkt(&(args
->fwa_id
), ntohl(tcp
->th_seq
),
1914 tcp
->th_flags
| TH_RST
);
1916 struct route sro
; /* fake route */
1918 bzero (&sro
, sizeof (sro
));
1919 ip_output(m
, NULL
, &sro
, 0, NULL
, NULL
);
1920 ROUTE_RELEASE(&sro
);
1923 m_freem(args
->fwa_m
);
1925 m_freem(args
->fwa_m
);
1931 * Given an ip_fw *, lookup_next_rule will return a pointer
1932 * to the next rule, which can be either the jump
1933 * target (for skipto instructions) or the next one in the list (in
1934 * all other cases including a missing jump target).
1935 * The result is also written in the "next_rule" field of the rule.
1936 * Backward jumps are not allowed, so start looking from the next
1939 * This never returns NULL -- in case we do not have an exact match,
1940 * the next rule is returned. When the ruleset is changed,
1941 * pointers are flushed so we are always correct.
1944 static struct ip_fw
*
1945 lookup_next_rule(struct ip_fw
*me
)
1947 struct ip_fw
*rule
= NULL
;
1950 /* look for action, in case it is a skipto */
1951 cmd
= ACTION_PTR(me
);
1952 if (cmd
->opcode
== O_LOG
)
1954 if ( cmd
->opcode
== O_SKIPTO
)
1955 for (rule
= me
->next
; rule
; rule
= rule
->next
)
1956 if (rule
->rulenum
>= cmd
->arg1
)
1958 if (rule
== NULL
) /* failure or not a skipto */
1960 me
->next_rule
= rule
;
1965 * The main check routine for the firewall.
1967 * All arguments are in args so we can modify them and return them
1968 * back to the caller.
1972 * args->fwa_m (in/out) The packet; we set to NULL when/if we nuke it.
1973 * Starts with the IP header.
1974 * args->fwa_eh (in) Mac header if present, or NULL for layer3 packet.
1975 * args->fwa_oif Outgoing interface, or NULL if packet is incoming.
1976 * The incoming interface is in the mbuf. (in)
1977 * args->fwa_divert_rule (in/out)
1978 * Skip up to the first rule past this rule number;
1979 * upon return, non-zero port number for divert or tee.
1981 * args->fwa_ipfw_rule Pointer to the last matching rule (in/out)
1982 * args->fwa_next_hop Socket we are forwarding to (out).
1983 * args->fwa_id Addresses grabbed from the packet (out)
1987 * IP_FW_PORT_DENY_FLAG the packet must be dropped.
1988 * 0 The packet is to be accepted and routed normally OR
1989 * the packet was denied/rejected and has been dropped;
1990 * in the latter case, *m is equal to NULL upon return.
1991 * port Divert the packet to port, with these caveats:
1993 * - If IP_FW_PORT_TEE_FLAG is set, tee the packet instead
1994 * of diverting it (ie, 'ipfw tee').
1996 * - If IP_FW_PORT_DYNT_FLAG is set, interpret the lower
1997 * 16 bits as a dummynet pipe number instead of diverting
2001 ipfw_chk(struct ip_fw_args
*args
)
2004 * Local variables hold state during the processing of a packet.
2006 * IMPORTANT NOTE: to speed up the processing of rules, there
2007 * are some assumption on the values of the variables, which
2008 * are documented here. Should you change them, please check
2009 * the implementation of the various instructions to make sure
2010 * that they still work.
2012 * args->fwa_eh The MAC header. It is non-null for a layer2
2013 * packet, it is NULL for a layer-3 packet.
2015 * m | args->fwa_m Pointer to the mbuf, as received from the caller.
2016 * It may change if ipfw_chk() does an m_pullup, or if it
2017 * consumes the packet because it calls send_reject().
2018 * XXX This has to change, so that ipfw_chk() never modifies
2019 * or consumes the buffer.
2020 * ip is simply an alias of the value of m, and it is kept
2021 * in sync with it (the packet is supposed to start with
2024 struct mbuf
*m
= args
->fwa_m
;
2025 struct ip
*ip
= mtod(m
, struct ip
*);
2028 * oif | args->fwa_oif If NULL, ipfw_chk has been called on the
2029 * inbound path (ether_input, bdg_forward, ip_input).
2030 * If non-NULL, ipfw_chk has been called on the outbound path
2031 * (ether_output, ip_output).
2033 struct ifnet
*oif
= args
->fwa_oif
;
2035 struct ip_fw
*f
= NULL
; /* matching rule */
2039 * hlen The length of the IPv4 header.
2040 * hlen >0 means we have an IPv4 packet.
2042 u_int hlen
= 0; /* hlen >0 means we have an IP pkt */
2045 * offset The offset of a fragment. offset != 0 means that
2046 * we have a fragment at this offset of an IPv4 packet.
2047 * offset == 0 means that (if this is an IPv4 packet)
2048 * this is the first or only fragment.
2053 * Local copies of addresses. They are only valid if we have
2056 * proto The protocol. Set to 0 for non-ip packets,
2057 * or to the protocol read from the packet otherwise.
2058 * proto != 0 means that we have an IPv4 packet.
2060 * src_port, dst_port port numbers, in HOST format. Only
2061 * valid for TCP and UDP packets.
2063 * src_ip, dst_ip ip addresses, in NETWORK format.
2064 * Only valid for IPv4 packets.
2067 u_int16_t src_port
= 0, dst_port
= 0; /* NOTE: host format */
2068 struct in_addr src_ip
= { 0 } , dst_ip
= { 0 }; /* NOTE: network format */
2071 int dyn_dir
= MATCH_UNKNOWN
;
2072 ipfw_dyn_rule
*q
= NULL
;
2073 struct timeval timenow
;
2075 if (m
->m_flags
& M_SKIP_FIREWALL
|| fw_bypass
) {
2076 return 0; /* accept */
2080 * Clear packet chain if we find one here.
2083 if (m
->m_nextpkt
!= NULL
) {
2084 m_freem_list(m
->m_nextpkt
);
2085 m
->m_nextpkt
= NULL
;
2088 lck_mtx_lock(ipfw_mutex
);
2090 getmicrotime(&timenow
);
2092 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
2093 * MATCH_NONE when checked and not matched (q = NULL),
2094 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
2097 pktlen
= m
->m_pkthdr
.len
;
2098 if (args
->fwa_eh
== NULL
|| /* layer 3 packet */
2099 ( m
->m_pkthdr
.len
>= sizeof(struct ip
) &&
2100 ntohs(args
->fwa_eh
->ether_type
) == ETHERTYPE_IP
))
2101 hlen
= ip
->ip_hl
<< 2;
2104 * Collect parameters into local variables for faster matching.
2106 if (hlen
== 0) { /* do not grab addresses for non-ip pkts */
2107 proto
= args
->fwa_id
.proto
= 0; /* mark f_id invalid */
2108 goto after_ip_checks
;
2111 proto
= args
->fwa_id
.proto
= ip
->ip_p
;
2112 src_ip
= ip
->ip_src
;
2113 dst_ip
= ip
->ip_dst
;
2114 if (args
->fwa_eh
!= NULL
) { /* layer 2 packets are as on the wire */
2115 offset
= ntohs(ip
->ip_off
) & IP_OFFMASK
;
2116 ip_len
= ntohs(ip
->ip_len
);
2118 offset
= ip
->ip_off
& IP_OFFMASK
;
2119 ip_len
= ip
->ip_len
;
2121 pktlen
= ip_len
< pktlen
? ip_len
: pktlen
;
2123 #define PULLUP_TO(len) \
2125 if ((m)->m_len < (len)) { \
2126 args->fwa_m = m = m_pullup(m, (len)); \
2128 goto pullup_failed; \
2129 ip = mtod(m, struct ip *); \
2139 PULLUP_TO(hlen
+ sizeof(struct tcphdr
));
2140 tcp
= L3HDR(struct tcphdr
, ip
);
2141 dst_port
= tcp
->th_dport
;
2142 src_port
= tcp
->th_sport
;
2143 args
->fwa_id
.flags
= tcp
->th_flags
;
2151 PULLUP_TO(hlen
+ sizeof(struct udphdr
));
2152 udp
= L3HDR(struct udphdr
, ip
);
2153 dst_port
= udp
->uh_dport
;
2154 src_port
= udp
->uh_sport
;
2159 PULLUP_TO(hlen
+ 4); /* type, code and checksum. */
2160 args
->fwa_id
.flags
= L3HDR(struct icmp
, ip
)->icmp_type
;
2169 args
->fwa_id
.src_ip
= ntohl(src_ip
.s_addr
);
2170 args
->fwa_id
.dst_ip
= ntohl(dst_ip
.s_addr
);
2171 args
->fwa_id
.src_port
= src_port
= ntohs(src_port
);
2172 args
->fwa_id
.dst_port
= dst_port
= ntohs(dst_port
);
2175 if (args
->fwa_ipfw_rule
) {
2177 * Packet has already been tagged. Look for the next rule
2178 * to restart processing.
2180 * If fw_one_pass != 0 then just accept it.
2181 * XXX should not happen here, but optimized out in
2185 lck_mtx_unlock(ipfw_mutex
);
2189 f
= args
->fwa_ipfw_rule
->next_rule
;
2191 f
= lookup_next_rule(args
->fwa_ipfw_rule
);
2194 * Find the starting rule. It can be either the first
2195 * one, or the one after divert_rule if asked so.
2197 int skipto
= args
->fwa_divert_rule
;
2200 if (args
->fwa_eh
== NULL
&& skipto
!= 0) {
2201 if (skipto
>= IPFW_DEFAULT_RULE
) {
2202 lck_mtx_unlock(ipfw_mutex
);
2203 return(IP_FW_PORT_DENY_FLAG
); /* invalid */
2205 while (f
&& f
->rulenum
<= skipto
)
2207 if (f
== NULL
) { /* drop packet */
2208 lck_mtx_unlock(ipfw_mutex
);
2209 return(IP_FW_PORT_DENY_FLAG
);
2213 args
->fwa_divert_rule
= 0; /* reset to avoid confusion later */
2216 * Now scan the rules, and parse microinstructions for each rule.
2218 for (; f
; f
= f
->next
) {
2221 int skip_or
; /* skip rest of OR block */
2224 if (f
->reserved_1
== IPFW_RULE_INACTIVE
) {
2228 if (set_disable
& (1 << f
->set
) )
2232 for (l
= f
->cmd_len
, cmd
= f
->cmd
; l
> 0 ;
2233 l
-= cmdlen
, cmd
+= cmdlen
) {
2237 * check_body is a jump target used when we find a
2238 * CHECK_STATE, and need to jump to the body of
2243 cmdlen
= F_LEN(cmd
);
2245 * An OR block (insn_1 || .. || insn_n) has the
2246 * F_OR bit set in all but the last instruction.
2247 * The first match will set "skip_or", and cause
2248 * the following instructions to be skipped until
2249 * past the one with the F_OR bit clear.
2251 if (skip_or
) { /* skip this instruction */
2252 if ((cmd
->len
& F_OR
) == 0)
2253 skip_or
= 0; /* next one is good */
2256 match
= 0; /* set to 1 if we succeed */
2258 switch (cmd
->opcode
) {
2260 * The first set of opcodes compares the packet's
2261 * fields with some pattern, setting 'match' if a
2262 * match is found. At the end of the loop there is
2263 * logic to deal with F_NOT and F_OR flags associated
2271 printf("ipfw: opcode %d unimplemented\n",
2280 * We only check offset == 0 && proto != 0,
2281 * as this ensures that we have an IPv4
2282 * packet with the ports info.
2288 struct inpcbinfo
*pi
;
2292 if (proto
== IPPROTO_TCP
) {
2295 } else if (proto
== IPPROTO_UDP
) {
2302 in_pcblookup_hash(pi
,
2303 dst_ip
, htons(dst_port
),
2304 src_ip
, htons(src_port
),
2306 in_pcblookup_hash(pi
,
2307 src_ip
, htons(src_port
),
2308 dst_ip
, htons(dst_port
),
2311 if (pcb
== NULL
|| pcb
->inp_socket
== NULL
)
2313 #if __FreeBSD_version < 500034
2314 #define socheckuid(a,b) (kauth_cred_getuid((a)->so_cred) != (b))
2316 if (cmd
->opcode
== O_UID
) {
2319 (kauth_cred_getuid(pcb
->inp_socket
->so_cred
) == (uid_t
)((ipfw_insn_u32
*)cmd
)->d
[0]);
2321 !socheckuid(pcb
->inp_socket
,
2322 (uid_t
)((ipfw_insn_u32
*)cmd
)->d
[0]);
2328 kauth_cred_ismember_gid(pcb
->inp_socket
->so_cred
,
2329 (gid_t
)((ipfw_insn_u32
*)cmd
)->d
[0], &match
);
2332 /* release reference on pcb */
2333 in_pcb_checkstate(pcb
, WNT_RELEASE
, 0);
2339 match
= iface_match(m
->m_pkthdr
.rcvif
,
2340 (ipfw_insn_if
*)cmd
);
2344 match
= iface_match(oif
, (ipfw_insn_if
*)cmd
);
2348 match
= iface_match(oif
? oif
:
2349 m
->m_pkthdr
.rcvif
, (ipfw_insn_if
*)cmd
);
2353 if (args
->fwa_eh
!= NULL
) { /* have MAC header */
2354 u_int32_t
*want
= (u_int32_t
*)
2355 ((ipfw_insn_mac
*)cmd
)->addr
;
2356 u_int32_t
*mask
= (u_int32_t
*)
2357 ((ipfw_insn_mac
*)cmd
)->mask
;
2358 u_int32_t
*hdr
= (u_int32_t
*)args
->fwa_eh
;
2361 ( want
[0] == (hdr
[0] & mask
[0]) &&
2362 want
[1] == (hdr
[1] & mask
[1]) &&
2363 want
[2] == (hdr
[2] & mask
[2]) );
2368 if (args
->fwa_eh
!= NULL
) {
2370 ntohs(args
->fwa_eh
->ether_type
);
2372 ((ipfw_insn_u16
*)cmd
)->ports
;
2375 for (i
= cmdlen
- 1; !match
&& i
>0;
2377 match
= (t
>=p
[0] && t
<=p
[1]);
2382 match
= (hlen
> 0 && offset
!= 0);
2385 case O_IN
: /* "out" is "not in" */
2386 match
= (oif
== NULL
);
2390 match
= (args
->fwa_eh
!= NULL
);
2395 * We do not allow an arg of 0 so the
2396 * check of "proto" only suffices.
2398 match
= (proto
== cmd
->arg1
);
2402 match
= (hlen
> 0 &&
2403 ((ipfw_insn_ip
*)cmd
)->addr
.s_addr
==
2411 (cmd
->opcode
== O_IP_DST_MASK
) ?
2412 dst_ip
.s_addr
: src_ip
.s_addr
;
2413 uint32_t *p
= ((ipfw_insn_u32
*)cmd
)->d
;
2416 for (; !match
&& i
>0; i
-= 2, p
+= 2)
2417 match
= (p
[0] == (a
& p
[1]));
2425 INADDR_TO_IFP(src_ip
, tif
);
2426 match
= (tif
!= NULL
);
2433 u_int32_t
*d
= (u_int32_t
*)(cmd
+1);
2435 cmd
->opcode
== O_IP_DST_SET
?
2436 args
->fwa_id
.dst_ip
:
2437 args
->fwa_id
.src_ip
;
2441 addr
-= d
[0]; /* subtract base */
2442 match
= (addr
< cmd
->arg1
) &&
2443 ( d
[ 1 + (addr
>>5)] &
2444 (1<<(addr
& 0x1f)) );
2449 match
= (hlen
> 0 &&
2450 ((ipfw_insn_ip
*)cmd
)->addr
.s_addr
==
2458 INADDR_TO_IFP(dst_ip
, tif
);
2459 match
= (tif
!= NULL
);
2466 * offset == 0 && proto != 0 is enough
2467 * to guarantee that we have an IPv4
2468 * packet with port info.
2470 if ((proto
==IPPROTO_UDP
|| proto
==IPPROTO_TCP
)
2473 (cmd
->opcode
== O_IP_SRCPORT
) ?
2474 src_port
: dst_port
;
2476 ((ipfw_insn_u16
*)cmd
)->ports
;
2479 for (i
= cmdlen
- 1; !match
&& i
>0;
2481 match
= (x
>=p
[0] && x
<=p
[1]);
2486 match
= (offset
== 0 && proto
==IPPROTO_ICMP
&&
2487 icmptype_match(ip
, (ipfw_insn_u32
*)cmd
) );
2491 match
= (hlen
> 0 && ipopts_match(ip
, cmd
) );
2495 match
= (hlen
> 0 && cmd
->arg1
== ip
->ip_v
);
2501 if (hlen
> 0) { /* only for IP packets */
2506 if (cmd
->opcode
== O_IPLEN
)
2508 else if (cmd
->opcode
== O_IPTTL
)
2510 else /* must be IPID */
2511 x
= ntohs(ip
->ip_id
);
2513 match
= (cmd
->arg1
== x
);
2516 /* otherwise we have ranges */
2517 p
= ((ipfw_insn_u16
*)cmd
)->ports
;
2519 for (; !match
&& i
>0; i
--, p
+= 2)
2520 match
= (x
>= p
[0] && x
<= p
[1]);
2524 case O_IPPRECEDENCE
:
2525 match
= (hlen
> 0 &&
2526 (cmd
->arg1
== (ip
->ip_tos
& 0xe0)) );
2530 match
= (hlen
> 0 &&
2531 flags_match(cmd
, ip
->ip_tos
));
2535 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
2537 L3HDR(struct tcphdr
,ip
)->th_flags
));
2541 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
2542 tcpopts_match(ip
, cmd
));
2546 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
2547 ((ipfw_insn_u32
*)cmd
)->d
[0] ==
2548 L3HDR(struct tcphdr
,ip
)->th_seq
);
2552 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
2553 ((ipfw_insn_u32
*)cmd
)->d
[0] ==
2554 L3HDR(struct tcphdr
,ip
)->th_ack
);
2558 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
2560 L3HDR(struct tcphdr
,ip
)->th_win
);
2564 /* reject packets which have SYN only */
2565 /* XXX should i also check for TH_ACK ? */
2566 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
2567 (L3HDR(struct tcphdr
,ip
)->th_flags
&
2568 (TH_RST
| TH_ACK
| TH_SYN
)) != TH_SYN
);
2573 ipfw_log(f
, hlen
, args
->fwa_eh
, m
, oif
);
2578 match
= (random()<((ipfw_insn_u32
*)cmd
)->d
[0]);
2582 /* Outgoing packets automatically pass/match */
2583 match
= ((oif
!= NULL
) ||
2584 (m
->m_pkthdr
.rcvif
== NULL
) ||
2585 verify_rev_path(src_ip
, m
->m_pkthdr
.rcvif
));
2590 match
= (m_tag_find(m
,
2591 PACKET_TAG_IPSEC_IN_DONE
, NULL
) != NULL
);
2594 match
= (ipsec_gethist(m
, NULL
) != NULL
);
2596 /* otherwise no match */
2600 * The second set of opcodes represents 'actions',
2601 * i.e. the terminal part of a rule once the packet
2602 * matches all previous patterns.
2603 * Typically there is only one action for each rule,
2604 * and the opcode is stored at the end of the rule
2605 * (but there are exceptions -- see below).
2607 * In general, here we set retval and terminate the
2608 * outer loop (would be a 'break 3' in some language,
2609 * but we need to do a 'goto done').
2612 * O_COUNT and O_SKIPTO actions:
2613 * instead of terminating, we jump to the next rule
2614 * ('goto next_rule', equivalent to a 'break 2'),
2615 * or to the SKIPTO target ('goto again' after
2616 * having set f, cmd and l), respectively.
2618 * O_LIMIT and O_KEEP_STATE: these opcodes are
2619 * not real 'actions', and are stored right
2620 * before the 'action' part of the rule.
2621 * These opcodes try to install an entry in the
2622 * state tables; if successful, we continue with
2623 * the next opcode (match=1; break;), otherwise
2624 * the packet * must be dropped
2625 * ('goto done' after setting retval);
2627 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2628 * cause a lookup of the state table, and a jump
2629 * to the 'action' part of the parent rule
2630 * ('goto check_body') if an entry is found, or
2631 * (CHECK_STATE only) a jump to the next rule if
2632 * the entry is not found ('goto next_rule').
2633 * The result of the lookup is cached to make
2634 * further instances of these opcodes are
2639 if (install_state(f
,
2640 (ipfw_insn_limit
*)cmd
, args
)) {
2641 retval
= IP_FW_PORT_DENY_FLAG
;
2642 goto done
; /* error/limit violation */
2650 * dynamic rules are checked at the first
2651 * keep-state or check-state occurrence,
2652 * with the result being stored in dyn_dir.
2653 * The compiler introduces a PROBE_STATE
2654 * instruction for us when we have a
2655 * KEEP_STATE (because PROBE_STATE needs
2658 if (dyn_dir
== MATCH_UNKNOWN
&&
2659 (q
= lookup_dyn_rule(&args
->fwa_id
,
2660 &dyn_dir
, proto
== IPPROTO_TCP
?
2661 L3HDR(struct tcphdr
, ip
) : NULL
))
2664 * Found dynamic entry, update stats
2665 * and jump to the 'action' part of
2671 cmd
= ACTION_PTR(f
);
2672 l
= f
->cmd_len
- f
->act_ofs
;
2676 * Dynamic entry not found. If CHECK_STATE,
2677 * skip to next rule, if PROBE_STATE just
2678 * ignore and continue with next opcode.
2680 if (cmd
->opcode
== O_CHECK_STATE
)
2686 retval
= 0; /* accept */
2691 args
->fwa_ipfw_rule
= f
; /* report matching rule */
2692 retval
= cmd
->arg1
| IP_FW_PORT_DYNT_FLAG
;
2697 if (args
->fwa_eh
) /* not on layer 2 */
2699 args
->fwa_divert_rule
= f
->rulenum
;
2700 retval
= (cmd
->opcode
== O_DIVERT
) ?
2702 cmd
->arg1
| IP_FW_PORT_TEE_FLAG
;
2707 f
->pcnt
++; /* update stats */
2709 f
->timestamp
= timenow
.tv_sec
;
2710 if (cmd
->opcode
== O_COUNT
)
2713 if (f
->next_rule
== NULL
)
2714 lookup_next_rule(f
);
2720 * Drop the packet and send a reject notice
2721 * if the packet is not ICMP (or is an ICMP
2722 * query), and it is not multicast/broadcast.
2724 if (hlen
> 0 && offset
== 0 &&
2725 (proto
!= IPPROTO_ICMP
||
2726 is_icmp_query(ip
)) &&
2727 !(m
->m_flags
& (M_BCAST
|M_MCAST
)) &&
2728 !IN_MULTICAST(dst_ip
.s_addr
)) {
2729 send_reject(args
, cmd
->arg1
,
2735 retval
= IP_FW_PORT_DENY_FLAG
;
2739 if (args
->fwa_eh
) /* not valid on layer2 pkts */
2741 if (!q
|| dyn_dir
== MATCH_FORWARD
)
2742 args
->fwa_next_hop
=
2743 &((ipfw_insn_sa
*)cmd
)->sa
;
2748 panic("-- unknown opcode %d\n", cmd
->opcode
);
2749 } /* end of switch() on opcodes */
2751 if (cmd
->len
& F_NOT
)
2755 if (cmd
->len
& F_OR
)
2758 if (!(cmd
->len
& F_OR
)) /* not an OR block, */
2759 break; /* try next rule */
2762 } /* end of inner for, scan opcodes */
2764 next_rule
:; /* try next rule */
2766 } /* end of outer for, scan rules */
2767 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
2768 lck_mtx_unlock(ipfw_mutex
);
2769 return(IP_FW_PORT_DENY_FLAG
);
2772 /* Update statistics */
2775 f
->timestamp
= timenow
.tv_sec
;
2776 lck_mtx_unlock(ipfw_mutex
);
2781 printf("ipfw: pullup failed\n");
2782 lck_mtx_unlock(ipfw_mutex
);
2783 return(IP_FW_PORT_DENY_FLAG
);
2787 * When a rule is added/deleted, clear the next_rule pointers in all rules.
2788 * These will be reconstructed on the fly as packets are matched.
2789 * Must be called at splimp().
2792 flush_rule_ptrs(void)
2796 for (rule
= layer3_chain
; rule
; rule
= rule
->next
)
2797 rule
->next_rule
= NULL
;
2801 * When pipes/queues are deleted, clear the "pipe_ptr" pointer to a given
2802 * pipe/queue, or to all of them (match == NULL).
2803 * Must be called at splimp().
2806 flush_pipe_ptrs(struct dn_flow_set
*match
)
2810 for (rule
= layer3_chain
; rule
; rule
= rule
->next
) {
2811 ipfw_insn_pipe
*cmd
= (ipfw_insn_pipe
*)ACTION_PTR(rule
);
2813 if (cmd
->o
.opcode
!= O_PIPE
&& cmd
->o
.opcode
!= O_QUEUE
)
2816 * XXX Use bcmp/bzero to handle pipe_ptr to overcome
2817 * possible alignment problems on 64-bit architectures.
2818 * This code is seldom used so we do not worry too
2819 * much about efficiency.
2821 if (match
== NULL
||
2822 !bcmp(&cmd
->pipe_ptr
, &match
, sizeof(match
)) )
2823 bzero(&cmd
->pipe_ptr
, sizeof(cmd
->pipe_ptr
));
2828 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
2829 * possibly create a rule number and add the rule to the list.
2830 * Update the rule_number in the input struct so the caller knows it as well.
2833 add_rule(struct ip_fw
**head
, struct ip_fw
*input_rule
)
2835 struct ip_fw
*rule
, *f
, *prev
;
2836 int l
= RULESIZE(input_rule
);
2838 if (*head
== NULL
&& input_rule
->rulenum
!= IPFW_DEFAULT_RULE
)
2841 rule
= _MALLOC(l
, M_IPFW
, M_WAIT
| M_ZERO
);
2843 printf("ipfw2: add_rule MALLOC failed\n");
2847 bcopy(input_rule
, rule
, l
);
2850 rule
->next_rule
= NULL
;
2854 rule
->timestamp
= 0;
2856 if (*head
== NULL
) { /* default rule */
2862 * If rulenum is 0, find highest numbered rule before the
2863 * default rule, and add autoinc_step
2865 if (autoinc_step
< 1)
2867 else if (autoinc_step
> 1000)
2868 autoinc_step
= 1000;
2869 if (rule
->rulenum
== 0) {
2871 * locate the highest numbered rule before default
2873 for (f
= *head
; f
; f
= f
->next
) {
2874 if (f
->rulenum
== IPFW_DEFAULT_RULE
)
2876 rule
->rulenum
= f
->rulenum
;
2878 if (rule
->rulenum
< IPFW_DEFAULT_RULE
- autoinc_step
)
2879 rule
->rulenum
+= autoinc_step
;
2880 input_rule
->rulenum
= rule
->rulenum
;
2884 * Now insert the new rule in the right place in the sorted list.
2886 for (prev
= NULL
, f
= *head
; f
; prev
= f
, f
= f
->next
) {
2887 if (f
->rulenum
> rule
->rulenum
) { /* found the location */
2891 } else { /* head insert */
2902 static_len_32
+= RULESIZE32(input_rule
);
2903 static_len_64
+= RULESIZE64(input_rule
);
2904 DEB(printf("ipfw: installed rule %d, static count now %d\n",
2905 rule
->rulenum
, static_count
);)
2910 * Free storage associated with a static rule (including derived
2912 * The caller is in charge of clearing rule pointers to avoid
2913 * dangling pointers.
2914 * @return a pointer to the next entry.
2915 * Arguments are not checked, so they better be correct.
2916 * Must be called at splimp().
2918 static struct ip_fw
*
2919 delete_rule(struct ip_fw
**head
, struct ip_fw
*prev
, struct ip_fw
*rule
)
2922 int l
= RULESIZE(rule
);
2925 remove_dyn_rule(rule
, NULL
/* force removal */);
2932 static_len_32
-= RULESIZE32(rule
);
2933 static_len_64
-= RULESIZE64(rule
);
2936 if (DUMMYNET_LOADED
)
2937 dn_ipfw_rule_delete(rule
);
2938 #endif /* DUMMYNET */
2939 _FREE(rule
, M_IPFW
);
2943 #if DEBUG_INACTIVE_RULES
2945 print_chain(struct ip_fw
**chain
)
2947 struct ip_fw
*rule
= *chain
;
2949 for (; rule
; rule
= rule
->next
) {
2950 ipfw_insn
*cmd
= ACTION_PTR(rule
);
2952 printf("ipfw: rule->rulenum = %d\n", rule
->rulenum
);
2954 if (rule
->reserved_1
== IPFW_RULE_INACTIVE
) {
2955 printf("ipfw: rule->reserved = IPFW_RULE_INACTIVE\n");
2958 switch (cmd
->opcode
) {
2960 printf("ipfw: ACTION: Deny\n");
2964 if (cmd
->arg1
==ICMP_REJECT_RST
)
2965 printf("ipfw: ACTION: Reset\n");
2966 else if (cmd
->arg1
==ICMP_UNREACH_HOST
)
2967 printf("ipfw: ACTION: Reject\n");
2971 printf("ipfw: ACTION: Accept\n");
2974 printf("ipfw: ACTION: Count\n");
2977 printf("ipfw: ACTION: Divert\n");
2980 printf("ipfw: ACTION: Tee\n");
2983 printf("ipfw: ACTION: SkipTo\n");
2986 printf("ipfw: ACTION: Pipe\n");
2989 printf("ipfw: ACTION: Queue\n");
2992 printf("ipfw: ACTION: Forward\n");
2995 printf("ipfw: invalid action! %d\n", cmd
->opcode
);
2999 #endif /* DEBUG_INACTIVE_RULES */
3002 flush_inactive(void *param
)
3004 struct ip_fw
*inactive_rule
= (struct ip_fw
*)param
;
3005 struct ip_fw
*rule
, *prev
;
3007 lck_mtx_lock(ipfw_mutex
);
3009 for (rule
= layer3_chain
, prev
= NULL
; rule
; ) {
3010 if (rule
== inactive_rule
&& rule
->reserved_1
== IPFW_RULE_INACTIVE
) {
3011 struct ip_fw
*n
= rule
;
3014 layer3_chain
= rule
->next
;
3017 prev
->next
= rule
->next
;
3028 #if DEBUG_INACTIVE_RULES
3029 print_chain(&layer3_chain
);
3031 lck_mtx_unlock(ipfw_mutex
);
3035 mark_inactive(struct ip_fw
**prev
, struct ip_fw
**rule
)
3037 int l
= RULESIZE(*rule
);
3039 if ((*rule
)->reserved_1
!= IPFW_RULE_INACTIVE
) {
3040 (*rule
)->reserved_1
= IPFW_RULE_INACTIVE
;
3043 static_len_32
-= RULESIZE32(*rule
);
3044 static_len_64
-= RULESIZE64(*rule
);
3046 timeout(flush_inactive
, *rule
, 30*hz
); /* 30 sec. */
3050 *rule
= (*rule
)->next
;
3054 * Deletes all rules from a chain (except rules in set RESVD_SET
3055 * unless kill_default = 1).
3056 * Must be called at splimp().
3059 free_chain(struct ip_fw
**chain
, int kill_default
)
3061 struct ip_fw
*prev
, *rule
;
3063 flush_rule_ptrs(); /* more efficient to do outside the loop */
3064 for (prev
= NULL
, rule
= *chain
; rule
; )
3065 if (kill_default
|| rule
->set
!= RESVD_SET
) {
3066 ipfw_insn
*cmd
= ACTION_PTR(rule
);
3068 /* skip over forwarding rules so struct isn't
3069 * deleted while pointer is still in use elsewhere
3071 if (cmd
->opcode
== O_FORWARD_IP
) {
3072 mark_inactive(&prev
, &rule
);
3075 rule
= delete_rule(chain
, prev
, rule
);
3085 * Remove all rules with given number, and also do set manipulation.
3086 * Assumes chain != NULL && *chain != NULL.
3088 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
3089 * the next 8 bits are the new set, the top 8 bits are the command:
3091 * 0 delete rules with given number
3092 * 1 delete rules with given set number
3093 * 2 move rules with given number to new set
3094 * 3 move rules with given set number to new set
3095 * 4 swap sets with given numbers
3098 del_entry(struct ip_fw
**chain
, u_int32_t arg
)
3100 struct ip_fw
*prev
= NULL
, *rule
= *chain
;
3101 u_int16_t rulenum
; /* rule or old_set */
3102 u_int8_t cmd
, new_set
;
3104 rulenum
= arg
& 0xffff;
3105 cmd
= (arg
>> 24) & 0xff;
3106 new_set
= (arg
>> 16) & 0xff;
3110 if (new_set
> RESVD_SET
)
3112 if (cmd
== 0 || cmd
== 2) {
3113 if (rulenum
>= IPFW_DEFAULT_RULE
)
3116 if (rulenum
> RESVD_SET
) /* old_set */
3121 case 0: /* delete rules with given number */
3123 * locate first rule to delete
3125 for (; rule
->rulenum
< rulenum
; prev
= rule
, rule
= rule
->next
)
3127 if (rule
->rulenum
!= rulenum
)
3131 * flush pointers outside the loop, then delete all matching
3132 * rules. prev remains the same throughout the cycle.
3135 while (rule
->rulenum
== rulenum
) {
3136 ipfw_insn
*insn
= ACTION_PTR(rule
);
3138 /* keep forwarding rules around so struct isn't
3139 * deleted while pointer is still in use elsewhere
3141 if (insn
->opcode
== O_FORWARD_IP
) {
3142 mark_inactive(&prev
, &rule
);
3145 rule
= delete_rule(chain
, prev
, rule
);
3150 case 1: /* delete all rules with given set number */
3152 while (rule
->rulenum
< IPFW_DEFAULT_RULE
) {
3153 if (rule
->set
== rulenum
) {
3154 ipfw_insn
*insn
= ACTION_PTR(rule
);
3156 /* keep forwarding rules around so struct isn't
3157 * deleted while pointer is still in use elsewhere
3159 if (insn
->opcode
== O_FORWARD_IP
) {
3160 mark_inactive(&prev
, &rule
);
3163 rule
= delete_rule(chain
, prev
, rule
);
3173 case 2: /* move rules with given number to new set */
3174 for (; rule
->rulenum
< IPFW_DEFAULT_RULE
; rule
= rule
->next
)
3175 if (rule
->rulenum
== rulenum
)
3176 rule
->set
= new_set
;
3179 case 3: /* move rules with given set number to new set */
3180 for (; rule
->rulenum
< IPFW_DEFAULT_RULE
; rule
= rule
->next
)
3181 if (rule
->set
== rulenum
)
3182 rule
->set
= new_set
;
3185 case 4: /* swap two sets */
3186 for (; rule
->rulenum
< IPFW_DEFAULT_RULE
; rule
= rule
->next
)
3187 if (rule
->set
== rulenum
)
3188 rule
->set
= new_set
;
3189 else if (rule
->set
== new_set
)
3190 rule
->set
= rulenum
;
3197 * Clear counters for a specific rule.
3200 clear_counters(struct ip_fw
*rule
, int log_only
)
3202 ipfw_insn_log
*l
= (ipfw_insn_log
*)ACTION_PTR(rule
);
3204 if (log_only
== 0) {
3205 rule
->bcnt
= rule
->pcnt
= 0;
3206 rule
->timestamp
= 0;
3208 if (l
->o
.opcode
== O_LOG
)
3209 l
->log_left
= l
->max_log
;
3213 * Reset some or all counters on firewall rules.
3214 * @arg frwl is null to clear all entries, or contains a specific
3216 * @arg log_only is 1 if we only want to reset logs, zero otherwise.
3219 zero_entry(int rulenum
, int log_only
)
3226 for (rule
= layer3_chain
; rule
; rule
= rule
->next
)
3227 clear_counters(rule
, log_only
);
3228 msg
= log_only
? "ipfw: All logging counts reset.\n" :
3229 "ipfw: Accounting cleared.\n";
3233 * We can have multiple rules with the same number, so we
3234 * need to clear them all.
3236 for (rule
= layer3_chain
; rule
; rule
= rule
->next
)
3237 if (rule
->rulenum
== rulenum
) {
3238 while (rule
&& rule
->rulenum
== rulenum
) {
3239 clear_counters(rule
, log_only
);
3245 if (!cleared
) /* we did not find any matching rules */
3247 msg
= log_only
? "ipfw: Entry %d logging count reset.\n" :
3248 "ipfw: Entry %d cleared.\n";
3252 dolog((LOG_AUTHPRIV
| LOG_NOTICE
, msg
, rulenum
));
3258 * Check validity of the structure before insert.
3259 * Fortunately rules are simple, so this mostly need to check rule sizes.
3262 check_ipfw_struct(struct ip_fw
*rule
, int size
)
3268 if (size
< sizeof(*rule
)) {
3269 printf("ipfw: rule too short\n");
3272 /* first, check for valid size */
3275 printf("ipfw: size mismatch (have %d want %d)\n", size
, l
);
3279 * Now go for the individual checks. Very simple ones, basically only
3280 * instruction sizes.
3282 for (l
= rule
->cmd_len
, cmd
= rule
->cmd
;
3283 l
> 0 ; l
-= cmdlen
, cmd
+= cmdlen
) {
3284 cmdlen
= F_LEN(cmd
);
3286 printf("ipfw: opcode %d size truncated\n",
3290 DEB(printf("ipfw: opcode %d\n", cmd
->opcode
);)
3291 switch (cmd
->opcode
) {
3302 case O_IPPRECEDENCE
:
3310 if (cmdlen
!= F_INSN_SIZE(ipfw_insn
))
3316 #endif /* __APPLE__ */
3323 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_u32
))
3328 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_limit
))
3333 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_log
))
3336 /* enforce logging limit */
3338 ((ipfw_insn_log
*)cmd
)->max_log
== 0 && verbose_limit
!= 0) {
3339 ((ipfw_insn_log
*)cmd
)->max_log
= verbose_limit
;
3342 ((ipfw_insn_log
*)cmd
)->log_left
=
3343 ((ipfw_insn_log
*)cmd
)->max_log
;
3349 /* only odd command lengths */
3350 if ( !(cmdlen
& 1) || cmdlen
> 31)
3356 if (cmd
->arg1
== 0 || cmd
->arg1
> 256) {
3357 printf("ipfw: invalid set size %d\n",
3361 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_u32
) +
3367 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_mac
))
3375 if (cmdlen
< 1 || cmdlen
> 31)
3381 case O_IP_DSTPORT
: /* XXX artificial limit, 30 port pairs */
3382 if (cmdlen
< 2 || cmdlen
> 31)
3389 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_if
))
3395 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_pipe
))
3400 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_sa
))
3404 case O_FORWARD_MAC
: /* XXX not implemented yet */
3413 if (cmdlen
!= F_INSN_SIZE(ipfw_insn
))
3417 printf("ipfw: opcode %d, multiple actions"
3424 printf("ipfw: opcode %d, action must be"
3431 printf("ipfw: opcode %d, unknown opcode\n",
3436 if (have_action
== 0) {
3437 printf("ipfw: missing action\n");
3443 printf("ipfw: opcode %d size %d wrong\n",
3444 cmd
->opcode
, cmdlen
);
3450 ipfw_kev_post_msg(u_int32_t event_code
)
3452 struct kev_msg ev_msg
;
3454 bzero(&ev_msg
, sizeof(struct kev_msg
));
3456 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
3457 ev_msg
.kev_class
= KEV_FIREWALL_CLASS
;
3458 ev_msg
.kev_subclass
= KEV_IPFW_SUBCLASS
;
3459 ev_msg
.event_code
= event_code
;
3461 kev_post_msg(&ev_msg
);
3466 * {set|get}sockopt parser.
3469 ipfw_ctl(struct sockopt
*sopt
)
3471 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
3472 u_int32_t api_version
;
3476 size_t rulesize
= RULE_MAXSIZE
;
3477 struct ip_fw
*bp
, *buf
, *rule
;
3480 /* copy of orig sopt to send to ipfw_get_command_and_version() */
3481 struct sockopt tmp_sopt
= *sopt
;
3482 struct timeval timenow
;
3484 getmicrotime(&timenow
);
3487 * Disallow modifications in really-really secure mode, but still allow
3488 * the logging counters to be reset.
3490 if (sopt
->sopt_name
== IP_FW_ADD
||
3491 (sopt
->sopt_dir
== SOPT_SET
&& sopt
->sopt_name
!= IP_FW_RESETLOG
)) {
3492 #if __FreeBSD_version >= 500034
3493 error
= securelevel_ge(sopt
->sopt_td
->td_ucred
, 3);
3496 #else /* FreeBSD 4.x */
3497 if (securelevel
>= 3)
3502 /* first get the command and version, then do conversion as necessary */
3503 error
= ipfw_get_command_and_version(&tmp_sopt
, &command
, &api_version
);
3505 /* error getting the version */
3509 if (proc_is64bit(sopt
->sopt_p
))
3517 * pass up a copy of the current rules. Static rules
3518 * come first (the last of which has number IPFW_DEFAULT_RULE),
3519 * followed by a possibly empty list of dynamic rule.
3520 * The last dynamic rule has NULL in the "next" field.
3522 lck_mtx_lock(ipfw_mutex
);
3525 size
= Get64static_len();
3526 dynrulesize
= sizeof(ipfw_dyn_rule_64
);
3528 size
+= (dyn_count
* dynrulesize
);
3530 size
= Get32static_len();
3531 dynrulesize
= sizeof(ipfw_dyn_rule_32
);
3533 size
+= (dyn_count
* dynrulesize
);
3537 * XXX todo: if the user passes a short length just to know
3538 * how much room is needed, do not bother filling up the
3539 * buffer, just jump to the sooptcopyout.
3541 buf
= _MALLOC(size
, M_TEMP
, M_WAITOK
| M_ZERO
);
3543 lck_mtx_unlock(ipfw_mutex
);
3549 for (rule
= layer3_chain
; rule
; rule
= rule
->next
) {
3551 if (rule
->reserved_1
== IPFW_RULE_INACTIVE
) {
3558 copyto64fw( rule
, (struct ip_fw_64
*)bp
, size
);
3559 bcopy(&set_disable
, &(( (struct ip_fw_64
*)bp
)->next_rule
), sizeof(set_disable
));
3560 /* do not use macro RULESIZE64 since we want RULESIZE for ip_fw_64 */
3561 rulesize_64
= sizeof(struct ip_fw_64
) + ((struct ip_fw_64
*)(bp
))->cmd_len
* 4 - 4;
3562 bp
= (struct ip_fw
*)((char *)bp
+ rulesize_64
);
3566 copyto32fw( rule
, (struct ip_fw_32
*)bp
, size
);
3567 bcopy(&set_disable
, &(( (struct ip_fw_32
*)bp
)->next_rule
), sizeof(set_disable
));
3568 /* do not use macro RULESIZE32 since we want RULESIZE for ip_fw_32 */
3569 rulesize_32
= sizeof(struct ip_fw_32
) + ((struct ip_fw_32
*)(bp
))->cmd_len
* 4 - 4;
3570 bp
= (struct ip_fw
*)((char *)bp
+ rulesize_32
);
3576 char *dst
, *last
= NULL
;
3579 for (i
= 0 ; i
< curr_dyn_buckets
; i
++ )
3580 for ( p
= ipfw_dyn_v
[i
] ; p
!= NULL
;
3581 p
= p
->next
, dst
+= dynrulesize
) {
3583 ipfw_dyn_rule_64
*ipfw_dyn_dst
;
3585 ipfw_dyn_dst
= (ipfw_dyn_rule_64
*)dst
;
3587 * store a non-null value in "next".
3588 * The userland code will interpret a
3589 * NULL here as a marker
3590 * for the last dynamic rule.
3592 ipfw_dyn_dst
->next
= CAST_DOWN_EXPLICIT(user64_addr_t
, dst
);
3593 ipfw_dyn_dst
->rule
= p
->rule
->rulenum
;
3594 ipfw_dyn_dst
->parent
= CAST_DOWN(user64_addr_t
, p
->parent
);
3595 ipfw_dyn_dst
->pcnt
= p
->pcnt
;
3596 ipfw_dyn_dst
->bcnt
= p
->bcnt
;
3597 externalize_flow_id(&ipfw_dyn_dst
->id
, &p
->id
);
3598 ipfw_dyn_dst
->expire
=
3599 TIME_LEQ(p
->expire
, timenow
.tv_sec
) ?
3600 0 : p
->expire
- timenow
.tv_sec
;
3601 ipfw_dyn_dst
->bucket
= p
->bucket
;
3602 ipfw_dyn_dst
->state
= p
->state
;
3603 ipfw_dyn_dst
->ack_fwd
= p
->ack_fwd
;
3604 ipfw_dyn_dst
->ack_rev
= p
->ack_rev
;
3605 ipfw_dyn_dst
->dyn_type
= p
->dyn_type
;
3606 ipfw_dyn_dst
->count
= p
->count
;
3607 last
= (char*)ipfw_dyn_dst
;
3609 ipfw_dyn_rule_32
*ipfw_dyn_dst
;
3611 ipfw_dyn_dst
= (ipfw_dyn_rule_32
*)dst
;
3613 * store a non-null value in "next".
3614 * The userland code will interpret a
3615 * NULL here as a marker
3616 * for the last dynamic rule.
3618 ipfw_dyn_dst
->next
= CAST_DOWN_EXPLICIT(user32_addr_t
, dst
);
3619 ipfw_dyn_dst
->rule
= p
->rule
->rulenum
;
3620 ipfw_dyn_dst
->parent
= CAST_DOWN_EXPLICIT(user32_addr_t
, p
->parent
);
3621 ipfw_dyn_dst
->pcnt
= p
->pcnt
;
3622 ipfw_dyn_dst
->bcnt
= p
->bcnt
;
3623 externalize_flow_id(&ipfw_dyn_dst
->id
, &p
->id
);
3624 ipfw_dyn_dst
->expire
=
3625 TIME_LEQ(p
->expire
, timenow
.tv_sec
) ?
3626 0 : p
->expire
- timenow
.tv_sec
;
3627 ipfw_dyn_dst
->bucket
= p
->bucket
;
3628 ipfw_dyn_dst
->state
= p
->state
;
3629 ipfw_dyn_dst
->ack_fwd
= p
->ack_fwd
;
3630 ipfw_dyn_dst
->ack_rev
= p
->ack_rev
;
3631 ipfw_dyn_dst
->dyn_type
= p
->dyn_type
;
3632 ipfw_dyn_dst
->count
= p
->count
;
3633 last
= (char*)ipfw_dyn_dst
;
3636 /* mark last dynamic rule */
3639 ((ipfw_dyn_rule_64
*)last
)->next
= 0;
3641 ((ipfw_dyn_rule_32
*)last
)->next
= 0;
3644 lck_mtx_unlock(ipfw_mutex
);
3646 /* convert back if necessary and copyout */
3647 if (api_version
== IP_FW_VERSION_0
) {
3649 struct ip_old_fw
*buf2
, *rule_vers0
;
3651 lck_mtx_lock(ipfw_mutex
);
3652 buf2
= _MALLOC(static_count
* sizeof(struct ip_old_fw
), M_TEMP
, M_WAITOK
);
3654 lck_mtx_unlock(ipfw_mutex
);
3662 for (i
= 0; i
< static_count
; i
++) {
3663 /* static rules have different sizes */
3664 int j
= RULESIZE(bp
);
3665 ipfw_convert_from_latest(bp
, rule_vers0
, api_version
, is64user
);
3666 bp
= (struct ip_fw
*)((char *)bp
+ j
);
3667 len
+= sizeof(*rule_vers0
);
3670 lck_mtx_unlock(ipfw_mutex
);
3671 error
= sooptcopyout(sopt
, buf2
, len
);
3672 _FREE(buf2
, M_TEMP
);
3674 } else if (api_version
== IP_FW_VERSION_1
) {
3675 int i
, len
= 0, buf_size
;
3676 struct ip_fw_compat
*buf2
;
3677 size_t ipfwcompsize
;
3678 size_t ipfwdyncompsize
;
3681 lck_mtx_lock(ipfw_mutex
);
3683 ipfwcompsize
= sizeof(struct ip_fw_compat_64
);
3684 ipfwdyncompsize
= sizeof(struct ipfw_dyn_rule_compat_64
);
3686 ipfwcompsize
= sizeof(struct ip_fw_compat_32
);
3687 ipfwdyncompsize
= sizeof(struct ipfw_dyn_rule_compat_32
);
3690 buf_size
= static_count
* ipfwcompsize
+
3691 dyn_count
* ipfwdyncompsize
;
3693 buf2
= _MALLOC(buf_size
, M_TEMP
, M_WAITOK
);
3695 lck_mtx_unlock(ipfw_mutex
);
3700 rule_vers1
= (char*)buf2
;
3702 /* first do static rules */
3703 for (i
= 0; i
< static_count
; i
++) {
3704 /* static rules have different sizes */
3707 ipfw_convert_from_latest(bp
, (void *)rule_vers1
, api_version
, is64user
);
3708 rulesize_64
= sizeof(struct ip_fw_64
) + ((struct ip_fw_64
*)(bp
))->cmd_len
* 4 - 4;
3709 bp
= (struct ip_fw
*)((char *)bp
+ rulesize_64
);
3712 ipfw_convert_from_latest(bp
, (void *)rule_vers1
, api_version
, is64user
);
3713 rulesize_32
= sizeof(struct ip_fw_32
) + ((struct ip_fw_32
*)(bp
))->cmd_len
* 4 - 4;
3714 bp
= (struct ip_fw
*)((char *)bp
+ rulesize_32
);
3716 len
+= ipfwcompsize
;
3717 rule_vers1
+= ipfwcompsize
;
3719 /* now do dynamic rules */
3721 cp_dyn_to_comp_64( (struct ipfw_dyn_rule_compat_64
*)rule_vers1
, &len
);
3723 cp_dyn_to_comp_32( (struct ipfw_dyn_rule_compat_32
*)rule_vers1
, &len
);
3725 lck_mtx_unlock(ipfw_mutex
);
3726 error
= sooptcopyout(sopt
, buf2
, len
);
3727 _FREE(buf2
, M_TEMP
);
3730 error
= sooptcopyout(sopt
, buf
, size
);
3739 * Normally we cannot release the lock on each iteration.
3740 * We could do it here only because we start from the head all
3741 * the times so there is no risk of missing some entries.
3742 * On the other hand, the risk is that we end up with
3743 * a very inconsistent ruleset, so better keep the lock
3744 * around the whole cycle.
3746 * XXX this code can be improved by resetting the head of
3747 * the list to point to the default rule, and then freeing
3748 * the old list without the need for a lock.
3751 lck_mtx_lock(ipfw_mutex
);
3752 free_chain(&layer3_chain
, 0 /* keep default rule */);
3754 #if DEBUG_INACTIVE_RULES
3755 print_chain(&layer3_chain
);
3757 lck_mtx_unlock(ipfw_mutex
);
3762 size_t savedsopt_valsize
=0;
3763 rule
= _MALLOC(RULE_MAXSIZE
, M_TEMP
, M_WAITOK
| M_ZERO
);
3769 if (api_version
!= IP_FW_CURRENT_API_VERSION
) {
3770 error
= ipfw_convert_to_latest(sopt
, rule
, api_version
, is64user
);
3773 savedsopt_valsize
= sopt
->sopt_valsize
; /* it might get modified in sooptcopyin_fw */
3774 error
= sooptcopyin_fw( sopt
, rule
, &rulesize
);
3779 if ((api_version
== IP_FW_VERSION_0
) || (api_version
== IP_FW_VERSION_1
)) {
3780 /* the rule has already been checked so just
3781 * adjust sopt_valsize to match what would be expected.
3783 sopt
->sopt_valsize
= RULESIZE(rule
);
3784 rulesize
= RULESIZE(rule
);
3786 error
= check_ipfw_struct(rule
, rulesize
);
3788 lck_mtx_lock(ipfw_mutex
);
3789 error
= add_rule(&layer3_chain
, rule
);
3790 if (!error
&& fw_bypass
)
3792 lck_mtx_unlock(ipfw_mutex
);
3794 size
= RULESIZE(rule
);
3795 if (!error
&& sopt
->sopt_dir
== SOPT_GET
) {
3796 /* convert back if necessary and copyout */
3797 if (api_version
== IP_FW_VERSION_0
) {
3798 struct ip_old_fw rule_vers0
;
3800 ipfw_convert_from_latest(rule
, &rule_vers0
, api_version
, is64user
);
3801 sopt
->sopt_valsize
= sizeof(struct ip_old_fw
);
3803 error
= sooptcopyout(sopt
, &rule_vers0
, sizeof(struct ip_old_fw
));
3804 } else if (api_version
== IP_FW_VERSION_1
) {
3805 struct ip_fw_compat rule_vers1
;
3806 ipfw_convert_from_latest(rule
, &rule_vers1
, api_version
, is64user
);
3807 sopt
->sopt_valsize
= sizeof(struct ip_fw_compat
);
3809 error
= sooptcopyout(sopt
, &rule_vers1
, sizeof(struct ip_fw_compat
));
3812 userrule
= _MALLOC(savedsopt_valsize
, M_TEMP
, M_WAITOK
);
3813 if ( userrule
== NULL
)
3814 userrule
= (char*)rule
;
3815 if (proc_is64bit(sopt
->sopt_p
)){
3816 copyto64fw( rule
, (struct ip_fw_64
*)userrule
, savedsopt_valsize
);
3819 copyto32fw( rule
, (struct ip_fw_32
*)userrule
, savedsopt_valsize
);
3821 error
= sooptcopyout(sopt
, userrule
, savedsopt_valsize
);
3823 _FREE(userrule
, M_TEMP
);
3829 _FREE(rule
, M_TEMP
);
3835 * IP_FW_DEL is used for deleting single rules or sets,
3836 * and (ab)used to atomically manipulate sets.
3837 * rule->rulenum != 0 indicates single rule delete
3838 * rule->set_masks used to manipulate sets
3839 * rule->set_masks[0] contains info on sets to be
3840 * disabled, swapped, or moved
3841 * rule->set_masks[1] contains sets to be enabled.
3844 /* there is only a simple rule passed in
3845 * (no cmds), so use a temp struct to copy
3847 struct ip_fw temp_rule
;
3851 bzero(&temp_rule
, sizeof(struct ip_fw
));
3852 if (api_version
!= IP_FW_CURRENT_API_VERSION
) {
3853 error
= ipfw_convert_to_latest(sopt
, &temp_rule
, api_version
, is64user
);
3856 error
= sooptcopyin_fw(sopt
, &temp_rule
, 0 );
3860 /* set_masks is used to distinguish between deleting
3861 * single rules or atomically manipulating sets
3863 lck_mtx_lock(ipfw_mutex
);
3865 arg
= temp_rule
.set_masks
[0];
3866 cmd
= (arg
>> 24) & 0xff;
3868 if (temp_rule
.rulenum
) {
3870 error
= del_entry(&layer3_chain
, temp_rule
.rulenum
);
3871 #if DEBUG_INACTIVE_RULES
3872 print_chain(&layer3_chain
);
3876 /* set reassignment - see comment above del_entry() for details */
3877 error
= del_entry(&layer3_chain
, temp_rule
.set_masks
[0]);
3878 #if DEBUG_INACTIVE_RULES
3879 print_chain(&layer3_chain
);
3882 else if (temp_rule
.set_masks
[0] != 0 ||
3883 temp_rule
.set_masks
[1] != 0) {
3884 /* set enable/disable */
3886 (set_disable
| temp_rule
.set_masks
[0]) & ~temp_rule
.set_masks
[1] &
3887 ~(1<<RESVD_SET
); /* set RESVD_SET always enabled */
3890 if (!layer3_chain
->next
)
3892 lck_mtx_unlock(ipfw_mutex
);
3897 case IP_FW_RESETLOG
: /* using rule->rulenum */
3899 /* there is only a simple rule passed in
3900 * (no cmds), so use a temp struct to copy
3902 struct ip_fw temp_rule
;
3904 bzero(&temp_rule
, sizeof(struct ip_fw
));
3906 if (api_version
!= IP_FW_CURRENT_API_VERSION
) {
3907 error
= ipfw_convert_to_latest(sopt
, &temp_rule
, api_version
, is64user
);
3910 if (sopt
->sopt_val
!= 0) {
3911 error
= sooptcopyin_fw( sopt
, &temp_rule
, 0);
3916 lck_mtx_lock(ipfw_mutex
);
3917 error
= zero_entry(temp_rule
.rulenum
, sopt
->sopt_name
== IP_FW_RESETLOG
);
3918 lck_mtx_unlock(ipfw_mutex
);
3923 printf("ipfw: ipfw_ctl invalid option %d\n", sopt
->sopt_name
);
3927 if (error
!= EINVAL
) {
3931 ipfw_kev_post_msg(KEV_IPFW_ADD
);
3935 ipfw_kev_post_msg(KEV_IPFW_DEL
);
3938 case IP_OLD_FW_FLUSH
:
3939 ipfw_kev_post_msg(KEV_IPFW_FLUSH
);
3951 * dummynet needs a reference to the default rule, because rules can be
3952 * deleted while packets hold a reference to them. When this happens,
3953 * dummynet changes the reference to the default rule (it could well be a
3954 * NULL pointer, but this way we do not need to check for the special
3955 * case, plus here he have info on the default behaviour).
3957 struct ip_fw
*ip_fw_default_rule
;
3960 * This procedure is only used to handle keepalives. It is invoked
3961 * every dyn_keepalive_period
3964 ipfw_tick(__unused
void * unused
)
3966 struct mbuf
*m0
, *m
, *mnext
, **mtailp
;
3969 struct timeval timenow
;
3970 static int stealth_cnt
= 0;
3972 if (ipfw_stealth_stats_needs_flush
) {
3974 if (!(stealth_cnt
% IPFW_STEALTH_TIMEOUT_FREQUENCY
)) {
3975 ipfw_stealth_flush_stats();
3979 if (dyn_keepalive
== 0 || ipfw_dyn_v
== NULL
|| dyn_count
== 0)
3982 getmicrotime(&timenow
);
3985 * We make a chain of packets to go out here -- not deferring
3986 * until after we drop the ipfw lock would result
3987 * in a lock order reversal with the normal packet input -> ipfw
3993 lck_mtx_lock(ipfw_mutex
);
3994 for (i
= 0 ; i
< curr_dyn_buckets
; i
++) {
3995 for (q
= ipfw_dyn_v
[i
] ; q
; q
= q
->next
) {
3996 if (q
->dyn_type
== O_LIMIT_PARENT
)
3998 if (q
->id
.proto
!= IPPROTO_TCP
)
4000 if ( (q
->state
& BOTH_SYN
) != BOTH_SYN
)
4002 if (TIME_LEQ( timenow
.tv_sec
+dyn_keepalive_interval
,
4004 continue; /* too early */
4005 if (TIME_LEQ(q
->expire
, timenow
.tv_sec
))
4006 continue; /* too late, rule expired */
4008 *mtailp
= send_pkt(&(q
->id
), q
->ack_rev
- 1, q
->ack_fwd
, TH_SYN
);
4009 if (*mtailp
!= NULL
)
4010 mtailp
= &(*mtailp
)->m_nextpkt
;
4012 *mtailp
= send_pkt(&(q
->id
), q
->ack_fwd
- 1, q
->ack_rev
, 0);
4013 if (*mtailp
!= NULL
)
4014 mtailp
= &(*mtailp
)->m_nextpkt
;
4017 lck_mtx_unlock(ipfw_mutex
);
4019 for (m
= mnext
= m0
; m
!= NULL
; m
= mnext
) {
4020 struct route sro
; /* fake route */
4022 mnext
= m
->m_nextpkt
;
4023 m
->m_nextpkt
= NULL
;
4024 bzero (&sro
, sizeof (sro
));
4025 ip_output(m
, NULL
, &sro
, 0, NULL
, NULL
);
4026 ROUTE_RELEASE(&sro
);
4029 timeout_with_leeway(ipfw_tick
, NULL
, dyn_keepalive_period
*hz
,
4030 DYN_KEEPALIVE_LEEWAY
*hz
);
4036 struct ip_fw default_rule
;
4039 ipfw_mutex_grp_attr
= lck_grp_attr_alloc_init();
4040 ipfw_mutex_grp
= lck_grp_alloc_init("ipfw", ipfw_mutex_grp_attr
);
4041 ipfw_mutex_attr
= lck_attr_alloc_init();
4042 lck_mtx_init(ipfw_mutex
, ipfw_mutex_grp
, ipfw_mutex_attr
);
4044 layer3_chain
= NULL
;
4046 bzero(&default_rule
, sizeof default_rule
);
4048 default_rule
.act_ofs
= 0;
4049 default_rule
.rulenum
= IPFW_DEFAULT_RULE
;
4050 default_rule
.cmd_len
= 1;
4051 default_rule
.set
= RESVD_SET
;
4053 default_rule
.cmd
[0].len
= 1;
4054 default_rule
.cmd
[0].opcode
=
4055 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4060 if (add_rule(&layer3_chain
, &default_rule
)) {
4061 printf("ipfw2: add_rule failed adding default rule\n");
4062 printf("ipfw2 failed initialization!!\n");
4066 ip_fw_default_rule
= layer3_chain
;
4068 #ifdef IPFIREWALL_VERBOSE
4071 #ifdef IPFIREWALL_VERBOSE_LIMIT
4072 verbose_limit
= IPFIREWALL_VERBOSE_LIMIT
;
4076 printf("ipfw2 verbose logging enabled: unlimited logging by default\n");
4078 printf("ipfw2 verbose logging enabled: limited to %d packets/entry by default\n",
4083 ip_fw_chk_ptr
= ipfw_chk
;
4084 ip_fw_ctl_ptr
= ipfw_ctl
;
4086 ipfwstringlen
= strlen( ipfwstring
);
4088 timeout(ipfw_tick
, NULL
, hz
);