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