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