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