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