1/*
2 * Copyright (c) 2004-2013 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
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.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
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.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28
29/*
30 * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
31 *
32 * Redistribution and use in source and binary forms, with or without
33 * modification, are permitted provided that the following conditions
34 * are met:
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.
40 *
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
51 * SUCH DAMAGE.
52 *
53 * $FreeBSD: src/sys/netinet/ip_fw2.c,v 1.6.2.18 2003/10/17 11:01:03 scottl Exp $
54 */
55
56#define        DEB(x)
57#define        DDB(x) x
58
59/*
60 * Implement IP packet firewall (new version)
61 */
62
63#ifndef INET
64#error IPFIREWALL requires INET.
65#endif /* INET */
66
67#if IPFW2
68#include <machine/spl.h>
69
70#include <sys/param.h>
71#include <sys/systm.h>
72#include <sys/malloc.h>
73#include <sys/mbuf.h>
74#include <sys/mcache.h>
75#include <sys/kernel.h>
76#include <sys/proc.h>
77#include <sys/socket.h>
78#include <sys/socketvar.h>
79#include <sys/sysctl.h>
80#include <sys/syslog.h>
81#include <sys/ucred.h>
82#include <sys/kern_event.h>
83#include <sys/kauth.h>
84
85#include <net/if.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>
96
97#if DUMMYNET
98#include <netinet/ip_dummynet.h>
99#endif /* DUMMYNET */
100
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>
107
108#ifdef IPSEC
109#include <netinet6/ipsec.h>
110#endif
111
112#include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
113
114#include "ip_fw2_compat.h"
115
116#include <sys/kern_event.h>
117#include <stdarg.h>
118
119/*
120#include <machine/in_cksum.h>
121*/	/* XXX for in_cksum */
122
123/*
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.
126 */
127#ifndef	M_SKIP_FIREWALL
128#define M_SKIP_FIREWALL         0x4000
129#endif
130
131/*
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.
138 */
139static u_int32_t set_disable;
140
141int fw_verbose;
142static int verbose_limit;
143extern int fw_bypass;
144
145#define IPFW_RULE_INACTIVE 1
146
147/*
148 * list of rules for layer 3
149 */
150static struct ip_fw *layer3_chain;
151
152MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
153
154static int fw_debug = 0;
155static int autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
156
157static void ipfw_kev_post_msg(u_int32_t );
158
159static int Get32static_len(void);
160static int Get64static_len(void);
161
162#ifdef SYSCTL_NODE
163
164static int ipfw_sysctl SYSCTL_HANDLER_ARGS;
165
166SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW|CTLFLAG_LOCKED, 0, "Firewall");
167SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, enable,
168    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
169    &fw_enable, 0, ipfw_sysctl, "I", "Enable ipfw");
170SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLFLAG_RW | CTLFLAG_LOCKED,
171    &autoinc_step, 0, "Rule number autincrement step");
172SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
173    CTLFLAG_RW | CTLFLAG_LOCKED,
174    &fw_one_pass, 0,
175    "Only do a single pass through ipfw when using dummynet(4)");
176SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug,
177    CTLFLAG_RW | CTLFLAG_LOCKED,
178    &fw_debug, 0, "Enable printing of debug ip_fw statements");
179SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
180    CTLFLAG_RW | CTLFLAG_LOCKED,
181    &fw_verbose, 0, "Log matches to ipfw rules");
182SYSCTL_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");
184
185/*
186 * IP FW Stealth Logging:
187 */
188typedef 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;
195
196#define IPFW_STEALTH_TIMEOUT_SEC 30
197
198#define	DYN_KEEPALIVE_LEEWAY	15
199
200// Piggybagging Stealth stats with ipfw_tick().
201#define IPFW_STEALTH_TIMEOUT_FREQUENCY (30 / dyn_keepalive_period)
202
203static const char* ipfw_stealth_stats_str [IPFW_STEALTH_STATS_MAX] = {
204  "UDP", "TCP", "UDP v6", "TCP v6",
205};
206
207static uint32_t ipfw_stealth_stats_needs_flush = FALSE;
208static uint32_t ipfw_stealth_stats[IPFW_STEALTH_STATS_MAX];
209
210static void ipfw_stealth_flush_stats(void);
211void ipfw_stealth_stats_incr_udp(void);
212void ipfw_stealth_stats_incr_tcp(void);
213void ipfw_stealth_stats_incr_udpv6(void);
214void ipfw_stealth_stats_incr_tcpv6(void);
215
216/*
217 * Description of dynamic rules.
218 *
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.
223 *
224 * XXX currently there is only one list, ipfw_dyn.
225 *
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:
230 *  + stateful rules;
231 *  + enforcing limits on the number of sessions;
232 *  + in-kernel NAT (not implemented yet)
233 *
234 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
235 * measured in seconds and depending on the flags.
236 *
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...).
243 *
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.
247 *
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!!!
251 */
252static ipfw_dyn_rule **ipfw_dyn_v = NULL;
253static u_int32_t dyn_buckets = 256; /* must be power of 2 */
254static u_int32_t curr_dyn_buckets = 256; /* must be power of 2 */
255
256/*
257 * Timeouts for various events in handing dynamic rules.
258 */
259static u_int32_t dyn_ack_lifetime = 300;
260static u_int32_t dyn_syn_lifetime = 20;
261static u_int32_t dyn_fin_lifetime = 1;
262static u_int32_t dyn_rst_lifetime = 1;
263static u_int32_t dyn_udp_lifetime = 10;
264static u_int32_t dyn_short_lifetime = 5;
265
266/*
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.
272 */
273
274static u_int32_t dyn_keepalive_interval = 25;
275static u_int32_t dyn_keepalive_period = 5;
276static u_int32_t dyn_keepalive = 1;	/* do send keepalives */
277
278static u_int32_t static_count;	/* # of static rules */
279static u_int32_t static_len;	/* size in bytes of static rules */
280static u_int32_t static_len_32;	/* size in bytes of static rules for 32 bit client */
281static u_int32_t static_len_64;	/* size in bytes of static rules for 64 bit client */
282static u_int32_t dyn_count;		/* # of dynamic rules */
283static u_int32_t dyn_max = 4096;	/* max # of dynamic rules */
284
285SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLFLAG_RW | CTLFLAG_LOCKED,
286    &dyn_buckets, 0, "Number of dyn. buckets");
287SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD | CTLFLAG_LOCKED,
288    &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
289SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD | CTLFLAG_LOCKED,
290    &dyn_count, 0, "Number of dyn. rules");
291SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW | CTLFLAG_LOCKED,
292    &dyn_max, 0, "Max number of dyn. rules");
293SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD | CTLFLAG_LOCKED,
294    &static_count, 0, "Number of static rules");
295SYSCTL_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");
297SYSCTL_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");
299SYSCTL_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");
301SYSCTL_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");
303SYSCTL_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");
305SYSCTL_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");
307SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW | CTLFLAG_LOCKED,
308    &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
309
310
311static int
312ipfw_sysctl SYSCTL_HANDLER_ARGS
313{
314#pragma unused(arg1, arg2)
315	int error;
316
317	error = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
318	if (error || !req->newptr)
319		return (error);
320
321	ipfw_kev_post_msg(KEV_IPFW_ENABLE);
322
323	return error;
324}
325
326#endif /* SYSCTL_NODE */
327
328
329static ip_fw_chk_t	ipfw_chk;
330
331/* firewall lock */
332lck_grp_t         *ipfw_mutex_grp;
333lck_grp_attr_t    *ipfw_mutex_grp_attr;
334lck_attr_t        *ipfw_mutex_attr;
335decl_lck_mtx_data(,ipfw_mutex_data);
336lck_mtx_t         *ipfw_mutex = &ipfw_mutex_data;
337
338extern  void    ipfwsyslog( int level, const char *format,...);
339
340#define KEV_LOG_SUBCLASS 10
341#define IPFWLOGEVENT    0
342
343#define         ipfwstring      "ipfw:"
344static          size_t		ipfwstringlen;
345
346#define dolog( a ) {		\
347	if ( fw_verbose == 2 )  	/* Apple logging, log to ipfw.log */ \
348		ipfwsyslog a ; 	\
349	else log a ;		\
350}
351
352#define RULESIZE64(rule)  (sizeof(struct ip_fw_64) + \
353							((struct ip_fw *)(rule))->cmd_len * 4 - 4)
354
355#define RULESIZE32(rule)  (sizeof(struct ip_fw_32) + \
356							((struct ip_fw *)(rule))->cmd_len * 4 - 4)
357
358void    ipfwsyslog( int level, const char *format,...)
359{
360#define		msgsize		100
361
362    struct kev_msg        ev_msg;
363    va_list             ap;
364    char                msgBuf[msgsize];
365    char                *dptr = msgBuf;
366    unsigned char       pri;
367    int			loglen;
368
369	bzero(msgBuf, msgsize);
370	bzero(&ev_msg, sizeof(struct kev_msg));
371	va_start( ap, format );
372        loglen = vsnprintf(msgBuf, msgsize, format, ap);
373        va_end( ap );
374
375        ev_msg.vendor_code    = KEV_VENDOR_APPLE;
376        ev_msg.kev_class      = KEV_NETWORK_CLASS;
377        ev_msg.kev_subclass   = KEV_LOG_SUBCLASS;
378        ev_msg.event_code         = IPFWLOGEVENT;
379
380	/* get rid of the trailing \n */
381	if (loglen < msgsize)
382		dptr[loglen-1] = 0;
383	else
384		dptr[msgsize-1] = 0;
385
386        pri = LOG_PRI(level);
387
388        /* remove "ipfw:" prefix if logging to ipfw log */
389        if ( !(strncmp( ipfwstring, msgBuf, ipfwstringlen))){
390                dptr = msgBuf+ipfwstringlen;
391        }
392
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;
398
399        kev_post_msg(&ev_msg);
400}
401
402static inline void ipfw_stealth_stats_incr(uint32_t type)
403{
404    if (type >= IPFW_STEALTH_STATS_MAX)
405        return;
406
407    ipfw_stealth_stats[type]++;
408
409    if (!ipfw_stealth_stats_needs_flush) {
410        ipfw_stealth_stats_needs_flush = TRUE;
411    }
412}
413
414void ipfw_stealth_stats_incr_udp(void)
415{
416    ipfw_stealth_stats_incr(IPFW_STEALTH_STATS_UDP);
417}
418
419void ipfw_stealth_stats_incr_tcp(void)
420{
421    ipfw_stealth_stats_incr(IPFW_STEALTH_STATS_TCP);
422}
423
424void ipfw_stealth_stats_incr_udpv6(void)
425{
426    ipfw_stealth_stats_incr(IPFW_STEALTH_STATS_UDPv6);
427}
428
429void ipfw_stealth_stats_incr_tcpv6(void)
430{
431    ipfw_stealth_stats_incr(IPFW_STEALTH_STATS_TCPv6);
432}
433
434static void ipfw_stealth_flush_stats(void)
435{
436    int i;
437
438    for (i = 0; i < IPFW_STEALTH_STATS_MAX; i++) {
439        if (ipfw_stealth_stats[i]) {
440           ipfwsyslog (LOG_INFO, "Stealth Mode connection attempt to %s %d times",
441                       ipfw_stealth_stats_str[i], ipfw_stealth_stats[i]);
442           ipfw_stealth_stats[i] = 0;
443       }
444    }
445    ipfw_stealth_stats_needs_flush = FALSE;
446}
447
448/*
449 * This macro maps an ip pointer into a layer3 header pointer of type T
450 */
451#define	L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
452
453static __inline int
454icmptype_match(struct ip *ip, ipfw_insn_u32 *cmd)
455{
456	int type = L3HDR(struct icmp,ip)->icmp_type;
457
458	return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
459}
460
461#define TT	( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
462    (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
463
464static int
465is_icmp_query(struct ip *ip)
466{
467	int type = L3HDR(struct icmp, ip)->icmp_type;
468	return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
469}
470#undef TT
471
472static int
473Get32static_len()
474{
475	int	diff;
476	int len = static_len_32;
477	struct ip_fw *rule;
478	char		 *useraction;
479
480	for (rule = layer3_chain; rule ; rule = rule->next) {
481		if (rule->reserved_1 == IPFW_RULE_INACTIVE) {
482			continue;
483		}
484		if ( rule->act_ofs ){
485			useraction =  (char*)ACTION_PTR( rule );
486			if ( ((ipfw_insn*)useraction)->opcode == O_QUEUE || ((ipfw_insn*)useraction)->opcode == O_PIPE){
487				diff = sizeof(ipfw_insn_pipe) - sizeof(ipfw_insn_pipe_32);
488				if (diff)
489					len -= diff;
490			}
491		}
492	}
493	return len;
494}
495
496static int
497Get64static_len()
498{
499	int	diff;
500	int len = static_len_64;
501	struct ip_fw *rule;
502	char		 *useraction;
503
504	for (rule = layer3_chain; rule ; rule = rule->next) {
505		if (rule->reserved_1 == IPFW_RULE_INACTIVE) {
506			continue;
507		}
508		if ( rule->act_ofs ){
509			useraction =  (char *)ACTION_PTR( rule );
510			if ( ((ipfw_insn*)useraction)->opcode == O_QUEUE || ((ipfw_insn*)useraction)->opcode == O_PIPE){
511				diff = sizeof(ipfw_insn_pipe_64) - sizeof(ipfw_insn_pipe);
512				if (diff)
513					len += diff;
514			}
515		}
516	}
517	return len;
518}
519
520static void
521copyto32fw_insn( struct ip_fw_32 *fw32 , struct ip_fw *user_ip_fw, int cmdsize)
522{
523	char		*end;
524	char		*fw32action;
525	char		*useraction;
526	int			justcmdsize;
527	int			diff=0;
528	int			actioncopysize;
529
530	end = ((char*)user_ip_fw->cmd) + cmdsize;
531	useraction = (char*)ACTION_PTR( user_ip_fw );
532	fw32action = (char*)fw32->cmd + (user_ip_fw->act_ofs * sizeof(uint32_t));
533	if ( ( justcmdsize = ( fw32action - (char*)fw32->cmd)))
534		bcopy( user_ip_fw->cmd, fw32->cmd, justcmdsize);
535	while ( useraction < end ){
536		if ( ((ipfw_insn*)useraction)->opcode == O_QUEUE || ((ipfw_insn*)useraction)->opcode == O_PIPE){
537			actioncopysize = sizeof(ipfw_insn_pipe_32);
538			((ipfw_insn*)fw32action)->opcode = ((ipfw_insn*)useraction)->opcode;
539			((ipfw_insn*)fw32action)->arg1 = ((ipfw_insn*)useraction)->arg1;
540			((ipfw_insn*)fw32action)->len = F_INSN_SIZE(ipfw_insn_pipe_32);
541			diff = ((ipfw_insn*)useraction)->len - ((ipfw_insn*)fw32action)->len;
542			if ( diff ){
543				fw32->cmd_len -= diff;
544			}
545		} else{
546			actioncopysize =  (F_LEN((ipfw_insn*)useraction) ? (F_LEN((ipfw_insn*)useraction)) : 1 ) * sizeof(uint32_t);
547			bcopy( useraction, fw32action, actioncopysize );
548		}
549		useraction += (F_LEN((ipfw_insn*)useraction) ? (F_LEN((ipfw_insn*)useraction)) : 1 ) * sizeof(uint32_t);
550		fw32action += actioncopysize;
551	}
552}
553
554static void
555copyto64fw_insn( struct ip_fw_64 *fw64 , struct ip_fw *user_ip_fw, int cmdsize)
556{
557	char		*end;
558	char		*fw64action;
559	char		*useraction;
560	int			justcmdsize;
561	int			diff;
562	int			actioncopysize;
563
564	end = ((char *)user_ip_fw->cmd) + cmdsize;
565	useraction = (char*)ACTION_PTR( user_ip_fw );
566	if ( (justcmdsize = (useraction - (char*)user_ip_fw->cmd)))
567		bcopy( user_ip_fw->cmd, fw64->cmd, justcmdsize);
568	fw64action = (char*)fw64->cmd + justcmdsize;
569	while ( useraction < end ){
570		if ( ((ipfw_insn*)user_ip_fw)->opcode == O_QUEUE || ((ipfw_insn*)user_ip_fw)->opcode == O_PIPE){
571			actioncopysize = sizeof(ipfw_insn_pipe_64);
572			((ipfw_insn*)fw64action)->opcode = ((ipfw_insn*)useraction)->opcode;
573			((ipfw_insn*)fw64action)->arg1 = ((ipfw_insn*)useraction)->arg1;
574			((ipfw_insn*)fw64action)->len = F_INSN_SIZE(ipfw_insn_pipe_64);
575			diff = ((ipfw_insn*)fw64action)->len - ((ipfw_insn*)useraction)->len;
576			if (diff)
577				fw64->cmd_len += diff;
578
579		} else{
580			actioncopysize = (F_LEN((ipfw_insn*)useraction) ? (F_LEN((ipfw_insn*)useraction)) : 1 ) * sizeof(uint32_t);
581			bcopy( useraction, fw64action, actioncopysize );
582		}
583		useraction += (F_LEN((ipfw_insn*)useraction) ? (F_LEN((ipfw_insn*)useraction)) : 1 ) * sizeof(uint32_t);
584		fw64action += actioncopysize;
585	}
586}
587
588static void
589copyto32fw( struct ip_fw *user_ip_fw, struct ip_fw_32 *fw32 , __unused size_t copysize)
590{
591	size_t	rulesize, cmdsize;
592
593	fw32->version = user_ip_fw->version;
594	fw32->context = CAST_DOWN_EXPLICIT( user32_addr_t, user_ip_fw->context);
595	fw32->next = CAST_DOWN_EXPLICIT(user32_addr_t, user_ip_fw->next);
596	fw32->next_rule = CAST_DOWN_EXPLICIT(user32_addr_t, user_ip_fw->next_rule);
597	fw32->act_ofs = user_ip_fw->act_ofs;
598	fw32->cmd_len = user_ip_fw->cmd_len;
599	fw32->rulenum = user_ip_fw->rulenum;
600	fw32->set = user_ip_fw->set;
601	fw32->set_masks[0] = user_ip_fw->set_masks[0];
602	fw32->set_masks[1] = user_ip_fw->set_masks[1];
603	fw32->pcnt = user_ip_fw->pcnt;
604	fw32->bcnt = user_ip_fw->bcnt;
605	fw32->timestamp = user_ip_fw->timestamp;
606	fw32->reserved_1 = user_ip_fw->reserved_1;
607	fw32->reserved_2 = user_ip_fw->reserved_2;
608	rulesize = sizeof(struct ip_fw_32) + (user_ip_fw->cmd_len * sizeof(ipfw_insn) - 4);
609	cmdsize = user_ip_fw->cmd_len * sizeof(u_int32_t);
610	copyto32fw_insn( fw32, user_ip_fw, cmdsize );
611}
612
613static void
614copyto64fw( struct ip_fw *user_ip_fw, struct ip_fw_64	*fw64, size_t copysize)
615{
616	size_t	rulesize, cmdsize;
617
618	fw64->version = user_ip_fw->version;
619	fw64->context = CAST_DOWN_EXPLICIT(__uint64_t, user_ip_fw->context);
620	fw64->next = CAST_DOWN_EXPLICIT(user64_addr_t, user_ip_fw->next);
621	fw64->next_rule = CAST_DOWN_EXPLICIT(user64_addr_t, user_ip_fw->next_rule);
622	fw64->act_ofs = user_ip_fw->act_ofs;
623	fw64->cmd_len = user_ip_fw->cmd_len;
624	fw64->rulenum = user_ip_fw->rulenum;
625	fw64->set = user_ip_fw->set;
626	fw64->set_masks[0] = user_ip_fw->set_masks[0];
627	fw64->set_masks[1] = user_ip_fw->set_masks[1];
628	fw64->pcnt = user_ip_fw->pcnt;
629	fw64->bcnt = user_ip_fw->bcnt;
630	fw64->timestamp = user_ip_fw->timestamp;
631	fw64->reserved_1 = user_ip_fw->reserved_1;
632	fw64->reserved_2 = user_ip_fw->reserved_2;
633	rulesize = sizeof(struct ip_fw_64) + (user_ip_fw->cmd_len * sizeof(ipfw_insn) - 4);
634	if (rulesize > copysize)
635		cmdsize = copysize - sizeof(struct ip_fw_64) + 4;
636	else
637		cmdsize = user_ip_fw->cmd_len * sizeof(u_int32_t);
638	copyto64fw_insn( fw64, user_ip_fw, cmdsize);
639}
640
641static int
642copyfrom32fw_insn( struct ip_fw_32 *fw32 , struct ip_fw *user_ip_fw, int cmdsize)
643{
644	char		*end;
645	char		*fw32action;
646	char		*useraction;
647	int			justcmdsize;
648	int			diff;
649	int			actioncopysize;
650
651	end = ((char*)fw32->cmd) + cmdsize;
652	fw32action = (char*)ACTION_PTR( fw32 );
653	if ((justcmdsize = (fw32action - (char*)fw32->cmd)))
654		bcopy( fw32->cmd, user_ip_fw->cmd, justcmdsize);
655	useraction = (char*)user_ip_fw->cmd + justcmdsize;
656	while ( fw32action < end ){
657		if ( ((ipfw_insn*)fw32action)->opcode == O_QUEUE || ((ipfw_insn*)fw32action)->opcode == O_PIPE){
658			actioncopysize = sizeof(ipfw_insn_pipe);
659			((ipfw_insn*)useraction)->opcode = ((ipfw_insn*)fw32action)->opcode;
660			((ipfw_insn*)useraction)->arg1 = ((ipfw_insn*)fw32action)->arg1;
661			((ipfw_insn*)useraction)->len = F_INSN_SIZE(ipfw_insn_pipe);
662			diff = ((ipfw_insn*)useraction)->len - ((ipfw_insn*)fw32action)->len;
663			if (diff){
664				/* readjust the cmd_len */
665				user_ip_fw->cmd_len += diff;
666			}
667		} else{
668			actioncopysize = (F_LEN((ipfw_insn*)fw32action) ? (F_LEN((ipfw_insn*)fw32action)) : 1 ) * sizeof(uint32_t);
669			bcopy( fw32action, useraction, actioncopysize );
670		}
671		fw32action += (F_LEN((ipfw_insn*)fw32action) ? (F_LEN((ipfw_insn*)fw32action)) : 1 ) * sizeof(uint32_t);
672		useraction += actioncopysize;
673	}
674
675	return( useraction - (char*)user_ip_fw->cmd );
676}
677
678static int
679copyfrom64fw_insn( struct ip_fw_64 *fw64 , struct ip_fw *user_ip_fw, int cmdsize)
680{
681	char		*end;
682	char		*fw64action;
683	char		*useraction;
684	int			justcmdsize;
685	int			diff;
686	int			actioncopysize;
687
688	end = ((char *)fw64->cmd) + cmdsize ;
689	fw64action = (char*)ACTION_PTR( fw64 );
690	if ( (justcmdsize = (fw64action - (char*)fw64->cmd)))
691		bcopy( fw64->cmd, user_ip_fw->cmd, justcmdsize);
692	useraction = (char*)user_ip_fw->cmd + justcmdsize;
693	while ( fw64action < end ){
694		if ( ((ipfw_insn*)fw64action)->opcode == O_QUEUE || ((ipfw_insn*)fw64action)->opcode == O_PIPE){
695			actioncopysize = sizeof(ipfw_insn_pipe);
696			((ipfw_insn*)useraction)->opcode = ((ipfw_insn*)fw64action)->opcode;
697			((ipfw_insn*)useraction)->arg1 = ((ipfw_insn*)fw64action)->arg1;
698			((ipfw_insn*)useraction)->len = F_INSN_SIZE(ipfw_insn_pipe);
699			diff = ((ipfw_insn*)fw64action)->len - ((ipfw_insn*)useraction)->len;
700			if (diff) {
701				/* readjust the cmd_len */
702				user_ip_fw->cmd_len -= diff;
703			}
704		} else{
705			actioncopysize = (F_LEN((ipfw_insn*)fw64action) ? (F_LEN((ipfw_insn*)fw64action)) : 1 ) * sizeof(uint32_t);
706			bcopy( fw64action, useraction, actioncopysize );
707		}
708		fw64action += (F_LEN((ipfw_insn*)fw64action) ? (F_LEN((ipfw_insn*)fw64action)) : 1 ) * sizeof(uint32_t);
709		useraction += actioncopysize;
710	}
711	return( useraction - (char*)user_ip_fw->cmd );
712}
713
714static size_t
715copyfrom32fw( struct ip_fw_32	*fw32, struct ip_fw *user_ip_fw, size_t copysize)
716{
717	size_t rulesize, cmdsize;
718
719	user_ip_fw->version = fw32->version;
720	user_ip_fw->context = CAST_DOWN(void *, fw32->context);
721	user_ip_fw->next = CAST_DOWN(struct ip_fw*, fw32->next);
722	user_ip_fw->next_rule = CAST_DOWN_EXPLICIT(struct ip_fw*, fw32->next_rule);
723	user_ip_fw->act_ofs = fw32->act_ofs;
724	user_ip_fw->cmd_len = fw32->cmd_len;
725	user_ip_fw->rulenum = fw32->rulenum;
726	user_ip_fw->set = fw32->set;
727	user_ip_fw->set_masks[0] = fw32->set_masks[0];
728	user_ip_fw->set_masks[1] = fw32->set_masks[1];
729	user_ip_fw->pcnt = fw32->pcnt;
730	user_ip_fw->bcnt = fw32->bcnt;
731	user_ip_fw->timestamp = fw32->timestamp;
732	user_ip_fw->reserved_1 = fw32->reserved_1;
733	user_ip_fw->reserved_2 = fw32->reserved_2;
734	rulesize = sizeof(struct ip_fw_32) + (fw32->cmd_len * sizeof(ipfw_insn) - 4);
735	if ( rulesize > copysize )
736		cmdsize = copysize - sizeof(struct ip_fw_32)-4;
737	else
738		cmdsize = fw32->cmd_len * sizeof(ipfw_insn);
739	cmdsize = copyfrom32fw_insn( fw32, user_ip_fw, cmdsize);
740	return( sizeof(struct ip_fw) + cmdsize - 4);
741}
742
743static size_t
744copyfrom64fw( struct ip_fw_64 *fw64, struct ip_fw *user_ip_fw, size_t copysize)
745{
746	size_t rulesize, cmdsize;
747
748	user_ip_fw->version = fw64->version;
749	user_ip_fw->context = CAST_DOWN_EXPLICIT( void *, fw64->context);
750	user_ip_fw->next = CAST_DOWN_EXPLICIT(struct ip_fw*, fw64->next);
751	user_ip_fw->next_rule = CAST_DOWN_EXPLICIT(struct ip_fw*, fw64->next_rule);
752	user_ip_fw->act_ofs = fw64->act_ofs;
753	user_ip_fw->cmd_len = fw64->cmd_len;
754	user_ip_fw->rulenum = fw64->rulenum;
755	user_ip_fw->set = fw64->set;
756	user_ip_fw->set_masks[0] = fw64->set_masks[0];
757	user_ip_fw->set_masks[1] = fw64->set_masks[1];
758	user_ip_fw->pcnt = fw64->pcnt;
759	user_ip_fw->bcnt = fw64->bcnt;
760	user_ip_fw->timestamp = fw64->timestamp;
761	user_ip_fw->reserved_1 = fw64->reserved_1;
762	user_ip_fw->reserved_2 = fw64->reserved_2;
763	//bcopy( fw64->cmd, user_ip_fw->cmd, fw64->cmd_len * sizeof(ipfw_insn));
764	rulesize = sizeof(struct ip_fw_64) + (fw64->cmd_len * sizeof(ipfw_insn) - 4);
765	if ( rulesize > copysize )
766		cmdsize = copysize - sizeof(struct ip_fw_64)-4;
767	else
768		cmdsize = fw64->cmd_len * sizeof(ipfw_insn);
769	cmdsize = copyfrom64fw_insn( fw64, user_ip_fw, cmdsize);
770	return( sizeof(struct ip_fw) + cmdsize - 4);
771}
772
773void
774externalize_flow_id(struct ipfw_flow_id *dst, struct ip_flow_id *src);
775void
776externalize_flow_id(struct ipfw_flow_id *dst, struct ip_flow_id *src)
777{
778	dst->dst_ip = src->dst_ip;
779	dst->src_ip = src->src_ip;
780	dst->dst_port = src->dst_port;
781	dst->src_port = src->src_port;
782	dst->proto = src->proto;
783	dst->flags = src->flags;
784}
785
786static
787void cp_dyn_to_comp_32( struct ipfw_dyn_rule_compat_32 *dyn_rule_vers1, int *len)
788{
789	struct ipfw_dyn_rule_compat_32 *dyn_last=NULL;
790	ipfw_dyn_rule 	*p;
791	int i;
792
793	if (ipfw_dyn_v) {
794		for (i = 0; i < curr_dyn_buckets; i++) {
795			for ( p = ipfw_dyn_v[i] ; p != NULL ; p = p->next) {
796				dyn_rule_vers1->chain = (user32_addr_t)(p->rule->rulenum);
797				externalize_flow_id(&dyn_rule_vers1->id, &p->id);
798				externalize_flow_id(&dyn_rule_vers1->mask, &p->id);
799				dyn_rule_vers1->type = p->dyn_type;
800				dyn_rule_vers1->expire = p->expire;
801				dyn_rule_vers1->pcnt = p->pcnt;
802				dyn_rule_vers1->bcnt = p->bcnt;
803				dyn_rule_vers1->bucket = p->bucket;
804				dyn_rule_vers1->state = p->state;
805
806				dyn_rule_vers1->next = CAST_DOWN_EXPLICIT( user32_addr_t, p->next);
807				dyn_last = dyn_rule_vers1;
808
809				*len += sizeof(*dyn_rule_vers1);
810				dyn_rule_vers1++;
811			}
812		}
813
814		if (dyn_last != NULL) {
815			dyn_last->next = ((user32_addr_t)0);
816		}
817	}
818}
819
820
821static
822void cp_dyn_to_comp_64( struct ipfw_dyn_rule_compat_64 *dyn_rule_vers1, int *len)
823{
824	struct ipfw_dyn_rule_compat_64 *dyn_last=NULL;
825	ipfw_dyn_rule 	*p;
826	int i;
827
828	if (ipfw_dyn_v) {
829		for (i = 0; i < curr_dyn_buckets; i++) {
830			for ( p = ipfw_dyn_v[i] ; p != NULL ; p = p->next) {
831				dyn_rule_vers1->chain = (user64_addr_t) p->rule->rulenum;
832				externalize_flow_id(&dyn_rule_vers1->id, &p->id);
833				externalize_flow_id(&dyn_rule_vers1->mask, &p->id);
834				dyn_rule_vers1->type = p->dyn_type;
835				dyn_rule_vers1->expire = p->expire;
836				dyn_rule_vers1->pcnt = p->pcnt;
837				dyn_rule_vers1->bcnt = p->bcnt;
838				dyn_rule_vers1->bucket = p->bucket;
839				dyn_rule_vers1->state = p->state;
840
841				dyn_rule_vers1->next = CAST_DOWN(user64_addr_t, p->next);
842				dyn_last = dyn_rule_vers1;
843
844				*len += sizeof(*dyn_rule_vers1);
845				dyn_rule_vers1++;
846			}
847		}
848
849		if (dyn_last != NULL) {
850			dyn_last->next = CAST_DOWN(user64_addr_t, NULL);
851		}
852	}
853}
854
855static int
856sooptcopyin_fw( struct sockopt *sopt, struct ip_fw *user_ip_fw, size_t *size )
857{
858	size_t	valsize, copyinsize = 0;
859	int	error = 0;
860
861	valsize = sopt->sopt_valsize;
862	if ( size )
863		copyinsize = *size;
864	if (proc_is64bit(sopt->sopt_p)) {
865		struct ip_fw_64	*fw64=NULL;
866
867		if ( valsize < sizeof(struct ip_fw_64) ) {
868			return(EINVAL);
869		}
870		if ( !copyinsize )
871			copyinsize = sizeof(struct ip_fw_64);
872		if ( valsize > copyinsize )
873			sopt->sopt_valsize = valsize = copyinsize;
874
875		if ( sopt->sopt_p != 0) {
876			fw64 = _MALLOC(copyinsize, M_TEMP, M_WAITOK);
877			if ( fw64 == NULL )
878				return(ENOBUFS);
879			if ((error = copyin(sopt->sopt_val, fw64, valsize)) != 0){
880				_FREE(fw64, M_TEMP);
881				return error;
882			}
883		}
884		else {
885			bcopy(CAST_DOWN(caddr_t, sopt->sopt_val), fw64, valsize);
886		}
887		valsize = copyfrom64fw( fw64, user_ip_fw, valsize );
888		_FREE( fw64, M_TEMP);
889	}else {
890		struct ip_fw_32 *fw32=NULL;
891
892		if ( valsize < sizeof(struct ip_fw_32) ) {
893			return(EINVAL);
894		}
895		if ( !copyinsize)
896			copyinsize = sizeof(struct ip_fw_32);
897		if ( valsize > copyinsize)
898			sopt->sopt_valsize = valsize = copyinsize;
899
900		if ( sopt->sopt_p != 0) {
901			fw32 = _MALLOC(copyinsize, M_TEMP, M_WAITOK);
902			if ( fw32 == NULL )
903				return(ENOBUFS);
904			if ( (error = copyin(sopt->sopt_val, fw32, valsize)) != 0){
905				_FREE( fw32, M_TEMP);
906				return( error );
907			}
908		}
909		else {
910			bcopy(CAST_DOWN(caddr_t, sopt->sopt_val), fw32, valsize);
911		}
912		valsize = copyfrom32fw( fw32, user_ip_fw, valsize);
913		_FREE( fw32, M_TEMP);
914	}
915	if ( size )
916		*size = valsize;
917	return error;
918}
919
920/*
921 * The following checks use two arrays of 8 or 16 bits to store the
922 * bits that we want set or clear, respectively. They are in the
923 * low and high half of cmd->arg1 or cmd->d[0].
924 *
925 * We scan options and store the bits we find set. We succeed if
926 *
927 *	(want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
928 *
929 * The code is sometimes optimized not to store additional variables.
930 */
931
932static int
933flags_match(ipfw_insn *cmd, u_int8_t bits)
934{
935	u_char want_clear;
936	bits = ~bits;
937
938	if ( ((cmd->arg1 & 0xff) & bits) != 0)
939		return 0; /* some bits we want set were clear */
940	want_clear = (cmd->arg1 >> 8) & 0xff;
941	if ( (want_clear & bits) != want_clear)
942		return 0; /* some bits we want clear were set */
943	return 1;
944}
945
946static int
947ipopts_match(struct ip *ip, ipfw_insn *cmd)
948{
949	int optlen, bits = 0;
950	u_char *cp = (u_char *)(ip + 1);
951	int x = (ip->ip_hl << 2) - sizeof (struct ip);
952
953	for (; x > 0; x -= optlen, cp += optlen) {
954		int opt = cp[IPOPT_OPTVAL];
955
956		if (opt == IPOPT_EOL)
957			break;
958		if (opt == IPOPT_NOP)
959			optlen = 1;
960		else {
961			optlen = cp[IPOPT_OLEN];
962			if (optlen <= 0 || optlen > x)
963				return 0; /* invalid or truncated */
964		}
965		switch (opt) {
966
967		default:
968			break;
969
970		case IPOPT_LSRR:
971			bits |= IP_FW_IPOPT_LSRR;
972			break;
973
974		case IPOPT_SSRR:
975			bits |= IP_FW_IPOPT_SSRR;
976			break;
977
978		case IPOPT_RR:
979			bits |= IP_FW_IPOPT_RR;
980			break;
981
982		case IPOPT_TS:
983			bits |= IP_FW_IPOPT_TS;
984			break;
985		}
986	}
987	return (flags_match(cmd, bits));
988}
989
990static int
991tcpopts_match(struct ip *ip, ipfw_insn *cmd)
992{
993	int optlen, bits = 0;
994	struct tcphdr *tcp = L3HDR(struct tcphdr,ip);
995	u_char *cp = (u_char *)(tcp + 1);
996	int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
997
998	for (; x > 0; x -= optlen, cp += optlen) {
999		int opt = cp[0];
1000		if (opt == TCPOPT_EOL)
1001			break;
1002		if (opt == TCPOPT_NOP)
1003			optlen = 1;
1004		else {
1005			optlen = cp[1];
1006			if (optlen <= 0)
1007				break;
1008		}
1009
1010		switch (opt) {
1011
1012		default:
1013			break;
1014
1015		case TCPOPT_MAXSEG:
1016			bits |= IP_FW_TCPOPT_MSS;
1017			break;
1018
1019		case TCPOPT_WINDOW:
1020			bits |= IP_FW_TCPOPT_WINDOW;
1021			break;
1022
1023		case TCPOPT_SACK_PERMITTED:
1024		case TCPOPT_SACK:
1025			bits |= IP_FW_TCPOPT_SACK;
1026			break;
1027
1028		case TCPOPT_TIMESTAMP:
1029			bits |= IP_FW_TCPOPT_TS;
1030			break;
1031
1032		case TCPOPT_CC:
1033		case TCPOPT_CCNEW:
1034		case TCPOPT_CCECHO:
1035			bits |= IP_FW_TCPOPT_CC;
1036			break;
1037		}
1038	}
1039	return (flags_match(cmd, bits));
1040}
1041
1042static int
1043iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
1044{
1045	if (ifp == NULL)	/* no iface with this packet, match fails */
1046		return 0;
1047	/* Check by name or by IP address */
1048	if (cmd->name[0] != '\0') { /* match by name */
1049		/* Check unit number (-1 is wildcard) */
1050		if (cmd->p.unit != -1 && cmd->p.unit != ifp->if_unit)
1051			return(0);
1052		/* Check name */
1053		if (!strncmp(ifp->if_name, cmd->name, IFNAMSIZ))
1054			return(1);
1055	} else {
1056		struct ifaddr *ia;
1057
1058		ifnet_lock_shared(ifp);
1059		TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
1060			IFA_LOCK(ia);
1061			if (ia->ifa_addr->sa_family != AF_INET) {
1062				IFA_UNLOCK(ia);
1063				continue;
1064			}
1065			if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
1066			    (ia->ifa_addr))->sin_addr.s_addr) {
1067				IFA_UNLOCK(ia);
1068				ifnet_lock_done(ifp);
1069				return(1);	/* match */
1070			}
1071			IFA_UNLOCK(ia);
1072		}
1073		ifnet_lock_done(ifp);
1074	}
1075	return(0);	/* no match, fail ... */
1076}
1077
1078/*
1079 * The 'verrevpath' option checks that the interface that an IP packet
1080 * arrives on is the same interface that traffic destined for the
1081 * packet's source address would be routed out of. This is a measure
1082 * to block forged packets. This is also commonly known as "anti-spoofing"
1083 * or Unicast Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The
1084 * name of the knob is purposely reminisent of the Cisco IOS command,
1085 *
1086 *   ip verify unicast reverse-path
1087 *
1088 * which implements the same functionality. But note that syntax is
1089 * misleading. The check may be performed on all IP packets whether unicast,
1090 * multicast, or broadcast.
1091 */
1092static int
1093verify_rev_path(struct in_addr src, struct ifnet *ifp)
1094{
1095	static struct route ro;
1096	struct sockaddr_in *dst;
1097
1098	bzero(&ro, sizeof (ro));
1099	dst = (struct sockaddr_in *)&(ro.ro_dst);
1100
1101	/* Check if we've cached the route from the previous call. */
1102	if (src.s_addr != dst->sin_addr.s_addr) {
1103		dst->sin_family = AF_INET;
1104		dst->sin_len = sizeof(*dst);
1105		dst->sin_addr = src;
1106
1107		rtalloc_ign(&ro, RTF_CLONING|RTF_PRCLONING);
1108	}
1109	if (ro.ro_rt != NULL) {
1110		RT_LOCK_SPIN(ro.ro_rt);
1111	} else {
1112		ROUTE_RELEASE(&ro);
1113		return 0;	/* No route */
1114	}
1115	if ((ifp == NULL) ||
1116	    (ro.ro_rt->rt_ifp->if_index != ifp->if_index)) {
1117		RT_UNLOCK(ro.ro_rt);
1118		ROUTE_RELEASE(&ro);
1119		return 0;
1120        }
1121	RT_UNLOCK(ro.ro_rt);
1122	ROUTE_RELEASE(&ro);
1123	return 1;
1124}
1125
1126
1127static u_int64_t norule_counter;	/* counter for ipfw_log(NULL...) */
1128
1129#define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
1130#define SNP(buf) buf, sizeof(buf)
1131
1132/*
1133 * We enter here when we have a rule with O_LOG.
1134 * XXX this function alone takes about 2Kbytes of code!
1135 */
1136static void
1137ipfw_log(struct ip_fw *f, u_int hlen, struct ether_header *eh,
1138	struct mbuf *m, struct ifnet *oif)
1139{
1140	const char *action;
1141	int limit_reached = 0;
1142	char ipv4str[MAX_IPv4_STR_LEN];
1143	char action2[40], proto[48], fragment[28];
1144
1145	fragment[0] = '\0';
1146	proto[0] = '\0';
1147
1148	if (f == NULL) {	/* bogus pkt */
1149		if (verbose_limit != 0 && norule_counter >= verbose_limit)
1150			return;
1151		norule_counter++;
1152		if (norule_counter == verbose_limit)
1153			limit_reached = verbose_limit;
1154		action = "Refuse";
1155	} else {	/* O_LOG is the first action, find the real one */
1156		ipfw_insn *cmd = ACTION_PTR(f);
1157		ipfw_insn_log *l = (ipfw_insn_log *)cmd;
1158
1159		if (l->max_log != 0 && l->log_left == 0)
1160			return;
1161		l->log_left--;
1162		if (l->log_left == 0)
1163			limit_reached = l->max_log;
1164		cmd += F_LEN(cmd);	/* point to first action */
1165		if (cmd->opcode == O_PROB)
1166			cmd += F_LEN(cmd);
1167
1168		action = action2;
1169		switch (cmd->opcode) {
1170		case O_DENY:
1171			action = "Deny";
1172			break;
1173
1174		case O_REJECT:
1175			if (cmd->arg1==ICMP_REJECT_RST)
1176				action = "Reset";
1177			else if (cmd->arg1==ICMP_UNREACH_HOST)
1178				action = "Reject";
1179			else
1180				snprintf(SNPARGS(action2, 0), "Unreach %d",
1181					cmd->arg1);
1182			break;
1183
1184		case O_ACCEPT:
1185			action = "Accept";
1186			break;
1187		case O_COUNT:
1188			action = "Count";
1189			break;
1190		case O_DIVERT:
1191			snprintf(SNPARGS(action2, 0), "Divert %d",
1192				cmd->arg1);
1193			break;
1194		case O_TEE:
1195			snprintf(SNPARGS(action2, 0), "Tee %d",
1196				cmd->arg1);
1197			break;
1198		case O_SKIPTO:
1199			snprintf(SNPARGS(action2, 0), "SkipTo %d",
1200				cmd->arg1);
1201			break;
1202		case O_PIPE:
1203			snprintf(SNPARGS(action2, 0), "Pipe %d",
1204				cmd->arg1);
1205			break;
1206		case O_QUEUE:
1207			snprintf(SNPARGS(action2, 0), "Queue %d",
1208				cmd->arg1);
1209			break;
1210		case O_FORWARD_IP: {
1211			ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
1212			int len;
1213
1214			if (f->reserved_1 == IPFW_RULE_INACTIVE) {
1215				break;
1216			}
1217			len = snprintf(SNPARGS(action2, 0), "Forward to %s",
1218				inet_ntop(AF_INET, &sa->sa.sin_addr, ipv4str, sizeof(ipv4str)));
1219			if (sa->sa.sin_port)
1220				snprintf(SNPARGS(action2, len), ":%d",
1221				    sa->sa.sin_port);
1222			}
1223			break;
1224		default:
1225			action = "UNKNOWN";
1226			break;
1227		}
1228	}
1229
1230	if (hlen == 0) {	/* non-ip */
1231		snprintf(SNPARGS(proto, 0), "MAC");
1232	} else {
1233		struct ip *ip = mtod(m, struct ip *);
1234		/* these three are all aliases to the same thing */
1235		struct icmp *const icmp = L3HDR(struct icmp, ip);
1236		struct tcphdr *const tcp = (struct tcphdr *)icmp;
1237		struct udphdr *const udp = (struct udphdr *)icmp;
1238
1239		int ip_off, offset, ip_len;
1240
1241		int len;
1242
1243		if (eh != NULL) { /* layer 2 packets are as on the wire */
1244			ip_off = ntohs(ip->ip_off);
1245			ip_len = ntohs(ip->ip_len);
1246		} else {
1247			ip_off = ip->ip_off;
1248			ip_len = ip->ip_len;
1249		}
1250		offset = ip_off & IP_OFFMASK;
1251		switch (ip->ip_p) {
1252		case IPPROTO_TCP:
1253			len = snprintf(SNPARGS(proto, 0), "TCP %s",
1254			    inet_ntop(AF_INET, &ip->ip_src, ipv4str, sizeof(ipv4str)));
1255			if (offset == 0)
1256				snprintf(SNPARGS(proto, len), ":%d %s:%d",
1257				    ntohs(tcp->th_sport),
1258				    inet_ntop(AF_INET, &ip->ip_dst, ipv4str, sizeof(ipv4str)),
1259				    ntohs(tcp->th_dport));
1260			else
1261				snprintf(SNPARGS(proto, len), " %s",
1262				    inet_ntop(AF_INET, &ip->ip_dst, ipv4str, sizeof(ipv4str)));
1263			break;
1264
1265		case IPPROTO_UDP:
1266			len = snprintf(SNPARGS(proto, 0), "UDP %s",
1267				inet_ntop(AF_INET, &ip->ip_src, ipv4str, sizeof(ipv4str)));
1268			if (offset == 0)
1269				snprintf(SNPARGS(proto, len), ":%d %s:%d",
1270				    ntohs(udp->uh_sport),
1271				    inet_ntop(AF_INET, &ip->ip_dst, ipv4str, sizeof(ipv4str)),
1272				    ntohs(udp->uh_dport));
1273			else
1274				snprintf(SNPARGS(proto, len), " %s",
1275				    inet_ntop(AF_INET, &ip->ip_dst, ipv4str, sizeof(ipv4str)));
1276			break;
1277
1278		case IPPROTO_ICMP:
1279			if (offset == 0)
1280				len = snprintf(SNPARGS(proto, 0),
1281				    "ICMP:%u.%u ",
1282				    icmp->icmp_type, icmp->icmp_code);
1283			else
1284				len = snprintf(SNPARGS(proto, 0), "ICMP ");
1285			len += snprintf(SNPARGS(proto, len), "%s",
1286			    inet_ntop(AF_INET, &ip->ip_src, ipv4str, sizeof(ipv4str)));
1287			snprintf(SNPARGS(proto, len), " %s",
1288			    inet_ntop(AF_INET, &ip->ip_dst, ipv4str, sizeof(ipv4str)));
1289			break;
1290
1291		default:
1292			len = snprintf(SNPARGS(proto, 0), "P:%d %s", ip->ip_p,
1293			    inet_ntop(AF_INET, &ip->ip_src, ipv4str, sizeof(ipv4str)));
1294			snprintf(SNPARGS(proto, len), " %s",
1295			    inet_ntop(AF_INET, &ip->ip_dst, ipv4str, sizeof(ipv4str)));
1296			break;
1297		}
1298
1299		if (ip_off & (IP_MF | IP_OFFMASK))
1300			snprintf(SNPARGS(fragment, 0), " (frag %d:%d@%d%s)",
1301			     ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
1302			     offset << 3,
1303			     (ip_off & IP_MF) ? "+" : "");
1304	}
1305	if (oif || m->m_pkthdr.rcvif)
1306	{
1307		dolog((LOG_AUTHPRIV | LOG_INFO,
1308		    "ipfw: %d %s %s %s via %s%d%s\n",
1309		    f ? f->rulenum : -1,
1310		    action, proto, oif ? "out" : "in",
1311		    oif ? oif->if_name : m->m_pkthdr.rcvif->if_name,
1312		    oif ? oif->if_unit : m->m_pkthdr.rcvif->if_unit,
1313		    fragment));
1314	}
1315	else{
1316		dolog((LOG_AUTHPRIV | LOG_INFO,
1317		    "ipfw: %d %s %s [no if info]%s\n",
1318		    f ? f->rulenum : -1,
1319		    action, proto, fragment));
1320	}
1321	if (limit_reached){
1322		dolog((LOG_AUTHPRIV | LOG_NOTICE,
1323		    "ipfw: limit %d reached on entry %d\n",
1324		    limit_reached, f ? f->rulenum : -1));
1325	}
1326}
1327
1328/*
1329 * IMPORTANT: the hash function for dynamic rules must be commutative
1330 * in source and destination (ip,port), because rules are bidirectional
1331 * and we want to find both in the same bucket.
1332 */
1333static __inline int
1334hash_packet(struct ip_flow_id *id)
1335{
1336	u_int32_t i;
1337
1338	i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
1339	i &= (curr_dyn_buckets - 1);
1340	return i;
1341}
1342
1343/**
1344 * unlink a dynamic rule from a chain. prev is a pointer to
1345 * the previous one, q is a pointer to the rule to delete,
1346 * head is a pointer to the head of the queue.
1347 * Modifies q and potentially also head.
1348 */
1349#define UNLINK_DYN_RULE(prev, head, q) {				\
1350	ipfw_dyn_rule *old_q = q;					\
1351									\
1352	/* remove a refcount to the parent */				\
1353	if (q->dyn_type == O_LIMIT)					\
1354		q->parent->count--;					\
1355	DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
1356		(q->id.src_ip), (q->id.src_port),			\
1357		(q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); )	\
1358	if (prev != NULL)						\
1359		prev->next = q = q->next;				\
1360	else								\
1361		head = q = q->next;					\
1362	dyn_count--;							\
1363	_FREE(old_q, M_IPFW); }
1364
1365#define TIME_LEQ(a,b)       ((int)((a)-(b)) <= 0)
1366
1367/**
1368 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
1369 *
1370 * If keep_me == NULL, rules are deleted even if not expired,
1371 * otherwise only expired rules are removed.
1372 *
1373 * The value of the second parameter is also used to point to identify
1374 * a rule we absolutely do not want to remove (e.g. because we are
1375 * holding a reference to it -- this is the case with O_LIMIT_PARENT
1376 * rules). The pointer is only used for comparison, so any non-null
1377 * value will do.
1378 */
1379static void
1380remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
1381{
1382	static u_int32_t last_remove = 0;
1383
1384#define FORCE (keep_me == NULL)
1385
1386	ipfw_dyn_rule *prev, *q;
1387	int i, pass = 0, max_pass = 0;
1388	struct timeval timenow;
1389
1390	getmicrotime(&timenow);
1391
1392	if (ipfw_dyn_v == NULL || dyn_count == 0)
1393		return;
1394	/* do not expire more than once per second, it is useless */
1395	if (!FORCE && last_remove == timenow.tv_sec)
1396		return;
1397	last_remove = timenow.tv_sec;
1398
1399	/*
1400	 * because O_LIMIT refer to parent rules, during the first pass only
1401	 * remove child and mark any pending LIMIT_PARENT, and remove
1402	 * them in a second pass.
1403	 */
1404next_pass:
1405	for (i = 0 ; i < curr_dyn_buckets ; i++) {
1406		for (prev=NULL, q = ipfw_dyn_v[i] ; q ; ) {
1407			/*
1408			 * Logic can become complex here, so we split tests.
1409			 */
1410			if (q == keep_me)
1411				goto next;
1412			if (rule != NULL && rule != q->rule)
1413				goto next; /* not the one we are looking for */
1414			if (q->dyn_type == O_LIMIT_PARENT) {
1415				/*
1416				 * handle parent in the second pass,
1417				 * record we need one.
1418				 */
1419				max_pass = 1;
1420				if (pass == 0)
1421					goto next;
1422				if (FORCE && q->count != 0 ) {
1423					/* XXX should not happen! */
1424					printf("ipfw: OUCH! cannot remove rule,"
1425					     " count %d\n", q->count);
1426				}
1427			} else {
1428				if (!FORCE &&
1429				    !TIME_LEQ( q->expire, timenow.tv_sec ))
1430					goto next;
1431			}
1432			if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
1433				UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
1434				continue;
1435			}
1436next:
1437			prev=q;
1438			q=q->next;
1439		}
1440	}
1441	if (pass++ < max_pass)
1442		goto next_pass;
1443}
1444
1445
1446/**
1447 * lookup a dynamic rule.
1448 */
1449static ipfw_dyn_rule *
1450lookup_dyn_rule(struct ip_flow_id *pkt, int *match_direction,
1451	struct tcphdr *tcp)
1452{
1453	/*
1454	 * stateful ipfw extensions.
1455	 * Lookup into dynamic session queue
1456	 */
1457#define MATCH_REVERSE	0
1458#define MATCH_FORWARD	1
1459#define MATCH_NONE	2
1460#define MATCH_UNKNOWN	3
1461#define BOTH_SYN        (TH_SYN | (TH_SYN << 8))
1462#define BOTH_FIN        (TH_FIN | (TH_FIN << 8))
1463
1464	int i, dir = MATCH_NONE;
1465	ipfw_dyn_rule *prev, *q=NULL;
1466	struct timeval timenow;
1467
1468	getmicrotime(&timenow);
1469
1470	if (ipfw_dyn_v == NULL)
1471		goto done;	/* not found */
1472	i = hash_packet( pkt );
1473	for (prev=NULL, q = ipfw_dyn_v[i] ; q != NULL ; ) {
1474		if (q->dyn_type == O_LIMIT_PARENT && q->count)
1475			goto next;
1476		if (TIME_LEQ( q->expire, timenow.tv_sec)) { /* expire entry */
1477                        int     dounlink = 1;
1478
1479			/* check if entry is TCP */
1480                        if ( q->id.proto == IPPROTO_TCP )
1481                        {
1482                                /* do not delete an established TCP connection which hasn't been closed by both sides */
1483                                if ( (q->state & (BOTH_SYN | BOTH_FIN)) != (BOTH_SYN | BOTH_FIN) )
1484                                        dounlink = 0;
1485                        }
1486                        if ( dounlink ){
1487                                UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
1488                                continue;
1489                        }
1490		}
1491		if (pkt->proto == q->id.proto &&
1492		    q->dyn_type != O_LIMIT_PARENT) {
1493			if (pkt->src_ip == q->id.src_ip &&
1494			    pkt->dst_ip == q->id.dst_ip &&
1495			    pkt->src_port == q->id.src_port &&
1496			    pkt->dst_port == q->id.dst_port ) {
1497				dir = MATCH_FORWARD;
1498				break;
1499			}
1500			if (pkt->src_ip == q->id.dst_ip &&
1501			    pkt->dst_ip == q->id.src_ip &&
1502			    pkt->src_port == q->id.dst_port &&
1503			    pkt->dst_port == q->id.src_port ) {
1504				dir = MATCH_REVERSE;
1505				break;
1506			}
1507		}
1508next:
1509		prev = q;
1510		q = q->next;
1511	}
1512	if (q == NULL)
1513		goto done; /* q = NULL, not found */
1514
1515	if ( prev != NULL) { /* found and not in front */
1516		prev->next = q->next;
1517		q->next = ipfw_dyn_v[i];
1518		ipfw_dyn_v[i] = q;
1519	}
1520	if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1521		u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1522
1523		q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1524		switch (q->state) {
1525		case TH_SYN:				/* opening */
1526			q->expire = timenow.tv_sec + dyn_syn_lifetime;
1527			break;
1528
1529		case BOTH_SYN:			/* move to established */
1530		case BOTH_SYN | TH_FIN :	/* one side tries to close */
1531		case BOTH_SYN | (TH_FIN << 8) :
1532 			if (tcp) {
1533#define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
1534			    u_int32_t ack = ntohl(tcp->th_ack);
1535			    if (dir == MATCH_FORWARD) {
1536				if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
1537				    q->ack_fwd = ack;
1538				else { /* ignore out-of-sequence */
1539				    break;
1540				}
1541			    } else {
1542				if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
1543				    q->ack_rev = ack;
1544				else { /* ignore out-of-sequence */
1545				    break;
1546				}
1547			    }
1548			}
1549			q->expire = timenow.tv_sec + dyn_ack_lifetime;
1550			break;
1551
1552		case BOTH_SYN | BOTH_FIN:	/* both sides closed */
1553			if (dyn_fin_lifetime >= dyn_keepalive_period)
1554				dyn_fin_lifetime = dyn_keepalive_period - 1;
1555			q->expire = timenow.tv_sec + dyn_fin_lifetime;
1556			break;
1557
1558		default:
1559#if 0
1560			/*
1561			 * reset or some invalid combination, but can also
1562			 * occur if we use keep-state the wrong way.
1563			 */
1564			if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
1565				printf("invalid state: 0x%x\n", q->state);
1566#endif
1567			if (dyn_rst_lifetime >= dyn_keepalive_period)
1568				dyn_rst_lifetime = dyn_keepalive_period - 1;
1569			q->expire = timenow.tv_sec + dyn_rst_lifetime;
1570			break;
1571		}
1572	} else if (pkt->proto == IPPROTO_UDP) {
1573		q->expire = timenow.tv_sec + dyn_udp_lifetime;
1574	} else {
1575		/* other protocols */
1576		q->expire = timenow.tv_sec + dyn_short_lifetime;
1577	}
1578done:
1579	if (match_direction)
1580		*match_direction = dir;
1581	return q;
1582}
1583
1584static void
1585realloc_dynamic_table(void)
1586{
1587	/*
1588	 * Try reallocation, make sure we have a power of 2 and do
1589	 * not allow more than 64k entries. In case of overflow,
1590	 * default to 1024.
1591	 */
1592
1593	if (dyn_buckets > 65536)
1594		dyn_buckets = 1024;
1595	if ((dyn_buckets & (dyn_buckets-1)) != 0) { /* not a power of 2 */
1596		dyn_buckets = curr_dyn_buckets; /* reset */
1597		return;
1598	}
1599	curr_dyn_buckets = dyn_buckets;
1600	if (ipfw_dyn_v != NULL)
1601		_FREE(ipfw_dyn_v, M_IPFW);
1602	for (;;) {
1603		ipfw_dyn_v = _MALLOC(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1604		       M_IPFW, M_NOWAIT | M_ZERO);
1605		if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
1606			break;
1607		curr_dyn_buckets /= 2;
1608	}
1609}
1610
1611/**
1612 * Install state of type 'type' for a dynamic session.
1613 * The hash table contains two type of rules:
1614 * - regular rules (O_KEEP_STATE)
1615 * - rules for sessions with limited number of sess per user
1616 *   (O_LIMIT). When they are created, the parent is
1617 *   increased by 1, and decreased on delete. In this case,
1618 *   the third parameter is the parent rule and not the chain.
1619 * - "parent" rules for the above (O_LIMIT_PARENT).
1620 */
1621static ipfw_dyn_rule *
1622add_dyn_rule(struct ip_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
1623{
1624	ipfw_dyn_rule *r;
1625	int i;
1626	struct timeval timenow;
1627
1628	getmicrotime(&timenow);
1629
1630	if (ipfw_dyn_v == NULL ||
1631	    (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
1632		realloc_dynamic_table();
1633		if (ipfw_dyn_v == NULL)
1634			return NULL; /* failed ! */
1635	}
1636	i = hash_packet(id);
1637
1638	r = _MALLOC(sizeof *r, M_IPFW, M_NOWAIT | M_ZERO);
1639	if (r == NULL) {
1640#if IPFW_DEBUG
1641		printf ("ipfw: sorry cannot allocate state\n");
1642#endif
1643		return NULL;
1644	}
1645
1646	/* increase refcount on parent, and set pointer */
1647	if (dyn_type == O_LIMIT) {
1648		ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1649		if ( parent->dyn_type != O_LIMIT_PARENT)
1650			panic("invalid parent");
1651		parent->count++;
1652		r->parent = parent;
1653		rule = parent->rule;
1654	}
1655
1656	r->id = *id;
1657	r->expire = timenow.tv_sec + dyn_syn_lifetime;
1658	r->rule = rule;
1659	r->dyn_type = dyn_type;
1660	r->pcnt = r->bcnt = 0;
1661	r->count = 0;
1662
1663	r->bucket = i;
1664	r->next = ipfw_dyn_v[i];
1665	ipfw_dyn_v[i] = r;
1666	dyn_count++;
1667	DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1668	   dyn_type,
1669	   (r->id.src_ip), (r->id.src_port),
1670	   (r->id.dst_ip), (r->id.dst_port),
1671	   dyn_count ); )
1672	return r;
1673}
1674
1675/**
1676 * lookup dynamic parent rule using pkt and rule as search keys.
1677 * If the lookup fails, then install one.
1678 */
1679static ipfw_dyn_rule *
1680lookup_dyn_parent(struct ip_flow_id *pkt, struct ip_fw *rule)
1681{
1682	ipfw_dyn_rule *q;
1683	int i;
1684	struct timeval timenow;
1685
1686	getmicrotime(&timenow);
1687
1688	if (ipfw_dyn_v) {
1689		i = hash_packet( pkt );
1690		for (q = ipfw_dyn_v[i] ; q != NULL ; q=q->next)
1691			if (q->dyn_type == O_LIMIT_PARENT &&
1692			    rule== q->rule &&
1693			    pkt->proto == q->id.proto &&
1694			    pkt->src_ip == q->id.src_ip &&
1695			    pkt->dst_ip == q->id.dst_ip &&
1696			    pkt->src_port == q->id.src_port &&
1697			    pkt->dst_port == q->id.dst_port) {
1698				q->expire = timenow.tv_sec + dyn_short_lifetime;
1699				DEB(printf("ipfw: lookup_dyn_parent found "
1700				    "0x%llx\n", (uint64_t)VM_KERNEL_ADDRPERM(q));)
1701				return q;
1702			}
1703	}
1704	return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1705}
1706
1707/**
1708 * Install dynamic state for rule type cmd->o.opcode
1709 *
1710 * Returns 1 (failure) if state is not installed because of errors or because
1711 * session limitations are enforced.
1712 */
1713static int
1714install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1715	struct ip_fw_args *args)
1716{
1717	static int last_log;
1718	struct timeval timenow;
1719
1720	ipfw_dyn_rule *q;
1721	getmicrotime(&timenow);
1722
1723	DEB(printf("ipfw: install state type %d 0x%08x %u -> 0x%08x %u\n",
1724	    cmd->o.opcode,
1725	    (args->fwa_id.src_ip), (args->fwa_id.src_port),
1726	    (args->fwa_id.dst_ip), (args->fwa_id.dst_port) );)
1727
1728	q = lookup_dyn_rule(&args->fwa_id, NULL, NULL);
1729
1730	if (q != NULL) { /* should never occur */
1731		if (last_log != timenow.tv_sec) {
1732			last_log = timenow.tv_sec;
1733			printf("ipfw: install_state: entry already present, done\n");
1734		}
1735		return 0;
1736	}
1737
1738	if (dyn_count >= dyn_max)
1739		/*
1740		 * Run out of slots, try to remove any expired rule.
1741		 */
1742		remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1743
1744	if (dyn_count >= dyn_max) {
1745		if (last_log != timenow.tv_sec) {
1746			last_log = timenow.tv_sec;
1747			printf("ipfw: install_state: Too many dynamic rules\n");
1748		}
1749		return 1; /* cannot install, notify caller */
1750	}
1751
1752	switch (cmd->o.opcode) {
1753	case O_KEEP_STATE: /* bidir rule */
1754		add_dyn_rule(&args->fwa_id, O_KEEP_STATE, rule);
1755		break;
1756
1757	case O_LIMIT: /* limit number of sessions */
1758	    {
1759		u_int16_t limit_mask = cmd->limit_mask;
1760		struct ip_flow_id id;
1761		ipfw_dyn_rule *parent;
1762
1763		DEB(printf("ipfw: installing dyn-limit rule %d\n",
1764		    cmd->conn_limit);)
1765
1766		id.dst_ip = id.src_ip = 0;
1767		id.dst_port = id.src_port = 0;
1768		id.proto = args->fwa_id.proto;
1769
1770		if (limit_mask & DYN_SRC_ADDR)
1771			id.src_ip = args->fwa_id.src_ip;
1772		if (limit_mask & DYN_DST_ADDR)
1773			id.dst_ip = args->fwa_id.dst_ip;
1774		if (limit_mask & DYN_SRC_PORT)
1775			id.src_port = args->fwa_id.src_port;
1776		if (limit_mask & DYN_DST_PORT)
1777			id.dst_port = args->fwa_id.dst_port;
1778		parent = lookup_dyn_parent(&id, rule);
1779		if (parent == NULL) {
1780			printf("ipfw: add parent failed\n");
1781			return 1;
1782		}
1783		if (parent->count >= cmd->conn_limit) {
1784			/*
1785			 * See if we can remove some expired rule.
1786			 */
1787			remove_dyn_rule(rule, parent);
1788			if (parent->count >= cmd->conn_limit) {
1789				if (fw_verbose && last_log != timenow.tv_sec) {
1790					last_log = timenow.tv_sec;
1791					dolog((LOG_AUTHPRIV | LOG_DEBUG,
1792					    "drop session, too many entries\n"));
1793				}
1794				return 1;
1795			}
1796		}
1797		add_dyn_rule(&args->fwa_id, O_LIMIT, (struct ip_fw *)parent);
1798	    }
1799		break;
1800	default:
1801		printf("ipfw: unknown dynamic rule type %u\n", cmd->o.opcode);
1802		return 1;
1803	}
1804	lookup_dyn_rule(&args->fwa_id, NULL, NULL); /* XXX just set lifetime */
1805	return 0;
1806}
1807
1808/*
1809 * Generate a TCP packet, containing either a RST or a keepalive.
1810 * When flags & TH_RST, we are sending a RST packet, because of a
1811 * "reset" action matched the packet.
1812 * Otherwise we are sending a keepalive, and flags & TH_
1813 */
1814static struct mbuf *
1815send_pkt(struct ip_flow_id *id, u_int32_t seq, u_int32_t ack, int flags)
1816{
1817	struct mbuf *m;
1818	struct ip *ip;
1819	struct tcphdr *tcp;
1820
1821	MGETHDR(m, M_DONTWAIT, MT_HEADER);	/* MAC-OK */
1822	if (m == 0)
1823		return NULL;
1824	m->m_pkthdr.rcvif = (struct ifnet *)0;
1825	m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1826	m->m_data += max_linkhdr;
1827
1828	ip = mtod(m, struct ip *);
1829	bzero(ip, m->m_len);
1830	tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1831	ip->ip_p = IPPROTO_TCP;
1832	tcp->th_off = 5;
1833	/*
1834	 * Assume we are sending a RST (or a keepalive in the reverse
1835	 * direction), swap src and destination addresses and ports.
1836	 */
1837	ip->ip_src.s_addr = htonl(id->dst_ip);
1838	ip->ip_dst.s_addr = htonl(id->src_ip);
1839	tcp->th_sport = htons(id->dst_port);
1840	tcp->th_dport = htons(id->src_port);
1841	if (flags & TH_RST) {	/* we are sending a RST */
1842		if (flags & TH_ACK) {
1843			tcp->th_seq = htonl(ack);
1844			tcp->th_ack = htonl(0);
1845			tcp->th_flags = TH_RST;
1846		} else {
1847			if (flags & TH_SYN)
1848				seq++;
1849			tcp->th_seq = htonl(0);
1850			tcp->th_ack = htonl(seq);
1851			tcp->th_flags = TH_RST | TH_ACK;
1852		}
1853	} else {
1854		/*
1855		 * We are sending a keepalive. flags & TH_SYN determines
1856		 * the direction, forward if set, reverse if clear.
1857		 * NOTE: seq and ack are always assumed to be correct
1858		 * as set by the caller. This may be confusing...
1859		 */
1860		if (flags & TH_SYN) {
1861			/*
1862			 * we have to rewrite the correct addresses!
1863			 */
1864			ip->ip_dst.s_addr = htonl(id->dst_ip);
1865			ip->ip_src.s_addr = htonl(id->src_ip);
1866			tcp->th_dport = htons(id->dst_port);
1867			tcp->th_sport = htons(id->src_port);
1868		}
1869		tcp->th_seq = htonl(seq);
1870		tcp->th_ack = htonl(ack);
1871		tcp->th_flags = TH_ACK;
1872	}
1873	/*
1874	 * set ip_len to the payload size so we can compute
1875	 * the tcp checksum on the pseudoheader
1876	 * XXX check this, could save a couple of words ?
1877	 */
1878	ip->ip_len = htons(sizeof(struct tcphdr));
1879	tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1880	/*
1881	 * now fill fields left out earlier
1882	 */
1883	ip->ip_ttl = ip_defttl;
1884	ip->ip_len = m->m_pkthdr.len;
1885	m->m_flags |= M_SKIP_FIREWALL;
1886
1887	return m;
1888}
1889
1890/*
1891 * sends a reject message, consuming the mbuf passed as an argument.
1892 */
1893static void
1894send_reject(struct ip_fw_args *args, int code, int offset, __unused int ip_len)
1895{
1896
1897	if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1898		/* We need the IP header in host order for icmp_error(). */
1899		if (args->fwa_eh != NULL) {
1900			struct ip *ip = mtod(args->fwa_m, struct ip *);
1901			ip->ip_len = ntohs(ip->ip_len);
1902			ip->ip_off = ntohs(ip->ip_off);
1903		}
1904		args->fwa_m->m_flags |= M_SKIP_FIREWALL;
1905		icmp_error(args->fwa_m, ICMP_UNREACH, code, 0L, 0);
1906	} else if (offset == 0 && args->fwa_id.proto == IPPROTO_TCP) {
1907		struct tcphdr *const tcp =
1908		    L3HDR(struct tcphdr, mtod(args->fwa_m, struct ip *));
1909		if ( (tcp->th_flags & TH_RST) == 0) {
1910			struct mbuf *m;
1911
1912			m = send_pkt(&(args->fwa_id), ntohl(tcp->th_seq),
1913				ntohl(tcp->th_ack),
1914				tcp->th_flags | TH_RST);
1915			if (m != NULL) {
1916				struct route sro;	/* fake route */
1917
1918				bzero (&sro, sizeof (sro));
1919				ip_output(m, NULL, &sro, 0, NULL, NULL);
1920				ROUTE_RELEASE(&sro);
1921			}
1922		}
1923		m_freem(args->fwa_m);
1924	} else
1925		m_freem(args->fwa_m);
1926	args->fwa_m = NULL;
1927}
1928
1929/**
1930 *
1931 * Given an ip_fw *, lookup_next_rule will return a pointer
1932 * to the next rule, which can be either the jump
1933 * target (for skipto instructions) or the next one in the list (in
1934 * all other cases including a missing jump target).
1935 * The result is also written in the "next_rule" field of the rule.
1936 * Backward jumps are not allowed, so start looking from the next
1937 * rule...
1938 *
1939 * This never returns NULL -- in case we do not have an exact match,
1940 * the next rule is returned. When the ruleset is changed,
1941 * pointers are flushed so we are always correct.
1942 */
1943
1944static struct ip_fw *
1945lookup_next_rule(struct ip_fw *me)
1946{
1947	struct ip_fw *rule = NULL;
1948	ipfw_insn *cmd;
1949
1950	/* look for action, in case it is a skipto */
1951	cmd = ACTION_PTR(me);
1952	if (cmd->opcode == O_LOG)
1953		cmd += F_LEN(cmd);
1954	if ( cmd->opcode == O_SKIPTO )
1955		for (rule = me->next; rule ; rule = rule->next)
1956			if (rule->rulenum >= cmd->arg1)
1957				break;
1958	if (rule == NULL)			/* failure or not a skipto */
1959		rule = me->next;
1960	me->next_rule = rule;
1961	return rule;
1962}
1963
1964/*
1965 * The main check routine for the firewall.
1966 *
1967 * All arguments are in args so we can modify them and return them
1968 * back to the caller.
1969 *
1970 * Parameters:
1971 *
1972 *	args->fwa_m	(in/out) The packet; we set to NULL when/if we nuke it.
1973 *		Starts with the IP header.
1974 *	args->fwa_eh (in)	Mac header if present, or NULL for layer3 packet.
1975 *	args->fwa_oif	Outgoing interface, or NULL if packet is incoming.
1976 *		The incoming interface is in the mbuf. (in)
1977 *	args->fwa_divert_rule (in/out)
1978 *		Skip up to the first rule past this rule number;
1979 *		upon return, non-zero port number for divert or tee.
1980 *
1981 *	args->fwa_ipfw_rule	Pointer to the last matching rule (in/out)
1982 *	args->fwa_next_hop	Socket we are forwarding to (out).
1983 *	args->fwa_id	Addresses grabbed from the packet (out)
1984 *
1985 * Return value:
1986 *
1987 *	IP_FW_PORT_DENY_FLAG	the packet must be dropped.
1988 *	0	The packet is to be accepted and routed normally OR
1989 *      	the packet was denied/rejected and has been dropped;
1990 *		in the latter case, *m is equal to NULL upon return.
1991 *	port	Divert the packet to port, with these caveats:
1992 *
1993 *		- If IP_FW_PORT_TEE_FLAG is set, tee the packet instead
1994 *		  of diverting it (ie, 'ipfw tee').
1995 *
1996 *		- If IP_FW_PORT_DYNT_FLAG is set, interpret the lower
1997 *		  16 bits as a dummynet pipe number instead of diverting
1998 */
1999
2000static int
2001ipfw_chk(struct ip_fw_args *args)
2002{
2003	/*
2004	 * Local variables hold state during the processing of a packet.
2005	 *
2006	 * IMPORTANT NOTE: to speed up the processing of rules, there
2007	 * are some assumption on the values of the variables, which
2008	 * are documented here. Should you change them, please check
2009	 * the implementation of the various instructions to make sure
2010	 * that they still work.
2011	 *
2012	 * args->fwa_eh	The MAC header. It is non-null for a layer2
2013	 *	packet, it is NULL for a layer-3 packet.
2014	 *
2015	 * m | args->fwa_m	Pointer to the mbuf, as received from the caller.
2016	 *	It may change if ipfw_chk() does an m_pullup, or if it
2017	 *	consumes the packet because it calls send_reject().
2018	 *	XXX This has to change, so that ipfw_chk() never modifies
2019	 *	or consumes the buffer.
2020	 * ip	is simply an alias of the value of m, and it is kept
2021	 *	in sync with it (the packet is	supposed to start with
2022	 *	the ip header).
2023	 */
2024	struct mbuf *m = args->fwa_m;
2025	struct ip *ip = mtod(m, struct ip *);
2026
2027	/*
2028	 * oif | args->fwa_oif	If NULL, ipfw_chk has been called on the
2029	 *	inbound path (ether_input, bdg_forward, ip_input).
2030	 *	If non-NULL, ipfw_chk has been called on the outbound path
2031	 *	(ether_output, ip_output).
2032	 */
2033	struct ifnet *oif = args->fwa_oif;
2034
2035	struct ip_fw *f = NULL;		/* matching rule */
2036	int retval = 0;
2037
2038	/*
2039	 * hlen	The length of the IPv4 header.
2040	 *	hlen >0 means we have an IPv4 packet.
2041	 */
2042	u_int hlen = 0;		/* hlen >0 means we have an IP pkt */
2043
2044	/*
2045	 * offset	The offset of a fragment. offset != 0 means that
2046	 *	we have a fragment at this offset of an IPv4 packet.
2047	 *	offset == 0 means that (if this is an IPv4 packet)
2048	 *	this is the first or only fragment.
2049	 */
2050	u_short offset = 0;
2051
2052	/*
2053	 * Local copies of addresses. They are only valid if we have
2054	 * an IP packet.
2055	 *
2056	 * proto	The protocol. Set to 0 for non-ip packets,
2057	 *	or to the protocol read from the packet otherwise.
2058	 *	proto != 0 means that we have an IPv4 packet.
2059	 *
2060	 * src_port, dst_port	port numbers, in HOST format. Only
2061	 *	valid for TCP and UDP packets.
2062	 *
2063	 * src_ip, dst_ip	ip addresses, in NETWORK format.
2064	 *	Only valid for IPv4 packets.
2065	 */
2066	u_int8_t proto;
2067	u_int16_t src_port = 0, dst_port = 0;	/* NOTE: host format	*/
2068	struct in_addr src_ip = { 0 } , dst_ip = { 0 };		/* NOTE: network format	*/
2069	u_int16_t ip_len=0;
2070	int pktlen;
2071	int dyn_dir = MATCH_UNKNOWN;
2072	ipfw_dyn_rule *q = NULL;
2073	struct timeval timenow;
2074
2075	if (m->m_flags & M_SKIP_FIREWALL || fw_bypass) {
2076		return 0;	/* accept */
2077	}
2078
2079	/*
2080	 * Clear packet chain if we find one here.
2081	 */
2082
2083	if (m->m_nextpkt != NULL) {
2084		m_freem_list(m->m_nextpkt);
2085		m->m_nextpkt = NULL;
2086	}
2087
2088	lck_mtx_lock(ipfw_mutex);
2089
2090	getmicrotime(&timenow);
2091	/*
2092	 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
2093	 * 	MATCH_NONE when checked and not matched (q = NULL),
2094	 *	MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
2095	 */
2096
2097	pktlen = m->m_pkthdr.len;
2098	if (args->fwa_eh == NULL ||		/* layer 3 packet */
2099		( m->m_pkthdr.len >= sizeof(struct ip) &&
2100		    ntohs(args->fwa_eh->ether_type) == ETHERTYPE_IP))
2101			hlen = ip->ip_hl << 2;
2102
2103	/*
2104	 * Collect parameters into local variables for faster matching.
2105	 */
2106	if (hlen == 0) {	/* do not grab addresses for non-ip pkts */
2107		proto = args->fwa_id.proto = 0;	/* mark f_id invalid */
2108		goto after_ip_checks;
2109	}
2110
2111	proto = args->fwa_id.proto = ip->ip_p;
2112	src_ip = ip->ip_src;
2113	dst_ip = ip->ip_dst;
2114	if (args->fwa_eh != NULL) { /* layer 2 packets are as on the wire */
2115		offset = ntohs(ip->ip_off) & IP_OFFMASK;
2116		ip_len = ntohs(ip->ip_len);
2117	} else {
2118		offset = ip->ip_off & IP_OFFMASK;
2119		ip_len = ip->ip_len;
2120	}
2121	pktlen = ip_len < pktlen ? ip_len : pktlen;
2122
2123#define PULLUP_TO(len)						\
2124		do {						\
2125			if ((m)->m_len < (len)) {		\
2126			    args->fwa_m = m = m_pullup(m, (len));	\
2127			    if (m == 0)				\
2128				goto pullup_failed;		\
2129			    ip = mtod(m, struct ip *);		\
2130			}					\
2131		} while (0)
2132
2133	if (offset == 0) {
2134		switch (proto) {
2135		case IPPROTO_TCP:
2136		    {
2137			struct tcphdr *tcp;
2138
2139			PULLUP_TO(hlen + sizeof(struct tcphdr));
2140			tcp = L3HDR(struct tcphdr, ip);
2141			dst_port = tcp->th_dport;
2142			src_port = tcp->th_sport;
2143			args->fwa_id.flags = tcp->th_flags;
2144			}
2145			break;
2146
2147		case IPPROTO_UDP:
2148		    {
2149			struct udphdr *udp;
2150
2151			PULLUP_TO(hlen + sizeof(struct udphdr));
2152			udp = L3HDR(struct udphdr, ip);
2153			dst_port = udp->uh_dport;
2154			src_port = udp->uh_sport;
2155			}
2156			break;
2157
2158		case IPPROTO_ICMP:
2159			PULLUP_TO(hlen + 4);	/* type, code and checksum. */
2160			args->fwa_id.flags = L3HDR(struct icmp, ip)->icmp_type;
2161			break;
2162
2163		default:
2164			break;
2165		}
2166#undef PULLUP_TO
2167	}
2168
2169	args->fwa_id.src_ip = ntohl(src_ip.s_addr);
2170	args->fwa_id.dst_ip = ntohl(dst_ip.s_addr);
2171	args->fwa_id.src_port = src_port = ntohs(src_port);
2172	args->fwa_id.dst_port = dst_port = ntohs(dst_port);
2173
2174after_ip_checks:
2175	if (args->fwa_ipfw_rule) {
2176		/*
2177		 * Packet has already been tagged. Look for the next rule
2178		 * to restart processing.
2179		 *
2180		 * If fw_one_pass != 0 then just accept it.
2181		 * XXX should not happen here, but optimized out in
2182		 * the caller.
2183		 */
2184		if (fw_one_pass) {
2185			lck_mtx_unlock(ipfw_mutex);
2186			return 0;
2187		}
2188
2189		f = args->fwa_ipfw_rule->next_rule;
2190		if (f == NULL)
2191			f = lookup_next_rule(args->fwa_ipfw_rule);
2192	} else {
2193		/*
2194		 * Find the starting rule. It can be either the first
2195		 * one, or the one after divert_rule if asked so.
2196		 */
2197		int skipto = args->fwa_divert_rule;
2198
2199		f = layer3_chain;
2200		if (args->fwa_eh == NULL && skipto != 0) {
2201			if (skipto >= IPFW_DEFAULT_RULE) {
2202				lck_mtx_unlock(ipfw_mutex);
2203				return(IP_FW_PORT_DENY_FLAG); /* invalid */
2204			}
2205			while (f && f->rulenum <= skipto)
2206				f = f->next;
2207			if (f == NULL) {	/* drop packet */
2208				lck_mtx_unlock(ipfw_mutex);
2209				return(IP_FW_PORT_DENY_FLAG);
2210			}
2211		}
2212	}
2213	args->fwa_divert_rule = 0;	/* reset to avoid confusion later */
2214
2215	/*
2216	 * Now scan the rules, and parse microinstructions for each rule.
2217	 */
2218	for (; f; f = f->next) {
2219		int l, cmdlen;
2220		ipfw_insn *cmd;
2221		int skip_or; /* skip rest of OR block */
2222
2223again:
2224		if (f->reserved_1 == IPFW_RULE_INACTIVE) {
2225			continue;
2226		}
2227
2228		if (set_disable & (1 << f->set) )
2229			continue;
2230
2231		skip_or = 0;
2232		for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
2233		    l -= cmdlen, cmd += cmdlen) {
2234			int match;
2235
2236			/*
2237			 * check_body is a jump target used when we find a
2238			 * CHECK_STATE, and need to jump to the body of
2239			 * the target rule.
2240			 */
2241
2242check_body:
2243			cmdlen = F_LEN(cmd);
2244			/*
2245			 * An OR block (insn_1 || .. || insn_n) has the
2246			 * F_OR bit set in all but the last instruction.
2247			 * The first match will set "skip_or", and cause
2248			 * the following instructions to be skipped until
2249			 * past the one with the F_OR bit clear.
2250			 */
2251			if (skip_or) {		/* skip this instruction */
2252				if ((cmd->len & F_OR) == 0)
2253					skip_or = 0;	/* next one is good */
2254				continue;
2255			}
2256			match = 0; /* set to 1 if we succeed */
2257
2258			switch (cmd->opcode) {
2259			/*
2260			 * The first set of opcodes compares the packet's
2261			 * fields with some pattern, setting 'match' if a
2262			 * match is found. At the end of the loop there is
2263			 * logic to deal with F_NOT and F_OR flags associated
2264			 * with the opcode.
2265			 */
2266			case O_NOP:
2267				match = 1;
2268				break;
2269
2270			case O_FORWARD_MAC:
2271				printf("ipfw: opcode %d unimplemented\n",
2272				    cmd->opcode);
2273				break;
2274
2275#ifndef __APPLE__
2276			case O_GID:
2277#endif
2278			case O_UID:
2279				/*
2280				 * We only check offset == 0 && proto != 0,
2281				 * as this ensures that we have an IPv4
2282				 * packet with the ports info.
2283				 */
2284				if (offset!=0)
2285					break;
2286
2287			    {
2288				struct inpcbinfo *pi;
2289				int wildcard;
2290				struct inpcb *pcb;
2291
2292				if (proto == IPPROTO_TCP) {
2293					wildcard = 0;
2294					pi = &tcbinfo;
2295				} else if (proto == IPPROTO_UDP) {
2296					wildcard = 1;
2297					pi = &udbinfo;
2298				} else
2299					break;
2300
2301				pcb =  (oif) ?
2302					in_pcblookup_hash(pi,
2303					    dst_ip, htons(dst_port),
2304					    src_ip, htons(src_port),
2305					    wildcard, oif) :
2306					in_pcblookup_hash(pi,
2307					    src_ip, htons(src_port),
2308					    dst_ip, htons(dst_port),
2309					    wildcard, NULL);
2310
2311				if (pcb == NULL || pcb->inp_socket == NULL)
2312					break;
2313#if __FreeBSD_version < 500034
2314#define socheckuid(a,b)	(kauth_cred_getuid((a)->so_cred) != (b))
2315#endif
2316				if (cmd->opcode == O_UID) {
2317					match =
2318#ifdef __APPLE__
2319						(kauth_cred_getuid(pcb->inp_socket->so_cred) == (uid_t)((ipfw_insn_u32 *)cmd)->d[0]);
2320#else
2321						!socheckuid(pcb->inp_socket,
2322						   (uid_t)((ipfw_insn_u32 *)cmd)->d[0]);
2323#endif
2324				}
2325#ifndef __APPLE__
2326				else  {
2327					match = 0;
2328					kauth_cred_ismember_gid(pcb->inp_socket->so_cred,
2329						(gid_t)((ipfw_insn_u32 *)cmd)->d[0], &match);
2330				}
2331#endif
2332				/* release reference on pcb */
2333				in_pcb_checkstate(pcb, WNT_RELEASE, 0);
2334				}
2335
2336			break;
2337
2338			case O_RECV:
2339				match = iface_match(m->m_pkthdr.rcvif,
2340				    (ipfw_insn_if *)cmd);
2341				break;
2342
2343			case O_XMIT:
2344				match = iface_match(oif, (ipfw_insn_if *)cmd);
2345				break;
2346
2347			case O_VIA:
2348				match = iface_match(oif ? oif :
2349				    m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
2350				break;
2351
2352			case O_MACADDR2:
2353				if (args->fwa_eh != NULL) {	/* have MAC header */
2354					u_int32_t *want = (u_int32_t *)
2355						((ipfw_insn_mac *)cmd)->addr;
2356					u_int32_t *mask = (u_int32_t *)
2357						((ipfw_insn_mac *)cmd)->mask;
2358					u_int32_t *hdr = (u_int32_t *)args->fwa_eh;
2359
2360					match =
2361					    ( want[0] == (hdr[0] & mask[0]) &&
2362					      want[1] == (hdr[1] & mask[1]) &&
2363					      want[2] == (hdr[2] & mask[2]) );
2364				}
2365				break;
2366
2367			case O_MAC_TYPE:
2368				if (args->fwa_eh != NULL) {
2369					u_int16_t t =
2370					    ntohs(args->fwa_eh->ether_type);
2371					u_int16_t *p =
2372					    ((ipfw_insn_u16 *)cmd)->ports;
2373					int i;
2374
2375					for (i = cmdlen - 1; !match && i>0;
2376					    i--, p += 2)
2377						match = (t>=p[0] && t<=p[1]);
2378				}
2379				break;
2380
2381			case O_FRAG:
2382				match = (hlen > 0 && offset != 0);
2383				break;
2384
2385			case O_IN:	/* "out" is "not in" */
2386				match = (oif == NULL);
2387				break;
2388
2389			case O_LAYER2:
2390				match = (args->fwa_eh != NULL);
2391				break;
2392
2393			case O_PROTO:
2394				/*
2395				 * We do not allow an arg of 0 so the
2396				 * check of "proto" only suffices.
2397				 */
2398				match = (proto == cmd->arg1);
2399				break;
2400
2401			case O_IP_SRC:
2402				match = (hlen > 0 &&
2403				    ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2404				    src_ip.s_addr);
2405				break;
2406
2407			case O_IP_SRC_MASK:
2408			case O_IP_DST_MASK:
2409				if (hlen > 0) {
2410				    uint32_t a =
2411					(cmd->opcode == O_IP_DST_MASK) ?
2412					    dst_ip.s_addr : src_ip.s_addr;
2413				    uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
2414				    int i = cmdlen-1;
2415
2416				    for (; !match && i>0; i-= 2, p+= 2)
2417					match = (p[0] == (a & p[1]));
2418				}
2419				break;
2420
2421			case O_IP_SRC_ME:
2422				if (hlen > 0) {
2423					struct ifnet *tif;
2424
2425					INADDR_TO_IFP(src_ip, tif);
2426					match = (tif != NULL);
2427				}
2428				break;
2429
2430			case O_IP_DST_SET:
2431			case O_IP_SRC_SET:
2432				if (hlen > 0) {
2433					u_int32_t *d = (u_int32_t *)(cmd+1);
2434					u_int32_t addr =
2435					    cmd->opcode == O_IP_DST_SET ?
2436						args->fwa_id.dst_ip :
2437						args->fwa_id.src_ip;
2438
2439					    if (addr < d[0])
2440						    break;
2441					    addr -= d[0]; /* subtract base */
2442					    match = (addr < cmd->arg1) &&
2443						( d[ 1 + (addr>>5)] &
2444						  (1<<(addr & 0x1f)) );
2445				}
2446				break;
2447
2448			case O_IP_DST:
2449				match = (hlen > 0 &&
2450				    ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2451				    dst_ip.s_addr);
2452				break;
2453
2454			case O_IP_DST_ME:
2455				if (hlen > 0) {
2456					struct ifnet *tif;
2457
2458					INADDR_TO_IFP(dst_ip, tif);
2459					match = (tif != NULL);
2460				}
2461				break;
2462
2463			case O_IP_SRCPORT:
2464			case O_IP_DSTPORT:
2465				/*
2466				 * offset == 0 && proto != 0 is enough
2467				 * to guarantee that we have an IPv4
2468				 * packet with port info.
2469				 */
2470				if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2471				    && offset == 0) {
2472					u_int16_t x =
2473					    (cmd->opcode == O_IP_SRCPORT) ?
2474						src_port : dst_port ;
2475					u_int16_t *p =
2476					    ((ipfw_insn_u16 *)cmd)->ports;
2477					int i;
2478
2479					for (i = cmdlen - 1; !match && i>0;
2480					    i--, p += 2)
2481						match = (x>=p[0] && x<=p[1]);
2482				}
2483				break;
2484
2485			case O_ICMPTYPE:
2486				match = (offset == 0 && proto==IPPROTO_ICMP &&
2487				    icmptype_match(ip, (ipfw_insn_u32 *)cmd) );
2488				break;
2489
2490			case O_IPOPT:
2491				match = (hlen > 0 && ipopts_match(ip, cmd) );
2492				break;
2493
2494			case O_IPVER:
2495				match = (hlen > 0 && cmd->arg1 == ip->ip_v);
2496				break;
2497
2498			case O_IPID:
2499			case O_IPLEN:
2500			case O_IPTTL:
2501				if (hlen > 0) {	/* only for IP packets */
2502				    uint16_t x;
2503				    uint16_t *p;
2504				    int i;
2505
2506				    if (cmd->opcode == O_IPLEN)
2507					x = ip_len;
2508				    else if (cmd->opcode == O_IPTTL)
2509					x = ip->ip_ttl;
2510				    else /* must be IPID */
2511					x = ntohs(ip->ip_id);
2512				    if (cmdlen == 1) {
2513					match = (cmd->arg1 == x);
2514					break;
2515				    }
2516				    /* otherwise we have ranges */
2517				    p = ((ipfw_insn_u16 *)cmd)->ports;
2518				    i = cmdlen - 1;
2519				    for (; !match && i>0; i--, p += 2)
2520					match = (x >= p[0] && x <= p[1]);
2521				}
2522				break;
2523
2524			case O_IPPRECEDENCE:
2525				match = (hlen > 0 &&
2526				    (cmd->arg1 == (ip->ip_tos & 0xe0)) );
2527				break;
2528
2529			case O_IPTOS:
2530				match = (hlen > 0 &&
2531				    flags_match(cmd, ip->ip_tos));
2532				break;
2533
2534			case O_TCPFLAGS:
2535				match = (proto == IPPROTO_TCP && offset == 0 &&
2536				    flags_match(cmd,
2537					L3HDR(struct tcphdr,ip)->th_flags));
2538				break;
2539
2540			case O_TCPOPTS:
2541				match = (proto == IPPROTO_TCP && offset == 0 &&
2542				    tcpopts_match(ip, cmd));
2543				break;
2544
2545			case O_TCPSEQ:
2546				match = (proto == IPPROTO_TCP && offset == 0 &&
2547				    ((ipfw_insn_u32 *)cmd)->d[0] ==
2548					L3HDR(struct tcphdr,ip)->th_seq);
2549				break;
2550
2551			case O_TCPACK:
2552				match = (proto == IPPROTO_TCP && offset == 0 &&
2553				    ((ipfw_insn_u32 *)cmd)->d[0] ==
2554					L3HDR(struct tcphdr,ip)->th_ack);
2555				break;
2556
2557			case O_TCPWIN:
2558				match = (proto == IPPROTO_TCP && offset == 0 &&
2559				    cmd->arg1 ==
2560					L3HDR(struct tcphdr,ip)->th_win);
2561				break;
2562
2563			case O_ESTAB:
2564				/* reject packets which have SYN only */
2565				/* XXX should i also check for TH_ACK ? */
2566				match = (proto == IPPROTO_TCP && offset == 0 &&
2567				    (L3HDR(struct tcphdr,ip)->th_flags &
2568				     (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2569				break;
2570
2571			case O_LOG:
2572				if (fw_verbose)
2573					ipfw_log(f, hlen, args->fwa_eh, m, oif);
2574				match = 1;
2575				break;
2576
2577			case O_PROB:
2578				match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
2579				break;
2580
2581			case O_VERREVPATH:
2582				/* Outgoing packets automatically pass/match */
2583				match = ((oif != NULL) ||
2584				    (m->m_pkthdr.rcvif == NULL) ||
2585				    verify_rev_path(src_ip, m->m_pkthdr.rcvif));
2586				break;
2587
2588			case O_IPSEC:
2589#ifdef FAST_IPSEC
2590				match = (m_tag_find(m,
2591				    PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
2592#endif
2593#ifdef IPSEC
2594				match = (ipsec_gethist(m, NULL) != NULL);
2595#endif
2596				/* otherwise no match */
2597				break;
2598
2599			/*
2600			 * The second set of opcodes represents 'actions',
2601			 * i.e. the terminal part of a rule once the packet
2602			 * matches all previous patterns.
2603			 * Typically there is only one action for each rule,
2604			 * and the opcode is stored at the end of the rule
2605			 * (but there are exceptions -- see below).
2606			 *
2607			 * In general, here we set retval and terminate the
2608			 * outer loop (would be a 'break 3' in some language,
2609			 * but we need to do a 'goto done').
2610			 *
2611			 * Exceptions:
2612			 * O_COUNT and O_SKIPTO actions:
2613			 *   instead of terminating, we jump to the next rule
2614			 *   ('goto next_rule', equivalent to a 'break 2'),
2615			 *   or to the SKIPTO target ('goto again' after
2616			 *   having set f, cmd and l), respectively.
2617			 *
2618			 * O_LIMIT and O_KEEP_STATE: these opcodes are
2619			 *   not real 'actions', and are stored right
2620			 *   before the 'action' part of the rule.
2621			 *   These opcodes try to install an entry in the
2622			 *   state tables; if successful, we continue with
2623			 *   the next opcode (match=1; break;), otherwise
2624			 *   the packet *   must be dropped
2625			 *   ('goto done' after setting retval);
2626			 *
2627			 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2628			 *   cause a lookup of the state table, and a jump
2629			 *   to the 'action' part of the parent rule
2630			 *   ('goto check_body') if an entry is found, or
2631			 *   (CHECK_STATE only) a jump to the next rule if
2632			 *   the entry is not found ('goto next_rule').
2633			 *   The result of the lookup is cached to make
2634			 *   further instances of these opcodes are
2635			 *   effectively NOPs.
2636			 */
2637			case O_LIMIT:
2638			case O_KEEP_STATE:
2639				if (install_state(f,
2640				    (ipfw_insn_limit *)cmd, args)) {
2641					retval = IP_FW_PORT_DENY_FLAG;
2642					goto done; /* error/limit violation */
2643				}
2644				match = 1;
2645				break;
2646
2647			case O_PROBE_STATE:
2648			case O_CHECK_STATE:
2649				/*
2650				 * dynamic rules are checked at the first
2651				 * keep-state or check-state occurrence,
2652				 * with the result being stored in dyn_dir.
2653				 * The compiler introduces a PROBE_STATE
2654				 * instruction for us when we have a
2655				 * KEEP_STATE (because PROBE_STATE needs
2656				 * to be run first).
2657				 */
2658				if (dyn_dir == MATCH_UNKNOWN &&
2659				    (q = lookup_dyn_rule(&args->fwa_id,
2660				     &dyn_dir, proto == IPPROTO_TCP ?
2661					L3HDR(struct tcphdr, ip) : NULL))
2662					!= NULL) {
2663					/*
2664					 * Found dynamic entry, update stats
2665					 * and jump to the 'action' part of
2666					 * the parent rule.
2667					 */
2668					q->pcnt++;
2669					q->bcnt += pktlen;
2670					f = q->rule;
2671					cmd = ACTION_PTR(f);
2672					l = f->cmd_len - f->act_ofs;
2673					goto check_body;
2674				}
2675				/*
2676				 * Dynamic entry not found. If CHECK_STATE,
2677				 * skip to next rule, if PROBE_STATE just
2678				 * ignore and continue with next opcode.
2679				 */
2680				if (cmd->opcode == O_CHECK_STATE)
2681					goto next_rule;
2682				match = 1;
2683				break;
2684
2685			case O_ACCEPT:
2686				retval = 0;	/* accept */
2687				goto done;
2688
2689			case O_PIPE:
2690			case O_QUEUE:
2691				args->fwa_ipfw_rule = f; /* report matching rule */
2692				retval = cmd->arg1 | IP_FW_PORT_DYNT_FLAG;
2693				goto done;
2694
2695			case O_DIVERT:
2696			case O_TEE:
2697				if (args->fwa_eh) /* not on layer 2 */
2698					break;
2699				args->fwa_divert_rule = f->rulenum;
2700				retval = (cmd->opcode == O_DIVERT) ?
2701				    cmd->arg1 :
2702				    cmd->arg1 | IP_FW_PORT_TEE_FLAG;
2703				goto done;
2704
2705			case O_COUNT:
2706			case O_SKIPTO:
2707				f->pcnt++;	/* update stats */
2708				f->bcnt += pktlen;
2709				f->timestamp = timenow.tv_sec;
2710				if (cmd->opcode == O_COUNT)
2711					goto next_rule;
2712				/* handle skipto */
2713				if (f->next_rule == NULL)
2714					lookup_next_rule(f);
2715				f = f->next_rule;
2716				goto again;
2717
2718			case O_REJECT:
2719				/*
2720				 * Drop the packet and send a reject notice
2721				 * if the packet is not ICMP (or is an ICMP
2722				 * query), and it is not multicast/broadcast.
2723				 */
2724				if (hlen > 0 && offset == 0 &&
2725				    (proto != IPPROTO_ICMP ||
2726				     is_icmp_query(ip)) &&
2727				    !(m->m_flags & (M_BCAST|M_MCAST)) &&
2728				    !IN_MULTICAST(dst_ip.s_addr)) {
2729					send_reject(args, cmd->arg1,
2730					    offset,ip_len);
2731					m = args->fwa_m;
2732				}
2733				/* FALLTHROUGH */
2734			case O_DENY:
2735				retval = IP_FW_PORT_DENY_FLAG;
2736				goto done;
2737
2738			case O_FORWARD_IP:
2739				if (args->fwa_eh)	/* not valid on layer2 pkts */
2740					break;
2741				if (!q || dyn_dir == MATCH_FORWARD)
2742					args->fwa_next_hop =
2743					    &((ipfw_insn_sa *)cmd)->sa;
2744				retval = 0;
2745				goto done;
2746
2747			default:
2748				panic("-- unknown opcode %d\n", cmd->opcode);
2749			} /* end of switch() on opcodes */
2750
2751			if (cmd->len & F_NOT)
2752				match = !match;
2753
2754			if (match) {
2755				if (cmd->len & F_OR)
2756					skip_or = 1;
2757			} else {
2758				if (!(cmd->len & F_OR)) /* not an OR block, */
2759					break;		/* try next rule    */
2760			}
2761
2762		}	/* end of inner for, scan opcodes */
2763
2764next_rule:;		/* try next rule		*/
2765
2766	}		/* end of outer for, scan rules */
2767	printf("ipfw: ouch!, skip past end of rules, denying packet\n");
2768	lck_mtx_unlock(ipfw_mutex);
2769	return(IP_FW_PORT_DENY_FLAG);
2770
2771done:
2772	/* Update statistics */
2773	f->pcnt++;
2774	f->bcnt += pktlen;
2775	f->timestamp = timenow.tv_sec;
2776	lck_mtx_unlock(ipfw_mutex);
2777	return retval;
2778
2779pullup_failed:
2780	if (fw_verbose)
2781		printf("ipfw: pullup failed\n");
2782	lck_mtx_unlock(ipfw_mutex);
2783	return(IP_FW_PORT_DENY_FLAG);
2784}
2785
2786/*
2787 * When a rule is added/deleted, clear the next_rule pointers in all rules.
2788 * These will be reconstructed on the fly as packets are matched.
2789 * Must be called at splimp().
2790 */
2791static void
2792flush_rule_ptrs(void)
2793{
2794	struct ip_fw *rule;
2795
2796	for (rule = layer3_chain; rule; rule = rule->next)
2797		rule->next_rule = NULL;
2798}
2799
2800/*
2801 * When pipes/queues are deleted, clear the "pipe_ptr" pointer to a given
2802 * pipe/queue, or to all of them (match == NULL).
2803 * Must be called at splimp().
2804 */
2805void
2806flush_pipe_ptrs(struct dn_flow_set *match)
2807{
2808	struct ip_fw *rule;
2809
2810	for (rule = layer3_chain; rule; rule = rule->next) {
2811		ipfw_insn_pipe *cmd = (ipfw_insn_pipe *)ACTION_PTR(rule);
2812
2813		if (cmd->o.opcode != O_PIPE && cmd->o.opcode != O_QUEUE)
2814			continue;
2815		/*
2816		 * XXX Use bcmp/bzero to handle pipe_ptr to overcome
2817		 * possible alignment problems on 64-bit architectures.
2818		 * This code is seldom used so we do not worry too
2819		 * much about efficiency.
2820		 */
2821		if (match == NULL ||
2822		    !bcmp(&cmd->pipe_ptr, &match, sizeof(match)) )
2823			bzero(&cmd->pipe_ptr, sizeof(cmd->pipe_ptr));
2824	}
2825}
2826
2827/*
2828 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
2829 * possibly create a rule number and add the rule to the list.
2830 * Update the rule_number in the input struct so the caller knows it as well.
2831 */
2832static int
2833add_rule(struct ip_fw **head, struct ip_fw *input_rule)
2834{
2835	struct ip_fw *rule, *f, *prev;
2836	int l = RULESIZE(input_rule);
2837
2838	if (*head == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
2839		return (EINVAL);
2840
2841	rule = _MALLOC(l, M_IPFW, M_WAIT);
2842	if (rule == NULL) {
2843		printf("ipfw2: add_rule MALLOC failed\n");
2844		return (ENOSPC);
2845	}
2846
2847	bzero(rule, l);
2848	bcopy(input_rule, rule, l);
2849
2850	rule->next = NULL;
2851	rule->next_rule = NULL;
2852
2853	rule->pcnt = 0;
2854	rule->bcnt = 0;
2855	rule->timestamp = 0;
2856
2857	if (*head == NULL) {	/* default rule */
2858		*head = rule;
2859		goto done;
2860        }
2861
2862	/*
2863	 * If rulenum is 0, find highest numbered rule before the
2864	 * default rule, and add autoinc_step
2865	 */
2866	if (autoinc_step < 1)
2867		autoinc_step = 1;
2868	else if (autoinc_step > 1000)
2869		autoinc_step = 1000;
2870	if (rule->rulenum == 0) {
2871		/*
2872		 * locate the highest numbered rule before default
2873		 */
2874		for (f = *head; f; f = f->next) {
2875			if (f->rulenum == IPFW_DEFAULT_RULE)
2876				break;
2877			rule->rulenum = f->rulenum;
2878		}
2879		if (rule->rulenum < IPFW_DEFAULT_RULE - autoinc_step)
2880			rule->rulenum += autoinc_step;
2881		input_rule->rulenum = rule->rulenum;
2882	}
2883
2884	/*
2885	 * Now insert the new rule in the right place in the sorted list.
2886	 */
2887	for (prev = NULL, f = *head; f; prev = f, f = f->next) {
2888		if (f->rulenum > rule->rulenum) { /* found the location */
2889			if (prev) {
2890				rule->next = f;
2891				prev->next = rule;
2892			} else { /* head insert */
2893				rule->next = *head;
2894				*head = rule;
2895			}
2896			break;
2897		}
2898	}
2899	flush_rule_ptrs();
2900done:
2901	static_count++;
2902	static_len += l;
2903	static_len_32 += RULESIZE32(input_rule);
2904	static_len_64 += RULESIZE64(input_rule);
2905	DEB(printf("ipfw: installed rule %d, static count now %d\n",
2906		rule->rulenum, static_count);)
2907	return (0);
2908}
2909
2910/**
2911 * Free storage associated with a static rule (including derived
2912 * dynamic rules).
2913 * The caller is in charge of clearing rule pointers to avoid
2914 * dangling pointers.
2915 * @return a pointer to the next entry.
2916 * Arguments are not checked, so they better be correct.
2917 * Must be called at splimp().
2918 */
2919static struct ip_fw *
2920delete_rule(struct ip_fw **head, struct ip_fw *prev, struct ip_fw *rule)
2921{
2922	struct ip_fw *n;
2923	int l = RULESIZE(rule);
2924
2925	n = rule->next;
2926	remove_dyn_rule(rule, NULL /* force removal */);
2927	if (prev == NULL)
2928		*head = n;
2929	else
2930		prev->next = n;
2931	static_count--;
2932	static_len -= l;
2933	static_len_32 -= RULESIZE32(rule);
2934	static_len_64 -= RULESIZE64(rule);
2935
2936#if DUMMYNET
2937	if (DUMMYNET_LOADED)
2938		dn_ipfw_rule_delete(rule);
2939#endif /* DUMMYNET */
2940	_FREE(rule, M_IPFW);
2941	return n;
2942}
2943
2944#if DEBUG_INACTIVE_RULES
2945static void
2946print_chain(struct ip_fw **chain)
2947{
2948	struct ip_fw *rule = *chain;
2949
2950	for (; rule; rule = rule->next) {
2951		ipfw_insn	*cmd = ACTION_PTR(rule);
2952
2953		printf("ipfw: rule->rulenum = %d\n", rule->rulenum);
2954
2955		if (rule->reserved_1 == IPFW_RULE_INACTIVE) {
2956			printf("ipfw: rule->reserved = IPFW_RULE_INACTIVE\n");
2957		}
2958
2959		switch (cmd->opcode) {
2960			case O_DENY:
2961				printf("ipfw: ACTION: Deny\n");
2962				break;
2963
2964			case O_REJECT:
2965				if (cmd->arg1==ICMP_REJECT_RST)
2966					printf("ipfw: ACTION: Reset\n");
2967				else if (cmd->arg1==ICMP_UNREACH_HOST)
2968					printf("ipfw: ACTION: Reject\n");
2969				break;
2970
2971			case O_ACCEPT:
2972				printf("ipfw: ACTION: Accept\n");
2973				break;
2974			case O_COUNT:
2975				printf("ipfw: ACTION: Count\n");
2976				break;
2977			case O_DIVERT:
2978				printf("ipfw: ACTION: Divert\n");
2979				break;
2980			case O_TEE:
2981				printf("ipfw: ACTION: Tee\n");
2982				break;
2983			case O_SKIPTO:
2984				printf("ipfw: ACTION: SkipTo\n");
2985				break;
2986			case O_PIPE:
2987				printf("ipfw: ACTION: Pipe\n");
2988				break;
2989			case O_QUEUE:
2990				printf("ipfw: ACTION: Queue\n");
2991				break;
2992			case O_FORWARD_IP:
2993				printf("ipfw: ACTION: Forward\n");
2994				break;
2995			default:
2996				printf("ipfw: invalid action! %d\n", cmd->opcode);
2997		}
2998	}
2999}
3000#endif /* DEBUG_INACTIVE_RULES */
3001
3002static void
3003flush_inactive(void *param)
3004{
3005	struct ip_fw *inactive_rule = (struct ip_fw *)param;
3006	struct ip_fw *rule, *prev;
3007
3008	lck_mtx_lock(ipfw_mutex);
3009
3010	for (rule = layer3_chain, prev = NULL; rule; ) {
3011		if (rule == inactive_rule && rule->reserved_1 == IPFW_RULE_INACTIVE) {
3012			struct ip_fw *n = rule;
3013
3014			if (prev == NULL) {
3015				layer3_chain = rule->next;
3016			}
3017			else {
3018				prev->next = rule->next;
3019			}
3020			rule = rule->next;
3021			_FREE(n, M_IPFW);
3022		}
3023		else {
3024			prev = rule;
3025			rule = rule->next;
3026		}
3027	}
3028
3029#if DEBUG_INACTIVE_RULES
3030	print_chain(&layer3_chain);
3031#endif
3032	lck_mtx_unlock(ipfw_mutex);
3033}
3034
3035static void
3036mark_inactive(struct ip_fw **prev, struct ip_fw **rule)
3037{
3038	int 			l = RULESIZE(*rule);
3039
3040	if ((*rule)->reserved_1 != IPFW_RULE_INACTIVE) {
3041		(*rule)->reserved_1 = IPFW_RULE_INACTIVE;
3042		static_count--;
3043		static_len -= l;
3044		static_len_32 -= RULESIZE32(*rule);
3045		static_len_64 -= RULESIZE64(*rule);
3046
3047		timeout(flush_inactive, *rule, 30*hz); /* 30 sec. */
3048	}
3049
3050	*prev = *rule;
3051	*rule = (*rule)->next;
3052}
3053
3054/*
3055 * Deletes all rules from a chain (except rules in set RESVD_SET
3056 * unless kill_default = 1).
3057 * Must be called at splimp().
3058 */
3059static void
3060free_chain(struct ip_fw **chain, int kill_default)
3061{
3062	struct ip_fw *prev, *rule;
3063
3064	flush_rule_ptrs(); /* more efficient to do outside the loop */
3065	for (prev = NULL, rule = *chain; rule ; )
3066		if (kill_default || rule->set != RESVD_SET) {
3067			ipfw_insn	*cmd = ACTION_PTR(rule);
3068
3069			/* skip over forwarding rules so struct isn't
3070			 * deleted while pointer is still in use elsewhere
3071			 */
3072			if (cmd->opcode == O_FORWARD_IP) {
3073				mark_inactive(&prev, &rule);
3074			}
3075			else {
3076				rule = delete_rule(chain, prev, rule);
3077			}
3078		}
3079		else {
3080			prev = rule;
3081			rule = rule->next;
3082		}
3083}
3084
3085/**
3086 * Remove all rules with given number, and also do set manipulation.
3087 * Assumes chain != NULL && *chain != NULL.
3088 *
3089 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
3090 * the next 8 bits are the new set, the top 8 bits are the command:
3091 *
3092 *	0	delete rules with given number
3093 *	1	delete rules with given set number
3094 *	2	move rules with given number to new set
3095 *	3	move rules with given set number to new set
3096 *	4	swap sets with given numbers
3097 */
3098static int
3099del_entry(struct ip_fw **chain, u_int32_t arg)
3100{
3101	struct ip_fw *prev = NULL, *rule = *chain;
3102	u_int16_t rulenum;	/* rule or old_set */
3103	u_int8_t cmd, new_set;
3104
3105	rulenum = arg & 0xffff;
3106	cmd = (arg >> 24) & 0xff;
3107	new_set = (arg >> 16) & 0xff;
3108
3109	if (cmd > 4)
3110		return EINVAL;
3111	if (new_set > RESVD_SET)
3112		return EINVAL;
3113	if (cmd == 0 || cmd == 2) {
3114		if (rulenum >= IPFW_DEFAULT_RULE)
3115			return EINVAL;
3116	} else {
3117		if (rulenum > RESVD_SET)	/* old_set */
3118			return EINVAL;
3119	}
3120
3121	switch (cmd) {
3122	case 0:	/* delete rules with given number */
3123		/*
3124		 * locate first rule to delete
3125		 */
3126		for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3127			;
3128		if (rule->rulenum != rulenum)
3129			return EINVAL;
3130
3131		/*
3132		 * flush pointers outside the loop, then delete all matching
3133		 * rules. prev remains the same throughout the cycle.
3134		 */
3135		flush_rule_ptrs();
3136		while (rule->rulenum == rulenum) {
3137			ipfw_insn	*insn = ACTION_PTR(rule);
3138
3139			/* keep forwarding rules around so struct isn't
3140			 * deleted while pointer is still in use elsewhere
3141			 */
3142			if (insn->opcode == O_FORWARD_IP) {
3143				mark_inactive(&prev, &rule);
3144			}
3145			else {
3146				rule = delete_rule(chain, prev, rule);
3147			}
3148		}
3149		break;
3150
3151	case 1:	/* delete all rules with given set number */
3152		flush_rule_ptrs();
3153		while (rule->rulenum < IPFW_DEFAULT_RULE) {
3154			if (rule->set == rulenum) {
3155				ipfw_insn	*insn = ACTION_PTR(rule);
3156
3157				/* keep forwarding rules around so struct isn't
3158				 * deleted while pointer is still in use elsewhere
3159				 */
3160				if (insn->opcode == O_FORWARD_IP) {
3161					mark_inactive(&prev, &rule);
3162				}
3163				else {
3164					rule = delete_rule(chain, prev, rule);
3165				}
3166			}
3167			else {
3168				prev = rule;
3169				rule = rule->next;
3170			}
3171		}
3172		break;
3173
3174	case 2:	/* move rules with given number to new set */
3175		for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3176			if (rule->rulenum == rulenum)
3177				rule->set = new_set;
3178		break;
3179
3180	case 3: /* move rules with given set number to new set */
3181		for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3182			if (rule->set == rulenum)
3183				rule->set = new_set;
3184		break;
3185
3186	case 4: /* swap two sets */
3187		for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3188			if (rule->set == rulenum)
3189				rule->set = new_set;
3190			else if (rule->set == new_set)
3191				rule->set = rulenum;
3192		break;
3193	}
3194	return 0;
3195}
3196
3197/*
3198 * Clear counters for a specific rule.
3199 */
3200static void
3201clear_counters(struct ip_fw *rule, int log_only)
3202{
3203	ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3204
3205	if (log_only == 0) {
3206		rule->bcnt = rule->pcnt = 0;
3207		rule->timestamp = 0;
3208	}
3209	if (l->o.opcode == O_LOG)
3210		l->log_left = l->max_log;
3211}
3212
3213/**
3214 * Reset some or all counters on firewall rules.
3215 * @arg frwl is null to clear all entries, or contains a specific
3216 * rule number.
3217 * @arg log_only is 1 if we only want to reset logs, zero otherwise.
3218 */
3219static int
3220zero_entry(int rulenum, int log_only)
3221{
3222	struct ip_fw *rule;
3223	const char *msg;
3224
3225	if (rulenum == 0) {
3226		norule_counter = 0;
3227		for (rule = layer3_chain; rule; rule = rule->next)
3228			clear_counters(rule, log_only);
3229		msg = log_only ? "ipfw: All logging counts reset.\n" :
3230				"ipfw: Accounting cleared.\n";
3231	} else {
3232		int cleared = 0;
3233		/*
3234		 * We can have multiple rules with the same number, so we
3235		 * need to clear them all.
3236		 */
3237		for (rule = layer3_chain; rule; rule = rule->next)
3238			if (rule->rulenum == rulenum) {
3239				while (rule && rule->rulenum == rulenum) {
3240					clear_counters(rule, log_only);
3241					rule = rule->next;
3242				}
3243				cleared = 1;
3244				break;
3245			}
3246		if (!cleared)	/* we did not find any matching rules */
3247			return (EINVAL);
3248		msg = log_only ? "ipfw: Entry %d logging count reset.\n" :
3249				"ipfw: Entry %d cleared.\n";
3250	}
3251	if (fw_verbose)
3252	{
3253		dolog((LOG_AUTHPRIV | LOG_NOTICE, msg, rulenum));
3254	}
3255	return (0);
3256}
3257
3258/*
3259 * Check validity of the structure before insert.
3260 * Fortunately rules are simple, so this mostly need to check rule sizes.
3261 */
3262static int
3263check_ipfw_struct(struct ip_fw *rule, int size)
3264{
3265	int l, cmdlen = 0;
3266	int have_action=0;
3267	ipfw_insn *cmd;
3268
3269	if (size < sizeof(*rule)) {
3270		printf("ipfw: rule too short\n");
3271		return (EINVAL);
3272	}
3273	/* first, check for valid size */
3274	l = RULESIZE(rule);
3275	if (l != size) {
3276		printf("ipfw: size mismatch (have %d want %d)\n", size, l);
3277		return (EINVAL);
3278	}
3279	/*
3280	 * Now go for the individual checks. Very simple ones, basically only
3281	 * instruction sizes.
3282	 */
3283	for (l = rule->cmd_len, cmd = rule->cmd ;
3284			l > 0 ; l -= cmdlen, cmd += cmdlen) {
3285		cmdlen = F_LEN(cmd);
3286		if (cmdlen > l) {
3287			printf("ipfw: opcode %d size truncated\n",
3288			    cmd->opcode);
3289			return EINVAL;
3290		}
3291		DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
3292		switch (cmd->opcode) {
3293		case O_PROBE_STATE:
3294		case O_KEEP_STATE:
3295		case O_PROTO:
3296		case O_IP_SRC_ME:
3297		case O_IP_DST_ME:
3298		case O_LAYER2:
3299		case O_IN:
3300		case O_FRAG:
3301		case O_IPOPT:
3302		case O_IPTOS:
3303		case O_IPPRECEDENCE:
3304		case O_IPVER:
3305		case O_TCPWIN:
3306		case O_TCPFLAGS:
3307		case O_TCPOPTS:
3308		case O_ESTAB:
3309		case O_VERREVPATH:
3310		case O_IPSEC:
3311			if (cmdlen != F_INSN_SIZE(ipfw_insn))
3312				goto bad_size;
3313			break;
3314		case O_UID:
3315#ifndef __APPLE__
3316		case O_GID:
3317#endif /* __APPLE__ */
3318		case O_IP_SRC:
3319		case O_IP_DST:
3320		case O_TCPSEQ:
3321		case O_TCPACK:
3322		case O_PROB:
3323		case O_ICMPTYPE:
3324			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3325				goto bad_size;
3326			break;
3327
3328		case O_LIMIT:
3329			if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3330				goto bad_size;
3331			break;
3332
3333		case O_LOG:
3334			if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3335				goto bad_size;
3336
3337			/* enforce logging limit */
3338			if (fw_verbose &&
3339				((ipfw_insn_log *)cmd)->max_log == 0 && verbose_limit != 0) {
3340				((ipfw_insn_log *)cmd)->max_log = verbose_limit;
3341			}
3342
3343			((ipfw_insn_log *)cmd)->log_left =
3344			    ((ipfw_insn_log *)cmd)->max_log;
3345
3346			break;
3347
3348		case O_IP_SRC_MASK:
3349		case O_IP_DST_MASK:
3350			/* only odd command lengths */
3351			if ( !(cmdlen & 1) || cmdlen > 31)
3352				goto bad_size;
3353			break;
3354
3355		case O_IP_SRC_SET:
3356		case O_IP_DST_SET:
3357			if (cmd->arg1 == 0 || cmd->arg1 > 256) {
3358				printf("ipfw: invalid set size %d\n",
3359					cmd->arg1);
3360				return EINVAL;
3361			}
3362			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3363			    (cmd->arg1+31)/32 )
3364				goto bad_size;
3365			break;
3366
3367		case O_MACADDR2:
3368			if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
3369				goto bad_size;
3370			break;
3371
3372		case O_NOP:
3373		case O_IPID:
3374		case O_IPTTL:
3375		case O_IPLEN:
3376			if (cmdlen < 1 || cmdlen > 31)
3377				goto bad_size;
3378			break;
3379
3380		case O_MAC_TYPE:
3381		case O_IP_SRCPORT:
3382		case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
3383			if (cmdlen < 2 || cmdlen > 31)
3384				goto bad_size;
3385			break;
3386
3387		case O_RECV:
3388		case O_XMIT:
3389		case O_VIA:
3390			if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
3391				goto bad_size;
3392			break;
3393
3394		case O_PIPE:
3395		case O_QUEUE:
3396			if (cmdlen != F_INSN_SIZE(ipfw_insn_pipe))
3397				goto bad_size;
3398			goto check_action;
3399
3400		case O_FORWARD_IP:
3401			if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
3402				goto bad_size;
3403			goto check_action;
3404
3405		case O_FORWARD_MAC: /* XXX not implemented yet */
3406		case O_CHECK_STATE:
3407		case O_COUNT:
3408		case O_ACCEPT:
3409		case O_DENY:
3410		case O_REJECT:
3411		case O_SKIPTO:
3412		case O_DIVERT:
3413		case O_TEE:
3414			if (cmdlen != F_INSN_SIZE(ipfw_insn))
3415				goto bad_size;
3416check_action:
3417			if (have_action) {
3418				printf("ipfw: opcode %d, multiple actions"
3419					" not allowed\n",
3420					cmd->opcode);
3421				return EINVAL;
3422			}
3423			have_action = 1;
3424			if (l != cmdlen) {
3425				printf("ipfw: opcode %d, action must be"
3426					" last opcode\n",
3427					cmd->opcode);
3428				return EINVAL;
3429			}
3430			break;
3431		default:
3432			printf("ipfw: opcode %d, unknown opcode\n",
3433				cmd->opcode);
3434			return EINVAL;
3435		}
3436	}
3437	if (have_action == 0) {
3438		printf("ipfw: missing action\n");
3439		return EINVAL;
3440	}
3441	return 0;
3442
3443bad_size:
3444	printf("ipfw: opcode %d size %d wrong\n",
3445		cmd->opcode, cmdlen);
3446	return EINVAL;
3447}
3448
3449
3450static void
3451ipfw_kev_post_msg(u_int32_t event_code)
3452{
3453	struct kev_msg		ev_msg;
3454
3455	bzero(&ev_msg, sizeof(struct kev_msg));
3456
3457	ev_msg.vendor_code = KEV_VENDOR_APPLE;
3458	ev_msg.kev_class = KEV_FIREWALL_CLASS;
3459	ev_msg.kev_subclass = KEV_IPFW_SUBCLASS;
3460	ev_msg.event_code = event_code;
3461
3462	kev_post_msg(&ev_msg);
3463
3464}
3465
3466/**
3467 * {set|get}sockopt parser.
3468 */
3469static int
3470ipfw_ctl(struct sockopt *sopt)
3471{
3472#define	RULE_MAXSIZE	(256*sizeof(u_int32_t))
3473	u_int32_t api_version;
3474	int command;
3475	int error;
3476	size_t size;
3477	size_t	rulesize = RULE_MAXSIZE;
3478	struct ip_fw *bp , *buf, *rule;
3479	int	is64user = 0;
3480
3481	/* copy of orig sopt to send to ipfw_get_command_and_version() */
3482	struct sockopt tmp_sopt = *sopt;
3483	struct timeval timenow;
3484
3485	getmicrotime(&timenow);
3486
3487	/*
3488	 * Disallow modifications in really-really secure mode, but still allow
3489	 * the logging counters to be reset.
3490	 */
3491	if (sopt->sopt_name == IP_FW_ADD ||
3492	    (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
3493#if __FreeBSD_version >= 500034
3494		error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3495		if (error)
3496			return (error);
3497#else /* FreeBSD 4.x */
3498		if (securelevel >= 3)
3499			return (EPERM);
3500#endif
3501	}
3502
3503	/* first get the command and version, then do conversion as necessary */
3504	error = ipfw_get_command_and_version(&tmp_sopt, &command, &api_version);
3505	if (error) {
3506		/* error getting the version */
3507		return error;
3508	}
3509
3510	if (proc_is64bit(sopt->sopt_p))
3511		is64user = 1;
3512
3513	switch (command) {
3514	case IP_FW_GET:
3515	{
3516		size_t	dynrulesize;
3517		/*
3518		 * pass up a copy of the current rules. Static rules
3519		 * come first (the last of which has number IPFW_DEFAULT_RULE),
3520		 * followed by a possibly empty list of dynamic rule.
3521		 * The last dynamic rule has NULL in the "next" field.
3522		 */
3523		lck_mtx_lock(ipfw_mutex);
3524
3525		if (is64user){
3526			size = Get64static_len();
3527			dynrulesize = sizeof(ipfw_dyn_rule_64);
3528			if (ipfw_dyn_v)
3529				size += (dyn_count * dynrulesize);
3530		}else {
3531			size = Get32static_len();
3532			dynrulesize = sizeof(ipfw_dyn_rule_32);
3533			if (ipfw_dyn_v)
3534				size += (dyn_count * dynrulesize);
3535		}
3536
3537		/*
3538		 * XXX todo: if the user passes a short length just to know
3539		 * how much room is needed, do not bother filling up the
3540		 * buffer, just jump to the sooptcopyout.
3541		 */
3542		buf = _MALLOC(size, M_TEMP, M_WAITOK);
3543		if (buf == 0) {
3544			lck_mtx_unlock(ipfw_mutex);
3545			error = ENOBUFS;
3546			break;
3547		}
3548
3549		bzero(buf, size);
3550
3551		bp = buf;
3552		for (rule = layer3_chain; rule ; rule = rule->next) {
3553
3554			if (rule->reserved_1 == IPFW_RULE_INACTIVE) {
3555				continue;
3556			}
3557
3558			if (is64user){
3559				int rulesize_64;
3560
3561				copyto64fw( rule, (struct ip_fw_64 *)bp, size);
3562				bcopy(&set_disable, &(( (struct ip_fw_64*)bp)->next_rule), sizeof(set_disable));
3563				/* do not use macro RULESIZE64 since we want RULESIZE for ip_fw_64 */
3564				rulesize_64 = sizeof(struct ip_fw_64) + ((struct ip_fw_64 *)(bp))->cmd_len * 4 - 4;
3565				bp = (struct ip_fw *)((char *)bp + rulesize_64);
3566			}else{
3567				int rulesize_32;
3568
3569				copyto32fw( rule, (struct ip_fw_32*)bp, size);
3570				bcopy(&set_disable, &(( (struct ip_fw_32*)bp)->next_rule), sizeof(set_disable));
3571				/* do not use macro RULESIZE32 since we want RULESIZE for ip_fw_32 */
3572				rulesize_32 = sizeof(struct ip_fw_32) + ((struct ip_fw_32 *)(bp))->cmd_len * 4 - 4;
3573				bp = (struct ip_fw *)((char *)bp + rulesize_32);
3574			}
3575		}
3576		if (ipfw_dyn_v) {
3577			int i;
3578			ipfw_dyn_rule *p;
3579			char *dst, *last = NULL;
3580
3581			dst = (char *)bp;
3582			for (i = 0 ; i < curr_dyn_buckets ; i++ )
3583				for ( p = ipfw_dyn_v[i] ; p != NULL ;
3584				    p = p->next, dst += dynrulesize ) {
3585					if ( is64user ){
3586						ipfw_dyn_rule_64	*ipfw_dyn_dst;
3587
3588						ipfw_dyn_dst = (ipfw_dyn_rule_64 *)dst;
3589						/*
3590						 * store a non-null value in "next".
3591						 * The userland code will interpret a
3592						 * NULL here as a marker
3593						 * for the last dynamic rule.
3594						 */
3595						ipfw_dyn_dst->next = CAST_DOWN_EXPLICIT(user64_addr_t, dst);
3596						ipfw_dyn_dst->rule = p->rule->rulenum;
3597						ipfw_dyn_dst->parent = CAST_DOWN(user64_addr_t, p->parent);
3598						ipfw_dyn_dst->pcnt = p->pcnt;
3599						ipfw_dyn_dst->bcnt = p->bcnt;
3600						externalize_flow_id(&ipfw_dyn_dst->id, &p->id);
3601						ipfw_dyn_dst->expire =
3602							TIME_LEQ(p->expire, timenow.tv_sec) ?
3603							0 : p->expire - timenow.tv_sec;
3604						ipfw_dyn_dst->bucket = p->bucket;
3605						ipfw_dyn_dst->state = p->state;
3606						ipfw_dyn_dst->ack_fwd = p->ack_fwd;
3607						ipfw_dyn_dst->ack_rev = p->ack_rev;
3608						ipfw_dyn_dst->dyn_type = p->dyn_type;
3609						ipfw_dyn_dst->count = p->count;
3610						last = (char*)&ipfw_dyn_dst->next;
3611					} else {
3612						ipfw_dyn_rule_32	*ipfw_dyn_dst;
3613
3614						ipfw_dyn_dst = (ipfw_dyn_rule_32 *)dst;
3615						/*
3616						 * store a non-null value in "next".
3617						 * The userland code will interpret a
3618						 * NULL here as a marker
3619						 * for the last dynamic rule.
3620						 */
3621						ipfw_dyn_dst->next = CAST_DOWN_EXPLICIT(user32_addr_t, dst);
3622						ipfw_dyn_dst->rule = p->rule->rulenum;
3623						ipfw_dyn_dst->parent = CAST_DOWN_EXPLICIT(user32_addr_t, p->parent);
3624						ipfw_dyn_dst->pcnt = p->pcnt;
3625						ipfw_dyn_dst->bcnt = p->bcnt;
3626						externalize_flow_id(&ipfw_dyn_dst->id, &p->id);
3627						ipfw_dyn_dst->expire =
3628							TIME_LEQ(p->expire, timenow.tv_sec) ?
3629							0 : p->expire - timenow.tv_sec;
3630						ipfw_dyn_dst->bucket = p->bucket;
3631						ipfw_dyn_dst->state = p->state;
3632						ipfw_dyn_dst->ack_fwd = p->ack_fwd;
3633						ipfw_dyn_dst->ack_rev = p->ack_rev;
3634						ipfw_dyn_dst->dyn_type = p->dyn_type;
3635						ipfw_dyn_dst->count = p->count;
3636						last = (char*)&ipfw_dyn_dst->next;
3637					}
3638				}
3639			if (last != NULL) /* mark last dynamic rule */
3640				bzero(last, sizeof(last));
3641		}
3642		lck_mtx_unlock(ipfw_mutex);
3643
3644		/* convert back if necessary and copyout */
3645		if (api_version == IP_FW_VERSION_0) {
3646			int	i, len = 0;
3647			struct ip_old_fw	*buf2, *rule_vers0;
3648
3649			lck_mtx_lock(ipfw_mutex);
3650			buf2 = _MALLOC(static_count * sizeof(struct ip_old_fw), M_TEMP, M_WAITOK);
3651			if (buf2 == 0) {
3652				lck_mtx_unlock(ipfw_mutex);
3653				error = ENOBUFS;
3654			}
3655
3656			if (!error) {
3657				bp = buf;
3658				rule_vers0 = buf2;
3659
3660				for (i = 0; i < static_count; i++) {
3661					/* static rules have different sizes */
3662					int j = RULESIZE(bp);
3663					ipfw_convert_from_latest(bp, rule_vers0, api_version, is64user);
3664					bp = (struct ip_fw *)((char *)bp + j);
3665					len += sizeof(*rule_vers0);
3666					rule_vers0++;
3667				}
3668				lck_mtx_unlock(ipfw_mutex);
3669				error = sooptcopyout(sopt, buf2, len);
3670				_FREE(buf2, M_TEMP);
3671			}
3672		} else if (api_version == IP_FW_VERSION_1) {
3673			int	i, len = 0, buf_size;
3674			struct ip_fw_compat	*buf2;
3675			size_t	ipfwcompsize;
3676			size_t	ipfwdyncompsize;
3677			char	*rule_vers1;
3678
3679			lck_mtx_lock(ipfw_mutex);
3680			if ( is64user ){
3681				ipfwcompsize = sizeof(struct ip_fw_compat_64);
3682				ipfwdyncompsize = sizeof(struct ipfw_dyn_rule_compat_64);
3683			} else {
3684				ipfwcompsize = sizeof(struct ip_fw_compat_32);
3685				ipfwdyncompsize = sizeof(struct ipfw_dyn_rule_compat_32);
3686			}
3687
3688			buf_size = static_count * ipfwcompsize +
3689						dyn_count * ipfwdyncompsize;
3690
3691			buf2 = _MALLOC(buf_size, M_TEMP, M_WAITOK);
3692			if (buf2 == 0) {
3693				lck_mtx_unlock(ipfw_mutex);
3694				error = ENOBUFS;
3695			}
3696			if (!error) {
3697				bp = buf;
3698				rule_vers1 = (char*)buf2;
3699
3700				/* first do static rules */
3701				for (i = 0; i < static_count; i++) {
3702					/* static rules have different sizes */
3703					if ( is64user ){
3704						int rulesize_64;
3705						ipfw_convert_from_latest(bp, (void *)rule_vers1, api_version, is64user);
3706						rulesize_64 = sizeof(struct ip_fw_64) + ((struct ip_fw_64 *)(bp))->cmd_len * 4 - 4;
3707						bp = (struct ip_fw *)((char *)bp + rulesize_64);
3708					}else {
3709						int rulesize_32;
3710						ipfw_convert_from_latest(bp, (void *)rule_vers1, api_version, is64user);
3711						rulesize_32 = sizeof(struct ip_fw_32) + ((struct ip_fw_32 *)(bp))->cmd_len * 4 - 4;
3712						bp = (struct ip_fw *)((char *)bp + rulesize_32);
3713					}
3714					len += ipfwcompsize;
3715					rule_vers1 += ipfwcompsize;
3716				}
3717				/* now do dynamic rules */
3718				if ( is64user )
3719					cp_dyn_to_comp_64( (struct ipfw_dyn_rule_compat_64 *)rule_vers1, &len);
3720				else
3721					cp_dyn_to_comp_32( (struct ipfw_dyn_rule_compat_32 *)rule_vers1, &len);
3722
3723				lck_mtx_unlock(ipfw_mutex);
3724				error = sooptcopyout(sopt, buf2, len);
3725				_FREE(buf2, M_TEMP);
3726			}
3727		} else {
3728			error = sooptcopyout(sopt, buf, size);
3729		}
3730
3731		_FREE(buf, M_TEMP);
3732		break;
3733	}
3734
3735	case IP_FW_FLUSH:
3736		/*
3737		 * Normally we cannot release the lock on each iteration.
3738		 * We could do it here only because we start from the head all
3739		 * the times so there is no risk of missing some entries.
3740		 * On the other hand, the risk is that we end up with
3741		 * a very inconsistent ruleset, so better keep the lock
3742		 * around the whole cycle.
3743		 *
3744		 * XXX this code can be improved by resetting the head of
3745		 * the list to point to the default rule, and then freeing
3746		 * the old list without the need for a lock.
3747		 */
3748
3749		lck_mtx_lock(ipfw_mutex);
3750		free_chain(&layer3_chain, 0 /* keep default rule */);
3751		fw_bypass = 1;
3752#if DEBUG_INACTIVE_RULES
3753			print_chain(&layer3_chain);
3754#endif
3755		lck_mtx_unlock(ipfw_mutex);
3756		break;
3757
3758	case IP_FW_ADD:
3759	{
3760		size_t savedsopt_valsize=0;
3761		rule = _MALLOC(RULE_MAXSIZE, M_TEMP, M_WAITOK);
3762		if (rule == 0) {
3763			error = ENOBUFS;
3764			break;
3765		}
3766
3767		bzero(rule, RULE_MAXSIZE);
3768
3769		if (api_version != IP_FW_CURRENT_API_VERSION) {
3770			error = ipfw_convert_to_latest(sopt, rule, api_version, is64user);
3771		}
3772		else {
3773			savedsopt_valsize = sopt->sopt_valsize;   /* it might get modified in sooptcopyin_fw */
3774			error = sooptcopyin_fw( sopt, rule, &rulesize);
3775
3776		}
3777
3778		if (!error) {
3779			if ((api_version == IP_FW_VERSION_0) || (api_version == IP_FW_VERSION_1)) {
3780				/* the rule has already been checked so just
3781				 * adjust sopt_valsize to match what would be expected.
3782				 */
3783				sopt->sopt_valsize = RULESIZE(rule);
3784				rulesize = RULESIZE(rule);
3785			}
3786			error = check_ipfw_struct(rule, rulesize);
3787			if (!error) {
3788				lck_mtx_lock(ipfw_mutex);
3789				error = add_rule(&layer3_chain, rule);
3790				if (!error && fw_bypass)
3791					fw_bypass = 0;
3792				lck_mtx_unlock(ipfw_mutex);
3793
3794				size = RULESIZE(rule);
3795				if (!error && sopt->sopt_dir == SOPT_GET) {
3796					/* convert back if necessary and copyout */
3797					if (api_version == IP_FW_VERSION_0) {
3798						struct ip_old_fw	rule_vers0;
3799
3800						ipfw_convert_from_latest(rule, &rule_vers0, api_version, is64user);
3801						sopt->sopt_valsize = sizeof(struct ip_old_fw);
3802
3803						error = sooptcopyout(sopt, &rule_vers0, sizeof(struct ip_old_fw));
3804					} else if (api_version == IP_FW_VERSION_1) {
3805						struct ip_fw_compat	rule_vers1;
3806						ipfw_convert_from_latest(rule, &rule_vers1, api_version, is64user);
3807						sopt->sopt_valsize = sizeof(struct ip_fw_compat);
3808
3809						error = sooptcopyout(sopt, &rule_vers1, sizeof(struct ip_fw_compat));
3810					} else {
3811						char *userrule;
3812						userrule = _MALLOC(savedsopt_valsize, M_TEMP, M_WAITOK);
3813						if ( userrule == NULL )
3814							userrule = (char*)rule;
3815						if (proc_is64bit(sopt->sopt_p)){
3816							copyto64fw( rule, (struct ip_fw_64*)userrule, savedsopt_valsize);
3817						}
3818						else {
3819								copyto32fw( rule, (struct ip_fw_32*)userrule, savedsopt_valsize);
3820						}
3821						error = sooptcopyout(sopt, userrule, savedsopt_valsize);
3822						if ( userrule )
3823							_FREE(userrule, M_TEMP);
3824					}
3825				}
3826			}
3827		}
3828
3829		_FREE(rule, M_TEMP);
3830		break;
3831	}
3832	case IP_FW_DEL:
3833	{
3834		/*
3835		 * IP_FW_DEL is used for deleting single rules or sets,
3836		 * and (ab)used to atomically manipulate sets.
3837		 * rule->rulenum != 0 indicates single rule delete
3838		 * rule->set_masks used to manipulate sets
3839		 * rule->set_masks[0] contains info on sets to be
3840		 *	disabled, swapped, or moved
3841		 * rule->set_masks[1] contains sets to be enabled.
3842		 */
3843
3844		/* there is only a simple rule passed in
3845		 * (no cmds), so use a temp struct to copy
3846		 */
3847		struct ip_fw	temp_rule;
3848		u_int32_t	arg;
3849		u_int8_t	cmd;
3850
3851		bzero(&temp_rule, sizeof(struct ip_fw));
3852		if (api_version != IP_FW_CURRENT_API_VERSION) {
3853			error = ipfw_convert_to_latest(sopt, &temp_rule, api_version, is64user);
3854		}
3855		else {
3856			error = sooptcopyin_fw(sopt, &temp_rule, 0 );
3857		}
3858
3859		if (!error) {
3860			/* set_masks is used to distinguish between deleting
3861			 * single rules or atomically manipulating sets
3862			 */
3863			lck_mtx_lock(ipfw_mutex);
3864
3865			arg = temp_rule.set_masks[0];
3866			cmd = (arg >> 24) & 0xff;
3867
3868			if (temp_rule.rulenum) {
3869				/* single rule */
3870				error = del_entry(&layer3_chain, temp_rule.rulenum);
3871#if DEBUG_INACTIVE_RULES
3872				print_chain(&layer3_chain);
3873#endif
3874			}
3875			else if (cmd) {
3876				/* set reassignment - see comment above del_entry() for details */
3877				error = del_entry(&layer3_chain, temp_rule.set_masks[0]);
3878#if DEBUG_INACTIVE_RULES
3879				print_chain(&layer3_chain);
3880#endif
3881			}
3882			else if (temp_rule.set_masks[0] != 0 ||
3883				temp_rule.set_masks[1] != 0) {
3884				/* set enable/disable */
3885				set_disable =
3886					(set_disable | temp_rule.set_masks[0]) & ~temp_rule.set_masks[1] &
3887					~(1<<RESVD_SET); /* set RESVD_SET always enabled */
3888			}
3889
3890			if (!layer3_chain->next)
3891				fw_bypass = 1;
3892			lck_mtx_unlock(ipfw_mutex);
3893		}
3894		break;
3895	}
3896	case IP_FW_ZERO:
3897	case IP_FW_RESETLOG: /* using rule->rulenum */
3898	{
3899		/* there is only a simple rule passed in
3900		 * (no cmds), so use a temp struct to copy
3901		 */
3902		struct ip_fw temp_rule;
3903
3904		bzero(&temp_rule, sizeof(struct ip_fw));
3905
3906		if (api_version != IP_FW_CURRENT_API_VERSION) {
3907			error = ipfw_convert_to_latest(sopt, &temp_rule, api_version, is64user);
3908		}
3909		else {
3910			if (sopt->sopt_val != 0) {
3911				error = sooptcopyin_fw( sopt, &temp_rule, 0);
3912			}
3913		}
3914
3915		if (!error) {
3916			lck_mtx_lock(ipfw_mutex);
3917			error = zero_entry(temp_rule.rulenum, sopt->sopt_name == IP_FW_RESETLOG);
3918			lck_mtx_unlock(ipfw_mutex);
3919		}
3920		break;
3921	}
3922	default:
3923		printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
3924		error = EINVAL;
3925	}
3926
3927	if (error != EINVAL) {
3928		switch (command) {
3929			case IP_FW_ADD:
3930			case IP_OLD_FW_ADD:
3931				ipfw_kev_post_msg(KEV_IPFW_ADD);
3932				break;
3933			case IP_OLD_FW_DEL:
3934			case IP_FW_DEL:
3935				ipfw_kev_post_msg(KEV_IPFW_DEL);
3936				break;
3937			case IP_FW_FLUSH:
3938			case IP_OLD_FW_FLUSH:
3939				ipfw_kev_post_msg(KEV_IPFW_FLUSH);
3940				break;
3941
3942			default:
3943				break;
3944		}
3945	}
3946
3947	return (error);
3948}
3949
3950/**
3951 * dummynet needs a reference to the default rule, because rules can be
3952 * deleted while packets hold a reference to them. When this happens,
3953 * dummynet changes the reference to the default rule (it could well be a
3954 * NULL pointer, but this way we do not need to check for the special
3955 * case, plus here he have info on the default behaviour).
3956 */
3957struct ip_fw *ip_fw_default_rule;
3958
3959/*
3960 * This procedure is only used to handle keepalives. It is invoked
3961 * every dyn_keepalive_period
3962 */
3963static void
3964ipfw_tick(__unused void * unused)
3965{
3966	struct mbuf *m0, *m, *mnext, **mtailp;
3967	int i;
3968	ipfw_dyn_rule *q;
3969	struct timeval timenow;
3970	static int stealth_cnt = 0;
3971
3972	if (ipfw_stealth_stats_needs_flush) {
3973	    stealth_cnt++;
3974	    if (!(stealth_cnt % IPFW_STEALTH_TIMEOUT_FREQUENCY)) {
3975	        ipfw_stealth_flush_stats();
3976	    }
3977	}
3978
3979	if (dyn_keepalive == 0 || ipfw_dyn_v == NULL || dyn_count == 0)
3980		goto done;
3981
3982	getmicrotime(&timenow);
3983
3984	/*
3985	 * We make a chain of packets to go out here -- not deferring
3986	 * until after we drop the ipfw lock would result
3987	 * in a lock order reversal with the normal packet input -> ipfw
3988	 * call stack.
3989	 */
3990	m0 = NULL;
3991	mtailp = &m0;
3992
3993	lck_mtx_lock(ipfw_mutex);
3994	for (i = 0 ; i < curr_dyn_buckets ; i++) {
3995		for (q = ipfw_dyn_v[i] ; q ; q = q->next ) {
3996			if (q->dyn_type == O_LIMIT_PARENT)
3997				continue;
3998			if (q->id.proto != IPPROTO_TCP)
3999				continue;
4000			if ( (q->state & BOTH_SYN) != BOTH_SYN)
4001				continue;
4002			if (TIME_LEQ( timenow.tv_sec+dyn_keepalive_interval,
4003			    q->expire))
4004				continue;	/* too early */
4005			if (TIME_LEQ(q->expire, timenow.tv_sec))
4006				continue;	/* too late, rule expired */
4007
4008			*mtailp = send_pkt(&(q->id), q->ack_rev - 1, q->ack_fwd, TH_SYN);
4009			if (*mtailp != NULL)
4010				mtailp = &(*mtailp)->m_nextpkt;
4011
4012			*mtailp = send_pkt(&(q->id), q->ack_fwd - 1, q->ack_rev, 0);
4013			if (*mtailp != NULL)
4014				mtailp = &(*mtailp)->m_nextpkt;
4015		}
4016	}
4017	lck_mtx_unlock(ipfw_mutex);
4018
4019	for (m = mnext = m0; m != NULL; m = mnext) {
4020		struct route sro;	/* fake route */
4021
4022		mnext = m->m_nextpkt;
4023		m->m_nextpkt = NULL;
4024		bzero (&sro, sizeof (sro));
4025		ip_output(m, NULL, &sro, 0, NULL, NULL);
4026		ROUTE_RELEASE(&sro);
4027	}
4028done:
4029	timeout_with_leeway(ipfw_tick, NULL, dyn_keepalive_period*hz,
4030	    DYN_KEEPALIVE_LEEWAY*hz);
4031}
4032
4033void
4034ipfw_init(void)
4035{
4036	struct ip_fw default_rule;
4037
4038	/* setup locks */
4039	ipfw_mutex_grp_attr = lck_grp_attr_alloc_init();
4040	ipfw_mutex_grp = lck_grp_alloc_init("ipfw", ipfw_mutex_grp_attr);
4041	ipfw_mutex_attr = lck_attr_alloc_init();
4042	lck_mtx_init(ipfw_mutex, ipfw_mutex_grp, ipfw_mutex_attr);
4043
4044	layer3_chain = NULL;
4045
4046	bzero(&default_rule, sizeof default_rule);
4047
4048	default_rule.act_ofs = 0;
4049	default_rule.rulenum = IPFW_DEFAULT_RULE;
4050	default_rule.cmd_len = 1;
4051	default_rule.set = RESVD_SET;
4052
4053	default_rule.cmd[0].len = 1;
4054	default_rule.cmd[0].opcode =
4055#ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4056				1 ? O_ACCEPT :
4057#endif
4058				O_DENY;
4059
4060	if (add_rule(&layer3_chain, &default_rule)) {
4061		printf("ipfw2: add_rule failed adding default rule\n");
4062		printf("ipfw2 failed initialization!!\n");
4063		fw_enable = 0;
4064	}
4065	else {
4066		ip_fw_default_rule = layer3_chain;
4067
4068	#ifdef IPFIREWALL_VERBOSE
4069		fw_verbose = 1;
4070	#endif
4071	#ifdef IPFIREWALL_VERBOSE_LIMIT
4072		verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4073	#endif
4074		if (fw_verbose) {
4075			if (!verbose_limit)
4076				printf("ipfw2 verbose logging enabled: unlimited logging by default\n");
4077			else
4078				printf("ipfw2 verbose logging enabled: limited to %d packets/entry by default\n",
4079					verbose_limit);
4080		}
4081	}
4082
4083	ip_fw_chk_ptr = ipfw_chk;
4084	ip_fw_ctl_ptr = ipfw_ctl;
4085
4086        ipfwstringlen = strlen( ipfwstring );
4087
4088	timeout(ipfw_tick, NULL, hz);
4089}
4090
4091#endif /* IPFW2 */
4092
4093