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