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