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