2 * Copyright (c) 2004-2016 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
30 * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
32 * Redistribution and use in source and binary forms, with or without
33 * modification, are permitted provided that the following conditions
35 * 1. Redistributions of source code must retain the above copyright
36 * notice, this list of conditions and the following disclaimer.
37 * 2. Redistributions in binary form must reproduce the above copyright
38 * notice, this list of conditions and the following disclaimer in the
39 * documentation and/or other materials provided with the distribution.
41 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
42 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53 * $FreeBSD: src/sys/netinet/ip_fw2.c,v 1.6.2.18 2003/10/17 11:01:03 scottl Exp $
60 * Implement IP packet firewall (new version)
64 #error IPFIREWALL requires INET.
69 #include <sys/param.h>
70 #include <sys/systm.h>
71 #include <sys/malloc.h>
73 #include <sys/mcache.h>
74 #include <sys/kernel.h>
76 #include <sys/socket.h>
77 #include <sys/socketvar.h>
78 #include <sys/sysctl.h>
79 #include <sys/syslog.h>
80 #include <sys/ucred.h>
81 #include <sys/kern_event.h>
82 #include <sys/kauth.h>
85 #include <net/net_kev.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
) {
322 ipfw_kev_post_msg(KEV_IPFW_ENABLE
);
327 #endif /* SYSCTL_NODE */
330 static ip_fw_chk_t ipfw_chk
;
333 lck_grp_t
*ipfw_mutex_grp
;
334 lck_grp_attr_t
*ipfw_mutex_grp_attr
;
335 lck_attr_t
*ipfw_mutex_attr
;
336 decl_lck_mtx_data(, ipfw_mutex_data
);
337 lck_mtx_t
*ipfw_mutex
= &ipfw_mutex_data
;
339 extern void ipfwsyslog( int level
, const char *format
, ...);
341 #define ipfwstring "ipfw:"
342 static size_t ipfwstringlen
;
344 #define dolog( a ) { \
345 if ( fw_verbose == 2 ) /* Apple logging, log to ipfw.log */ \
350 #define RULESIZE64(rule) (sizeof(struct ip_fw_64) + \
351 ((struct ip_fw *)(rule))->cmd_len * 4 - 4)
353 #define RULESIZE32(rule) (sizeof(struct ip_fw_32) + \
354 ((struct ip_fw *)(rule))->cmd_len * 4 - 4)
357 ipfwsyslog( int level
, const char *format
, ...)
361 struct kev_msg ev_msg
;
363 char msgBuf
[msgsize
];
368 bzero(msgBuf
, msgsize
);
369 bzero(&ev_msg
, sizeof(struct kev_msg
));
370 va_start( ap
, format
);
371 loglen
= vsnprintf(msgBuf
, msgsize
, format
, ap
);
374 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
375 ev_msg
.kev_class
= KEV_NETWORK_CLASS
;
376 ev_msg
.kev_subclass
= KEV_LOG_SUBCLASS
;
377 ev_msg
.event_code
= IPFWLOGEVENT
;
379 /* get rid of the trailing \n */
380 if (loglen
< msgsize
) {
381 dptr
[loglen
- 1] = 0;
383 dptr
[msgsize
- 1] = 0;
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
);
403 ipfw_stealth_stats_incr(uint32_t type
)
405 if (type
>= IPFW_STEALTH_STATS_MAX
) {
409 ipfw_stealth_stats
[type
]++;
411 if (!ipfw_stealth_stats_needs_flush
) {
412 ipfw_stealth_stats_needs_flush
= TRUE
;
417 ipfw_stealth_stats_incr_udp(void)
419 ipfw_stealth_stats_incr(IPFW_STEALTH_STATS_UDP
);
423 ipfw_stealth_stats_incr_tcp(void)
425 ipfw_stealth_stats_incr(IPFW_STEALTH_STATS_TCP
);
429 ipfw_stealth_stats_incr_udpv6(void)
431 ipfw_stealth_stats_incr(IPFW_STEALTH_STATS_UDPv6
);
435 ipfw_stealth_stats_incr_tcpv6(void)
437 ipfw_stealth_stats_incr(IPFW_STEALTH_STATS_TCPv6
);
441 ipfw_stealth_flush_stats(void)
445 for (i
= 0; i
< IPFW_STEALTH_STATS_MAX
; i
++) {
446 if (ipfw_stealth_stats
[i
]) {
447 ipfwsyslog(LOG_INFO
, "Stealth Mode connection attempt to %s %d times",
448 ipfw_stealth_stats_str
[i
], ipfw_stealth_stats
[i
]);
449 ipfw_stealth_stats
[i
] = 0;
452 ipfw_stealth_stats_needs_flush
= FALSE
;
456 * This macro maps an ip pointer into a layer3 header pointer of type T
458 #define L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
461 icmptype_match(struct ip
*ip
, ipfw_insn_u32
*cmd
)
463 int type
= L3HDR(struct icmp
, ip
)->icmp_type
;
465 return type
<= ICMP_MAXTYPE
&& (cmd
->d
[0] & (1 << type
));
468 #define TT ( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
469 (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
472 is_icmp_query(struct ip
*ip
)
474 int type
= L3HDR(struct icmp
, ip
)->icmp_type
;
475 return type
<= ICMP_MAXTYPE
&& (TT
& (1 << type
));
480 Get32static_len(void)
483 int len
= static_len_32
;
487 for (rule
= layer3_chain
; rule
; rule
= rule
->next
) {
488 if (rule
->reserved_1
== IPFW_RULE_INACTIVE
) {
492 useraction
= (char*)ACTION_PTR( rule
);
493 if (((ipfw_insn
*)useraction
)->opcode
== O_QUEUE
|| ((ipfw_insn
*)useraction
)->opcode
== O_PIPE
) {
494 diff
= sizeof(ipfw_insn_pipe
) - sizeof(ipfw_insn_pipe_32
);
505 Get64static_len(void)
508 int len
= static_len_64
;
512 for (rule
= layer3_chain
; rule
; rule
= rule
->next
) {
513 if (rule
->reserved_1
== IPFW_RULE_INACTIVE
) {
517 useraction
= (char *)ACTION_PTR( rule
);
518 if (((ipfw_insn
*)useraction
)->opcode
== O_QUEUE
|| ((ipfw_insn
*)useraction
)->opcode
== O_PIPE
) {
519 diff
= sizeof(ipfw_insn_pipe_64
) - sizeof(ipfw_insn_pipe
);
530 copyto32fw_insn( struct ip_fw_32
*fw32
, struct ip_fw
*user_ip_fw
, int cmdsize
)
539 end
= ((char*)user_ip_fw
->cmd
) + cmdsize
;
540 useraction
= (char*)ACTION_PTR( user_ip_fw
);
541 fw32action
= (char*)fw32
->cmd
+ (user_ip_fw
->act_ofs
* sizeof(uint32_t));
542 if ((justcmdsize
= (fw32action
- (char*)fw32
->cmd
))) {
543 bcopy( user_ip_fw
->cmd
, fw32
->cmd
, justcmdsize
);
545 while (useraction
< end
) {
546 if (((ipfw_insn
*)useraction
)->opcode
== O_QUEUE
|| ((ipfw_insn
*)useraction
)->opcode
== O_PIPE
) {
547 actioncopysize
= sizeof(ipfw_insn_pipe_32
);
548 ((ipfw_insn
*)fw32action
)->opcode
= ((ipfw_insn
*)useraction
)->opcode
;
549 ((ipfw_insn
*)fw32action
)->arg1
= ((ipfw_insn
*)useraction
)->arg1
;
550 ((ipfw_insn
*)fw32action
)->len
= F_INSN_SIZE(ipfw_insn_pipe_32
);
551 diff
= ((ipfw_insn
*)useraction
)->len
- ((ipfw_insn
*)fw32action
)->len
;
553 fw32
->cmd_len
-= diff
;
556 actioncopysize
= (F_LEN((ipfw_insn
*)useraction
) ? (F_LEN((ipfw_insn
*)useraction
)) : 1) * sizeof(uint32_t);
557 bcopy( useraction
, fw32action
, actioncopysize
);
559 useraction
+= (F_LEN((ipfw_insn
*)useraction
) ? (F_LEN((ipfw_insn
*)useraction
)) : 1) * sizeof(uint32_t);
560 fw32action
+= actioncopysize
;
565 copyto64fw_insn( struct ip_fw_64
*fw64
, struct ip_fw
*user_ip_fw
, int cmdsize
)
574 end
= ((char *)user_ip_fw
->cmd
) + cmdsize
;
575 useraction
= (char*)ACTION_PTR( user_ip_fw
);
576 if ((justcmdsize
= (useraction
- (char*)user_ip_fw
->cmd
))) {
577 bcopy( user_ip_fw
->cmd
, fw64
->cmd
, justcmdsize
);
579 fw64action
= (char*)fw64
->cmd
+ justcmdsize
;
580 while (useraction
< end
) {
581 if (((ipfw_insn
*)user_ip_fw
)->opcode
== O_QUEUE
|| ((ipfw_insn
*)user_ip_fw
)->opcode
== O_PIPE
) {
582 actioncopysize
= sizeof(ipfw_insn_pipe_64
);
583 ((ipfw_insn
*)fw64action
)->opcode
= ((ipfw_insn
*)useraction
)->opcode
;
584 ((ipfw_insn
*)fw64action
)->arg1
= ((ipfw_insn
*)useraction
)->arg1
;
585 ((ipfw_insn
*)fw64action
)->len
= F_INSN_SIZE(ipfw_insn_pipe_64
);
586 diff
= ((ipfw_insn
*)fw64action
)->len
- ((ipfw_insn
*)useraction
)->len
;
588 fw64
->cmd_len
+= diff
;
591 actioncopysize
= (F_LEN((ipfw_insn
*)useraction
) ? (F_LEN((ipfw_insn
*)useraction
)) : 1) * sizeof(uint32_t);
592 bcopy( useraction
, fw64action
, actioncopysize
);
594 useraction
+= (F_LEN((ipfw_insn
*)useraction
) ? (F_LEN((ipfw_insn
*)useraction
)) : 1) * sizeof(uint32_t);
595 fw64action
+= actioncopysize
;
600 copyto32fw( struct ip_fw
*user_ip_fw
, struct ip_fw_32
*fw32
, __unused
size_t copysize
)
602 size_t rulesize
, cmdsize
;
604 fw32
->version
= user_ip_fw
->version
;
605 fw32
->context
= CAST_DOWN_EXPLICIT( user32_addr_t
, user_ip_fw
->context
);
606 fw32
->next
= CAST_DOWN_EXPLICIT(user32_addr_t
, user_ip_fw
->next
);
607 fw32
->next_rule
= CAST_DOWN_EXPLICIT(user32_addr_t
, user_ip_fw
->next_rule
);
608 fw32
->act_ofs
= user_ip_fw
->act_ofs
;
609 fw32
->cmd_len
= user_ip_fw
->cmd_len
;
610 fw32
->rulenum
= user_ip_fw
->rulenum
;
611 fw32
->set
= user_ip_fw
->set
;
612 fw32
->set_masks
[0] = user_ip_fw
->set_masks
[0];
613 fw32
->set_masks
[1] = user_ip_fw
->set_masks
[1];
614 fw32
->pcnt
= user_ip_fw
->pcnt
;
615 fw32
->bcnt
= user_ip_fw
->bcnt
;
616 fw32
->timestamp
= user_ip_fw
->timestamp
;
617 fw32
->reserved_1
= user_ip_fw
->reserved_1
;
618 fw32
->reserved_2
= user_ip_fw
->reserved_2
;
619 rulesize
= sizeof(struct ip_fw_32
) + (user_ip_fw
->cmd_len
* sizeof(ipfw_insn
) - 4);
620 cmdsize
= user_ip_fw
->cmd_len
* sizeof(u_int32_t
);
621 copyto32fw_insn( fw32
, user_ip_fw
, cmdsize
);
625 copyto64fw( struct ip_fw
*user_ip_fw
, struct ip_fw_64
*fw64
, size_t copysize
)
627 size_t rulesize
, cmdsize
;
629 fw64
->version
= user_ip_fw
->version
;
630 fw64
->context
= CAST_DOWN_EXPLICIT(__uint64_t
, user_ip_fw
->context
);
631 fw64
->next
= CAST_DOWN_EXPLICIT(user64_addr_t
, user_ip_fw
->next
);
632 fw64
->next_rule
= CAST_DOWN_EXPLICIT(user64_addr_t
, user_ip_fw
->next_rule
);
633 fw64
->act_ofs
= user_ip_fw
->act_ofs
;
634 fw64
->cmd_len
= user_ip_fw
->cmd_len
;
635 fw64
->rulenum
= user_ip_fw
->rulenum
;
636 fw64
->set
= user_ip_fw
->set
;
637 fw64
->set_masks
[0] = user_ip_fw
->set_masks
[0];
638 fw64
->set_masks
[1] = user_ip_fw
->set_masks
[1];
639 fw64
->pcnt
= user_ip_fw
->pcnt
;
640 fw64
->bcnt
= user_ip_fw
->bcnt
;
641 fw64
->timestamp
= user_ip_fw
->timestamp
;
642 fw64
->reserved_1
= user_ip_fw
->reserved_1
;
643 fw64
->reserved_2
= user_ip_fw
->reserved_2
;
644 rulesize
= sizeof(struct ip_fw_64
) + (user_ip_fw
->cmd_len
* sizeof(ipfw_insn
) - 4);
645 if (rulesize
> copysize
) {
646 cmdsize
= copysize
- sizeof(struct ip_fw_64
) + 4;
648 cmdsize
= user_ip_fw
->cmd_len
* sizeof(u_int32_t
);
650 copyto64fw_insn( fw64
, user_ip_fw
, cmdsize
);
654 copyfrom32fw_insn( struct ip_fw_32
*fw32
, struct ip_fw
*user_ip_fw
, int cmdsize
)
663 end
= ((char*)fw32
->cmd
) + cmdsize
;
664 fw32action
= (char*)ACTION_PTR( fw32
);
665 if ((justcmdsize
= (fw32action
- (char*)fw32
->cmd
))) {
666 bcopy( fw32
->cmd
, user_ip_fw
->cmd
, justcmdsize
);
668 useraction
= (char*)user_ip_fw
->cmd
+ justcmdsize
;
669 while (fw32action
< end
) {
670 if (((ipfw_insn
*)fw32action
)->opcode
== O_QUEUE
|| ((ipfw_insn
*)fw32action
)->opcode
== O_PIPE
) {
671 actioncopysize
= sizeof(ipfw_insn_pipe
);
672 ((ipfw_insn
*)useraction
)->opcode
= ((ipfw_insn
*)fw32action
)->opcode
;
673 ((ipfw_insn
*)useraction
)->arg1
= ((ipfw_insn
*)fw32action
)->arg1
;
674 ((ipfw_insn
*)useraction
)->len
= F_INSN_SIZE(ipfw_insn_pipe
);
675 diff
= ((ipfw_insn
*)useraction
)->len
- ((ipfw_insn
*)fw32action
)->len
;
677 /* readjust the cmd_len */
678 user_ip_fw
->cmd_len
+= diff
;
681 actioncopysize
= (F_LEN((ipfw_insn
*)fw32action
) ? (F_LEN((ipfw_insn
*)fw32action
)) : 1) * sizeof(uint32_t);
682 bcopy( fw32action
, useraction
, actioncopysize
);
684 fw32action
+= (F_LEN((ipfw_insn
*)fw32action
) ? (F_LEN((ipfw_insn
*)fw32action
)) : 1) * sizeof(uint32_t);
685 useraction
+= actioncopysize
;
688 return useraction
- (char*)user_ip_fw
->cmd
;
692 copyfrom64fw_insn( struct ip_fw_64
*fw64
, struct ip_fw
*user_ip_fw
, int cmdsize
)
701 end
= ((char *)fw64
->cmd
) + cmdsize
;
702 fw64action
= (char*)ACTION_PTR( fw64
);
703 if ((justcmdsize
= (fw64action
- (char*)fw64
->cmd
))) {
704 bcopy( fw64
->cmd
, user_ip_fw
->cmd
, justcmdsize
);
706 useraction
= (char*)user_ip_fw
->cmd
+ justcmdsize
;
707 while (fw64action
< end
) {
708 if (((ipfw_insn
*)fw64action
)->opcode
== O_QUEUE
|| ((ipfw_insn
*)fw64action
)->opcode
== O_PIPE
) {
709 actioncopysize
= sizeof(ipfw_insn_pipe
);
710 ((ipfw_insn
*)useraction
)->opcode
= ((ipfw_insn
*)fw64action
)->opcode
;
711 ((ipfw_insn
*)useraction
)->arg1
= ((ipfw_insn
*)fw64action
)->arg1
;
712 ((ipfw_insn
*)useraction
)->len
= F_INSN_SIZE(ipfw_insn_pipe
);
713 diff
= ((ipfw_insn
*)fw64action
)->len
- ((ipfw_insn
*)useraction
)->len
;
715 /* readjust the cmd_len */
716 user_ip_fw
->cmd_len
-= diff
;
719 actioncopysize
= (F_LEN((ipfw_insn
*)fw64action
) ? (F_LEN((ipfw_insn
*)fw64action
)) : 1) * sizeof(uint32_t);
720 bcopy( fw64action
, useraction
, actioncopysize
);
722 fw64action
+= (F_LEN((ipfw_insn
*)fw64action
) ? (F_LEN((ipfw_insn
*)fw64action
)) : 1) * sizeof(uint32_t);
723 useraction
+= actioncopysize
;
725 return useraction
- (char*)user_ip_fw
->cmd
;
729 copyfrom32fw( struct ip_fw_32
*fw32
, struct ip_fw
*user_ip_fw
, size_t copysize
)
731 size_t rulesize
, cmdsize
;
733 user_ip_fw
->version
= fw32
->version
;
734 user_ip_fw
->context
= CAST_DOWN(void *, fw32
->context
);
735 user_ip_fw
->next
= CAST_DOWN(struct ip_fw
*, fw32
->next
);
736 user_ip_fw
->next_rule
= CAST_DOWN_EXPLICIT(struct ip_fw
*, fw32
->next_rule
);
737 user_ip_fw
->act_ofs
= fw32
->act_ofs
;
738 user_ip_fw
->cmd_len
= fw32
->cmd_len
;
739 user_ip_fw
->rulenum
= fw32
->rulenum
;
740 user_ip_fw
->set
= fw32
->set
;
741 user_ip_fw
->set_masks
[0] = fw32
->set_masks
[0];
742 user_ip_fw
->set_masks
[1] = fw32
->set_masks
[1];
743 user_ip_fw
->pcnt
= fw32
->pcnt
;
744 user_ip_fw
->bcnt
= fw32
->bcnt
;
745 user_ip_fw
->timestamp
= fw32
->timestamp
;
746 user_ip_fw
->reserved_1
= fw32
->reserved_1
;
747 user_ip_fw
->reserved_2
= fw32
->reserved_2
;
748 rulesize
= sizeof(struct ip_fw_32
) + (fw32
->cmd_len
* sizeof(ipfw_insn
) - 4);
749 if (rulesize
> copysize
) {
750 cmdsize
= copysize
- sizeof(struct ip_fw_32
) - 4;
752 cmdsize
= fw32
->cmd_len
* sizeof(ipfw_insn
);
754 cmdsize
= copyfrom32fw_insn( fw32
, user_ip_fw
, cmdsize
);
755 return sizeof(struct ip_fw
) + cmdsize
- 4;
759 copyfrom64fw( struct ip_fw_64
*fw64
, struct ip_fw
*user_ip_fw
, size_t copysize
)
761 size_t rulesize
, cmdsize
;
763 user_ip_fw
->version
= fw64
->version
;
764 user_ip_fw
->context
= CAST_DOWN_EXPLICIT( void *, fw64
->context
);
765 user_ip_fw
->next
= CAST_DOWN_EXPLICIT(struct ip_fw
*, fw64
->next
);
766 user_ip_fw
->next_rule
= CAST_DOWN_EXPLICIT(struct ip_fw
*, fw64
->next_rule
);
767 user_ip_fw
->act_ofs
= fw64
->act_ofs
;
768 user_ip_fw
->cmd_len
= fw64
->cmd_len
;
769 user_ip_fw
->rulenum
= fw64
->rulenum
;
770 user_ip_fw
->set
= fw64
->set
;
771 user_ip_fw
->set_masks
[0] = fw64
->set_masks
[0];
772 user_ip_fw
->set_masks
[1] = fw64
->set_masks
[1];
773 user_ip_fw
->pcnt
= fw64
->pcnt
;
774 user_ip_fw
->bcnt
= fw64
->bcnt
;
775 user_ip_fw
->timestamp
= fw64
->timestamp
;
776 user_ip_fw
->reserved_1
= fw64
->reserved_1
;
777 user_ip_fw
->reserved_2
= fw64
->reserved_2
;
778 //bcopy( fw64->cmd, user_ip_fw->cmd, fw64->cmd_len * sizeof(ipfw_insn));
779 rulesize
= sizeof(struct ip_fw_64
) + (fw64
->cmd_len
* sizeof(ipfw_insn
) - 4);
780 if (rulesize
> copysize
) {
781 cmdsize
= copysize
- sizeof(struct ip_fw_64
) - 4;
783 cmdsize
= fw64
->cmd_len
* sizeof(ipfw_insn
);
785 cmdsize
= copyfrom64fw_insn( fw64
, user_ip_fw
, cmdsize
);
786 return sizeof(struct ip_fw
) + cmdsize
- 4;
790 externalize_flow_id(struct ipfw_flow_id
*dst
, struct ip_flow_id
*src
);
792 externalize_flow_id(struct ipfw_flow_id
*dst
, struct ip_flow_id
*src
)
794 dst
->dst_ip
= src
->dst_ip
;
795 dst
->src_ip
= src
->src_ip
;
796 dst
->dst_port
= src
->dst_port
;
797 dst
->src_port
= src
->src_port
;
798 dst
->proto
= src
->proto
;
799 dst
->flags
= src
->flags
;
804 cp_dyn_to_comp_32( struct ipfw_dyn_rule_compat_32
*dyn_rule_vers1
, int *len
)
806 struct ipfw_dyn_rule_compat_32
*dyn_last
= NULL
;
811 for (i
= 0; i
< curr_dyn_buckets
; i
++) {
812 for (p
= ipfw_dyn_v
[i
]; p
!= NULL
; p
= p
->next
) {
813 dyn_rule_vers1
->chain
= (user32_addr_t
)(p
->rule
->rulenum
);
814 externalize_flow_id(&dyn_rule_vers1
->id
, &p
->id
);
815 externalize_flow_id(&dyn_rule_vers1
->mask
, &p
->id
);
816 dyn_rule_vers1
->type
= p
->dyn_type
;
817 dyn_rule_vers1
->expire
= p
->expire
;
818 dyn_rule_vers1
->pcnt
= p
->pcnt
;
819 dyn_rule_vers1
->bcnt
= p
->bcnt
;
820 dyn_rule_vers1
->bucket
= p
->bucket
;
821 dyn_rule_vers1
->state
= p
->state
;
823 dyn_rule_vers1
->next
= CAST_DOWN_EXPLICIT( user32_addr_t
, p
->next
);
824 dyn_last
= dyn_rule_vers1
;
826 *len
+= sizeof(*dyn_rule_vers1
);
831 if (dyn_last
!= NULL
) {
832 dyn_last
->next
= ((user32_addr_t
)0);
840 cp_dyn_to_comp_64( struct ipfw_dyn_rule_compat_64
*dyn_rule_vers1
, int *len
)
842 struct ipfw_dyn_rule_compat_64
*dyn_last
= NULL
;
847 for (i
= 0; i
< curr_dyn_buckets
; i
++) {
848 for (p
= ipfw_dyn_v
[i
]; p
!= NULL
; p
= p
->next
) {
849 dyn_rule_vers1
->chain
= (user64_addr_t
) p
->rule
->rulenum
;
850 externalize_flow_id(&dyn_rule_vers1
->id
, &p
->id
);
851 externalize_flow_id(&dyn_rule_vers1
->mask
, &p
->id
);
852 dyn_rule_vers1
->type
= p
->dyn_type
;
853 dyn_rule_vers1
->expire
= p
->expire
;
854 dyn_rule_vers1
->pcnt
= p
->pcnt
;
855 dyn_rule_vers1
->bcnt
= p
->bcnt
;
856 dyn_rule_vers1
->bucket
= p
->bucket
;
857 dyn_rule_vers1
->state
= p
->state
;
859 dyn_rule_vers1
->next
= CAST_DOWN(user64_addr_t
, p
->next
);
860 dyn_last
= dyn_rule_vers1
;
862 *len
+= sizeof(*dyn_rule_vers1
);
867 if (dyn_last
!= NULL
) {
868 dyn_last
->next
= CAST_DOWN(user64_addr_t
, NULL
);
874 sooptcopyin_fw( struct sockopt
*sopt
, struct ip_fw
*user_ip_fw
, size_t *size
)
876 size_t valsize
, copyinsize
= 0;
879 valsize
= sopt
->sopt_valsize
;
883 if (proc_is64bit(sopt
->sopt_p
)) {
884 struct ip_fw_64
*fw64
= NULL
;
886 if (valsize
< sizeof(struct ip_fw_64
)) {
890 copyinsize
= sizeof(struct ip_fw_64
);
892 if (valsize
> copyinsize
) {
893 sopt
->sopt_valsize
= valsize
= copyinsize
;
896 if (sopt
->sopt_p
!= 0) {
897 fw64
= _MALLOC(copyinsize
, M_TEMP
, M_WAITOK
);
901 if ((error
= copyin(sopt
->sopt_val
, fw64
, valsize
)) != 0) {
906 bcopy(CAST_DOWN(caddr_t
, sopt
->sopt_val
), fw64
, valsize
);
908 valsize
= copyfrom64fw( fw64
, user_ip_fw
, valsize
);
909 _FREE( fw64
, M_TEMP
);
911 struct ip_fw_32
*fw32
= NULL
;
913 if (valsize
< sizeof(struct ip_fw_32
)) {
917 copyinsize
= sizeof(struct ip_fw_32
);
919 if (valsize
> copyinsize
) {
920 sopt
->sopt_valsize
= valsize
= copyinsize
;
923 if (sopt
->sopt_p
!= 0) {
924 fw32
= _MALLOC(copyinsize
, M_TEMP
, M_WAITOK
);
928 if ((error
= copyin(sopt
->sopt_val
, fw32
, valsize
)) != 0) {
929 _FREE( fw32
, M_TEMP
);
933 bcopy(CAST_DOWN(caddr_t
, sopt
->sopt_val
), fw32
, valsize
);
935 valsize
= copyfrom32fw( fw32
, user_ip_fw
, valsize
);
936 _FREE( fw32
, M_TEMP
);
945 * The following checks use two arrays of 8 or 16 bits to store the
946 * bits that we want set or clear, respectively. They are in the
947 * low and high half of cmd->arg1 or cmd->d[0].
949 * We scan options and store the bits we find set. We succeed if
951 * (want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
953 * The code is sometimes optimized not to store additional variables.
957 flags_match(ipfw_insn
*cmd
, u_int8_t bits
)
962 if (((cmd
->arg1
& 0xff) & bits
) != 0) {
963 return 0; /* some bits we want set were clear */
965 want_clear
= (cmd
->arg1
>> 8) & 0xff;
966 if ((want_clear
& bits
) != want_clear
) {
967 return 0; /* some bits we want clear were set */
973 ipopts_match(struct ip
*ip
, ipfw_insn
*cmd
)
975 int optlen
, bits
= 0;
976 u_char
*cp
= (u_char
*)(ip
+ 1);
977 int x
= (ip
->ip_hl
<< 2) - sizeof(struct ip
);
979 for (; x
> 0; x
-= optlen
, cp
+= optlen
) {
980 int opt
= cp
[IPOPT_OPTVAL
];
982 if (opt
== IPOPT_EOL
) {
985 if (opt
== IPOPT_NOP
) {
988 optlen
= cp
[IPOPT_OLEN
];
989 if (optlen
<= 0 || optlen
> x
) {
990 return 0; /* invalid or truncated */
998 bits
|= IP_FW_IPOPT_LSRR
;
1002 bits
|= IP_FW_IPOPT_SSRR
;
1006 bits
|= IP_FW_IPOPT_RR
;
1010 bits
|= IP_FW_IPOPT_TS
;
1014 return flags_match(cmd
, bits
);
1018 tcpopts_match(struct ip
*ip
, ipfw_insn
*cmd
)
1020 int optlen
, bits
= 0;
1021 struct tcphdr
*tcp
= L3HDR(struct tcphdr
, ip
);
1022 u_char
*cp
= (u_char
*)(tcp
+ 1);
1023 int x
= (tcp
->th_off
<< 2) - sizeof(struct tcphdr
);
1025 for (; x
> 0; x
-= optlen
, cp
+= optlen
) {
1027 if (opt
== TCPOPT_EOL
) {
1030 if (opt
== TCPOPT_NOP
) {
1044 bits
|= IP_FW_TCPOPT_MSS
;
1048 bits
|= IP_FW_TCPOPT_WINDOW
;
1051 case TCPOPT_SACK_PERMITTED
:
1053 bits
|= IP_FW_TCPOPT_SACK
;
1056 case TCPOPT_TIMESTAMP
:
1057 bits
|= IP_FW_TCPOPT_TS
;
1063 bits
|= IP_FW_TCPOPT_CC
;
1067 return flags_match(cmd
, bits
);
1071 iface_match(struct ifnet
*ifp
, ipfw_insn_if
*cmd
)
1073 if (ifp
== NULL
) { /* no iface with this packet, match fails */
1076 /* Check by name or by IP address */
1077 if (cmd
->name
[0] != '\0') { /* match by name */
1078 /* Check unit number (-1 is wildcard) */
1079 if (cmd
->p
.unit
!= -1 && cmd
->p
.unit
!= ifp
->if_unit
) {
1083 if (!strncmp(ifp
->if_name
, cmd
->name
, IFNAMSIZ
)) {
1089 ifnet_lock_shared(ifp
);
1090 TAILQ_FOREACH(ia
, &ifp
->if_addrhead
, ifa_link
) {
1092 if (ia
->ifa_addr
->sa_family
!= AF_INET
) {
1096 if (cmd
->p
.ip
.s_addr
== ((struct sockaddr_in
*)
1097 (ia
->ifa_addr
))->sin_addr
.s_addr
) {
1099 ifnet_lock_done(ifp
);
1100 return 1; /* match */
1104 ifnet_lock_done(ifp
);
1106 return 0; /* no match, fail ... */
1110 * The 'verrevpath' option checks that the interface that an IP packet
1111 * arrives on is the same interface that traffic destined for the
1112 * packet's source address would be routed out of. This is a measure
1113 * to block forged packets. This is also commonly known as "anti-spoofing"
1114 * or Unicast Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The
1115 * name of the knob is purposely reminisent of the Cisco IOS command,
1117 * ip verify unicast reverse-path
1119 * which implements the same functionality. But note that syntax is
1120 * misleading. The check may be performed on all IP packets whether unicast,
1121 * multicast, or broadcast.
1124 verify_rev_path(struct in_addr src
, struct ifnet
*ifp
)
1126 static struct route ro
;
1127 struct sockaddr_in
*dst
;
1129 bzero(&ro
, sizeof(ro
));
1130 dst
= (struct sockaddr_in
*)&(ro
.ro_dst
);
1132 /* Check if we've cached the route from the previous call. */
1133 if (src
.s_addr
!= dst
->sin_addr
.s_addr
) {
1134 dst
->sin_family
= AF_INET
;
1135 dst
->sin_len
= sizeof(*dst
);
1136 dst
->sin_addr
= src
;
1138 rtalloc_ign(&ro
, RTF_CLONING
| RTF_PRCLONING
, false);
1140 if (ro
.ro_rt
!= NULL
) {
1141 RT_LOCK_SPIN(ro
.ro_rt
);
1144 return 0; /* No route */
1146 if ((ifp
== NULL
) ||
1147 (ro
.ro_rt
->rt_ifp
->if_index
!= ifp
->if_index
)) {
1148 RT_UNLOCK(ro
.ro_rt
);
1152 RT_UNLOCK(ro
.ro_rt
);
1158 static u_int64_t norule_counter
; /* counter for ipfw_log(NULL...) */
1160 #define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
1161 #define SNP(buf) buf, sizeof(buf)
1164 * We enter here when we have a rule with O_LOG.
1165 * XXX this function alone takes about 2Kbytes of code!
1168 ipfw_log(struct ip_fw
*f
, u_int hlen
, struct ether_header
*eh
,
1169 struct mbuf
*m
, struct ifnet
*oif
)
1172 int limit_reached
= 0;
1173 char ipv4str
[MAX_IPv4_STR_LEN
];
1174 char action2
[40], proto
[48], fragment
[28];
1179 if (f
== NULL
) { /* bogus pkt */
1180 if (verbose_limit
!= 0 && norule_counter
>= verbose_limit
) {
1184 if (norule_counter
== verbose_limit
) {
1185 limit_reached
= verbose_limit
;
1188 } else { /* O_LOG is the first action, find the real one */
1189 ipfw_insn
*cmd
= ACTION_PTR(f
);
1190 ipfw_insn_log
*l
= (ipfw_insn_log
*)cmd
;
1192 if (l
->max_log
!= 0 && l
->log_left
== 0) {
1196 if (l
->log_left
== 0) {
1197 limit_reached
= l
->max_log
;
1199 cmd
+= F_LEN(cmd
); /* point to first action */
1200 if (cmd
->opcode
== O_PROB
) {
1205 switch (cmd
->opcode
) {
1211 if (cmd
->arg1
== ICMP_REJECT_RST
) {
1213 } else if (cmd
->arg1
== ICMP_UNREACH_HOST
) {
1216 snprintf(SNPARGS(action2
, 0), "Unreach %d",
1228 snprintf(SNPARGS(action2
, 0), "Divert %d",
1232 snprintf(SNPARGS(action2
, 0), "Tee %d",
1236 snprintf(SNPARGS(action2
, 0), "SkipTo %d",
1240 snprintf(SNPARGS(action2
, 0), "Pipe %d",
1244 snprintf(SNPARGS(action2
, 0), "Queue %d",
1247 case O_FORWARD_IP
: {
1248 ipfw_insn_sa
*sa
= (ipfw_insn_sa
*)cmd
;
1251 if (f
->reserved_1
== IPFW_RULE_INACTIVE
) {
1254 len
= snprintf(SNPARGS(action2
, 0), "Forward to %s",
1255 inet_ntop(AF_INET
, &sa
->sa
.sin_addr
, ipv4str
, sizeof(ipv4str
)));
1256 if (sa
->sa
.sin_port
) {
1257 snprintf(SNPARGS(action2
, len
), ":%d",
1268 if (hlen
== 0) { /* non-ip */
1269 snprintf(SNPARGS(proto
, 0), "MAC");
1271 struct ip
*ip
= mtod(m
, struct ip
*);
1272 /* these three are all aliases to the same thing */
1273 struct icmp
*const icmp
= L3HDR(struct icmp
, ip
);
1274 struct tcphdr
*const tcp
= (struct tcphdr
*)icmp
;
1275 struct udphdr
*const udp
= (struct udphdr
*)icmp
;
1277 int ip_off
, offset
, ip_len
;
1281 if (eh
!= NULL
) { /* layer 2 packets are as on the wire */
1282 ip_off
= ntohs(ip
->ip_off
);
1283 ip_len
= ntohs(ip
->ip_len
);
1285 ip_off
= ip
->ip_off
;
1286 ip_len
= ip
->ip_len
;
1288 offset
= ip_off
& IP_OFFMASK
;
1291 len
= snprintf(SNPARGS(proto
, 0), "TCP %s",
1292 inet_ntop(AF_INET
, &ip
->ip_src
, ipv4str
, sizeof(ipv4str
)));
1294 snprintf(SNPARGS(proto
, len
), ":%d %s:%d",
1295 ntohs(tcp
->th_sport
),
1296 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)),
1297 ntohs(tcp
->th_dport
));
1299 snprintf(SNPARGS(proto
, len
), " %s",
1300 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)));
1305 len
= snprintf(SNPARGS(proto
, 0), "UDP %s",
1306 inet_ntop(AF_INET
, &ip
->ip_src
, ipv4str
, sizeof(ipv4str
)));
1308 snprintf(SNPARGS(proto
, len
), ":%d %s:%d",
1309 ntohs(udp
->uh_sport
),
1310 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)),
1311 ntohs(udp
->uh_dport
));
1313 snprintf(SNPARGS(proto
, len
), " %s",
1314 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)));
1320 len
= snprintf(SNPARGS(proto
, 0),
1322 icmp
->icmp_type
, icmp
->icmp_code
);
1324 len
= snprintf(SNPARGS(proto
, 0), "ICMP ");
1326 len
+= snprintf(SNPARGS(proto
, len
), "%s",
1327 inet_ntop(AF_INET
, &ip
->ip_src
, ipv4str
, sizeof(ipv4str
)));
1328 snprintf(SNPARGS(proto
, len
), " %s",
1329 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)));
1333 len
= snprintf(SNPARGS(proto
, 0), "P:%d %s", ip
->ip_p
,
1334 inet_ntop(AF_INET
, &ip
->ip_src
, ipv4str
, sizeof(ipv4str
)));
1335 snprintf(SNPARGS(proto
, len
), " %s",
1336 inet_ntop(AF_INET
, &ip
->ip_dst
, ipv4str
, sizeof(ipv4str
)));
1340 if (ip_off
& (IP_MF
| IP_OFFMASK
)) {
1341 snprintf(SNPARGS(fragment
, 0), " (frag %d:%d@%d%s)",
1342 ntohs(ip
->ip_id
), ip_len
- (ip
->ip_hl
<< 2),
1344 (ip_off
& IP_MF
) ? "+" : "");
1347 if (oif
|| m
->m_pkthdr
.rcvif
) {
1348 dolog((LOG_AUTHPRIV
| LOG_INFO
,
1349 "ipfw: %d %s %s %s via %s%d%s\n",
1350 f
? f
->rulenum
: -1,
1351 action
, proto
, oif
? "out" : "in",
1352 oif
? oif
->if_name
: m
->m_pkthdr
.rcvif
->if_name
,
1353 oif
? oif
->if_unit
: m
->m_pkthdr
.rcvif
->if_unit
,
1356 dolog((LOG_AUTHPRIV
| LOG_INFO
,
1357 "ipfw: %d %s %s [no if info]%s\n",
1358 f
? f
->rulenum
: -1,
1359 action
, proto
, fragment
));
1361 if (limit_reached
) {
1362 dolog((LOG_AUTHPRIV
| LOG_NOTICE
,
1363 "ipfw: limit %d reached on entry %d\n",
1364 limit_reached
, f
? f
->rulenum
: -1));
1369 * IMPORTANT: the hash function for dynamic rules must be commutative
1370 * in source and destination (ip,port), because rules are bidirectional
1371 * and we want to find both in the same bucket.
1374 hash_packet(struct ip_flow_id
*id
)
1378 i
= (id
->dst_ip
) ^ (id
->src_ip
) ^ (id
->dst_port
) ^ (id
->src_port
);
1379 i
&= (curr_dyn_buckets
- 1);
1384 * unlink a dynamic rule from a chain. prev is a pointer to
1385 * the previous one, q is a pointer to the rule to delete,
1386 * head is a pointer to the head of the queue.
1387 * Modifies q and potentially also head.
1389 #define UNLINK_DYN_RULE(prev, head, q) { \
1390 ipfw_dyn_rule *old_q = q; \
1392 /* remove a refcount to the parent */ \
1393 if (q->dyn_type == O_LIMIT) \
1394 q->parent->count--; \
1395 DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
1396 (q->id.src_ip), (q->id.src_port), \
1397 (q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); ) \
1399 prev->next = q = q->next; \
1401 head = q = q->next; \
1403 _FREE(old_q, M_IPFW); }
1405 #define TIME_LEQ(a, b) ((int)((a)-(b)) <= 0)
1408 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
1410 * If keep_me == NULL, rules are deleted even if not expired,
1411 * otherwise only expired rules are removed.
1413 * The value of the second parameter is also used to point to identify
1414 * a rule we absolutely do not want to remove (e.g. because we are
1415 * holding a reference to it -- this is the case with O_LIMIT_PARENT
1416 * rules). The pointer is only used for comparison, so any non-null
1420 remove_dyn_rule(struct ip_fw
*rule
, ipfw_dyn_rule
*keep_me
)
1422 static u_int32_t last_remove
= 0;
1424 #define FORCE (keep_me == NULL)
1426 ipfw_dyn_rule
*prev
, *q
;
1427 int i
, pass
= 0, max_pass
= 0;
1428 struct timeval timenow
;
1430 getmicrotime(&timenow
);
1432 if (ipfw_dyn_v
== NULL
|| dyn_count
== 0) {
1435 /* do not expire more than once per second, it is useless */
1436 if (!FORCE
&& last_remove
== timenow
.tv_sec
) {
1439 last_remove
= timenow
.tv_sec
;
1442 * because O_LIMIT refer to parent rules, during the first pass only
1443 * remove child and mark any pending LIMIT_PARENT, and remove
1444 * them in a second pass.
1447 for (i
= 0; i
< curr_dyn_buckets
; i
++) {
1448 for (prev
= NULL
, q
= ipfw_dyn_v
[i
]; q
;) {
1450 * Logic can become complex here, so we split tests.
1455 if (rule
!= NULL
&& rule
!= q
->rule
) {
1456 goto next
; /* not the one we are looking for */
1458 if (q
->dyn_type
== O_LIMIT_PARENT
) {
1460 * handle parent in the second pass,
1461 * record we need one.
1467 if (FORCE
&& q
->count
!= 0) {
1468 /* XXX should not happen! */
1469 printf("ipfw: OUCH! cannot remove rule,"
1470 " count %d\n", q
->count
);
1474 !TIME_LEQ( q
->expire
, timenow
.tv_sec
)) {
1478 if (q
->dyn_type
!= O_LIMIT_PARENT
|| !q
->count
) {
1479 UNLINK_DYN_RULE(prev
, ipfw_dyn_v
[i
], q
);
1487 if (pass
++ < max_pass
) {
1494 * lookup a dynamic rule.
1496 static ipfw_dyn_rule
*
1497 lookup_dyn_rule(struct ip_flow_id
*pkt
, int *match_direction
,
1501 * stateful ipfw extensions.
1502 * Lookup into dynamic session queue
1504 #define MATCH_REVERSE 0
1505 #define MATCH_FORWARD 1
1506 #define MATCH_NONE 2
1507 #define MATCH_UNKNOWN 3
1508 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
1509 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
1511 int i
, dir
= MATCH_NONE
;
1512 ipfw_dyn_rule
*prev
, *q
= NULL
;
1513 struct timeval timenow
;
1515 getmicrotime(&timenow
);
1517 if (ipfw_dyn_v
== NULL
) {
1518 goto done
; /* not found */
1520 i
= hash_packet( pkt
);
1521 for (prev
= NULL
, q
= ipfw_dyn_v
[i
]; q
!= NULL
;) {
1522 if (q
->dyn_type
== O_LIMIT_PARENT
&& q
->count
) {
1525 if (TIME_LEQ( q
->expire
, timenow
.tv_sec
)) { /* expire entry */
1528 /* check if entry is TCP */
1529 if (q
->id
.proto
== IPPROTO_TCP
) {
1530 /* do not delete an established TCP connection which hasn't been closed by both sides */
1531 if ((q
->state
& (BOTH_SYN
| BOTH_FIN
)) != (BOTH_SYN
| BOTH_FIN
)) {
1536 UNLINK_DYN_RULE(prev
, ipfw_dyn_v
[i
], q
);
1540 if (pkt
->proto
== q
->id
.proto
&&
1541 q
->dyn_type
!= O_LIMIT_PARENT
) {
1542 if (pkt
->src_ip
== q
->id
.src_ip
&&
1543 pkt
->dst_ip
== q
->id
.dst_ip
&&
1544 pkt
->src_port
== q
->id
.src_port
&&
1545 pkt
->dst_port
== q
->id
.dst_port
) {
1546 dir
= MATCH_FORWARD
;
1549 if (pkt
->src_ip
== q
->id
.dst_ip
&&
1550 pkt
->dst_ip
== q
->id
.src_ip
&&
1551 pkt
->src_port
== q
->id
.dst_port
&&
1552 pkt
->dst_port
== q
->id
.src_port
) {
1553 dir
= MATCH_REVERSE
;
1562 goto done
; /* q = NULL, not found */
1564 if (prev
!= NULL
) { /* found and not in front */
1565 prev
->next
= q
->next
;
1566 q
->next
= ipfw_dyn_v
[i
];
1569 if (pkt
->proto
== IPPROTO_TCP
) { /* update state according to flags */
1570 u_char flags
= pkt
->flags
& (TH_FIN
| TH_SYN
| TH_RST
);
1572 q
->state
|= (dir
== MATCH_FORWARD
) ? flags
: (flags
<< 8);
1574 case TH_SYN
: /* opening */
1575 q
->expire
= timenow
.tv_sec
+ dyn_syn_lifetime
;
1578 case BOTH_SYN
: /* move to established */
1579 case BOTH_SYN
| TH_FIN
: /* one side tries to close */
1580 case BOTH_SYN
| (TH_FIN
<< 8):
1582 #define _SEQ_GE(a, b) ((int)(a) - (int)(b) >= 0)
1583 u_int32_t ack
= ntohl(tcp
->th_ack
);
1584 if (dir
== MATCH_FORWARD
) {
1585 if (q
->ack_fwd
== 0 || _SEQ_GE(ack
, q
->ack_fwd
)) {
1587 } else { /* ignore out-of-sequence */
1591 if (q
->ack_rev
== 0 || _SEQ_GE(ack
, q
->ack_rev
)) {
1593 } else { /* ignore out-of-sequence */
1598 q
->expire
= timenow
.tv_sec
+ dyn_ack_lifetime
;
1601 case BOTH_SYN
| BOTH_FIN
: /* both sides closed */
1602 if (dyn_fin_lifetime
>= dyn_keepalive_period
) {
1603 dyn_fin_lifetime
= dyn_keepalive_period
- 1;
1605 q
->expire
= timenow
.tv_sec
+ dyn_fin_lifetime
;
1611 * reset or some invalid combination, but can also
1612 * occur if we use keep-state the wrong way.
1614 if ((q
->state
& ((TH_RST
<< 8) | TH_RST
)) == 0) {
1615 printf("invalid state: 0x%x\n", q
->state
);
1618 if (dyn_rst_lifetime
>= dyn_keepalive_period
) {
1619 dyn_rst_lifetime
= dyn_keepalive_period
- 1;
1621 q
->expire
= timenow
.tv_sec
+ dyn_rst_lifetime
;
1624 } else if (pkt
->proto
== IPPROTO_UDP
) {
1625 q
->expire
= timenow
.tv_sec
+ dyn_udp_lifetime
;
1627 /* other protocols */
1628 q
->expire
= timenow
.tv_sec
+ dyn_short_lifetime
;
1631 if (match_direction
) {
1632 *match_direction
= dir
;
1638 realloc_dynamic_table(void)
1641 * Try reallocation, make sure we have a power of 2 and do
1642 * not allow more than 64k entries. In case of overflow,
1646 if (dyn_buckets
> 65536) {
1649 if ((dyn_buckets
& (dyn_buckets
- 1)) != 0) { /* not a power of 2 */
1650 dyn_buckets
= curr_dyn_buckets
; /* reset */
1653 curr_dyn_buckets
= dyn_buckets
;
1654 if (ipfw_dyn_v
!= NULL
) {
1655 _FREE(ipfw_dyn_v
, M_IPFW
);
1658 ipfw_dyn_v
= _MALLOC(curr_dyn_buckets
* sizeof(ipfw_dyn_rule
*),
1659 M_IPFW
, M_NOWAIT
| M_ZERO
);
1660 if (ipfw_dyn_v
!= NULL
|| curr_dyn_buckets
<= 2) {
1663 curr_dyn_buckets
/= 2;
1668 * Install state of type 'type' for a dynamic session.
1669 * The hash table contains two type of rules:
1670 * - regular rules (O_KEEP_STATE)
1671 * - rules for sessions with limited number of sess per user
1672 * (O_LIMIT). When they are created, the parent is
1673 * increased by 1, and decreased on delete. In this case,
1674 * the third parameter is the parent rule and not the chain.
1675 * - "parent" rules for the above (O_LIMIT_PARENT).
1677 static ipfw_dyn_rule
*
1678 add_dyn_rule(struct ip_flow_id
*id
, u_int8_t dyn_type
, struct ip_fw
*rule
)
1682 struct timeval timenow
;
1684 getmicrotime(&timenow
);
1686 if (ipfw_dyn_v
== NULL
||
1687 (dyn_count
== 0 && dyn_buckets
!= curr_dyn_buckets
)) {
1688 realloc_dynamic_table();
1689 if (ipfw_dyn_v
== NULL
) {
1690 return NULL
; /* failed ! */
1693 i
= hash_packet(id
);
1695 r
= _MALLOC(sizeof *r
, M_IPFW
, M_NOWAIT
| M_ZERO
);
1698 printf("ipfw: sorry cannot allocate state\n");
1703 /* increase refcount on parent, and set pointer */
1704 if (dyn_type
== O_LIMIT
) {
1705 ipfw_dyn_rule
*parent
= (ipfw_dyn_rule
*)rule
;
1706 if (parent
->dyn_type
!= O_LIMIT_PARENT
) {
1707 panic("invalid parent");
1711 rule
= parent
->rule
;
1715 r
->expire
= timenow
.tv_sec
+ dyn_syn_lifetime
;
1717 r
->dyn_type
= dyn_type
;
1718 r
->pcnt
= r
->bcnt
= 0;
1722 r
->next
= ipfw_dyn_v
[i
];
1725 DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1727 (r
->id
.src_ip
), (r
->id
.src_port
),
1728 (r
->id
.dst_ip
), (r
->id
.dst_port
),
1734 * lookup dynamic parent rule using pkt and rule as search keys.
1735 * If the lookup fails, then install one.
1737 static ipfw_dyn_rule
*
1738 lookup_dyn_parent(struct ip_flow_id
*pkt
, struct ip_fw
*rule
)
1742 struct timeval timenow
;
1744 getmicrotime(&timenow
);
1747 i
= hash_packet( pkt
);
1748 for (q
= ipfw_dyn_v
[i
]; q
!= NULL
; q
= q
->next
) {
1749 if (q
->dyn_type
== O_LIMIT_PARENT
&&
1751 pkt
->proto
== q
->id
.proto
&&
1752 pkt
->src_ip
== q
->id
.src_ip
&&
1753 pkt
->dst_ip
== q
->id
.dst_ip
&&
1754 pkt
->src_port
== q
->id
.src_port
&&
1755 pkt
->dst_port
== q
->id
.dst_port
) {
1756 q
->expire
= timenow
.tv_sec
+ dyn_short_lifetime
;
1757 DEB(printf("ipfw: lookup_dyn_parent found "
1758 "0x%llx\n", (uint64_t)VM_KERNEL_ADDRPERM(q
)); )
1763 return add_dyn_rule(pkt
, O_LIMIT_PARENT
, rule
);
1767 * Install dynamic state for rule type cmd->o.opcode
1769 * Returns 1 (failure) if state is not installed because of errors or because
1770 * session limitations are enforced.
1773 install_state(struct ip_fw
*rule
, ipfw_insn_limit
*cmd
,
1774 struct ip_fw_args
*args
)
1776 static int last_log
;
1777 struct timeval timenow
;
1780 getmicrotime(&timenow
);
1782 DEB(printf("ipfw: install state type %d 0x%08x %u -> 0x%08x %u\n",
1784 (args
->fwa_id
.src_ip
), (args
->fwa_id
.src_port
),
1785 (args
->fwa_id
.dst_ip
), (args
->fwa_id
.dst_port
)); )
1787 q
= lookup_dyn_rule(&args
->fwa_id
, NULL
, NULL
);
1789 if (q
!= NULL
) { /* should never occur */
1790 if (last_log
!= timenow
.tv_sec
) {
1791 last_log
= timenow
.tv_sec
;
1792 printf("ipfw: install_state: entry already present, done\n");
1797 if (dyn_count
>= dyn_max
) {
1799 * Run out of slots, try to remove any expired rule.
1801 remove_dyn_rule(NULL
, (ipfw_dyn_rule
*)1);
1804 if (dyn_count
>= dyn_max
) {
1805 if (last_log
!= timenow
.tv_sec
) {
1806 last_log
= timenow
.tv_sec
;
1807 printf("ipfw: install_state: Too many dynamic rules\n");
1809 return 1; /* cannot install, notify caller */
1812 switch (cmd
->o
.opcode
) {
1813 case O_KEEP_STATE
: /* bidir rule */
1814 add_dyn_rule(&args
->fwa_id
, O_KEEP_STATE
, rule
);
1817 case O_LIMIT
: /* limit number of sessions */
1819 u_int16_t limit_mask
= cmd
->limit_mask
;
1820 struct ip_flow_id id
;
1821 ipfw_dyn_rule
*parent
;
1823 DEB(printf("ipfw: installing dyn-limit rule %d\n",
1826 id
.dst_ip
= id
.src_ip
= 0;
1827 id
.dst_port
= id
.src_port
= 0;
1828 id
.proto
= args
->fwa_id
.proto
;
1830 if (limit_mask
& DYN_SRC_ADDR
) {
1831 id
.src_ip
= args
->fwa_id
.src_ip
;
1833 if (limit_mask
& DYN_DST_ADDR
) {
1834 id
.dst_ip
= args
->fwa_id
.dst_ip
;
1836 if (limit_mask
& DYN_SRC_PORT
) {
1837 id
.src_port
= args
->fwa_id
.src_port
;
1839 if (limit_mask
& DYN_DST_PORT
) {
1840 id
.dst_port
= args
->fwa_id
.dst_port
;
1842 parent
= lookup_dyn_parent(&id
, rule
);
1843 if (parent
== NULL
) {
1844 printf("ipfw: add parent failed\n");
1847 if (parent
->count
>= cmd
->conn_limit
) {
1849 * See if we can remove some expired rule.
1851 remove_dyn_rule(rule
, parent
);
1852 if (parent
->count
>= cmd
->conn_limit
) {
1853 if (fw_verbose
&& last_log
!= timenow
.tv_sec
) {
1854 last_log
= timenow
.tv_sec
;
1855 dolog((LOG_AUTHPRIV
| LOG_DEBUG
,
1856 "drop session, too many entries\n"));
1861 add_dyn_rule(&args
->fwa_id
, O_LIMIT
, (struct ip_fw
*)parent
);
1865 printf("ipfw: unknown dynamic rule type %u\n", cmd
->o
.opcode
);
1868 lookup_dyn_rule(&args
->fwa_id
, NULL
, NULL
); /* XXX just set lifetime */
1873 * Generate a TCP packet, containing either a RST or a keepalive.
1874 * When flags & TH_RST, we are sending a RST packet, because of a
1875 * "reset" action matched the packet.
1876 * Otherwise we are sending a keepalive, and flags & TH_
1878 static struct mbuf
*
1879 send_pkt(struct ip_flow_id
*id
, u_int32_t seq
, u_int32_t ack
, int flags
)
1885 MGETHDR(m
, M_DONTWAIT
, MT_HEADER
); /* MAC-OK */
1889 m
->m_pkthdr
.rcvif
= (struct ifnet
*)0;
1890 m
->m_pkthdr
.len
= m
->m_len
= sizeof(struct ip
) + sizeof(struct tcphdr
);
1891 m
->m_data
+= max_linkhdr
;
1893 ip
= mtod(m
, struct ip
*);
1894 bzero(ip
, m
->m_len
);
1895 tcp
= (struct tcphdr
*)(ip
+ 1); /* no IP options */
1896 ip
->ip_p
= IPPROTO_TCP
;
1899 * Assume we are sending a RST (or a keepalive in the reverse
1900 * direction), swap src and destination addresses and ports.
1902 ip
->ip_src
.s_addr
= htonl(id
->dst_ip
);
1903 ip
->ip_dst
.s_addr
= htonl(id
->src_ip
);
1904 tcp
->th_sport
= htons(id
->dst_port
);
1905 tcp
->th_dport
= htons(id
->src_port
);
1906 if (flags
& TH_RST
) { /* we are sending a RST */
1907 if (flags
& TH_ACK
) {
1908 tcp
->th_seq
= htonl(ack
);
1909 tcp
->th_ack
= htonl(0);
1910 tcp
->th_flags
= TH_RST
;
1912 if (flags
& TH_SYN
) {
1915 tcp
->th_seq
= htonl(0);
1916 tcp
->th_ack
= htonl(seq
);
1917 tcp
->th_flags
= TH_RST
| TH_ACK
;
1921 * We are sending a keepalive. flags & TH_SYN determines
1922 * the direction, forward if set, reverse if clear.
1923 * NOTE: seq and ack are always assumed to be correct
1924 * as set by the caller. This may be confusing...
1926 if (flags
& TH_SYN
) {
1928 * we have to rewrite the correct addresses!
1930 ip
->ip_dst
.s_addr
= htonl(id
->dst_ip
);
1931 ip
->ip_src
.s_addr
= htonl(id
->src_ip
);
1932 tcp
->th_dport
= htons(id
->dst_port
);
1933 tcp
->th_sport
= htons(id
->src_port
);
1935 tcp
->th_seq
= htonl(seq
);
1936 tcp
->th_ack
= htonl(ack
);
1937 tcp
->th_flags
= TH_ACK
;
1940 * set ip_len to the payload size so we can compute
1941 * the tcp checksum on the pseudoheader
1942 * XXX check this, could save a couple of words ?
1944 ip
->ip_len
= htons(sizeof(struct tcphdr
));
1945 tcp
->th_sum
= in_cksum(m
, m
->m_pkthdr
.len
);
1947 * now fill fields left out earlier
1949 ip
->ip_ttl
= ip_defttl
;
1950 ip
->ip_len
= m
->m_pkthdr
.len
;
1951 m
->m_flags
|= M_SKIP_FIREWALL
;
1957 * sends a reject message, consuming the mbuf passed as an argument.
1960 send_reject(struct ip_fw_args
*args
, int code
, int offset
, __unused
int ip_len
)
1962 if (code
!= ICMP_REJECT_RST
) { /* Send an ICMP unreach */
1963 /* We need the IP header in host order for icmp_error(). */
1964 if (args
->fwa_eh
!= NULL
) {
1965 struct ip
*ip
= mtod(args
->fwa_m
, struct ip
*);
1966 ip
->ip_len
= ntohs(ip
->ip_len
);
1967 ip
->ip_off
= ntohs(ip
->ip_off
);
1969 args
->fwa_m
->m_flags
|= M_SKIP_FIREWALL
;
1970 icmp_error(args
->fwa_m
, ICMP_UNREACH
, code
, 0L, 0);
1971 } else if (offset
== 0 && args
->fwa_id
.proto
== IPPROTO_TCP
) {
1972 struct tcphdr
*const tcp
=
1973 L3HDR(struct tcphdr
, mtod(args
->fwa_m
, struct ip
*));
1974 if ((tcp
->th_flags
& TH_RST
) == 0) {
1977 m
= send_pkt(&(args
->fwa_id
), ntohl(tcp
->th_seq
),
1979 tcp
->th_flags
| TH_RST
);
1981 struct route sro
; /* fake route */
1983 bzero(&sro
, sizeof(sro
));
1984 ip_output(m
, NULL
, &sro
, 0, NULL
, NULL
);
1985 ROUTE_RELEASE(&sro
);
1988 m_freem(args
->fwa_m
);
1990 m_freem(args
->fwa_m
);
1997 * Given an ip_fw *, lookup_next_rule will return a pointer
1998 * to the next rule, which can be either the jump
1999 * target (for skipto instructions) or the next one in the list (in
2000 * all other cases including a missing jump target).
2001 * The result is also written in the "next_rule" field of the rule.
2002 * Backward jumps are not allowed, so start looking from the next
2005 * This never returns NULL -- in case we do not have an exact match,
2006 * the next rule is returned. When the ruleset is changed,
2007 * pointers are flushed so we are always correct.
2010 static struct ip_fw
*
2011 lookup_next_rule(struct ip_fw
*me
)
2013 struct ip_fw
*rule
= NULL
;
2016 /* look for action, in case it is a skipto */
2017 cmd
= ACTION_PTR(me
);
2018 if (cmd
->opcode
== O_LOG
) {
2021 if (cmd
->opcode
== O_SKIPTO
) {
2022 for (rule
= me
->next
; rule
; rule
= rule
->next
) {
2023 if (rule
->rulenum
>= cmd
->arg1
) {
2028 if (rule
== NULL
) { /* failure or not a skipto */
2031 me
->next_rule
= rule
;
2036 * The main check routine for the firewall.
2038 * All arguments are in args so we can modify them and return them
2039 * back to the caller.
2043 * args->fwa_m (in/out) The packet; we set to NULL when/if we nuke it.
2044 * Starts with the IP header.
2045 * args->fwa_eh (in) Mac header if present, or NULL for layer3 packet.
2046 * args->fwa_oif Outgoing interface, or NULL if packet is incoming.
2047 * The incoming interface is in the mbuf. (in)
2048 * args->fwa_divert_rule (in/out)
2049 * Skip up to the first rule past this rule number;
2050 * upon return, non-zero port number for divert or tee.
2052 * args->fwa_ipfw_rule Pointer to the last matching rule (in/out)
2053 * args->fwa_next_hop Socket we are forwarding to (out).
2054 * args->fwa_id Addresses grabbed from the packet (out)
2058 * IP_FW_PORT_DENY_FLAG the packet must be dropped.
2059 * 0 The packet is to be accepted and routed normally OR
2060 * the packet was denied/rejected and has been dropped;
2061 * in the latter case, *m is equal to NULL upon return.
2062 * port Divert the packet to port, with these caveats:
2064 * - If IP_FW_PORT_TEE_FLAG is set, tee the packet instead
2065 * of diverting it (ie, 'ipfw tee').
2067 * - If IP_FW_PORT_DYNT_FLAG is set, interpret the lower
2068 * 16 bits as a dummynet pipe number instead of diverting
2072 ipfw_chk(struct ip_fw_args
*args
)
2075 * Local variables hold state during the processing of a packet.
2077 * IMPORTANT NOTE: to speed up the processing of rules, there
2078 * are some assumption on the values of the variables, which
2079 * are documented here. Should you change them, please check
2080 * the implementation of the various instructions to make sure
2081 * that they still work.
2083 * args->fwa_eh The MAC header. It is non-null for a layer2
2084 * packet, it is NULL for a layer-3 packet.
2086 * m | args->fwa_m Pointer to the mbuf, as received from the caller.
2087 * It may change if ipfw_chk() does an m_pullup, or if it
2088 * consumes the packet because it calls send_reject().
2089 * XXX This has to change, so that ipfw_chk() never modifies
2090 * or consumes the buffer.
2091 * ip is simply an alias of the value of m, and it is kept
2092 * in sync with it (the packet is supposed to start with
2095 struct mbuf
*m
= args
->fwa_m
;
2096 struct ip
*ip
= mtod(m
, struct ip
*);
2099 * oif | args->fwa_oif If NULL, ipfw_chk has been called on the
2100 * inbound path (ether_input, bdg_forward, ip_input).
2101 * If non-NULL, ipfw_chk has been called on the outbound path
2102 * (ether_output, ip_output).
2104 struct ifnet
*oif
= args
->fwa_oif
;
2106 struct ip_fw
*f
= NULL
; /* matching rule */
2110 * hlen The length of the IPv4 header.
2111 * hlen >0 means we have an IPv4 packet.
2113 u_int hlen
= 0; /* hlen >0 means we have an IP pkt */
2116 * offset The offset of a fragment. offset != 0 means that
2117 * we have a fragment at this offset of an IPv4 packet.
2118 * offset == 0 means that (if this is an IPv4 packet)
2119 * this is the first or only fragment.
2124 * Local copies of addresses. They are only valid if we have
2127 * proto The protocol. Set to 0 for non-ip packets,
2128 * or to the protocol read from the packet otherwise.
2129 * proto != 0 means that we have an IPv4 packet.
2131 * src_port, dst_port port numbers, in HOST format. Only
2132 * valid for TCP and UDP packets.
2134 * src_ip, dst_ip ip addresses, in NETWORK format.
2135 * Only valid for IPv4 packets.
2138 u_int16_t src_port
= 0, dst_port
= 0; /* NOTE: host format */
2139 struct in_addr src_ip
= { 0 }, dst_ip
= { 0 }; /* NOTE: network format */
2140 u_int16_t ip_len
= 0;
2142 int dyn_dir
= MATCH_UNKNOWN
;
2143 ipfw_dyn_rule
*q
= NULL
;
2144 struct timeval timenow
;
2146 if (m
->m_flags
& M_SKIP_FIREWALL
|| fw_bypass
) {
2147 return 0; /* accept */
2151 * Clear packet chain if we find one here.
2154 if (m
->m_nextpkt
!= NULL
) {
2155 m_freem_list(m
->m_nextpkt
);
2156 m
->m_nextpkt
= NULL
;
2159 lck_mtx_lock(ipfw_mutex
);
2161 getmicrotime(&timenow
);
2163 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
2164 * MATCH_NONE when checked and not matched (q = NULL),
2165 * MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
2168 pktlen
= m
->m_pkthdr
.len
;
2169 if (args
->fwa_eh
== NULL
|| /* layer 3 packet */
2170 (m
->m_pkthdr
.len
>= sizeof(struct ip
) &&
2171 ntohs(args
->fwa_eh
->ether_type
) == ETHERTYPE_IP
)) {
2172 hlen
= ip
->ip_hl
<< 2;
2176 * Collect parameters into local variables for faster matching.
2178 if (hlen
== 0) { /* do not grab addresses for non-ip pkts */
2179 proto
= args
->fwa_id
.proto
= 0; /* mark f_id invalid */
2180 goto after_ip_checks
;
2183 proto
= args
->fwa_id
.proto
= ip
->ip_p
;
2184 src_ip
= ip
->ip_src
;
2185 dst_ip
= ip
->ip_dst
;
2186 if (args
->fwa_eh
!= NULL
) { /* layer 2 packets are as on the wire */
2187 offset
= ntohs(ip
->ip_off
) & IP_OFFMASK
;
2188 ip_len
= ntohs(ip
->ip_len
);
2190 offset
= ip
->ip_off
& IP_OFFMASK
;
2191 ip_len
= ip
->ip_len
;
2193 pktlen
= ip_len
< pktlen
? ip_len
: pktlen
;
2195 #define PULLUP_TO(len) \
2197 if ((m)->m_len < (len)) { \
2198 args->fwa_m = m = m_pullup(m, (len)); \
2200 goto pullup_failed; \
2201 ip = mtod(m, struct ip *); \
2211 PULLUP_TO(hlen
+ sizeof(struct tcphdr
));
2212 tcp
= L3HDR(struct tcphdr
, ip
);
2213 dst_port
= tcp
->th_dport
;
2214 src_port
= tcp
->th_sport
;
2215 args
->fwa_id
.flags
= tcp
->th_flags
;
2223 PULLUP_TO(hlen
+ sizeof(struct udphdr
));
2224 udp
= L3HDR(struct udphdr
, ip
);
2225 dst_port
= udp
->uh_dport
;
2226 src_port
= udp
->uh_sport
;
2231 PULLUP_TO(hlen
+ 4); /* type, code and checksum. */
2232 args
->fwa_id
.flags
= L3HDR(struct icmp
, ip
)->icmp_type
;
2241 args
->fwa_id
.src_ip
= ntohl(src_ip
.s_addr
);
2242 args
->fwa_id
.dst_ip
= ntohl(dst_ip
.s_addr
);
2243 args
->fwa_id
.src_port
= src_port
= ntohs(src_port
);
2244 args
->fwa_id
.dst_port
= dst_port
= ntohs(dst_port
);
2247 if (args
->fwa_ipfw_rule
) {
2249 * Packet has already been tagged. Look for the next rule
2250 * to restart processing.
2252 * If fw_one_pass != 0 then just accept it.
2253 * XXX should not happen here, but optimized out in
2257 lck_mtx_unlock(ipfw_mutex
);
2261 f
= args
->fwa_ipfw_rule
->next_rule
;
2263 f
= lookup_next_rule(args
->fwa_ipfw_rule
);
2267 * Find the starting rule. It can be either the first
2268 * one, or the one after divert_rule if asked so.
2270 int skipto
= args
->fwa_divert_rule
;
2273 if (args
->fwa_eh
== NULL
&& skipto
!= 0) {
2274 if (skipto
>= IPFW_DEFAULT_RULE
) {
2275 lck_mtx_unlock(ipfw_mutex
);
2276 return IP_FW_PORT_DENY_FLAG
; /* invalid */
2278 while (f
&& f
->rulenum
<= skipto
) {
2281 if (f
== NULL
) { /* drop packet */
2282 lck_mtx_unlock(ipfw_mutex
);
2283 return IP_FW_PORT_DENY_FLAG
;
2287 args
->fwa_divert_rule
= 0; /* reset to avoid confusion later */
2290 * Now scan the rules, and parse microinstructions for each rule.
2292 for (; f
; f
= f
->next
) {
2295 int skip_or
; /* skip rest of OR block */
2298 if (f
->reserved_1
== IPFW_RULE_INACTIVE
) {
2302 if (set_disable
& (1 << f
->set
)) {
2307 for (l
= f
->cmd_len
, cmd
= f
->cmd
; l
> 0;
2308 l
-= cmdlen
, cmd
+= cmdlen
) {
2312 * check_body is a jump target used when we find a
2313 * CHECK_STATE, and need to jump to the body of
2318 cmdlen
= F_LEN(cmd
);
2320 * An OR block (insn_1 || .. || insn_n) has the
2321 * F_OR bit set in all but the last instruction.
2322 * The first match will set "skip_or", and cause
2323 * the following instructions to be skipped until
2324 * past the one with the F_OR bit clear.
2326 if (skip_or
) { /* skip this instruction */
2327 if ((cmd
->len
& F_OR
) == 0) {
2328 skip_or
= 0; /* next one is good */
2332 match
= 0; /* set to 1 if we succeed */
2334 switch (cmd
->opcode
) {
2336 * The first set of opcodes compares the packet's
2337 * fields with some pattern, setting 'match' if a
2338 * match is found. At the end of the loop there is
2339 * logic to deal with F_NOT and F_OR flags associated
2347 printf("ipfw: opcode %d unimplemented\n",
2356 * We only check offset == 0 && proto != 0,
2357 * as this ensures that we have an IPv4
2358 * packet with the ports info.
2365 struct inpcbinfo
*pi
;
2369 if (proto
== IPPROTO_TCP
) {
2372 } else if (proto
== IPPROTO_UDP
) {
2380 in_pcblookup_hash(pi
,
2381 dst_ip
, htons(dst_port
),
2382 src_ip
, htons(src_port
),
2384 in_pcblookup_hash(pi
,
2385 src_ip
, htons(src_port
),
2386 dst_ip
, htons(dst_port
),
2389 if (pcb
== NULL
|| pcb
->inp_socket
== NULL
) {
2392 #if __FreeBSD_version < 500034
2393 #define socheckuid(a, b) (kauth_cred_getuid((a)->so_cred) != (b))
2395 if (cmd
->opcode
== O_UID
) {
2398 (kauth_cred_getuid(pcb
->inp_socket
->so_cred
) == (uid_t
)((ipfw_insn_u32
*)cmd
)->d
[0]);
2400 !socheckuid(pcb
->inp_socket
,
2401 (uid_t
)((ipfw_insn_u32
*)cmd
)->d
[0]);
2407 kauth_cred_ismember_gid(pcb
->inp_socket
->so_cred
,
2408 (gid_t
)((ipfw_insn_u32
*)cmd
)->d
[0], &match
);
2411 /* release reference on pcb */
2412 in_pcb_checkstate(pcb
, WNT_RELEASE
, 0);
2418 match
= iface_match(m
->m_pkthdr
.rcvif
,
2419 (ipfw_insn_if
*)cmd
);
2423 match
= iface_match(oif
, (ipfw_insn_if
*)cmd
);
2427 match
= iface_match(oif
? oif
:
2428 m
->m_pkthdr
.rcvif
, (ipfw_insn_if
*)cmd
);
2432 if (args
->fwa_eh
!= NULL
) { /* have MAC header */
2433 u_int32_t
*want
= (u_int32_t
*)
2434 ((ipfw_insn_mac
*)cmd
)->addr
;
2435 u_int32_t
*mask
= (u_int32_t
*)
2436 ((ipfw_insn_mac
*)cmd
)->mask
;
2437 u_int32_t
*hdr
= (u_int32_t
*)args
->fwa_eh
;
2440 (want
[0] == (hdr
[0] & mask
[0]) &&
2441 want
[1] == (hdr
[1] & mask
[1]) &&
2442 want
[2] == (hdr
[2] & mask
[2]));
2447 if (args
->fwa_eh
!= NULL
) {
2449 ntohs(args
->fwa_eh
->ether_type
);
2451 ((ipfw_insn_u16
*)cmd
)->ports
;
2454 for (i
= cmdlen
- 1; !match
&& i
> 0;
2456 match
= (t
>= p
[0] && t
<= p
[1]);
2462 match
= (hlen
> 0 && offset
!= 0);
2465 case O_IN
: /* "out" is "not in" */
2466 match
= (oif
== NULL
);
2470 match
= (args
->fwa_eh
!= NULL
);
2475 * We do not allow an arg of 0 so the
2476 * check of "proto" only suffices.
2478 match
= (proto
== cmd
->arg1
);
2482 match
= (hlen
> 0 &&
2483 ((ipfw_insn_ip
*)cmd
)->addr
.s_addr
==
2491 (cmd
->opcode
== O_IP_DST_MASK
) ?
2492 dst_ip
.s_addr
: src_ip
.s_addr
;
2493 uint32_t *p
= ((ipfw_insn_u32
*)cmd
)->d
;
2496 for (; !match
&& i
> 0; i
-= 2, p
+= 2) {
2497 match
= (p
[0] == (a
& p
[1]));
2506 INADDR_TO_IFP(src_ip
, tif
);
2507 match
= (tif
!= NULL
);
2514 u_int32_t
*d
= (u_int32_t
*)(cmd
+ 1);
2516 cmd
->opcode
== O_IP_DST_SET
?
2517 args
->fwa_id
.dst_ip
:
2518 args
->fwa_id
.src_ip
;
2523 addr
-= d
[0]; /* subtract base */
2524 match
= (addr
< cmd
->arg1
) &&
2525 (d
[1 + (addr
>> 5)] &
2526 (1 << (addr
& 0x1f)));
2531 match
= (hlen
> 0 &&
2532 ((ipfw_insn_ip
*)cmd
)->addr
.s_addr
==
2540 INADDR_TO_IFP(dst_ip
, tif
);
2541 match
= (tif
!= NULL
);
2548 * offset == 0 && proto != 0 is enough
2549 * to guarantee that we have an IPv4
2550 * packet with port info.
2552 if ((proto
== IPPROTO_UDP
|| proto
== IPPROTO_TCP
)
2555 (cmd
->opcode
== O_IP_SRCPORT
) ?
2556 src_port
: dst_port
;
2558 ((ipfw_insn_u16
*)cmd
)->ports
;
2561 for (i
= cmdlen
- 1; !match
&& i
> 0;
2563 match
= (x
>= p
[0] && x
<= p
[1]);
2569 match
= (offset
== 0 && proto
== IPPROTO_ICMP
&&
2570 icmptype_match(ip
, (ipfw_insn_u32
*)cmd
));
2574 match
= (hlen
> 0 && ipopts_match(ip
, cmd
));
2578 match
= (hlen
> 0 && cmd
->arg1
== ip
->ip_v
);
2584 if (hlen
> 0) { /* only for IP packets */
2589 if (cmd
->opcode
== O_IPLEN
) {
2591 } else if (cmd
->opcode
== O_IPTTL
) {
2593 } else { /* must be IPID */
2594 x
= ntohs(ip
->ip_id
);
2597 match
= (cmd
->arg1
== x
);
2600 /* otherwise we have ranges */
2601 p
= ((ipfw_insn_u16
*)cmd
)->ports
;
2603 for (; !match
&& i
> 0; i
--, p
+= 2) {
2604 match
= (x
>= p
[0] && x
<= p
[1]);
2609 case O_IPPRECEDENCE
:
2610 match
= (hlen
> 0 &&
2611 (cmd
->arg1
== (ip
->ip_tos
& 0xe0)));
2615 match
= (hlen
> 0 &&
2616 flags_match(cmd
, ip
->ip_tos
));
2620 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
2622 L3HDR(struct tcphdr
, ip
)->th_flags
));
2626 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
2627 tcpopts_match(ip
, cmd
));
2631 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
2632 ((ipfw_insn_u32
*)cmd
)->d
[0] ==
2633 L3HDR(struct tcphdr
, ip
)->th_seq
);
2637 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
2638 ((ipfw_insn_u32
*)cmd
)->d
[0] ==
2639 L3HDR(struct tcphdr
, ip
)->th_ack
);
2643 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
2645 L3HDR(struct tcphdr
, ip
)->th_win
);
2649 /* reject packets which have SYN only */
2650 /* XXX should i also check for TH_ACK ? */
2651 match
= (proto
== IPPROTO_TCP
&& offset
== 0 &&
2652 (L3HDR(struct tcphdr
, ip
)->th_flags
&
2653 (TH_RST
| TH_ACK
| TH_SYN
)) != TH_SYN
);
2658 ipfw_log(f
, hlen
, args
->fwa_eh
, m
, oif
);
2664 match
= (random() < ((ipfw_insn_u32
*)cmd
)->d
[0]);
2668 /* Outgoing packets automatically pass/match */
2669 match
= ((oif
!= NULL
) ||
2670 (m
->m_pkthdr
.rcvif
== NULL
) ||
2671 verify_rev_path(src_ip
, m
->m_pkthdr
.rcvif
));
2676 match
= (m_tag_find(m
,
2677 PACKET_TAG_IPSEC_IN_DONE
, NULL
) != NULL
);
2680 match
= (ipsec_gethist(m
, NULL
) != NULL
);
2682 /* otherwise no match */
2686 * The second set of opcodes represents 'actions',
2687 * i.e. the terminal part of a rule once the packet
2688 * matches all previous patterns.
2689 * Typically there is only one action for each rule,
2690 * and the opcode is stored at the end of the rule
2691 * (but there are exceptions -- see below).
2693 * In general, here we set retval and terminate the
2694 * outer loop (would be a 'break 3' in some language,
2695 * but we need to do a 'goto done').
2698 * O_COUNT and O_SKIPTO actions:
2699 * instead of terminating, we jump to the next rule
2700 * ('goto next_rule', equivalent to a 'break 2'),
2701 * or to the SKIPTO target ('goto again' after
2702 * having set f, cmd and l), respectively.
2704 * O_LIMIT and O_KEEP_STATE: these opcodes are
2705 * not real 'actions', and are stored right
2706 * before the 'action' part of the rule.
2707 * These opcodes try to install an entry in the
2708 * state tables; if successful, we continue with
2709 * the next opcode (match=1; break;), otherwise
2710 * the packet * must be dropped
2711 * ('goto done' after setting retval);
2713 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2714 * cause a lookup of the state table, and a jump
2715 * to the 'action' part of the parent rule
2716 * ('goto check_body') if an entry is found, or
2717 * (CHECK_STATE only) a jump to the next rule if
2718 * the entry is not found ('goto next_rule').
2719 * The result of the lookup is cached to make
2720 * further instances of these opcodes are
2725 if (install_state(f
,
2726 (ipfw_insn_limit
*)cmd
, args
)) {
2727 retval
= IP_FW_PORT_DENY_FLAG
;
2728 goto done
; /* error/limit violation */
2736 * dynamic rules are checked at the first
2737 * keep-state or check-state occurrence,
2738 * with the result being stored in dyn_dir.
2739 * The compiler introduces a PROBE_STATE
2740 * instruction for us when we have a
2741 * KEEP_STATE (because PROBE_STATE needs
2744 if (dyn_dir
== MATCH_UNKNOWN
&&
2745 (q
= lookup_dyn_rule(&args
->fwa_id
,
2746 &dyn_dir
, proto
== IPPROTO_TCP
?
2747 L3HDR(struct tcphdr
, ip
) : NULL
))
2750 * Found dynamic entry, update stats
2751 * and jump to the 'action' part of
2757 cmd
= ACTION_PTR(f
);
2758 l
= f
->cmd_len
- f
->act_ofs
;
2762 * Dynamic entry not found. If CHECK_STATE,
2763 * skip to next rule, if PROBE_STATE just
2764 * ignore and continue with next opcode.
2766 if (cmd
->opcode
== O_CHECK_STATE
) {
2773 retval
= 0; /* accept */
2778 args
->fwa_ipfw_rule
= f
; /* report matching rule */
2779 retval
= cmd
->arg1
| IP_FW_PORT_DYNT_FLAG
;
2784 if (args
->fwa_eh
) { /* not on layer 2 */
2787 args
->fwa_divert_rule
= f
->rulenum
;
2788 retval
= (cmd
->opcode
== O_DIVERT
) ?
2790 cmd
->arg1
| IP_FW_PORT_TEE_FLAG
;
2795 f
->pcnt
++; /* update stats */
2797 f
->timestamp
= timenow
.tv_sec
;
2798 if (cmd
->opcode
== O_COUNT
) {
2802 if (f
->next_rule
== NULL
) {
2803 lookup_next_rule(f
);
2810 * Drop the packet and send a reject notice
2811 * if the packet is not ICMP (or is an ICMP
2812 * query), and it is not multicast/broadcast.
2814 if (hlen
> 0 && offset
== 0 &&
2815 (proto
!= IPPROTO_ICMP
||
2816 is_icmp_query(ip
)) &&
2817 !(m
->m_flags
& (M_BCAST
| M_MCAST
)) &&
2818 !IN_MULTICAST(dst_ip
.s_addr
)) {
2819 send_reject(args
, cmd
->arg1
,
2825 retval
= IP_FW_PORT_DENY_FLAG
;
2829 if (args
->fwa_eh
) { /* not valid on layer2 pkts */
2832 if (!q
|| dyn_dir
== MATCH_FORWARD
) {
2833 args
->fwa_next_hop
=
2834 &((ipfw_insn_sa
*)cmd
)->sa
;
2840 panic("-- unknown opcode %d\n", cmd
->opcode
);
2841 } /* end of switch() on opcodes */
2843 if (cmd
->len
& F_NOT
) {
2848 if (cmd
->len
& F_OR
) {
2852 if (!(cmd
->len
& F_OR
)) { /* not an OR block, */
2853 break; /* try next rule */
2856 } /* end of inner for, scan opcodes */
2858 next_rule
: ; /* try next rule */
2859 } /* end of outer for, scan rules */
2860 printf("ipfw: ouch!, skip past end of rules, denying packet\n");
2861 lck_mtx_unlock(ipfw_mutex
);
2862 return IP_FW_PORT_DENY_FLAG
;
2865 /* Update statistics */
2868 f
->timestamp
= timenow
.tv_sec
;
2869 lck_mtx_unlock(ipfw_mutex
);
2874 printf("ipfw: pullup failed\n");
2876 lck_mtx_unlock(ipfw_mutex
);
2877 return IP_FW_PORT_DENY_FLAG
;
2881 * When a rule is added/deleted, clear the next_rule pointers in all rules.
2882 * These will be reconstructed on the fly as packets are matched.
2883 * Must be called at splimp().
2886 flush_rule_ptrs(void)
2890 for (rule
= layer3_chain
; rule
; rule
= rule
->next
) {
2891 rule
->next_rule
= NULL
;
2896 * When pipes/queues are deleted, clear the "pipe_ptr" pointer to a given
2897 * pipe/queue, or to all of them (match == NULL).
2898 * Must be called at splimp().
2901 flush_pipe_ptrs(struct dn_flow_set
*match
)
2905 for (rule
= layer3_chain
; rule
; rule
= rule
->next
) {
2906 ipfw_insn_pipe
*cmd
= (ipfw_insn_pipe
*)ACTION_PTR(rule
);
2908 if (cmd
->o
.opcode
!= O_PIPE
&& cmd
->o
.opcode
!= O_QUEUE
) {
2912 * XXX Use bcmp/bzero to handle pipe_ptr to overcome
2913 * possible alignment problems on 64-bit architectures.
2914 * This code is seldom used so we do not worry too
2915 * much about efficiency.
2917 if (match
== NULL
||
2918 !bcmp(&cmd
->pipe_ptr
, &match
, sizeof(match
))) {
2919 bzero(&cmd
->pipe_ptr
, sizeof(cmd
->pipe_ptr
));
2925 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
2926 * possibly create a rule number and add the rule to the list.
2927 * Update the rule_number in the input struct so the caller knows it as well.
2930 add_rule(struct ip_fw
**head
, struct ip_fw
*input_rule
)
2932 struct ip_fw
*rule
, *f
, *prev
;
2933 int l
= RULESIZE(input_rule
);
2935 if (*head
== NULL
&& input_rule
->rulenum
!= IPFW_DEFAULT_RULE
) {
2939 rule
= _MALLOC(l
, M_IPFW
, M_WAIT
| M_ZERO
);
2941 printf("ipfw2: add_rule MALLOC failed\n");
2945 bcopy(input_rule
, rule
, l
);
2948 rule
->next_rule
= NULL
;
2952 rule
->timestamp
= 0;
2954 if (*head
== NULL
) { /* default rule */
2960 * If rulenum is 0, find highest numbered rule before the
2961 * default rule, and add autoinc_step
2963 if (autoinc_step
< 1) {
2965 } else if (autoinc_step
> 1000) {
2966 autoinc_step
= 1000;
2968 if (rule
->rulenum
== 0) {
2970 * locate the highest numbered rule before default
2972 for (f
= *head
; f
; f
= f
->next
) {
2973 if (f
->rulenum
== IPFW_DEFAULT_RULE
) {
2976 rule
->rulenum
= f
->rulenum
;
2978 if (rule
->rulenum
< IPFW_DEFAULT_RULE
- autoinc_step
) {
2979 rule
->rulenum
+= autoinc_step
;
2981 input_rule
->rulenum
= rule
->rulenum
;
2985 * Now insert the new rule in the right place in the sorted list.
2987 for (prev
= NULL
, f
= *head
; f
; prev
= f
, f
= f
->next
) {
2988 if (f
->rulenum
> rule
->rulenum
) { /* found the location */
2992 } else { /* head insert */
3003 static_len_32
+= RULESIZE32(input_rule
);
3004 static_len_64
+= RULESIZE64(input_rule
);
3005 DEB(printf("ipfw: installed rule %d, static count now %d\n",
3006 rule
->rulenum
, static_count
); )
3011 * Free storage associated with a static rule (including derived
3013 * The caller is in charge of clearing rule pointers to avoid
3014 * dangling pointers.
3015 * @return a pointer to the next entry.
3016 * Arguments are not checked, so they better be correct.
3017 * Must be called at splimp().
3019 static struct ip_fw
*
3020 delete_rule(struct ip_fw
**head
, struct ip_fw
*prev
, struct ip_fw
*rule
)
3023 int l
= RULESIZE(rule
);
3026 remove_dyn_rule(rule
, NULL
/* force removal */);
3034 static_len_32
-= RULESIZE32(rule
);
3035 static_len_64
-= RULESIZE64(rule
);
3038 if (DUMMYNET_LOADED
) {
3039 dn_ipfw_rule_delete(rule
);
3041 #endif /* DUMMYNET */
3042 _FREE(rule
, M_IPFW
);
3046 #if DEBUG_INACTIVE_RULES
3048 print_chain(struct ip_fw
**chain
)
3050 struct ip_fw
*rule
= *chain
;
3052 for (; rule
; rule
= rule
->next
) {
3053 ipfw_insn
*cmd
= ACTION_PTR(rule
);
3055 printf("ipfw: rule->rulenum = %d\n", rule
->rulenum
);
3057 if (rule
->reserved_1
== IPFW_RULE_INACTIVE
) {
3058 printf("ipfw: rule->reserved = IPFW_RULE_INACTIVE\n");
3061 switch (cmd
->opcode
) {
3063 printf("ipfw: ACTION: Deny\n");
3067 if (cmd
->arg1
== ICMP_REJECT_RST
) {
3068 printf("ipfw: ACTION: Reset\n");
3069 } else if (cmd
->arg1
== ICMP_UNREACH_HOST
) {
3070 printf("ipfw: ACTION: Reject\n");
3075 printf("ipfw: ACTION: Accept\n");
3078 printf("ipfw: ACTION: Count\n");
3081 printf("ipfw: ACTION: Divert\n");
3084 printf("ipfw: ACTION: Tee\n");
3087 printf("ipfw: ACTION: SkipTo\n");
3090 printf("ipfw: ACTION: Pipe\n");
3093 printf("ipfw: ACTION: Queue\n");
3096 printf("ipfw: ACTION: Forward\n");
3099 printf("ipfw: invalid action! %d\n", cmd
->opcode
);
3103 #endif /* DEBUG_INACTIVE_RULES */
3106 flush_inactive(void *param
)
3108 struct ip_fw
*inactive_rule
= (struct ip_fw
*)param
;
3109 struct ip_fw
*rule
, *prev
;
3111 lck_mtx_lock(ipfw_mutex
);
3113 for (rule
= layer3_chain
, prev
= NULL
; rule
;) {
3114 if (rule
== inactive_rule
&& rule
->reserved_1
== IPFW_RULE_INACTIVE
) {
3115 struct ip_fw
*n
= rule
;
3118 layer3_chain
= rule
->next
;
3120 prev
->next
= rule
->next
;
3130 #if DEBUG_INACTIVE_RULES
3131 print_chain(&layer3_chain
);
3133 lck_mtx_unlock(ipfw_mutex
);
3137 mark_inactive(struct ip_fw
**prev
, struct ip_fw
**rule
)
3139 int l
= RULESIZE(*rule
);
3141 if ((*rule
)->reserved_1
!= IPFW_RULE_INACTIVE
) {
3142 (*rule
)->reserved_1
= IPFW_RULE_INACTIVE
;
3145 static_len_32
-= RULESIZE32(*rule
);
3146 static_len_64
-= RULESIZE64(*rule
);
3148 timeout(flush_inactive
, *rule
, 30 * hz
); /* 30 sec. */
3152 *rule
= (*rule
)->next
;
3156 * Deletes all rules from a chain (except rules in set RESVD_SET
3157 * unless kill_default = 1).
3158 * Must be called at splimp().
3161 free_chain(struct ip_fw
**chain
, int kill_default
)
3163 struct ip_fw
*prev
, *rule
;
3165 flush_rule_ptrs(); /* more efficient to do outside the loop */
3166 for (prev
= NULL
, rule
= *chain
; rule
;) {
3167 if (kill_default
|| rule
->set
!= RESVD_SET
) {
3168 ipfw_insn
*cmd
= ACTION_PTR(rule
);
3170 /* skip over forwarding rules so struct isn't
3171 * deleted while pointer is still in use elsewhere
3173 if (cmd
->opcode
== O_FORWARD_IP
) {
3174 mark_inactive(&prev
, &rule
);
3176 rule
= delete_rule(chain
, prev
, rule
);
3186 * Remove all rules with given number, and also do set manipulation.
3187 * Assumes chain != NULL && *chain != NULL.
3189 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
3190 * the next 8 bits are the new set, the top 8 bits are the command:
3192 * 0 delete rules with given number
3193 * 1 delete rules with given set number
3194 * 2 move rules with given number to new set
3195 * 3 move rules with given set number to new set
3196 * 4 swap sets with given numbers
3199 del_entry(struct ip_fw
**chain
, u_int32_t arg
)
3201 struct ip_fw
*prev
= NULL
, *rule
= *chain
;
3202 u_int16_t rulenum
; /* rule or old_set */
3203 u_int8_t cmd
, new_set
;
3205 rulenum
= arg
& 0xffff;
3206 cmd
= (arg
>> 24) & 0xff;
3207 new_set
= (arg
>> 16) & 0xff;
3212 if (new_set
> RESVD_SET
) {
3215 if (cmd
== 0 || cmd
== 2) {
3216 if (rulenum
>= IPFW_DEFAULT_RULE
) {
3220 if (rulenum
> RESVD_SET
) { /* old_set */
3226 case 0: /* delete rules with given number */
3228 * locate first rule to delete
3230 for (; rule
->rulenum
< rulenum
; prev
= rule
, rule
= rule
->next
) {
3233 if (rule
->rulenum
!= rulenum
) {
3238 * flush pointers outside the loop, then delete all matching
3239 * rules. prev remains the same throughout the cycle.
3242 while (rule
->rulenum
== rulenum
) {
3243 ipfw_insn
*insn
= ACTION_PTR(rule
);
3245 /* keep forwarding rules around so struct isn't
3246 * deleted while pointer is still in use elsewhere
3248 if (insn
->opcode
== O_FORWARD_IP
) {
3249 mark_inactive(&prev
, &rule
);
3251 rule
= delete_rule(chain
, prev
, rule
);
3256 case 1: /* delete all rules with given set number */
3258 while (rule
->rulenum
< IPFW_DEFAULT_RULE
) {
3259 if (rule
->set
== rulenum
) {
3260 ipfw_insn
*insn
= ACTION_PTR(rule
);
3262 /* keep forwarding rules around so struct isn't
3263 * deleted while pointer is still in use elsewhere
3265 if (insn
->opcode
== O_FORWARD_IP
) {
3266 mark_inactive(&prev
, &rule
);
3268 rule
= delete_rule(chain
, prev
, rule
);
3277 case 2: /* move rules with given number to new set */
3278 for (; rule
->rulenum
< IPFW_DEFAULT_RULE
; rule
= rule
->next
) {
3279 if (rule
->rulenum
== rulenum
) {
3280 rule
->set
= new_set
;
3285 case 3: /* move rules with given set number to new set */
3286 for (; rule
->rulenum
< IPFW_DEFAULT_RULE
; rule
= rule
->next
) {
3287 if (rule
->set
== rulenum
) {
3288 rule
->set
= new_set
;
3293 case 4: /* swap two sets */
3294 for (; rule
->rulenum
< IPFW_DEFAULT_RULE
; rule
= rule
->next
) {
3295 if (rule
->set
== rulenum
) {
3296 rule
->set
= new_set
;
3297 } else if (rule
->set
== new_set
) {
3298 rule
->set
= rulenum
;
3307 * Clear counters for a specific rule.
3310 clear_counters(struct ip_fw
*rule
, int log_only
)
3312 ipfw_insn_log
*l
= (ipfw_insn_log
*)ACTION_PTR(rule
);
3314 if (log_only
== 0) {
3315 rule
->bcnt
= rule
->pcnt
= 0;
3316 rule
->timestamp
= 0;
3318 if (l
->o
.opcode
== O_LOG
) {
3319 l
->log_left
= l
->max_log
;
3324 * Reset some or all counters on firewall rules.
3325 * @arg frwl is null to clear all entries, or contains a specific
3327 * @arg log_only is 1 if we only want to reset logs, zero otherwise.
3330 zero_entry(int rulenum
, int log_only
)
3337 for (rule
= layer3_chain
; rule
; rule
= rule
->next
) {
3338 clear_counters(rule
, log_only
);
3340 msg
= log_only
? "ipfw: All logging counts reset.\n" :
3341 "ipfw: Accounting cleared.\n";
3345 * We can have multiple rules with the same number, so we
3346 * need to clear them all.
3348 for (rule
= layer3_chain
; rule
; rule
= rule
->next
) {
3349 if (rule
->rulenum
== rulenum
) {
3350 while (rule
&& rule
->rulenum
== rulenum
) {
3351 clear_counters(rule
, log_only
);
3358 if (!cleared
) { /* we did not find any matching rules */
3361 msg
= log_only
? "ipfw: Entry %d logging count reset.\n" :
3362 "ipfw: Entry %d cleared.\n";
3365 dolog((LOG_AUTHPRIV
| LOG_NOTICE
, msg
, rulenum
));
3371 * Check validity of the structure before insert.
3372 * Fortunately rules are simple, so this mostly need to check rule sizes.
3375 check_ipfw_struct(struct ip_fw
*rule
, int size
)
3378 int have_action
= 0;
3381 if (size
< sizeof(*rule
)) {
3382 printf("ipfw: rule too short\n");
3385 /* first, check for valid size */
3388 printf("ipfw: size mismatch (have %d want %d)\n", size
, l
);
3392 * Now go for the individual checks. Very simple ones, basically only
3393 * instruction sizes.
3395 for (l
= rule
->cmd_len
, cmd
= rule
->cmd
;
3396 l
> 0; l
-= cmdlen
, cmd
+= cmdlen
) {
3397 cmdlen
= F_LEN(cmd
);
3399 printf("ipfw: opcode %d size truncated\n",
3403 DEB(printf("ipfw: opcode %d\n", cmd
->opcode
); )
3404 switch (cmd
->opcode
) {
3415 case O_IPPRECEDENCE
:
3423 if (cmdlen
!= F_INSN_SIZE(ipfw_insn
)) {
3430 #endif /* __APPLE__ */
3437 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_u32
)) {
3443 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_limit
)) {
3449 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_log
)) {
3453 /* enforce logging limit */
3455 ((ipfw_insn_log
*)cmd
)->max_log
== 0 && verbose_limit
!= 0) {
3456 ((ipfw_insn_log
*)cmd
)->max_log
= verbose_limit
;
3459 ((ipfw_insn_log
*)cmd
)->log_left
=
3460 ((ipfw_insn_log
*)cmd
)->max_log
;
3466 /* only odd command lengths */
3467 if (!(cmdlen
& 1) || cmdlen
> 31) {
3474 if (cmd
->arg1
== 0 || cmd
->arg1
> 256) {
3475 printf("ipfw: invalid set size %d\n",
3479 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_u32
) +
3480 (cmd
->arg1
+ 31) / 32) {
3486 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_mac
)) {
3495 if (cmdlen
< 1 || cmdlen
> 31) {
3502 case O_IP_DSTPORT
: /* XXX artificial limit, 30 port pairs */
3503 if (cmdlen
< 2 || cmdlen
> 31) {
3511 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_if
)) {
3518 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_pipe
)) {
3524 if (cmdlen
!= F_INSN_SIZE(ipfw_insn_sa
)) {
3529 case O_FORWARD_MAC
: /* XXX not implemented yet */
3538 if (cmdlen
!= F_INSN_SIZE(ipfw_insn
)) {
3543 printf("ipfw: opcode %d, multiple actions"
3550 printf("ipfw: opcode %d, action must be"
3557 printf("ipfw: opcode %d, unknown opcode\n",
3562 if (have_action
== 0) {
3563 printf("ipfw: missing action\n");
3569 printf("ipfw: opcode %d size %d wrong\n",
3570 cmd
->opcode
, cmdlen
);
3576 ipfw_kev_post_msg(u_int32_t event_code
)
3578 struct kev_msg ev_msg
;
3580 bzero(&ev_msg
, sizeof(struct kev_msg
));
3582 ev_msg
.vendor_code
= KEV_VENDOR_APPLE
;
3583 ev_msg
.kev_class
= KEV_FIREWALL_CLASS
;
3584 ev_msg
.kev_subclass
= KEV_IPFW_SUBCLASS
;
3585 ev_msg
.event_code
= event_code
;
3587 kev_post_msg(&ev_msg
);
3591 * {set|get}sockopt parser.
3594 ipfw_ctl(struct sockopt
*sopt
)
3596 #define RULE_MAXSIZE (256*sizeof(u_int32_t))
3597 u_int32_t api_version
;
3601 size_t rulesize
= RULE_MAXSIZE
;
3602 struct ip_fw
*bp
, *buf
, *rule
;
3605 /* copy of orig sopt to send to ipfw_get_command_and_version() */
3606 struct sockopt tmp_sopt
= *sopt
;
3607 struct timeval timenow
;
3609 getmicrotime(&timenow
);
3612 * Disallow modifications in really-really secure mode, but still allow
3613 * the logging counters to be reset.
3615 if (sopt
->sopt_name
== IP_FW_ADD
||
3616 (sopt
->sopt_dir
== SOPT_SET
&& sopt
->sopt_name
!= IP_FW_RESETLOG
)) {
3617 #if __FreeBSD_version >= 500034
3618 error
= securelevel_ge(sopt
->sopt_td
->td_ucred
, 3);
3622 #else /* FreeBSD 4.x */
3623 if (securelevel
>= 3) {
3629 /* first get the command and version, then do conversion as necessary */
3630 error
= ipfw_get_command_and_version(&tmp_sopt
, &command
, &api_version
);
3632 /* error getting the version */
3636 if (proc_is64bit(sopt
->sopt_p
)) {
3645 * pass up a copy of the current rules. Static rules
3646 * come first (the last of which has number IPFW_DEFAULT_RULE),
3647 * followed by a possibly empty list of dynamic rule.
3648 * The last dynamic rule has NULL in the "next" field.
3650 lck_mtx_lock(ipfw_mutex
);
3653 size
= Get64static_len();
3654 dynrulesize
= sizeof(ipfw_dyn_rule_64
);
3656 size
+= (dyn_count
* dynrulesize
);
3659 size
= Get32static_len();
3660 dynrulesize
= sizeof(ipfw_dyn_rule_32
);
3662 size
+= (dyn_count
* dynrulesize
);
3667 * XXX todo: if the user passes a short length just to know
3668 * how much room is needed, do not bother filling up the
3669 * buffer, just jump to the sooptcopyout.
3671 buf
= _MALLOC(size
, M_TEMP
, M_WAITOK
| M_ZERO
);
3673 lck_mtx_unlock(ipfw_mutex
);
3679 for (rule
= layer3_chain
; rule
; rule
= rule
->next
) {
3680 if (rule
->reserved_1
== IPFW_RULE_INACTIVE
) {
3687 copyto64fw( rule
, (struct ip_fw_64
*)bp
, size
);
3688 bcopy(&set_disable
, &(((struct ip_fw_64
*)bp
)->next_rule
), sizeof(set_disable
));
3689 /* do not use macro RULESIZE64 since we want RULESIZE for ip_fw_64 */
3690 rulesize_64
= sizeof(struct ip_fw_64
) + ((struct ip_fw_64
*)(bp
))->cmd_len
* 4 - 4;
3691 bp
= (struct ip_fw
*)((char *)bp
+ rulesize_64
);
3695 copyto32fw( rule
, (struct ip_fw_32
*)bp
, size
);
3696 bcopy(&set_disable
, &(((struct ip_fw_32
*)bp
)->next_rule
), sizeof(set_disable
));
3697 /* do not use macro RULESIZE32 since we want RULESIZE for ip_fw_32 */
3698 rulesize_32
= sizeof(struct ip_fw_32
) + ((struct ip_fw_32
*)(bp
))->cmd_len
* 4 - 4;
3699 bp
= (struct ip_fw
*)((char *)bp
+ rulesize_32
);
3705 char *dst
, *last
= NULL
;
3708 for (i
= 0; i
< curr_dyn_buckets
; i
++) {
3709 for (p
= ipfw_dyn_v
[i
]; p
!= NULL
;
3710 p
= p
->next
, dst
+= dynrulesize
) {
3712 ipfw_dyn_rule_64
*ipfw_dyn_dst
;
3714 ipfw_dyn_dst
= (ipfw_dyn_rule_64
*)dst
;
3716 * store a non-null value in "next".
3717 * The userland code will interpret a
3718 * NULL here as a marker
3719 * for the last dynamic rule.
3721 ipfw_dyn_dst
->next
= CAST_DOWN_EXPLICIT(user64_addr_t
, dst
);
3722 ipfw_dyn_dst
->rule
= p
->rule
->rulenum
;
3723 ipfw_dyn_dst
->parent
= CAST_DOWN(user64_addr_t
, p
->parent
);
3724 ipfw_dyn_dst
->pcnt
= p
->pcnt
;
3725 ipfw_dyn_dst
->bcnt
= p
->bcnt
;
3726 externalize_flow_id(&ipfw_dyn_dst
->id
, &p
->id
);
3727 ipfw_dyn_dst
->expire
=
3728 TIME_LEQ(p
->expire
, timenow
.tv_sec
) ?
3729 0 : p
->expire
- timenow
.tv_sec
;
3730 ipfw_dyn_dst
->bucket
= p
->bucket
;
3731 ipfw_dyn_dst
->state
= p
->state
;
3732 ipfw_dyn_dst
->ack_fwd
= p
->ack_fwd
;
3733 ipfw_dyn_dst
->ack_rev
= p
->ack_rev
;
3734 ipfw_dyn_dst
->dyn_type
= p
->dyn_type
;
3735 ipfw_dyn_dst
->count
= p
->count
;
3736 last
= (char*)ipfw_dyn_dst
;
3738 ipfw_dyn_rule_32
*ipfw_dyn_dst
;
3740 ipfw_dyn_dst
= (ipfw_dyn_rule_32
*)dst
;
3742 * store a non-null value in "next".
3743 * The userland code will interpret a
3744 * NULL here as a marker
3745 * for the last dynamic rule.
3747 ipfw_dyn_dst
->next
= CAST_DOWN_EXPLICIT(user32_addr_t
, dst
);
3748 ipfw_dyn_dst
->rule
= p
->rule
->rulenum
;
3749 ipfw_dyn_dst
->parent
= CAST_DOWN_EXPLICIT(user32_addr_t
, p
->parent
);
3750 ipfw_dyn_dst
->pcnt
= p
->pcnt
;
3751 ipfw_dyn_dst
->bcnt
= p
->bcnt
;
3752 externalize_flow_id(&ipfw_dyn_dst
->id
, &p
->id
);
3753 ipfw_dyn_dst
->expire
=
3754 TIME_LEQ(p
->expire
, timenow
.tv_sec
) ?
3755 0 : p
->expire
- timenow
.tv_sec
;
3756 ipfw_dyn_dst
->bucket
= p
->bucket
;
3757 ipfw_dyn_dst
->state
= p
->state
;
3758 ipfw_dyn_dst
->ack_fwd
= p
->ack_fwd
;
3759 ipfw_dyn_dst
->ack_rev
= p
->ack_rev
;
3760 ipfw_dyn_dst
->dyn_type
= p
->dyn_type
;
3761 ipfw_dyn_dst
->count
= p
->count
;
3762 last
= (char*)ipfw_dyn_dst
;
3766 /* mark last dynamic rule */
3769 ((ipfw_dyn_rule_64
*)last
)->next
= 0;
3771 ((ipfw_dyn_rule_32
*)last
)->next
= 0;
3775 lck_mtx_unlock(ipfw_mutex
);
3777 /* convert back if necessary and copyout */
3778 if (api_version
== IP_FW_VERSION_0
) {
3780 struct ip_old_fw
*buf2
, *rule_vers0
;
3782 lck_mtx_lock(ipfw_mutex
);
3783 buf2
= _MALLOC(static_count
* sizeof(struct ip_old_fw
), M_TEMP
, M_WAITOK
| M_ZERO
);
3785 lck_mtx_unlock(ipfw_mutex
);
3793 for (i
= 0; i
< static_count
; i
++) {
3794 /* static rules have different sizes */
3795 int j
= RULESIZE(bp
);
3796 ipfw_convert_from_latest(bp
, rule_vers0
, api_version
, is64user
);
3797 bp
= (struct ip_fw
*)((char *)bp
+ j
);
3798 len
+= sizeof(*rule_vers0
);
3801 lck_mtx_unlock(ipfw_mutex
);
3802 error
= sooptcopyout(sopt
, buf2
, len
);
3803 _FREE(buf2
, M_TEMP
);
3805 } else if (api_version
== IP_FW_VERSION_1
) {
3806 int i
, len
= 0, buf_size
;
3807 struct ip_fw_compat
*buf2
;
3808 size_t ipfwcompsize
;
3809 size_t ipfwdyncompsize
;
3812 lck_mtx_lock(ipfw_mutex
);
3814 ipfwcompsize
= sizeof(struct ip_fw_compat_64
);
3815 ipfwdyncompsize
= sizeof(struct ipfw_dyn_rule_compat_64
);
3817 ipfwcompsize
= sizeof(struct ip_fw_compat_32
);
3818 ipfwdyncompsize
= sizeof(struct ipfw_dyn_rule_compat_32
);
3821 buf_size
= static_count
* ipfwcompsize
+
3822 dyn_count
* ipfwdyncompsize
;
3824 buf2
= _MALLOC(buf_size
, M_TEMP
, M_WAITOK
| M_ZERO
);
3826 lck_mtx_unlock(ipfw_mutex
);
3831 rule_vers1
= (char*)buf2
;
3833 /* first do static rules */
3834 for (i
= 0; i
< static_count
; i
++) {
3835 /* static rules have different sizes */
3838 ipfw_convert_from_latest(bp
, (void *)rule_vers1
, api_version
, is64user
);
3839 rulesize_64
= sizeof(struct ip_fw_64
) + ((struct ip_fw_64
*)(bp
))->cmd_len
* 4 - 4;
3840 bp
= (struct ip_fw
*)((char *)bp
+ rulesize_64
);
3843 ipfw_convert_from_latest(bp
, (void *)rule_vers1
, api_version
, is64user
);
3844 rulesize_32
= sizeof(struct ip_fw_32
) + ((struct ip_fw_32
*)(bp
))->cmd_len
* 4 - 4;
3845 bp
= (struct ip_fw
*)((char *)bp
+ rulesize_32
);
3847 len
+= ipfwcompsize
;
3848 rule_vers1
+= ipfwcompsize
;
3850 /* now do dynamic rules */
3852 cp_dyn_to_comp_64((struct ipfw_dyn_rule_compat_64
*)rule_vers1
, &len
);
3854 cp_dyn_to_comp_32((struct ipfw_dyn_rule_compat_32
*)rule_vers1
, &len
);
3857 lck_mtx_unlock(ipfw_mutex
);
3858 error
= sooptcopyout(sopt
, buf2
, len
);
3859 _FREE(buf2
, M_TEMP
);
3862 error
= sooptcopyout(sopt
, buf
, size
);
3871 * Normally we cannot release the lock on each iteration.
3872 * We could do it here only because we start from the head all
3873 * the times so there is no risk of missing some entries.
3874 * On the other hand, the risk is that we end up with
3875 * a very inconsistent ruleset, so better keep the lock
3876 * around the whole cycle.
3878 * XXX this code can be improved by resetting the head of
3879 * the list to point to the default rule, and then freeing
3880 * the old list without the need for a lock.
3883 lck_mtx_lock(ipfw_mutex
);
3884 free_chain(&layer3_chain
, 0 /* keep default rule */);
3886 #if DEBUG_INACTIVE_RULES
3887 print_chain(&layer3_chain
);
3889 lck_mtx_unlock(ipfw_mutex
);
3894 size_t savedsopt_valsize
= 0;
3895 rule
= _MALLOC(RULE_MAXSIZE
, M_TEMP
, M_WAITOK
| M_ZERO
);
3901 if (api_version
!= IP_FW_CURRENT_API_VERSION
) {
3902 error
= ipfw_convert_to_latest(sopt
, rule
, api_version
, is64user
);
3904 savedsopt_valsize
= sopt
->sopt_valsize
; /* it might get modified in sooptcopyin_fw */
3905 error
= sooptcopyin_fw( sopt
, rule
, &rulesize
);
3909 if ((api_version
== IP_FW_VERSION_0
) || (api_version
== IP_FW_VERSION_1
)) {
3910 /* the rule has already been checked so just
3911 * adjust sopt_valsize to match what would be expected.
3913 sopt
->sopt_valsize
= RULESIZE(rule
);
3914 rulesize
= RULESIZE(rule
);
3916 error
= check_ipfw_struct(rule
, rulesize
);
3918 lck_mtx_lock(ipfw_mutex
);
3919 error
= add_rule(&layer3_chain
, rule
);
3920 if (!error
&& fw_bypass
) {
3923 lck_mtx_unlock(ipfw_mutex
);
3925 size
= RULESIZE(rule
);
3926 if (!error
&& sopt
->sopt_dir
== SOPT_GET
) {
3927 /* convert back if necessary and copyout */
3928 if (api_version
== IP_FW_VERSION_0
) {
3929 struct ip_old_fw rule_vers0
= {};
3931 ipfw_convert_from_latest(rule
, &rule_vers0
, api_version
, is64user
);
3932 sopt
->sopt_valsize
= sizeof(struct ip_old_fw
);
3934 error
= sooptcopyout(sopt
, &rule_vers0
, sizeof(struct ip_old_fw
));
3935 } else if (api_version
== IP_FW_VERSION_1
) {
3936 struct ip_fw_compat rule_vers1
= {};
3937 ipfw_convert_from_latest(rule
, &rule_vers1
, api_version
, is64user
);
3938 sopt
->sopt_valsize
= sizeof(struct ip_fw_compat
);
3940 error
= sooptcopyout(sopt
, &rule_vers1
, sizeof(struct ip_fw_compat
));
3943 userrule
= _MALLOC(savedsopt_valsize
, M_TEMP
, M_WAITOK
| M_ZERO
);
3944 if (userrule
== NULL
) {
3945 userrule
= (char*)rule
;
3947 if (proc_is64bit(sopt
->sopt_p
)) {
3948 copyto64fw( rule
, (struct ip_fw_64
*)userrule
, savedsopt_valsize
);
3950 copyto32fw( rule
, (struct ip_fw_32
*)userrule
, savedsopt_valsize
);
3952 error
= sooptcopyout(sopt
, userrule
, savedsopt_valsize
);
3954 _FREE(userrule
, M_TEMP
);
3961 _FREE(rule
, M_TEMP
);
3967 * IP_FW_DEL is used for deleting single rules or sets,
3968 * and (ab)used to atomically manipulate sets.
3969 * rule->rulenum != 0 indicates single rule delete
3970 * rule->set_masks used to manipulate sets
3971 * rule->set_masks[0] contains info on sets to be
3972 * disabled, swapped, or moved
3973 * rule->set_masks[1] contains sets to be enabled.
3976 /* there is only a simple rule passed in
3977 * (no cmds), so use a temp struct to copy
3979 struct ip_fw temp_rule
;
3983 bzero(&temp_rule
, sizeof(struct ip_fw
));
3984 if (api_version
!= IP_FW_CURRENT_API_VERSION
) {
3985 error
= ipfw_convert_to_latest(sopt
, &temp_rule
, api_version
, is64user
);
3987 error
= sooptcopyin_fw(sopt
, &temp_rule
, 0 );
3991 /* set_masks is used to distinguish between deleting
3992 * single rules or atomically manipulating sets
3994 lck_mtx_lock(ipfw_mutex
);
3996 arg
= temp_rule
.set_masks
[0];
3997 cmd
= (arg
>> 24) & 0xff;
3999 if (temp_rule
.rulenum
) {
4001 error
= del_entry(&layer3_chain
, temp_rule
.rulenum
);
4002 #if DEBUG_INACTIVE_RULES
4003 print_chain(&layer3_chain
);
4006 /* set reassignment - see comment above del_entry() for details */
4007 error
= del_entry(&layer3_chain
, temp_rule
.set_masks
[0]);
4008 #if DEBUG_INACTIVE_RULES
4009 print_chain(&layer3_chain
);
4011 } else if (temp_rule
.set_masks
[0] != 0 ||
4012 temp_rule
.set_masks
[1] != 0) {
4013 /* set enable/disable */
4015 (set_disable
| temp_rule
.set_masks
[0]) & ~temp_rule
.set_masks
[1] &
4016 ~(1 << RESVD_SET
); /* set RESVD_SET always enabled */
4019 if (!layer3_chain
->next
) {
4022 lck_mtx_unlock(ipfw_mutex
);
4027 case IP_FW_RESETLOG
: /* using rule->rulenum */
4029 /* there is only a simple rule passed in
4030 * (no cmds), so use a temp struct to copy
4032 struct ip_fw temp_rule
;
4034 bzero(&temp_rule
, sizeof(struct ip_fw
));
4036 if (api_version
!= IP_FW_CURRENT_API_VERSION
) {
4037 error
= ipfw_convert_to_latest(sopt
, &temp_rule
, api_version
, is64user
);
4039 if (sopt
->sopt_val
!= 0) {
4040 error
= sooptcopyin_fw( sopt
, &temp_rule
, 0);
4045 lck_mtx_lock(ipfw_mutex
);
4046 error
= zero_entry(temp_rule
.rulenum
, sopt
->sopt_name
== IP_FW_RESETLOG
);
4047 lck_mtx_unlock(ipfw_mutex
);
4052 printf("ipfw: ipfw_ctl invalid option %d\n", sopt
->sopt_name
);
4056 if (error
!= EINVAL
) {
4060 ipfw_kev_post_msg(KEV_IPFW_ADD
);
4064 ipfw_kev_post_msg(KEV_IPFW_DEL
);
4067 case IP_OLD_FW_FLUSH
:
4068 ipfw_kev_post_msg(KEV_IPFW_FLUSH
);
4080 * dummynet needs a reference to the default rule, because rules can be
4081 * deleted while packets hold a reference to them. When this happens,
4082 * dummynet changes the reference to the default rule (it could well be a
4083 * NULL pointer, but this way we do not need to check for the special
4084 * case, plus here he have info on the default behaviour).
4086 struct ip_fw
*ip_fw_default_rule
;
4089 * This procedure is only used to handle keepalives. It is invoked
4090 * every dyn_keepalive_period
4093 ipfw_tick(__unused
void * unused
)
4095 struct mbuf
*m0
, *m
, *mnext
, **mtailp
;
4098 struct timeval timenow
;
4099 static int stealth_cnt
= 0;
4101 if (ipfw_stealth_stats_needs_flush
) {
4103 if (!(stealth_cnt
% IPFW_STEALTH_TIMEOUT_FREQUENCY
)) {
4104 ipfw_stealth_flush_stats();
4108 if (dyn_keepalive
== 0 || ipfw_dyn_v
== NULL
|| dyn_count
== 0) {
4112 getmicrotime(&timenow
);
4115 * We make a chain of packets to go out here -- not deferring
4116 * until after we drop the ipfw lock would result
4117 * in a lock order reversal with the normal packet input -> ipfw
4123 lck_mtx_lock(ipfw_mutex
);
4124 for (i
= 0; i
< curr_dyn_buckets
; i
++) {
4125 for (q
= ipfw_dyn_v
[i
]; q
; q
= q
->next
) {
4126 if (q
->dyn_type
== O_LIMIT_PARENT
) {
4129 if (q
->id
.proto
!= IPPROTO_TCP
) {
4132 if ((q
->state
& BOTH_SYN
) != BOTH_SYN
) {
4135 if (TIME_LEQ( timenow
.tv_sec
+ dyn_keepalive_interval
,
4137 continue; /* too early */
4139 if (TIME_LEQ(q
->expire
, timenow
.tv_sec
)) {
4140 continue; /* too late, rule expired */
4142 *mtailp
= send_pkt(&(q
->id
), q
->ack_rev
- 1, q
->ack_fwd
, TH_SYN
);
4143 if (*mtailp
!= NULL
) {
4144 mtailp
= &(*mtailp
)->m_nextpkt
;
4147 *mtailp
= send_pkt(&(q
->id
), q
->ack_fwd
- 1, q
->ack_rev
, 0);
4148 if (*mtailp
!= NULL
) {
4149 mtailp
= &(*mtailp
)->m_nextpkt
;
4153 lck_mtx_unlock(ipfw_mutex
);
4155 for (m
= mnext
= m0
; m
!= NULL
; m
= mnext
) {
4156 struct route sro
; /* fake route */
4158 mnext
= m
->m_nextpkt
;
4159 m
->m_nextpkt
= NULL
;
4160 bzero(&sro
, sizeof(sro
));
4161 ip_output(m
, NULL
, &sro
, 0, NULL
, NULL
);
4162 ROUTE_RELEASE(&sro
);
4165 timeout_with_leeway(ipfw_tick
, NULL
, dyn_keepalive_period
* hz
,
4166 DYN_KEEPALIVE_LEEWAY
* hz
);
4172 struct ip_fw default_rule
;
4175 ipfw_mutex_grp_attr
= lck_grp_attr_alloc_init();
4176 ipfw_mutex_grp
= lck_grp_alloc_init("ipfw", ipfw_mutex_grp_attr
);
4177 ipfw_mutex_attr
= lck_attr_alloc_init();
4178 lck_mtx_init(ipfw_mutex
, ipfw_mutex_grp
, ipfw_mutex_attr
);
4180 layer3_chain
= NULL
;
4182 bzero(&default_rule
, sizeof default_rule
);
4184 default_rule
.act_ofs
= 0;
4185 default_rule
.rulenum
= IPFW_DEFAULT_RULE
;
4186 default_rule
.cmd_len
= 1;
4187 default_rule
.set
= RESVD_SET
;
4189 default_rule
.cmd
[0].len
= 1;
4190 default_rule
.cmd
[0].opcode
=
4191 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4196 if (add_rule(&layer3_chain
, &default_rule
)) {
4197 printf("ipfw2: add_rule failed adding default rule\n");
4198 printf("ipfw2 failed initialization!!\n");
4201 ip_fw_default_rule
= layer3_chain
;
4203 #ifdef IPFIREWALL_VERBOSE
4206 #ifdef IPFIREWALL_VERBOSE_LIMIT
4207 verbose_limit
= IPFIREWALL_VERBOSE_LIMIT
;
4210 if (!verbose_limit
) {
4211 printf("ipfw2 verbose logging enabled: unlimited logging by default\n");
4213 printf("ipfw2 verbose logging enabled: limited to %d packets/entry by default\n",
4219 ip_fw_chk_ptr
= ipfw_chk
;
4220 ip_fw_ctl_ptr
= ipfw_ctl
;
4222 ipfwstringlen
= strlen( ipfwstring
);
4224 timeout(ipfw_tick
, NULL
, hz
);