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