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