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