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