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