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