ip_fw2.c revision 225030
1146297Sobrien/*-
2240373Sdelphij * Copyright (c) 2002-2009 Luigi Rizzo, Universita` di Pisa
3146297Sobrien *
4146297Sobrien * Redistribution and use in source and binary forms, with or without
5146297Sobrien * modification, are permitted provided that the following conditions
6146297Sobrien * are met:
7146297Sobrien * 1. Redistributions of source code must retain the above copyright
8146297Sobrien *    notice, this list of conditions and the following disclaimer.
9146297Sobrien * 2. Redistributions in binary form must reproduce the above copyright
10146297Sobrien *    notice, this list of conditions and the following disclaimer in the
11146297Sobrien *    documentation and/or other materials provided with the distribution.
12146297Sobrien *
13146297Sobrien * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14146297Sobrien * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15146297Sobrien * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16240373Sdelphij * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17146297Sobrien * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18146297Sobrien * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19146297Sobrien * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20240373Sdelphij * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21146297Sobrien * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22146297Sobrien * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23146297Sobrien * SUCH DAMAGE.
24146297Sobrien */
25146297Sobrien
26146297Sobrien#include <sys/cdefs.h>
27__FBSDID("$FreeBSD: head/sys/netinet/ipfw/ip_fw2.c 225030 2011-08-20 12:40:17Z bz $");
28
29/*
30 * The FreeBSD IP packet firewall, main file
31 */
32
33#if !defined(KLD_MODULE)
34#include "opt_ipfw.h"
35#include "opt_ipdivert.h"
36#include "opt_ipdn.h"
37#include "opt_inet.h"
38#ifndef INET
39#error IPFIREWALL requires INET.
40#endif /* INET */
41#endif
42#include "opt_inet6.h"
43#include "opt_ipsec.h"
44
45#include <sys/param.h>
46#include <sys/systm.h>
47#include <sys/condvar.h>
48#include <sys/eventhandler.h>
49#include <sys/malloc.h>
50#include <sys/mbuf.h>
51#include <sys/kernel.h>
52#include <sys/lock.h>
53#include <sys/jail.h>
54#include <sys/module.h>
55#include <sys/priv.h>
56#include <sys/proc.h>
57#include <sys/rwlock.h>
58#include <sys/socket.h>
59#include <sys/socketvar.h>
60#include <sys/sysctl.h>
61#include <sys/syslog.h>
62#include <sys/ucred.h>
63#include <net/ethernet.h> /* for ETHERTYPE_IP */
64#include <net/if.h>
65#include <net/route.h>
66#include <net/pf_mtag.h>
67#include <net/vnet.h>
68
69#include <netinet/in.h>
70#include <netinet/in_var.h>
71#include <netinet/in_pcb.h>
72#include <netinet/ip.h>
73#include <netinet/ip_var.h>
74#include <netinet/ip_icmp.h>
75#include <netinet/ip_fw.h>
76#include <netinet/ipfw/ip_fw_private.h>
77#include <netinet/ip_carp.h>
78#include <netinet/pim.h>
79#include <netinet/tcp_var.h>
80#include <netinet/udp.h>
81#include <netinet/udp_var.h>
82#include <netinet/sctp.h>
83
84#include <netinet/ip6.h>
85#include <netinet/icmp6.h>
86#ifdef INET6
87#include <netinet6/in6_pcb.h>
88#include <netinet6/scope6_var.h>
89#include <netinet6/ip6_var.h>
90#endif
91
92#include <machine/in_cksum.h>	/* XXX for in_cksum */
93
94#ifdef MAC
95#include <security/mac/mac_framework.h>
96#endif
97
98/*
99 * static variables followed by global ones.
100 * All ipfw global variables are here.
101 */
102
103/* ipfw_vnet_ready controls when we are open for business */
104static VNET_DEFINE(int, ipfw_vnet_ready) = 0;
105#define	V_ipfw_vnet_ready	VNET(ipfw_vnet_ready)
106
107static VNET_DEFINE(int, fw_deny_unknown_exthdrs);
108#define	V_fw_deny_unknown_exthdrs	VNET(fw_deny_unknown_exthdrs)
109
110static VNET_DEFINE(int, fw_permit_single_frag6) = 1;
111#define	V_fw_permit_single_frag6	VNET(fw_permit_single_frag6)
112
113#ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
114static int default_to_accept = 1;
115#else
116static int default_to_accept;
117#endif
118
119VNET_DEFINE(int, autoinc_step);
120VNET_DEFINE(int, fw_one_pass) = 1;
121
122/*
123 * Each rule belongs to one of 32 different sets (0..31).
124 * The variable set_disable contains one bit per set.
125 * If the bit is set, all rules in the corresponding set
126 * are disabled. Set RESVD_SET(31) is reserved for the default rule
127 * and rules that are not deleted by the flush command,
128 * and CANNOT be disabled.
129 * Rules in set RESVD_SET can only be deleted individually.
130 */
131VNET_DEFINE(u_int32_t, set_disable);
132#define	V_set_disable			VNET(set_disable)
133
134VNET_DEFINE(int, fw_verbose);
135/* counter for ipfw_log(NULL...) */
136VNET_DEFINE(u_int64_t, norule_counter);
137VNET_DEFINE(int, verbose_limit);
138
139/* layer3_chain contains the list of rules for layer 3 */
140VNET_DEFINE(struct ip_fw_chain, layer3_chain);
141
142ipfw_nat_t *ipfw_nat_ptr = NULL;
143struct cfg_nat *(*lookup_nat_ptr)(struct nat_list *, int);
144ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
145ipfw_nat_cfg_t *ipfw_nat_del_ptr;
146ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
147ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
148
149#ifdef SYSCTL_NODE
150uint32_t dummy_def = IPFW_DEFAULT_RULE;
151uint32_t dummy_tables_max = IPFW_TABLES_MAX;
152
153SYSBEGIN(f3)
154
155SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
156SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
157    CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_one_pass), 0,
158    "Only do a single pass through ipfw when using dummynet(4)");
159SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step,
160    CTLFLAG_RW, &VNET_NAME(autoinc_step), 0,
161    "Rule number auto-increment step");
162SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose,
163    CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_verbose), 0,
164    "Log matches to ipfw rules");
165SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit,
166    CTLFLAG_RW, &VNET_NAME(verbose_limit), 0,
167    "Set upper limit of matches of ipfw rules logged");
168SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
169    &dummy_def, 0,
170    "The default/max possible rule number.");
171SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, tables_max, CTLFLAG_RD,
172    &dummy_tables_max, 0,
173    "The maximum number of tables.");
174SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, default_to_accept, CTLFLAG_RDTUN,
175    &default_to_accept, 0,
176    "Make the default rule accept all packets.");
177TUNABLE_INT("net.inet.ip.fw.default_to_accept", &default_to_accept);
178SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, static_count,
179    CTLFLAG_RD, &VNET_NAME(layer3_chain.n_rules), 0,
180    "Number of static rules");
181
182#ifdef INET6
183SYSCTL_DECL(_net_inet6_ip6);
184SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
185SYSCTL_VNET_INT(_net_inet6_ip6_fw, OID_AUTO, deny_unknown_exthdrs,
186    CTLFLAG_RW | CTLFLAG_SECURE, &VNET_NAME(fw_deny_unknown_exthdrs), 0,
187    "Deny packets with unknown IPv6 Extension Headers");
188SYSCTL_VNET_INT(_net_inet6_ip6_fw, OID_AUTO, permit_single_frag6,
189    CTLFLAG_RW | CTLFLAG_SECURE, &VNET_NAME(fw_permit_single_frag6), 0,
190    "Permit single packet IPv6 fragments");
191#endif /* INET6 */
192
193SYSEND
194
195#endif /* SYSCTL_NODE */
196
197
198/*
199 * Some macros used in the various matching options.
200 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
201 * Other macros just cast void * into the appropriate type
202 */
203#define	L3HDR(T, ip)	((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
204#define	TCP(p)		((struct tcphdr *)(p))
205#define	SCTP(p)		((struct sctphdr *)(p))
206#define	UDP(p)		((struct udphdr *)(p))
207#define	ICMP(p)		((struct icmphdr *)(p))
208#define	ICMP6(p)	((struct icmp6_hdr *)(p))
209
210static __inline int
211icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
212{
213	int type = icmp->icmp_type;
214
215	return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
216}
217
218#define TT	( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
219    (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
220
221static int
222is_icmp_query(struct icmphdr *icmp)
223{
224	int type = icmp->icmp_type;
225
226	return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
227}
228#undef TT
229
230/*
231 * The following checks use two arrays of 8 or 16 bits to store the
232 * bits that we want set or clear, respectively. They are in the
233 * low and high half of cmd->arg1 or cmd->d[0].
234 *
235 * We scan options and store the bits we find set. We succeed if
236 *
237 *	(want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
238 *
239 * The code is sometimes optimized not to store additional variables.
240 */
241
242static int
243flags_match(ipfw_insn *cmd, u_int8_t bits)
244{
245	u_char want_clear;
246	bits = ~bits;
247
248	if ( ((cmd->arg1 & 0xff) & bits) != 0)
249		return 0; /* some bits we want set were clear */
250	want_clear = (cmd->arg1 >> 8) & 0xff;
251	if ( (want_clear & bits) != want_clear)
252		return 0; /* some bits we want clear were set */
253	return 1;
254}
255
256static int
257ipopts_match(struct ip *ip, ipfw_insn *cmd)
258{
259	int optlen, bits = 0;
260	u_char *cp = (u_char *)(ip + 1);
261	int x = (ip->ip_hl << 2) - sizeof (struct ip);
262
263	for (; x > 0; x -= optlen, cp += optlen) {
264		int opt = cp[IPOPT_OPTVAL];
265
266		if (opt == IPOPT_EOL)
267			break;
268		if (opt == IPOPT_NOP)
269			optlen = 1;
270		else {
271			optlen = cp[IPOPT_OLEN];
272			if (optlen <= 0 || optlen > x)
273				return 0; /* invalid or truncated */
274		}
275		switch (opt) {
276
277		default:
278			break;
279
280		case IPOPT_LSRR:
281			bits |= IP_FW_IPOPT_LSRR;
282			break;
283
284		case IPOPT_SSRR:
285			bits |= IP_FW_IPOPT_SSRR;
286			break;
287
288		case IPOPT_RR:
289			bits |= IP_FW_IPOPT_RR;
290			break;
291
292		case IPOPT_TS:
293			bits |= IP_FW_IPOPT_TS;
294			break;
295		}
296	}
297	return (flags_match(cmd, bits));
298}
299
300static int
301tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
302{
303	int optlen, bits = 0;
304	u_char *cp = (u_char *)(tcp + 1);
305	int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
306
307	for (; x > 0; x -= optlen, cp += optlen) {
308		int opt = cp[0];
309		if (opt == TCPOPT_EOL)
310			break;
311		if (opt == TCPOPT_NOP)
312			optlen = 1;
313		else {
314			optlen = cp[1];
315			if (optlen <= 0)
316				break;
317		}
318
319		switch (opt) {
320
321		default:
322			break;
323
324		case TCPOPT_MAXSEG:
325			bits |= IP_FW_TCPOPT_MSS;
326			break;
327
328		case TCPOPT_WINDOW:
329			bits |= IP_FW_TCPOPT_WINDOW;
330			break;
331
332		case TCPOPT_SACK_PERMITTED:
333		case TCPOPT_SACK:
334			bits |= IP_FW_TCPOPT_SACK;
335			break;
336
337		case TCPOPT_TIMESTAMP:
338			bits |= IP_FW_TCPOPT_TS;
339			break;
340
341		}
342	}
343	return (flags_match(cmd, bits));
344}
345
346static int
347iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
348{
349	if (ifp == NULL)	/* no iface with this packet, match fails */
350		return 0;
351	/* Check by name or by IP address */
352	if (cmd->name[0] != '\0') { /* match by name */
353		/* Check name */
354		if (cmd->p.glob) {
355			if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
356				return(1);
357		} else {
358			if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
359				return(1);
360		}
361	} else {
362#ifdef __FreeBSD__	/* and OSX too ? */
363		struct ifaddr *ia;
364
365		if_addr_rlock(ifp);
366		TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
367			if (ia->ifa_addr->sa_family != AF_INET)
368				continue;
369			if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
370			    (ia->ifa_addr))->sin_addr.s_addr) {
371				if_addr_runlock(ifp);
372				return(1);	/* match */
373			}
374		}
375		if_addr_runlock(ifp);
376#endif /* __FreeBSD__ */
377	}
378	return(0);	/* no match, fail ... */
379}
380
381/*
382 * The verify_path function checks if a route to the src exists and
383 * if it is reachable via ifp (when provided).
384 *
385 * The 'verrevpath' option checks that the interface that an IP packet
386 * arrives on is the same interface that traffic destined for the
387 * packet's source address would be routed out of.
388 * The 'versrcreach' option just checks that the source address is
389 * reachable via any route (except default) in the routing table.
390 * These two are a measure to block forged packets. This is also
391 * commonly known as "anti-spoofing" or Unicast Reverse Path
392 * Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
393 * is purposely reminiscent of the Cisco IOS command,
394 *
395 *   ip verify unicast reverse-path
396 *   ip verify unicast source reachable-via any
397 *
398 * which implements the same functionality. But note that the syntax
399 * is misleading, and the check may be performed on all IP packets
400 * whether unicast, multicast, or broadcast.
401 */
402static int
403verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
404{
405#ifndef __FreeBSD__
406	return 0;
407#else
408	struct route ro;
409	struct sockaddr_in *dst;
410
411	bzero(&ro, sizeof(ro));
412
413	dst = (struct sockaddr_in *)&(ro.ro_dst);
414	dst->sin_family = AF_INET;
415	dst->sin_len = sizeof(*dst);
416	dst->sin_addr = src;
417	in_rtalloc_ign(&ro, 0, fib);
418
419	if (ro.ro_rt == NULL)
420		return 0;
421
422	/*
423	 * If ifp is provided, check for equality with rtentry.
424	 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
425	 * in order to pass packets injected back by if_simloop():
426	 * if useloopback == 1 routing entry (via lo0) for our own address
427	 * may exist, so we need to handle routing assymetry.
428	 */
429	if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
430		RTFREE(ro.ro_rt);
431		return 0;
432	}
433
434	/* if no ifp provided, check if rtentry is not default route */
435	if (ifp == NULL &&
436	     satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
437		RTFREE(ro.ro_rt);
438		return 0;
439	}
440
441	/* or if this is a blackhole/reject route */
442	if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
443		RTFREE(ro.ro_rt);
444		return 0;
445	}
446
447	/* found valid route */
448	RTFREE(ro.ro_rt);
449	return 1;
450#endif /* __FreeBSD__ */
451}
452
453#ifdef INET6
454/*
455 * ipv6 specific rules here...
456 */
457static __inline int
458icmp6type_match (int type, ipfw_insn_u32 *cmd)
459{
460	return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
461}
462
463static int
464flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
465{
466	int i;
467	for (i=0; i <= cmd->o.arg1; ++i )
468		if (curr_flow == cmd->d[i] )
469			return 1;
470	return 0;
471}
472
473/* support for IP6_*_ME opcodes */
474static int
475search_ip6_addr_net (struct in6_addr * ip6_addr)
476{
477	struct ifnet *mdc;
478	struct ifaddr *mdc2;
479	struct in6_ifaddr *fdm;
480	struct in6_addr copia;
481
482	TAILQ_FOREACH(mdc, &V_ifnet, if_link) {
483		if_addr_rlock(mdc);
484		TAILQ_FOREACH(mdc2, &mdc->if_addrhead, ifa_link) {
485			if (mdc2->ifa_addr->sa_family == AF_INET6) {
486				fdm = (struct in6_ifaddr *)mdc2;
487				copia = fdm->ia_addr.sin6_addr;
488				/* need for leaving scope_id in the sock_addr */
489				in6_clearscope(&copia);
490				if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia)) {
491					if_addr_runlock(mdc);
492					return 1;
493				}
494			}
495		}
496		if_addr_runlock(mdc);
497	}
498	return 0;
499}
500
501static int
502verify_path6(struct in6_addr *src, struct ifnet *ifp)
503{
504	struct route_in6 ro;
505	struct sockaddr_in6 *dst;
506
507	bzero(&ro, sizeof(ro));
508
509	dst = (struct sockaddr_in6 * )&(ro.ro_dst);
510	dst->sin6_family = AF_INET6;
511	dst->sin6_len = sizeof(*dst);
512	dst->sin6_addr = *src;
513	/* XXX MRT 0 for ipv6 at this time */
514	rtalloc_ign((struct route *)&ro, 0);
515
516	if (ro.ro_rt == NULL)
517		return 0;
518
519	/*
520	 * if ifp is provided, check for equality with rtentry
521	 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
522	 * to support the case of sending packets to an address of our own.
523	 * (where the former interface is the first argument of if_simloop()
524	 *  (=ifp), the latter is lo0)
525	 */
526	if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
527		RTFREE(ro.ro_rt);
528		return 0;
529	}
530
531	/* if no ifp provided, check if rtentry is not default route */
532	if (ifp == NULL &&
533	    IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
534		RTFREE(ro.ro_rt);
535		return 0;
536	}
537
538	/* or if this is a blackhole/reject route */
539	if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
540		RTFREE(ro.ro_rt);
541		return 0;
542	}
543
544	/* found valid route */
545	RTFREE(ro.ro_rt);
546	return 1;
547
548}
549
550static int
551is_icmp6_query(int icmp6_type)
552{
553	if ((icmp6_type <= ICMP6_MAXTYPE) &&
554	    (icmp6_type == ICMP6_ECHO_REQUEST ||
555	    icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
556	    icmp6_type == ICMP6_WRUREQUEST ||
557	    icmp6_type == ICMP6_FQDN_QUERY ||
558	    icmp6_type == ICMP6_NI_QUERY))
559		return (1);
560
561	return (0);
562}
563
564static void
565send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
566{
567	struct mbuf *m;
568
569	m = args->m;
570	if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
571		struct tcphdr *tcp;
572		tcp = (struct tcphdr *)((char *)ip6 + hlen);
573
574		if ((tcp->th_flags & TH_RST) == 0) {
575			struct mbuf *m0;
576			m0 = ipfw_send_pkt(args->m, &(args->f_id),
577			    ntohl(tcp->th_seq), ntohl(tcp->th_ack),
578			    tcp->th_flags | TH_RST);
579			if (m0 != NULL)
580				ip6_output(m0, NULL, NULL, 0, NULL, NULL,
581				    NULL);
582		}
583		FREE_PKT(m);
584	} else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
585#if 0
586		/*
587		 * Unlike above, the mbufs need to line up with the ip6 hdr,
588		 * as the contents are read. We need to m_adj() the
589		 * needed amount.
590		 * The mbuf will however be thrown away so we can adjust it.
591		 * Remember we did an m_pullup on it already so we
592		 * can make some assumptions about contiguousness.
593		 */
594		if (args->L3offset)
595			m_adj(m, args->L3offset);
596#endif
597		icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
598	} else
599		FREE_PKT(m);
600
601	args->m = NULL;
602}
603
604#endif /* INET6 */
605
606
607/*
608 * sends a reject message, consuming the mbuf passed as an argument.
609 */
610static void
611send_reject(struct ip_fw_args *args, int code, int iplen, struct ip *ip)
612{
613
614#if 0
615	/* XXX When ip is not guaranteed to be at mtod() we will
616	 * need to account for this */
617	 * The mbuf will however be thrown away so we can adjust it.
618	 * Remember we did an m_pullup on it already so we
619	 * can make some assumptions about contiguousness.
620	 */
621	if (args->L3offset)
622		m_adj(m, args->L3offset);
623#endif
624	if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
625		/* We need the IP header in host order for icmp_error(). */
626		SET_HOST_IPLEN(ip);
627		icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
628	} else if (args->f_id.proto == IPPROTO_TCP) {
629		struct tcphdr *const tcp =
630		    L3HDR(struct tcphdr, mtod(args->m, struct ip *));
631		if ( (tcp->th_flags & TH_RST) == 0) {
632			struct mbuf *m;
633			m = ipfw_send_pkt(args->m, &(args->f_id),
634				ntohl(tcp->th_seq), ntohl(tcp->th_ack),
635				tcp->th_flags | TH_RST);
636			if (m != NULL)
637				ip_output(m, NULL, NULL, 0, NULL, NULL);
638		}
639		FREE_PKT(args->m);
640	} else
641		FREE_PKT(args->m);
642	args->m = NULL;
643}
644
645/*
646 * Support for uid/gid/jail lookup. These tests are expensive
647 * (because we may need to look into the list of active sockets)
648 * so we cache the results. ugid_lookupp is 0 if we have not
649 * yet done a lookup, 1 if we succeeded, and -1 if we tried
650 * and failed. The function always returns the match value.
651 * We could actually spare the variable and use *uc, setting
652 * it to '(void *)check_uidgid if we have no info, NULL if
653 * we tried and failed, or any other value if successful.
654 */
655static int
656check_uidgid(ipfw_insn_u32 *insn, struct ip_fw_args *args, int *ugid_lookupp,
657    struct ucred **uc)
658{
659#ifndef __FreeBSD__
660	/* XXX */
661	return cred_check(insn, proto, oif,
662	    dst_ip, dst_port, src_ip, src_port,
663	    (struct bsd_ucred *)uc, ugid_lookupp, ((struct mbuf *)inp)->m_skb);
664#else  /* FreeBSD */
665	struct in_addr src_ip, dst_ip;
666	struct inpcbinfo *pi;
667	struct ipfw_flow_id *id;
668	struct inpcb *pcb, *inp;
669	struct ifnet *oif;
670	int lookupflags;
671	int match;
672
673	id = &args->f_id;
674	inp = args->inp;
675	oif = args->oif;
676
677	/*
678	 * Check to see if the UDP or TCP stack supplied us with
679	 * the PCB. If so, rather then holding a lock and looking
680	 * up the PCB, we can use the one that was supplied.
681	 */
682	if (inp && *ugid_lookupp == 0) {
683		INP_LOCK_ASSERT(inp);
684		if (inp->inp_socket != NULL) {
685			*uc = crhold(inp->inp_cred);
686			*ugid_lookupp = 1;
687		} else
688			*ugid_lookupp = -1;
689	}
690	/*
691	 * If we have already been here and the packet has no
692	 * PCB entry associated with it, then we can safely
693	 * assume that this is a no match.
694	 */
695	if (*ugid_lookupp == -1)
696		return (0);
697	if (id->proto == IPPROTO_TCP) {
698		lookupflags = 0;
699		pi = &V_tcbinfo;
700	} else if (id->proto == IPPROTO_UDP) {
701		lookupflags = INPLOOKUP_WILDCARD;
702		pi = &V_udbinfo;
703	} else
704		return 0;
705	lookupflags |= INPLOOKUP_RLOCKPCB;
706	match = 0;
707	if (*ugid_lookupp == 0) {
708		if (id->addr_type == 6) {
709#ifdef INET6
710			if (oif == NULL)
711				pcb = in6_pcblookup_mbuf(pi,
712				    &id->src_ip6, htons(id->src_port),
713				    &id->dst_ip6, htons(id->dst_port),
714				    lookupflags, oif, args->m);
715			else
716				pcb = in6_pcblookup_mbuf(pi,
717				    &id->dst_ip6, htons(id->dst_port),
718				    &id->src_ip6, htons(id->src_port),
719				    lookupflags, oif, args->m);
720#else
721			*ugid_lookupp = -1;
722			return (0);
723#endif
724		} else {
725			src_ip.s_addr = htonl(id->src_ip);
726			dst_ip.s_addr = htonl(id->dst_ip);
727			if (oif == NULL)
728				pcb = in_pcblookup_mbuf(pi,
729				    src_ip, htons(id->src_port),
730				    dst_ip, htons(id->dst_port),
731				    lookupflags, oif, args->m);
732			else
733				pcb = in_pcblookup_mbuf(pi,
734				    dst_ip, htons(id->dst_port),
735				    src_ip, htons(id->src_port),
736				    lookupflags, oif, args->m);
737		}
738		if (pcb != NULL) {
739			INP_RLOCK_ASSERT(pcb);
740			*uc = crhold(pcb->inp_cred);
741			*ugid_lookupp = 1;
742			INP_RUNLOCK(pcb);
743		}
744		if (*ugid_lookupp == 0) {
745			/*
746			 * We tried and failed, set the variable to -1
747			 * so we will not try again on this packet.
748			 */
749			*ugid_lookupp = -1;
750			return (0);
751		}
752	}
753	if (insn->o.opcode == O_UID)
754		match = ((*uc)->cr_uid == (uid_t)insn->d[0]);
755	else if (insn->o.opcode == O_GID)
756		match = groupmember((gid_t)insn->d[0], *uc);
757	else if (insn->o.opcode == O_JAIL)
758		match = ((*uc)->cr_prison->pr_id == (int)insn->d[0]);
759	return (match);
760#endif /* __FreeBSD__ */
761}
762
763/*
764 * Helper function to set args with info on the rule after the matching
765 * one. slot is precise, whereas we guess rule_id as they are
766 * assigned sequentially.
767 */
768static inline void
769set_match(struct ip_fw_args *args, int slot,
770	struct ip_fw_chain *chain)
771{
772	args->rule.chain_id = chain->id;
773	args->rule.slot = slot + 1; /* we use 0 as a marker */
774	args->rule.rule_id = 1 + chain->map[slot]->id;
775	args->rule.rulenum = chain->map[slot]->rulenum;
776}
777
778/*
779 * The main check routine for the firewall.
780 *
781 * All arguments are in args so we can modify them and return them
782 * back to the caller.
783 *
784 * Parameters:
785 *
786 *	args->m	(in/out) The packet; we set to NULL when/if we nuke it.
787 *		Starts with the IP header.
788 *	args->eh (in)	Mac header if present, NULL for layer3 packet.
789 *	args->L3offset	Number of bytes bypassed if we came from L2.
790 *			e.g. often sizeof(eh)  ** NOTYET **
791 *	args->oif	Outgoing interface, NULL if packet is incoming.
792 *		The incoming interface is in the mbuf. (in)
793 *	args->divert_rule (in/out)
794 *		Skip up to the first rule past this rule number;
795 *		upon return, non-zero port number for divert or tee.
796 *
797 *	args->rule	Pointer to the last matching rule (in/out)
798 *	args->next_hop	Socket we are forwarding to (out).
799 *	args->f_id	Addresses grabbed from the packet (out)
800 * 	args->rule.info	a cookie depending on rule action
801 *
802 * Return value:
803 *
804 *	IP_FW_PASS	the packet must be accepted
805 *	IP_FW_DENY	the packet must be dropped
806 *	IP_FW_DIVERT	divert packet, port in m_tag
807 *	IP_FW_TEE	tee packet, port in m_tag
808 *	IP_FW_DUMMYNET	to dummynet, pipe in args->cookie
809 *	IP_FW_NETGRAPH	into netgraph, cookie args->cookie
810 *		args->rule contains the matching rule,
811 *		args->rule.info has additional information.
812 *
813 */
814int
815ipfw_chk(struct ip_fw_args *args)
816{
817
818	/*
819	 * Local variables holding state while processing a packet:
820	 *
821	 * IMPORTANT NOTE: to speed up the processing of rules, there
822	 * are some assumption on the values of the variables, which
823	 * are documented here. Should you change them, please check
824	 * the implementation of the various instructions to make sure
825	 * that they still work.
826	 *
827	 * args->eh	The MAC header. It is non-null for a layer2
828	 *	packet, it is NULL for a layer-3 packet.
829	 * **notyet**
830	 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
831	 *
832	 * m | args->m	Pointer to the mbuf, as received from the caller.
833	 *	It may change if ipfw_chk() does an m_pullup, or if it
834	 *	consumes the packet because it calls send_reject().
835	 *	XXX This has to change, so that ipfw_chk() never modifies
836	 *	or consumes the buffer.
837	 * ip	is the beginning of the ip(4 or 6) header.
838	 *	Calculated by adding the L3offset to the start of data.
839	 *	(Until we start using L3offset, the packet is
840	 *	supposed to start with the ip header).
841	 */
842	struct mbuf *m = args->m;
843	struct ip *ip = mtod(m, struct ip *);
844
845	/*
846	 * For rules which contain uid/gid or jail constraints, cache
847	 * a copy of the users credentials after the pcb lookup has been
848	 * executed. This will speed up the processing of rules with
849	 * these types of constraints, as well as decrease contention
850	 * on pcb related locks.
851	 */
852#ifndef __FreeBSD__
853	struct bsd_ucred ucred_cache;
854#else
855	struct ucred *ucred_cache = NULL;
856#endif
857	int ucred_lookup = 0;
858
859	/*
860	 * oif | args->oif	If NULL, ipfw_chk has been called on the
861	 *	inbound path (ether_input, ip_input).
862	 *	If non-NULL, ipfw_chk has been called on the outbound path
863	 *	(ether_output, ip_output).
864	 */
865	struct ifnet *oif = args->oif;
866
867	int f_pos = 0;		/* index of current rule in the array */
868	int retval = 0;
869
870	/*
871	 * hlen	The length of the IP header.
872	 */
873	u_int hlen = 0;		/* hlen >0 means we have an IP pkt */
874
875	/*
876	 * offset	The offset of a fragment. offset != 0 means that
877	 *	we have a fragment at this offset of an IPv4 packet.
878	 *	offset == 0 means that (if this is an IPv4 packet)
879	 *	this is the first or only fragment.
880	 *	For IPv6 offset == 0 means there is no Fragment Header or there
881	 *	is a single packet fragement (fragement header added without
882	 *	needed).  We will treat a single packet fragment as if there
883	 *	was no fragment header (or log/block depending on the
884	 *	V_fw_permit_single_frag6 sysctl setting).
885	 *	If offset != 0 for IPv6 always use correct mask to
886	 *	get the correct offset because we add IP6F_MORE_FRAG to be able
887	 *	to dectect the first of multiple fragments which would
888	 *	otherwise have offset = 0.
889	 */
890	u_short offset = 0;
891
892	/*
893	 * Local copies of addresses. They are only valid if we have
894	 * an IP packet.
895	 *
896	 * proto	The protocol. Set to 0 for non-ip packets,
897	 *	or to the protocol read from the packet otherwise.
898	 *	proto != 0 means that we have an IPv4 packet.
899	 *
900	 * src_port, dst_port	port numbers, in HOST format. Only
901	 *	valid for TCP and UDP packets.
902	 *
903	 * src_ip, dst_ip	ip addresses, in NETWORK format.
904	 *	Only valid for IPv4 packets.
905	 */
906	uint8_t proto;
907	uint16_t src_port = 0, dst_port = 0;	/* NOTE: host format	*/
908	struct in_addr src_ip, dst_ip;		/* NOTE: network format	*/
909	uint16_t iplen=0;
910	int pktlen;
911	uint16_t	etype = 0;	/* Host order stored ether type */
912
913	/*
914	 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
915	 * 	MATCH_NONE when checked and not matched (q = NULL),
916	 *	MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
917	 */
918	int dyn_dir = MATCH_UNKNOWN;
919	ipfw_dyn_rule *q = NULL;
920	struct ip_fw_chain *chain = &V_layer3_chain;
921
922	/*
923	 * We store in ulp a pointer to the upper layer protocol header.
924	 * In the ipv4 case this is easy to determine from the header,
925	 * but for ipv6 we might have some additional headers in the middle.
926	 * ulp is NULL if not found.
927	 */
928	void *ulp = NULL;		/* upper layer protocol pointer. */
929
930	/* XXX ipv6 variables */
931	int is_ipv6 = 0;
932	uint8_t	icmp6_type = 0;
933	uint16_t ext_hd = 0;	/* bits vector for extension header filtering */
934	/* end of ipv6 variables */
935
936	int is_ipv4 = 0;
937
938	int done = 0;		/* flag to exit the outer loop */
939
940	if (m->m_flags & M_SKIP_FIREWALL || (! V_ipfw_vnet_ready))
941		return (IP_FW_PASS);	/* accept */
942
943	dst_ip.s_addr = 0;		/* make sure it is initialized */
944	src_ip.s_addr = 0;		/* make sure it is initialized */
945	pktlen = m->m_pkthdr.len;
946	args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
947	proto = args->f_id.proto = 0;	/* mark f_id invalid */
948		/* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
949
950/*
951 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
952 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
953 * pointer might become stale after other pullups (but we never use it
954 * this way).
955 */
956#define PULLUP_TO(_len, p, T)	PULLUP_LEN(_len, p, sizeof(T))
957#define PULLUP_LEN(_len, p, T)					\
958do {								\
959	int x = (_len) + T;					\
960	if ((m)->m_len < x) {					\
961		args->m = m = m_pullup(m, x);			\
962		if (m == NULL)					\
963			goto pullup_failed;			\
964	}							\
965	p = (mtod(m, char *) + (_len));				\
966} while (0)
967
968	/*
969	 * if we have an ether header,
970	 */
971	if (args->eh)
972		etype = ntohs(args->eh->ether_type);
973
974	/* Identify IP packets and fill up variables. */
975	if (pktlen >= sizeof(struct ip6_hdr) &&
976	    (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
977		struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
978		is_ipv6 = 1;
979		args->f_id.addr_type = 6;
980		hlen = sizeof(struct ip6_hdr);
981		proto = ip6->ip6_nxt;
982
983		/* Search extension headers to find upper layer protocols */
984		while (ulp == NULL) {
985			switch (proto) {
986			case IPPROTO_ICMPV6:
987				PULLUP_TO(hlen, ulp, struct icmp6_hdr);
988				icmp6_type = ICMP6(ulp)->icmp6_type;
989				break;
990
991			case IPPROTO_TCP:
992				PULLUP_TO(hlen, ulp, struct tcphdr);
993				dst_port = TCP(ulp)->th_dport;
994				src_port = TCP(ulp)->th_sport;
995				/* save flags for dynamic rules */
996				args->f_id._flags = TCP(ulp)->th_flags;
997				break;
998
999			case IPPROTO_SCTP:
1000				PULLUP_TO(hlen, ulp, struct sctphdr);
1001				src_port = SCTP(ulp)->src_port;
1002				dst_port = SCTP(ulp)->dest_port;
1003				break;
1004
1005			case IPPROTO_UDP:
1006				PULLUP_TO(hlen, ulp, struct udphdr);
1007				dst_port = UDP(ulp)->uh_dport;
1008				src_port = UDP(ulp)->uh_sport;
1009				break;
1010
1011			case IPPROTO_HOPOPTS:	/* RFC 2460 */
1012				PULLUP_TO(hlen, ulp, struct ip6_hbh);
1013				ext_hd |= EXT_HOPOPTS;
1014				hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1015				proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1016				ulp = NULL;
1017				break;
1018
1019			case IPPROTO_ROUTING:	/* RFC 2460 */
1020				PULLUP_TO(hlen, ulp, struct ip6_rthdr);
1021				switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
1022				case 0:
1023					ext_hd |= EXT_RTHDR0;
1024					break;
1025				case 2:
1026					ext_hd |= EXT_RTHDR2;
1027					break;
1028				default:
1029					printf("IPFW2: IPV6 - Unknown Routing "
1030					    "Header type(%d)\n",
1031					    ((struct ip6_rthdr *)ulp)->ip6r_type);
1032					if (V_fw_deny_unknown_exthdrs)
1033					    return (IP_FW_DENY);
1034					break;
1035				}
1036				ext_hd |= EXT_ROUTING;
1037				hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
1038				proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
1039				ulp = NULL;
1040				break;
1041
1042			case IPPROTO_FRAGMENT:	/* RFC 2460 */
1043				PULLUP_TO(hlen, ulp, struct ip6_frag);
1044				ext_hd |= EXT_FRAGMENT;
1045				hlen += sizeof (struct ip6_frag);
1046				proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
1047				offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
1048					IP6F_OFF_MASK;
1049				/* Add IP6F_MORE_FRAG for offset of first
1050				 * fragment to be != 0 if there shall be more. */
1051				offset |= ((struct ip6_frag *)ulp)->ip6f_offlg &
1052					IP6F_MORE_FRAG;
1053				if (V_fw_permit_single_frag6 == 0 &&
1054				    offset == 0) {
1055					printf("IPFW2: IPV6 - Invalid Fragment "
1056					    "Header\n");
1057					if (V_fw_deny_unknown_exthdrs)
1058					    return (IP_FW_DENY);
1059					break;
1060				}
1061				args->f_id.extra =
1062				    ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
1063				ulp = NULL;
1064				break;
1065
1066			case IPPROTO_DSTOPTS:	/* RFC 2460 */
1067				PULLUP_TO(hlen, ulp, struct ip6_hbh);
1068				ext_hd |= EXT_DSTOPTS;
1069				hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1070				proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1071				ulp = NULL;
1072				break;
1073
1074			case IPPROTO_AH:	/* RFC 2402 */
1075				PULLUP_TO(hlen, ulp, struct ip6_ext);
1076				ext_hd |= EXT_AH;
1077				hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
1078				proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
1079				ulp = NULL;
1080				break;
1081
1082			case IPPROTO_ESP:	/* RFC 2406 */
1083				PULLUP_TO(hlen, ulp, uint32_t);	/* SPI, Seq# */
1084				/* Anything past Seq# is variable length and
1085				 * data past this ext. header is encrypted. */
1086				ext_hd |= EXT_ESP;
1087				break;
1088
1089			case IPPROTO_NONE:	/* RFC 2460 */
1090				/*
1091				 * Packet ends here, and IPv6 header has
1092				 * already been pulled up. If ip6e_len!=0
1093				 * then octets must be ignored.
1094				 */
1095				ulp = ip; /* non-NULL to get out of loop. */
1096				break;
1097
1098			case IPPROTO_OSPFIGP:
1099				/* XXX OSPF header check? */
1100				PULLUP_TO(hlen, ulp, struct ip6_ext);
1101				break;
1102
1103			case IPPROTO_PIM:
1104				/* XXX PIM header check? */
1105				PULLUP_TO(hlen, ulp, struct pim);
1106				break;
1107
1108			case IPPROTO_CARP:
1109				PULLUP_TO(hlen, ulp, struct carp_header);
1110				if (((struct carp_header *)ulp)->carp_version !=
1111				    CARP_VERSION)
1112					return (IP_FW_DENY);
1113				if (((struct carp_header *)ulp)->carp_type !=
1114				    CARP_ADVERTISEMENT)
1115					return (IP_FW_DENY);
1116				break;
1117
1118			case IPPROTO_IPV6:	/* RFC 2893 */
1119				PULLUP_TO(hlen, ulp, struct ip6_hdr);
1120				break;
1121
1122			case IPPROTO_IPV4:	/* RFC 2893 */
1123				PULLUP_TO(hlen, ulp, struct ip);
1124				break;
1125
1126			default:
1127				printf("IPFW2: IPV6 - Unknown Extension "
1128				    "Header(%d), ext_hd=%x\n", proto, ext_hd);
1129				if (V_fw_deny_unknown_exthdrs)
1130				    return (IP_FW_DENY);
1131				PULLUP_TO(hlen, ulp, struct ip6_ext);
1132				break;
1133			} /*switch */
1134		}
1135		ip = mtod(m, struct ip *);
1136		ip6 = (struct ip6_hdr *)ip;
1137		args->f_id.src_ip6 = ip6->ip6_src;
1138		args->f_id.dst_ip6 = ip6->ip6_dst;
1139		args->f_id.src_ip = 0;
1140		args->f_id.dst_ip = 0;
1141		args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
1142	} else if (pktlen >= sizeof(struct ip) &&
1143	    (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
1144	    	is_ipv4 = 1;
1145		hlen = ip->ip_hl << 2;
1146		args->f_id.addr_type = 4;
1147
1148		/*
1149		 * Collect parameters into local variables for faster matching.
1150		 */
1151		proto = ip->ip_p;
1152		src_ip = ip->ip_src;
1153		dst_ip = ip->ip_dst;
1154		offset = ntohs(ip->ip_off) & IP_OFFMASK;
1155		iplen = ntohs(ip->ip_len);
1156		pktlen = iplen < pktlen ? iplen : pktlen;
1157
1158		if (offset == 0) {
1159			switch (proto) {
1160			case IPPROTO_TCP:
1161				PULLUP_TO(hlen, ulp, struct tcphdr);
1162				dst_port = TCP(ulp)->th_dport;
1163				src_port = TCP(ulp)->th_sport;
1164				/* save flags for dynamic rules */
1165				args->f_id._flags = TCP(ulp)->th_flags;
1166				break;
1167
1168			case IPPROTO_SCTP:
1169				PULLUP_TO(hlen, ulp, struct sctphdr);
1170				src_port = SCTP(ulp)->src_port;
1171				dst_port = SCTP(ulp)->dest_port;
1172				break;
1173
1174			case IPPROTO_UDP:
1175				PULLUP_TO(hlen, ulp, struct udphdr);
1176				dst_port = UDP(ulp)->uh_dport;
1177				src_port = UDP(ulp)->uh_sport;
1178				break;
1179
1180			case IPPROTO_ICMP:
1181				PULLUP_TO(hlen, ulp, struct icmphdr);
1182				//args->f_id.flags = ICMP(ulp)->icmp_type;
1183				break;
1184
1185			default:
1186				break;
1187			}
1188		}
1189
1190		ip = mtod(m, struct ip *);
1191		args->f_id.src_ip = ntohl(src_ip.s_addr);
1192		args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1193	}
1194#undef PULLUP_TO
1195	if (proto) { /* we may have port numbers, store them */
1196		args->f_id.proto = proto;
1197		args->f_id.src_port = src_port = ntohs(src_port);
1198		args->f_id.dst_port = dst_port = ntohs(dst_port);
1199	}
1200
1201	IPFW_RLOCK(chain);
1202	if (! V_ipfw_vnet_ready) { /* shutting down, leave NOW. */
1203		IPFW_RUNLOCK(chain);
1204		return (IP_FW_PASS);	/* accept */
1205	}
1206	if (args->rule.slot) {
1207		/*
1208		 * Packet has already been tagged as a result of a previous
1209		 * match on rule args->rule aka args->rule_id (PIPE, QUEUE,
1210		 * REASS, NETGRAPH, DIVERT/TEE...)
1211		 * Validate the slot and continue from the next one
1212		 * if still present, otherwise do a lookup.
1213		 */
1214		f_pos = (args->rule.chain_id == chain->id) ?
1215		    args->rule.slot :
1216		    ipfw_find_rule(chain, args->rule.rulenum,
1217			args->rule.rule_id);
1218	} else {
1219		f_pos = 0;
1220	}
1221
1222	/*
1223	 * Now scan the rules, and parse microinstructions for each rule.
1224	 * We have two nested loops and an inner switch. Sometimes we
1225	 * need to break out of one or both loops, or re-enter one of
1226	 * the loops with updated variables. Loop variables are:
1227	 *
1228	 *	f_pos (outer loop) points to the current rule.
1229	 *		On output it points to the matching rule.
1230	 *	done (outer loop) is used as a flag to break the loop.
1231	 *	l (inner loop)	residual length of current rule.
1232	 *		cmd points to the current microinstruction.
1233	 *
1234	 * We break the inner loop by setting l=0 and possibly
1235	 * cmdlen=0 if we don't want to advance cmd.
1236	 * We break the outer loop by setting done=1
1237	 * We can restart the inner loop by setting l>0 and f_pos, f, cmd
1238	 * as needed.
1239	 */
1240	for (; f_pos < chain->n_rules; f_pos++) {
1241		ipfw_insn *cmd;
1242		uint32_t tablearg = 0;
1243		int l, cmdlen, skip_or; /* skip rest of OR block */
1244		struct ip_fw *f;
1245
1246		f = chain->map[f_pos];
1247		if (V_set_disable & (1 << f->set) )
1248			continue;
1249
1250		skip_or = 0;
1251		for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
1252		    l -= cmdlen, cmd += cmdlen) {
1253			int match;
1254
1255			/*
1256			 * check_body is a jump target used when we find a
1257			 * CHECK_STATE, and need to jump to the body of
1258			 * the target rule.
1259			 */
1260
1261/* check_body: */
1262			cmdlen = F_LEN(cmd);
1263			/*
1264			 * An OR block (insn_1 || .. || insn_n) has the
1265			 * F_OR bit set in all but the last instruction.
1266			 * The first match will set "skip_or", and cause
1267			 * the following instructions to be skipped until
1268			 * past the one with the F_OR bit clear.
1269			 */
1270			if (skip_or) {		/* skip this instruction */
1271				if ((cmd->len & F_OR) == 0)
1272					skip_or = 0;	/* next one is good */
1273				continue;
1274			}
1275			match = 0; /* set to 1 if we succeed */
1276
1277			switch (cmd->opcode) {
1278			/*
1279			 * The first set of opcodes compares the packet's
1280			 * fields with some pattern, setting 'match' if a
1281			 * match is found. At the end of the loop there is
1282			 * logic to deal with F_NOT and F_OR flags associated
1283			 * with the opcode.
1284			 */
1285			case O_NOP:
1286				match = 1;
1287				break;
1288
1289			case O_FORWARD_MAC:
1290				printf("ipfw: opcode %d unimplemented\n",
1291				    cmd->opcode);
1292				break;
1293
1294			case O_GID:
1295			case O_UID:
1296			case O_JAIL:
1297				/*
1298				 * We only check offset == 0 && proto != 0,
1299				 * as this ensures that we have a
1300				 * packet with the ports info.
1301				 */
1302				if (offset != 0)
1303					break;
1304				if (proto == IPPROTO_TCP ||
1305				    proto == IPPROTO_UDP)
1306					match = check_uidgid(
1307						    (ipfw_insn_u32 *)cmd,
1308						    args, &ucred_lookup,
1309#ifdef __FreeBSD__
1310						    &ucred_cache);
1311#else
1312						    (void *)&ucred_cache);
1313#endif
1314				break;
1315
1316			case O_RECV:
1317				match = iface_match(m->m_pkthdr.rcvif,
1318				    (ipfw_insn_if *)cmd);
1319				break;
1320
1321			case O_XMIT:
1322				match = iface_match(oif, (ipfw_insn_if *)cmd);
1323				break;
1324
1325			case O_VIA:
1326				match = iface_match(oif ? oif :
1327				    m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
1328				break;
1329
1330			case O_MACADDR2:
1331				if (args->eh != NULL) {	/* have MAC header */
1332					u_int32_t *want = (u_int32_t *)
1333						((ipfw_insn_mac *)cmd)->addr;
1334					u_int32_t *mask = (u_int32_t *)
1335						((ipfw_insn_mac *)cmd)->mask;
1336					u_int32_t *hdr = (u_int32_t *)args->eh;
1337
1338					match =
1339					    ( want[0] == (hdr[0] & mask[0]) &&
1340					      want[1] == (hdr[1] & mask[1]) &&
1341					      want[2] == (hdr[2] & mask[2]) );
1342				}
1343				break;
1344
1345			case O_MAC_TYPE:
1346				if (args->eh != NULL) {
1347					u_int16_t *p =
1348					    ((ipfw_insn_u16 *)cmd)->ports;
1349					int i;
1350
1351					for (i = cmdlen - 1; !match && i>0;
1352					    i--, p += 2)
1353						match = (etype >= p[0] &&
1354						    etype <= p[1]);
1355				}
1356				break;
1357
1358			case O_FRAG:
1359				match = (offset != 0);
1360				break;
1361
1362			case O_IN:	/* "out" is "not in" */
1363				match = (oif == NULL);
1364				break;
1365
1366			case O_LAYER2:
1367				match = (args->eh != NULL);
1368				break;
1369
1370			case O_DIVERTED:
1371			    {
1372				/* For diverted packets, args->rule.info
1373				 * contains the divert port (in host format)
1374				 * reason and direction.
1375				 */
1376				uint32_t i = args->rule.info;
1377				match = (i&IPFW_IS_MASK) == IPFW_IS_DIVERT &&
1378				    cmd->arg1 & ((i & IPFW_INFO_IN) ? 1 : 2);
1379			    }
1380				break;
1381
1382			case O_PROTO:
1383				/*
1384				 * We do not allow an arg of 0 so the
1385				 * check of "proto" only suffices.
1386				 */
1387				match = (proto == cmd->arg1);
1388				break;
1389
1390			case O_IP_SRC:
1391				match = is_ipv4 &&
1392				    (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1393				    src_ip.s_addr);
1394				break;
1395
1396			case O_IP_SRC_LOOKUP:
1397			case O_IP_DST_LOOKUP:
1398				if (is_ipv4) {
1399				    uint32_t key =
1400					(cmd->opcode == O_IP_DST_LOOKUP) ?
1401					    dst_ip.s_addr : src_ip.s_addr;
1402				    uint32_t v = 0;
1403
1404				    if (cmdlen > F_INSN_SIZE(ipfw_insn_u32)) {
1405					/* generic lookup. The key must be
1406					 * in 32bit big-endian format.
1407					 */
1408					v = ((ipfw_insn_u32 *)cmd)->d[1];
1409					if (v == 0)
1410					    key = dst_ip.s_addr;
1411					else if (v == 1)
1412					    key = src_ip.s_addr;
1413					else if (v == 6) /* dscp */
1414					    key = (ip->ip_tos >> 2) & 0x3f;
1415					else if (offset != 0)
1416					    break;
1417					else if (proto != IPPROTO_TCP &&
1418						proto != IPPROTO_UDP)
1419					    break;
1420					else if (v == 2)
1421					    key = htonl(dst_port);
1422					else if (v == 3)
1423					    key = htonl(src_port);
1424					else if (v == 4 || v == 5) {
1425					    check_uidgid(
1426						(ipfw_insn_u32 *)cmd,
1427						args, &ucred_lookup,
1428#ifdef __FreeBSD__
1429						&ucred_cache);
1430					    if (v == 4 /* O_UID */)
1431						key = ucred_cache->cr_uid;
1432					    else if (v == 5 /* O_JAIL */)
1433						key = ucred_cache->cr_prison->pr_id;
1434#else /* !__FreeBSD__ */
1435						(void *)&ucred_cache);
1436					    if (v ==4 /* O_UID */)
1437						key = ucred_cache.uid;
1438					    else if (v == 5 /* O_JAIL */)
1439						key = ucred_cache.xid;
1440#endif /* !__FreeBSD__ */
1441					    key = htonl(key);
1442					} else
1443					    break;
1444				    }
1445				    match = ipfw_lookup_table(chain,
1446					cmd->arg1, key, &v);
1447				    if (!match)
1448					break;
1449				    if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
1450					match =
1451					    ((ipfw_insn_u32 *)cmd)->d[0] == v;
1452				    else
1453					tablearg = v;
1454				}
1455				break;
1456
1457			case O_IP_SRC_MASK:
1458			case O_IP_DST_MASK:
1459				if (is_ipv4) {
1460				    uint32_t a =
1461					(cmd->opcode == O_IP_DST_MASK) ?
1462					    dst_ip.s_addr : src_ip.s_addr;
1463				    uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
1464				    int i = cmdlen-1;
1465
1466				    for (; !match && i>0; i-= 2, p+= 2)
1467					match = (p[0] == (a & p[1]));
1468				}
1469				break;
1470
1471			case O_IP_SRC_ME:
1472				if (is_ipv4) {
1473					struct ifnet *tif;
1474
1475					INADDR_TO_IFP(src_ip, tif);
1476					match = (tif != NULL);
1477					break;
1478				}
1479#ifdef INET6
1480				/* FALLTHROUGH */
1481			case O_IP6_SRC_ME:
1482				match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
1483#endif
1484				break;
1485
1486			case O_IP_DST_SET:
1487			case O_IP_SRC_SET:
1488				if (is_ipv4) {
1489					u_int32_t *d = (u_int32_t *)(cmd+1);
1490					u_int32_t addr =
1491					    cmd->opcode == O_IP_DST_SET ?
1492						args->f_id.dst_ip :
1493						args->f_id.src_ip;
1494
1495					    if (addr < d[0])
1496						    break;
1497					    addr -= d[0]; /* subtract base */
1498					    match = (addr < cmd->arg1) &&
1499						( d[ 1 + (addr>>5)] &
1500						  (1<<(addr & 0x1f)) );
1501				}
1502				break;
1503
1504			case O_IP_DST:
1505				match = is_ipv4 &&
1506				    (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1507				    dst_ip.s_addr);
1508				break;
1509
1510			case O_IP_DST_ME:
1511				if (is_ipv4) {
1512					struct ifnet *tif;
1513
1514					INADDR_TO_IFP(dst_ip, tif);
1515					match = (tif != NULL);
1516					break;
1517				}
1518#ifdef INET6
1519				/* FALLTHROUGH */
1520			case O_IP6_DST_ME:
1521				match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
1522#endif
1523				break;
1524
1525
1526			case O_IP_SRCPORT:
1527			case O_IP_DSTPORT:
1528				/*
1529				 * offset == 0 && proto != 0 is enough
1530				 * to guarantee that we have a
1531				 * packet with port info.
1532				 */
1533				if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
1534				    && offset == 0) {
1535					u_int16_t x =
1536					    (cmd->opcode == O_IP_SRCPORT) ?
1537						src_port : dst_port ;
1538					u_int16_t *p =
1539					    ((ipfw_insn_u16 *)cmd)->ports;
1540					int i;
1541
1542					for (i = cmdlen - 1; !match && i>0;
1543					    i--, p += 2)
1544						match = (x>=p[0] && x<=p[1]);
1545				}
1546				break;
1547
1548			case O_ICMPTYPE:
1549				match = (offset == 0 && proto==IPPROTO_ICMP &&
1550				    icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
1551				break;
1552
1553#ifdef INET6
1554			case O_ICMP6TYPE:
1555				match = is_ipv6 && offset == 0 &&
1556				    proto==IPPROTO_ICMPV6 &&
1557				    icmp6type_match(
1558					ICMP6(ulp)->icmp6_type,
1559					(ipfw_insn_u32 *)cmd);
1560				break;
1561#endif /* INET6 */
1562
1563			case O_IPOPT:
1564				match = (is_ipv4 &&
1565				    ipopts_match(ip, cmd) );
1566				break;
1567
1568			case O_IPVER:
1569				match = (is_ipv4 &&
1570				    cmd->arg1 == ip->ip_v);
1571				break;
1572
1573			case O_IPID:
1574			case O_IPLEN:
1575			case O_IPTTL:
1576				if (is_ipv4) {	/* only for IP packets */
1577				    uint16_t x;
1578				    uint16_t *p;
1579				    int i;
1580
1581				    if (cmd->opcode == O_IPLEN)
1582					x = iplen;
1583				    else if (cmd->opcode == O_IPTTL)
1584					x = ip->ip_ttl;
1585				    else /* must be IPID */
1586					x = ntohs(ip->ip_id);
1587				    if (cmdlen == 1) {
1588					match = (cmd->arg1 == x);
1589					break;
1590				    }
1591				    /* otherwise we have ranges */
1592				    p = ((ipfw_insn_u16 *)cmd)->ports;
1593				    i = cmdlen - 1;
1594				    for (; !match && i>0; i--, p += 2)
1595					match = (x >= p[0] && x <= p[1]);
1596				}
1597				break;
1598
1599			case O_IPPRECEDENCE:
1600				match = (is_ipv4 &&
1601				    (cmd->arg1 == (ip->ip_tos & 0xe0)) );
1602				break;
1603
1604			case O_IPTOS:
1605				match = (is_ipv4 &&
1606				    flags_match(cmd, ip->ip_tos));
1607				break;
1608
1609			case O_TCPDATALEN:
1610				if (proto == IPPROTO_TCP && offset == 0) {
1611				    struct tcphdr *tcp;
1612				    uint16_t x;
1613				    uint16_t *p;
1614				    int i;
1615
1616				    tcp = TCP(ulp);
1617				    x = iplen -
1618					((ip->ip_hl + tcp->th_off) << 2);
1619				    if (cmdlen == 1) {
1620					match = (cmd->arg1 == x);
1621					break;
1622				    }
1623				    /* otherwise we have ranges */
1624				    p = ((ipfw_insn_u16 *)cmd)->ports;
1625				    i = cmdlen - 1;
1626				    for (; !match && i>0; i--, p += 2)
1627					match = (x >= p[0] && x <= p[1]);
1628				}
1629				break;
1630
1631			case O_TCPFLAGS:
1632				match = (proto == IPPROTO_TCP && offset == 0 &&
1633				    flags_match(cmd, TCP(ulp)->th_flags));
1634				break;
1635
1636			case O_TCPOPTS:
1637				PULLUP_LEN(hlen, ulp, (TCP(ulp)->th_off << 2));
1638				match = (proto == IPPROTO_TCP && offset == 0 &&
1639				    tcpopts_match(TCP(ulp), cmd));
1640				break;
1641
1642			case O_TCPSEQ:
1643				match = (proto == IPPROTO_TCP && offset == 0 &&
1644				    ((ipfw_insn_u32 *)cmd)->d[0] ==
1645					TCP(ulp)->th_seq);
1646				break;
1647
1648			case O_TCPACK:
1649				match = (proto == IPPROTO_TCP && offset == 0 &&
1650				    ((ipfw_insn_u32 *)cmd)->d[0] ==
1651					TCP(ulp)->th_ack);
1652				break;
1653
1654			case O_TCPWIN:
1655				match = (proto == IPPROTO_TCP && offset == 0 &&
1656				    cmd->arg1 == TCP(ulp)->th_win);
1657				break;
1658
1659			case O_ESTAB:
1660				/* reject packets which have SYN only */
1661				/* XXX should i also check for TH_ACK ? */
1662				match = (proto == IPPROTO_TCP && offset == 0 &&
1663				    (TCP(ulp)->th_flags &
1664				     (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
1665				break;
1666
1667			case O_ALTQ: {
1668				struct pf_mtag *at;
1669				ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
1670
1671				match = 1;
1672				at = pf_find_mtag(m);
1673				if (at != NULL && at->qid != 0)
1674					break;
1675				at = pf_get_mtag(m);
1676				if (at == NULL) {
1677					/*
1678					 * Let the packet fall back to the
1679					 * default ALTQ.
1680					 */
1681					break;
1682				}
1683				at->qid = altq->qid;
1684				at->hdr = ip;
1685				break;
1686			}
1687
1688			case O_LOG:
1689				ipfw_log(f, hlen, args, m,
1690					    oif, offset, tablearg, ip);
1691				match = 1;
1692				break;
1693
1694			case O_PROB:
1695				match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
1696				break;
1697
1698			case O_VERREVPATH:
1699				/* Outgoing packets automatically pass/match */
1700				match = ((oif != NULL) ||
1701				    (m->m_pkthdr.rcvif == NULL) ||
1702				    (
1703#ifdef INET6
1704				    is_ipv6 ?
1705					verify_path6(&(args->f_id.src_ip6),
1706					    m->m_pkthdr.rcvif) :
1707#endif
1708				    verify_path(src_ip, m->m_pkthdr.rcvif,
1709				        args->f_id.fib)));
1710				break;
1711
1712			case O_VERSRCREACH:
1713				/* Outgoing packets automatically pass/match */
1714				match = (hlen > 0 && ((oif != NULL) ||
1715#ifdef INET6
1716				    is_ipv6 ?
1717				        verify_path6(&(args->f_id.src_ip6),
1718				            NULL) :
1719#endif
1720				    verify_path(src_ip, NULL, args->f_id.fib)));
1721				break;
1722
1723			case O_ANTISPOOF:
1724				/* Outgoing packets automatically pass/match */
1725				if (oif == NULL && hlen > 0 &&
1726				    (  (is_ipv4 && in_localaddr(src_ip))
1727#ifdef INET6
1728				    || (is_ipv6 &&
1729				        in6_localaddr(&(args->f_id.src_ip6)))
1730#endif
1731				    ))
1732					match =
1733#ifdef INET6
1734					    is_ipv6 ? verify_path6(
1735					        &(args->f_id.src_ip6),
1736					        m->m_pkthdr.rcvif) :
1737#endif
1738					    verify_path(src_ip,
1739					    	m->m_pkthdr.rcvif,
1740					        args->f_id.fib);
1741				else
1742					match = 1;
1743				break;
1744
1745			case O_IPSEC:
1746#ifdef IPSEC
1747				match = (m_tag_find(m,
1748				    PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
1749#endif
1750				/* otherwise no match */
1751				break;
1752
1753#ifdef INET6
1754			case O_IP6_SRC:
1755				match = is_ipv6 &&
1756				    IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
1757				    &((ipfw_insn_ip6 *)cmd)->addr6);
1758				break;
1759
1760			case O_IP6_DST:
1761				match = is_ipv6 &&
1762				IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
1763				    &((ipfw_insn_ip6 *)cmd)->addr6);
1764				break;
1765			case O_IP6_SRC_MASK:
1766			case O_IP6_DST_MASK:
1767				if (is_ipv6) {
1768					int i = cmdlen - 1;
1769					struct in6_addr p;
1770					struct in6_addr *d =
1771					    &((ipfw_insn_ip6 *)cmd)->addr6;
1772
1773					for (; !match && i > 0; d += 2,
1774					    i -= F_INSN_SIZE(struct in6_addr)
1775					    * 2) {
1776						p = (cmd->opcode ==
1777						    O_IP6_SRC_MASK) ?
1778						    args->f_id.src_ip6:
1779						    args->f_id.dst_ip6;
1780						APPLY_MASK(&p, &d[1]);
1781						match =
1782						    IN6_ARE_ADDR_EQUAL(&d[0],
1783						    &p);
1784					}
1785				}
1786				break;
1787
1788			case O_FLOW6ID:
1789				match = is_ipv6 &&
1790				    flow6id_match(args->f_id.flow_id6,
1791				    (ipfw_insn_u32 *) cmd);
1792				break;
1793
1794			case O_EXT_HDR:
1795				match = is_ipv6 &&
1796				    (ext_hd & ((ipfw_insn *) cmd)->arg1);
1797				break;
1798
1799			case O_IP6:
1800				match = is_ipv6;
1801				break;
1802#endif
1803
1804			case O_IP4:
1805				match = is_ipv4;
1806				break;
1807
1808			case O_TAG: {
1809				struct m_tag *mtag;
1810				uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
1811				    tablearg : cmd->arg1;
1812
1813				/* Packet is already tagged with this tag? */
1814				mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
1815
1816				/* We have `untag' action when F_NOT flag is
1817				 * present. And we must remove this mtag from
1818				 * mbuf and reset `match' to zero (`match' will
1819				 * be inversed later).
1820				 * Otherwise we should allocate new mtag and
1821				 * push it into mbuf.
1822				 */
1823				if (cmd->len & F_NOT) { /* `untag' action */
1824					if (mtag != NULL)
1825						m_tag_delete(m, mtag);
1826					match = 0;
1827				} else {
1828					if (mtag == NULL) {
1829						mtag = m_tag_alloc( MTAG_IPFW,
1830						    tag, 0, M_NOWAIT);
1831						if (mtag != NULL)
1832							m_tag_prepend(m, mtag);
1833					}
1834					match = 1;
1835				}
1836				break;
1837			}
1838
1839			case O_FIB: /* try match the specified fib */
1840				if (args->f_id.fib == cmd->arg1)
1841					match = 1;
1842				break;
1843
1844			case O_SOCKARG:	{
1845				struct inpcb *inp = args->inp;
1846				struct inpcbinfo *pi;
1847
1848				if (is_ipv6) /* XXX can we remove this ? */
1849					break;
1850
1851				if (proto == IPPROTO_TCP)
1852					pi = &V_tcbinfo;
1853				else if (proto == IPPROTO_UDP)
1854					pi = &V_udbinfo;
1855				else
1856					break;
1857
1858				/*
1859				 * XXXRW: so_user_cookie should almost
1860				 * certainly be inp_user_cookie?
1861				 */
1862
1863				/* For incomming packet, lookup up the
1864				inpcb using the src/dest ip/port tuple */
1865				if (inp == NULL) {
1866					inp = in_pcblookup(pi,
1867						src_ip, htons(src_port),
1868						dst_ip, htons(dst_port),
1869						INPLOOKUP_RLOCKPCB, NULL);
1870					if (inp != NULL) {
1871						tablearg =
1872						    inp->inp_socket->so_user_cookie;
1873						if (tablearg)
1874							match = 1;
1875						INP_RUNLOCK(inp);
1876					}
1877				} else {
1878					if (inp->inp_socket) {
1879						tablearg =
1880						    inp->inp_socket->so_user_cookie;
1881						if (tablearg)
1882							match = 1;
1883					}
1884				}
1885				break;
1886			}
1887
1888			case O_TAGGED: {
1889				struct m_tag *mtag;
1890				uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
1891				    tablearg : cmd->arg1;
1892
1893				if (cmdlen == 1) {
1894					match = m_tag_locate(m, MTAG_IPFW,
1895					    tag, NULL) != NULL;
1896					break;
1897				}
1898
1899				/* we have ranges */
1900				for (mtag = m_tag_first(m);
1901				    mtag != NULL && !match;
1902				    mtag = m_tag_next(m, mtag)) {
1903					uint16_t *p;
1904					int i;
1905
1906					if (mtag->m_tag_cookie != MTAG_IPFW)
1907						continue;
1908
1909					p = ((ipfw_insn_u16 *)cmd)->ports;
1910					i = cmdlen - 1;
1911					for(; !match && i > 0; i--, p += 2)
1912						match =
1913						    mtag->m_tag_id >= p[0] &&
1914						    mtag->m_tag_id <= p[1];
1915				}
1916				break;
1917			}
1918
1919			/*
1920			 * The second set of opcodes represents 'actions',
1921			 * i.e. the terminal part of a rule once the packet
1922			 * matches all previous patterns.
1923			 * Typically there is only one action for each rule,
1924			 * and the opcode is stored at the end of the rule
1925			 * (but there are exceptions -- see below).
1926			 *
1927			 * In general, here we set retval and terminate the
1928			 * outer loop (would be a 'break 3' in some language,
1929			 * but we need to set l=0, done=1)
1930			 *
1931			 * Exceptions:
1932			 * O_COUNT and O_SKIPTO actions:
1933			 *   instead of terminating, we jump to the next rule
1934			 *   (setting l=0), or to the SKIPTO target (setting
1935			 *   f/f_len, cmd and l as needed), respectively.
1936			 *
1937			 * O_TAG, O_LOG and O_ALTQ action parameters:
1938			 *   perform some action and set match = 1;
1939			 *
1940			 * O_LIMIT and O_KEEP_STATE: these opcodes are
1941			 *   not real 'actions', and are stored right
1942			 *   before the 'action' part of the rule.
1943			 *   These opcodes try to install an entry in the
1944			 *   state tables; if successful, we continue with
1945			 *   the next opcode (match=1; break;), otherwise
1946			 *   the packet must be dropped (set retval,
1947			 *   break loops with l=0, done=1)
1948			 *
1949			 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
1950			 *   cause a lookup of the state table, and a jump
1951			 *   to the 'action' part of the parent rule
1952			 *   if an entry is found, or
1953			 *   (CHECK_STATE only) a jump to the next rule if
1954			 *   the entry is not found.
1955			 *   The result of the lookup is cached so that
1956			 *   further instances of these opcodes become NOPs.
1957			 *   The jump to the next rule is done by setting
1958			 *   l=0, cmdlen=0.
1959			 */
1960			case O_LIMIT:
1961			case O_KEEP_STATE:
1962				if (ipfw_install_state(f,
1963				    (ipfw_insn_limit *)cmd, args, tablearg)) {
1964					/* error or limit violation */
1965					retval = IP_FW_DENY;
1966					l = 0;	/* exit inner loop */
1967					done = 1; /* exit outer loop */
1968				}
1969				match = 1;
1970				break;
1971
1972			case O_PROBE_STATE:
1973			case O_CHECK_STATE:
1974				/*
1975				 * dynamic rules are checked at the first
1976				 * keep-state or check-state occurrence,
1977				 * with the result being stored in dyn_dir.
1978				 * The compiler introduces a PROBE_STATE
1979				 * instruction for us when we have a
1980				 * KEEP_STATE (because PROBE_STATE needs
1981				 * to be run first).
1982				 */
1983				if (dyn_dir == MATCH_UNKNOWN &&
1984				    (q = ipfw_lookup_dyn_rule(&args->f_id,
1985				     &dyn_dir, proto == IPPROTO_TCP ?
1986					TCP(ulp) : NULL))
1987					!= NULL) {
1988					/*
1989					 * Found dynamic entry, update stats
1990					 * and jump to the 'action' part of
1991					 * the parent rule by setting
1992					 * f, cmd, l and clearing cmdlen.
1993					 */
1994					q->pcnt++;
1995					q->bcnt += pktlen;
1996					/* XXX we would like to have f_pos
1997					 * readily accessible in the dynamic
1998				         * rule, instead of having to
1999					 * lookup q->rule.
2000					 */
2001					f = q->rule;
2002					f_pos = ipfw_find_rule(chain,
2003						f->rulenum, f->id);
2004					cmd = ACTION_PTR(f);
2005					l = f->cmd_len - f->act_ofs;
2006					ipfw_dyn_unlock();
2007					cmdlen = 0;
2008					match = 1;
2009					break;
2010				}
2011				/*
2012				 * Dynamic entry not found. If CHECK_STATE,
2013				 * skip to next rule, if PROBE_STATE just
2014				 * ignore and continue with next opcode.
2015				 */
2016				if (cmd->opcode == O_CHECK_STATE)
2017					l = 0;	/* exit inner loop */
2018				match = 1;
2019				break;
2020
2021			case O_ACCEPT:
2022				retval = 0;	/* accept */
2023				l = 0;		/* exit inner loop */
2024				done = 1;	/* exit outer loop */
2025				break;
2026
2027			case O_PIPE:
2028			case O_QUEUE:
2029				set_match(args, f_pos, chain);
2030				args->rule.info = (cmd->arg1 == IP_FW_TABLEARG) ?
2031					tablearg : cmd->arg1;
2032				if (cmd->opcode == O_PIPE)
2033					args->rule.info |= IPFW_IS_PIPE;
2034				if (V_fw_one_pass)
2035					args->rule.info |= IPFW_ONEPASS;
2036				retval = IP_FW_DUMMYNET;
2037				l = 0;          /* exit inner loop */
2038				done = 1;       /* exit outer loop */
2039				break;
2040
2041			case O_DIVERT:
2042			case O_TEE:
2043				if (args->eh) /* not on layer 2 */
2044				    break;
2045				/* otherwise this is terminal */
2046				l = 0;		/* exit inner loop */
2047				done = 1;	/* exit outer loop */
2048				retval = (cmd->opcode == O_DIVERT) ?
2049					IP_FW_DIVERT : IP_FW_TEE;
2050				set_match(args, f_pos, chain);
2051				args->rule.info = (cmd->arg1 == IP_FW_TABLEARG) ?
2052				    tablearg : cmd->arg1;
2053				break;
2054
2055			case O_COUNT:
2056				f->pcnt++;	/* update stats */
2057				f->bcnt += pktlen;
2058				f->timestamp = time_uptime;
2059				l = 0;		/* exit inner loop */
2060				break;
2061
2062			case O_SKIPTO:
2063			    f->pcnt++;	/* update stats */
2064			    f->bcnt += pktlen;
2065			    f->timestamp = time_uptime;
2066			    /* If possible use cached f_pos (in f->next_rule),
2067			     * whose version is written in f->next_rule
2068			     * (horrible hacks to avoid changing the ABI).
2069			     */
2070			    if (cmd->arg1 != IP_FW_TABLEARG &&
2071				    (uintptr_t)f->x_next == chain->id) {
2072				f_pos = (uintptr_t)f->next_rule;
2073			    } else {
2074				int i = (cmd->arg1 == IP_FW_TABLEARG) ?
2075					tablearg : cmd->arg1;
2076				/* make sure we do not jump backward */
2077				if (i <= f->rulenum)
2078				    i = f->rulenum + 1;
2079				f_pos = ipfw_find_rule(chain, i, 0);
2080				/* update the cache */
2081				if (cmd->arg1 != IP_FW_TABLEARG) {
2082				    f->next_rule =
2083					(void *)(uintptr_t)f_pos;
2084				    f->x_next =
2085					(void *)(uintptr_t)chain->id;
2086				}
2087			    }
2088			    /*
2089			     * Skip disabled rules, and re-enter
2090			     * the inner loop with the correct
2091			     * f_pos, f, l and cmd.
2092			     * Also clear cmdlen and skip_or
2093			     */
2094			    for (; f_pos < chain->n_rules - 1 &&
2095				    (V_set_disable &
2096				     (1 << chain->map[f_pos]->set));
2097				    f_pos++)
2098				;
2099			    /* Re-enter the inner loop at the skipto rule. */
2100			    f = chain->map[f_pos];
2101			    l = f->cmd_len;
2102			    cmd = f->cmd;
2103			    match = 1;
2104			    cmdlen = 0;
2105			    skip_or = 0;
2106			    continue;
2107			    break;	/* not reached */
2108
2109			case O_CALLRETURN: {
2110				/*
2111				 * Implementation of `subroutine' call/return,
2112				 * in the stack carried in an mbuf tag. This
2113				 * is different from `skipto' in that any call
2114				 * address is possible (`skipto' must prevent
2115				 * backward jumps to avoid endless loops).
2116				 * We have `return' action when F_NOT flag is
2117				 * present. The `m_tag_id' field is used as
2118				 * stack pointer.
2119				 */
2120				struct m_tag *mtag;
2121				uint16_t jmpto, *stack;
2122
2123#define	IS_CALL		((cmd->len & F_NOT) == 0)
2124#define	IS_RETURN	((cmd->len & F_NOT) != 0)
2125				/*
2126				 * Hand-rolled version of m_tag_locate() with
2127				 * wildcard `type'.
2128				 * If not already tagged, allocate new tag.
2129				 */
2130				mtag = m_tag_first(m);
2131				while (mtag != NULL) {
2132					if (mtag->m_tag_cookie ==
2133					    MTAG_IPFW_CALL)
2134						break;
2135					mtag = m_tag_next(m, mtag);
2136				}
2137				if (mtag == NULL && IS_CALL) {
2138					mtag = m_tag_alloc(MTAG_IPFW_CALL, 0,
2139					    IPFW_CALLSTACK_SIZE *
2140					    sizeof(uint16_t), M_NOWAIT);
2141					if (mtag != NULL)
2142						m_tag_prepend(m, mtag);
2143				}
2144
2145				/*
2146				 * On error both `call' and `return' just
2147				 * continue with next rule.
2148				 */
2149				if (IS_RETURN && (mtag == NULL ||
2150				    mtag->m_tag_id == 0)) {
2151					l = 0;		/* exit inner loop */
2152					break;
2153				}
2154				if (IS_CALL && (mtag == NULL ||
2155				    mtag->m_tag_id >= IPFW_CALLSTACK_SIZE)) {
2156					printf("ipfw: call stack error, "
2157					    "go to next rule\n");
2158					l = 0;		/* exit inner loop */
2159					break;
2160				}
2161
2162				f->pcnt++;	/* update stats */
2163				f->bcnt += pktlen;
2164				f->timestamp = time_uptime;
2165				stack = (uint16_t *)(mtag + 1);
2166
2167				/*
2168				 * The `call' action may use cached f_pos
2169				 * (in f->next_rule), whose version is written
2170				 * in f->next_rule.
2171				 * The `return' action, however, doesn't have
2172				 * fixed jump address in cmd->arg1 and can't use
2173				 * cache.
2174				 */
2175				if (IS_CALL) {
2176					stack[mtag->m_tag_id] = f->rulenum;
2177					mtag->m_tag_id++;
2178					if (cmd->arg1 != IP_FW_TABLEARG &&
2179					    (uintptr_t)f->x_next == chain->id) {
2180						f_pos = (uintptr_t)f->next_rule;
2181					} else {
2182						jmpto = (cmd->arg1 ==
2183						    IP_FW_TABLEARG) ? tablearg:
2184						    cmd->arg1;
2185						f_pos = ipfw_find_rule(chain,
2186						    jmpto, 0);
2187						/* update the cache */
2188						if (cmd->arg1 !=
2189						    IP_FW_TABLEARG) {
2190							f->next_rule =
2191							    (void *)(uintptr_t)
2192							    f_pos;
2193							f->x_next =
2194							    (void *)(uintptr_t)
2195							    chain->id;
2196						}
2197					}
2198				} else {	/* `return' action */
2199					mtag->m_tag_id--;
2200					jmpto = stack[mtag->m_tag_id] + 1;
2201					f_pos = ipfw_find_rule(chain, jmpto, 0);
2202				}
2203
2204				/*
2205				 * Skip disabled rules, and re-enter
2206				 * the inner loop with the correct
2207				 * f_pos, f, l and cmd.
2208				 * Also clear cmdlen and skip_or
2209				 */
2210				for (; f_pos < chain->n_rules - 1 &&
2211				    (V_set_disable &
2212				    (1 << chain->map[f_pos]->set)); f_pos++)
2213					;
2214				/* Re-enter the inner loop at the dest rule. */
2215				f = chain->map[f_pos];
2216				l = f->cmd_len;
2217				cmd = f->cmd;
2218				cmdlen = 0;
2219				skip_or = 0;
2220				continue;
2221				break;	/* NOTREACHED */
2222			}
2223#undef IS_CALL
2224#undef IS_RETURN
2225
2226			case O_REJECT:
2227				/*
2228				 * Drop the packet and send a reject notice
2229				 * if the packet is not ICMP (or is an ICMP
2230				 * query), and it is not multicast/broadcast.
2231				 */
2232				if (hlen > 0 && is_ipv4 && offset == 0 &&
2233				    (proto != IPPROTO_ICMP ||
2234				     is_icmp_query(ICMP(ulp))) &&
2235				    !(m->m_flags & (M_BCAST|M_MCAST)) &&
2236				    !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2237					send_reject(args, cmd->arg1, iplen, ip);
2238					m = args->m;
2239				}
2240				/* FALLTHROUGH */
2241#ifdef INET6
2242			case O_UNREACH6:
2243				if (hlen > 0 && is_ipv6 &&
2244				    ((offset & IP6F_OFF_MASK) == 0) &&
2245				    (proto != IPPROTO_ICMPV6 ||
2246				     (is_icmp6_query(icmp6_type) == 1)) &&
2247				    !(m->m_flags & (M_BCAST|M_MCAST)) &&
2248				    !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
2249					send_reject6(
2250					    args, cmd->arg1, hlen,
2251					    (struct ip6_hdr *)ip);
2252					m = args->m;
2253				}
2254				/* FALLTHROUGH */
2255#endif
2256			case O_DENY:
2257				retval = IP_FW_DENY;
2258				l = 0;		/* exit inner loop */
2259				done = 1;	/* exit outer loop */
2260				break;
2261
2262			case O_FORWARD_IP:
2263				if (args->eh)	/* not valid on layer2 pkts */
2264					break;
2265				if (q == NULL || q->rule != f ||
2266				    dyn_dir == MATCH_FORWARD) {
2267				    struct sockaddr_in *sa;
2268				    sa = &(((ipfw_insn_sa *)cmd)->sa);
2269				    if (sa->sin_addr.s_addr == INADDR_ANY) {
2270					bcopy(sa, &args->hopstore,
2271							sizeof(*sa));
2272					args->hopstore.sin_addr.s_addr =
2273						    htonl(tablearg);
2274					args->next_hop = &args->hopstore;
2275				    } else {
2276					args->next_hop = sa;
2277				    }
2278				}
2279				retval = IP_FW_PASS;
2280				l = 0;          /* exit inner loop */
2281				done = 1;       /* exit outer loop */
2282				break;
2283
2284			case O_NETGRAPH:
2285			case O_NGTEE:
2286				set_match(args, f_pos, chain);
2287				args->rule.info = (cmd->arg1 == IP_FW_TABLEARG) ?
2288					tablearg : cmd->arg1;
2289				if (V_fw_one_pass)
2290					args->rule.info |= IPFW_ONEPASS;
2291				retval = (cmd->opcode == O_NETGRAPH) ?
2292				    IP_FW_NETGRAPH : IP_FW_NGTEE;
2293				l = 0;          /* exit inner loop */
2294				done = 1;       /* exit outer loop */
2295				break;
2296
2297			case O_SETFIB: {
2298				uint32_t fib;
2299
2300				f->pcnt++;	/* update stats */
2301				f->bcnt += pktlen;
2302				f->timestamp = time_uptime;
2303				fib = (cmd->arg1 == IP_FW_TABLEARG) ? tablearg:
2304				    cmd->arg1;
2305				if (fib >= rt_numfibs)
2306					fib = 0;
2307				M_SETFIB(m, fib);
2308				args->f_id.fib = fib;
2309				l = 0;		/* exit inner loop */
2310				break;
2311		        }
2312
2313			case O_NAT:
2314 				if (!IPFW_NAT_LOADED) {
2315				    retval = IP_FW_DENY;
2316				} else {
2317				    struct cfg_nat *t;
2318				    int nat_id;
2319
2320				    set_match(args, f_pos, chain);
2321				    /* Check if this is 'global' nat rule */
2322				    if (cmd->arg1 == 0) {
2323					    retval = ipfw_nat_ptr(args, NULL, m);
2324					    l = 0;
2325					    done = 1;
2326					    break;
2327				    }
2328				    t = ((ipfw_insn_nat *)cmd)->nat;
2329				    if (t == NULL) {
2330					nat_id = (cmd->arg1 == IP_FW_TABLEARG) ?
2331						tablearg : cmd->arg1;
2332					t = (*lookup_nat_ptr)(&chain->nat, nat_id);
2333
2334					if (t == NULL) {
2335					    retval = IP_FW_DENY;
2336					    l = 0;	/* exit inner loop */
2337					    done = 1;	/* exit outer loop */
2338					    break;
2339					}
2340					if (cmd->arg1 != IP_FW_TABLEARG)
2341					    ((ipfw_insn_nat *)cmd)->nat = t;
2342				    }
2343				    retval = ipfw_nat_ptr(args, t, m);
2344				}
2345				l = 0;          /* exit inner loop */
2346				done = 1;       /* exit outer loop */
2347				break;
2348
2349			case O_REASS: {
2350				int ip_off;
2351
2352				f->pcnt++;
2353				f->bcnt += pktlen;
2354				l = 0;	/* in any case exit inner loop */
2355				ip_off = ntohs(ip->ip_off);
2356
2357				/* if not fragmented, go to next rule */
2358				if ((ip_off & (IP_MF | IP_OFFMASK)) == 0)
2359				    break;
2360				/*
2361				 * ip_reass() expects len & off in host
2362				 * byte order.
2363				 */
2364				SET_HOST_IPLEN(ip);
2365
2366				args->m = m = ip_reass(m);
2367
2368				/*
2369				 * do IP header checksum fixup.
2370				 */
2371				if (m == NULL) { /* fragment got swallowed */
2372				    retval = IP_FW_DENY;
2373				} else { /* good, packet complete */
2374				    int hlen;
2375
2376				    ip = mtod(m, struct ip *);
2377				    hlen = ip->ip_hl << 2;
2378				    SET_NET_IPLEN(ip);
2379				    ip->ip_sum = 0;
2380				    if (hlen == sizeof(struct ip))
2381					ip->ip_sum = in_cksum_hdr(ip);
2382				    else
2383					ip->ip_sum = in_cksum(m, hlen);
2384				    retval = IP_FW_REASS;
2385				    set_match(args, f_pos, chain);
2386				}
2387				done = 1;	/* exit outer loop */
2388				break;
2389			}
2390
2391			default:
2392				panic("-- unknown opcode %d\n", cmd->opcode);
2393			} /* end of switch() on opcodes */
2394			/*
2395			 * if we get here with l=0, then match is irrelevant.
2396			 */
2397
2398			if (cmd->len & F_NOT)
2399				match = !match;
2400
2401			if (match) {
2402				if (cmd->len & F_OR)
2403					skip_or = 1;
2404			} else {
2405				if (!(cmd->len & F_OR)) /* not an OR block, */
2406					break;		/* try next rule    */
2407			}
2408
2409		}	/* end of inner loop, scan opcodes */
2410#undef PULLUP_LEN
2411
2412		if (done)
2413			break;
2414
2415/* next_rule:; */	/* try next rule		*/
2416
2417	}		/* end of outer for, scan rules */
2418
2419	if (done) {
2420		struct ip_fw *rule = chain->map[f_pos];
2421		/* Update statistics */
2422		rule->pcnt++;
2423		rule->bcnt += pktlen;
2424		rule->timestamp = time_uptime;
2425	} else {
2426		retval = IP_FW_DENY;
2427		printf("ipfw: ouch!, skip past end of rules, denying packet\n");
2428	}
2429	IPFW_RUNLOCK(chain);
2430#ifdef __FreeBSD__
2431	if (ucred_cache != NULL)
2432		crfree(ucred_cache);
2433#endif
2434	return (retval);
2435
2436pullup_failed:
2437	if (V_fw_verbose)
2438		printf("ipfw: pullup failed\n");
2439	return (IP_FW_DENY);
2440}
2441
2442/*
2443 * Module and VNET glue
2444 */
2445
2446/*
2447 * Stuff that must be initialised only on boot or module load
2448 */
2449static int
2450ipfw_init(void)
2451{
2452	int error = 0;
2453
2454	ipfw_dyn_attach();
2455	/*
2456 	 * Only print out this stuff the first time around,
2457	 * when called from the sysinit code.
2458	 */
2459	printf("ipfw2 "
2460#ifdef INET6
2461		"(+ipv6) "
2462#endif
2463		"initialized, divert %s, nat %s, "
2464		"rule-based forwarding "
2465#ifdef IPFIREWALL_FORWARD
2466		"enabled, "
2467#else
2468		"disabled, "
2469#endif
2470		"default to %s, logging ",
2471#ifdef IPDIVERT
2472		"enabled",
2473#else
2474		"loadable",
2475#endif
2476#ifdef IPFIREWALL_NAT
2477		"enabled",
2478#else
2479		"loadable",
2480#endif
2481		default_to_accept ? "accept" : "deny");
2482
2483	/*
2484	 * Note: V_xxx variables can be accessed here but the vnet specific
2485	 * initializer may not have been called yet for the VIMAGE case.
2486	 * Tuneables will have been processed. We will print out values for
2487	 * the default vnet.
2488	 * XXX This should all be rationalized AFTER 8.0
2489	 */
2490	if (V_fw_verbose == 0)
2491		printf("disabled\n");
2492	else if (V_verbose_limit == 0)
2493		printf("unlimited\n");
2494	else
2495		printf("limited to %d packets/entry by default\n",
2496		    V_verbose_limit);
2497
2498	ipfw_log_bpf(1); /* init */
2499	return (error);
2500}
2501
2502/*
2503 * Called for the removal of the last instance only on module unload.
2504 */
2505static void
2506ipfw_destroy(void)
2507{
2508
2509	ipfw_log_bpf(0); /* uninit */
2510	ipfw_dyn_detach();
2511	printf("IP firewall unloaded\n");
2512}
2513
2514/*
2515 * Stuff that must be initialized for every instance
2516 * (including the first of course).
2517 */
2518static int
2519vnet_ipfw_init(const void *unused)
2520{
2521	int error;
2522	struct ip_fw *rule = NULL;
2523	struct ip_fw_chain *chain;
2524
2525	chain = &V_layer3_chain;
2526
2527	/* First set up some values that are compile time options */
2528	V_autoinc_step = 100;	/* bounded to 1..1000 in add_rule() */
2529	V_fw_deny_unknown_exthdrs = 1;
2530#ifdef IPFIREWALL_VERBOSE
2531	V_fw_verbose = 1;
2532#endif
2533#ifdef IPFIREWALL_VERBOSE_LIMIT
2534	V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
2535#endif
2536#ifdef IPFIREWALL_NAT
2537	LIST_INIT(&chain->nat);
2538#endif
2539
2540	/* insert the default rule and create the initial map */
2541	chain->n_rules = 1;
2542	chain->static_len = sizeof(struct ip_fw);
2543	chain->map = malloc(sizeof(struct ip_fw *), M_IPFW, M_NOWAIT | M_ZERO);
2544	if (chain->map)
2545		rule = malloc(chain->static_len, M_IPFW, M_NOWAIT | M_ZERO);
2546	if (rule == NULL) {
2547		if (chain->map)
2548			free(chain->map, M_IPFW);
2549		printf("ipfw2: ENOSPC initializing default rule "
2550			"(support disabled)\n");
2551		return (ENOSPC);
2552	}
2553	error = ipfw_init_tables(chain);
2554	if (error) {
2555		panic("init_tables"); /* XXX Marko fix this ! */
2556	}
2557
2558	/* fill and insert the default rule */
2559	rule->act_ofs = 0;
2560	rule->rulenum = IPFW_DEFAULT_RULE;
2561	rule->cmd_len = 1;
2562	rule->set = RESVD_SET;
2563	rule->cmd[0].len = 1;
2564	rule->cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY;
2565	chain->rules = chain->default_rule = chain->map[0] = rule;
2566	chain->id = rule->id = 1;
2567
2568	IPFW_LOCK_INIT(chain);
2569	ipfw_dyn_init();
2570
2571	/* First set up some values that are compile time options */
2572	V_ipfw_vnet_ready = 1;		/* Open for business */
2573
2574	/*
2575	 * Hook the sockopt handler, and the layer2 (V_ip_fw_chk_ptr)
2576	 * and pfil hooks for ipv4 and ipv6. Even if the latter two fail
2577	 * we still keep the module alive because the sockopt and
2578	 * layer2 paths are still useful.
2579	 * ipfw[6]_hook return 0 on success, ENOENT on failure,
2580	 * so we can ignore the exact return value and just set a flag.
2581	 *
2582	 * Note that V_fw[6]_enable are manipulated by a SYSCTL_PROC so
2583	 * changes in the underlying (per-vnet) variables trigger
2584	 * immediate hook()/unhook() calls.
2585	 * In layer2 we have the same behaviour, except that V_ether_ipfw
2586	 * is checked on each packet because there are no pfil hooks.
2587	 */
2588	V_ip_fw_ctl_ptr = ipfw_ctl;
2589	V_ip_fw_chk_ptr = ipfw_chk;
2590	error = ipfw_attach_hooks(1);
2591	return (error);
2592}
2593
2594/*
2595 * Called for the removal of each instance.
2596 */
2597static int
2598vnet_ipfw_uninit(const void *unused)
2599{
2600	struct ip_fw *reap, *rule;
2601	struct ip_fw_chain *chain = &V_layer3_chain;
2602	int i;
2603
2604	V_ipfw_vnet_ready = 0; /* tell new callers to go away */
2605	/*
2606	 * disconnect from ipv4, ipv6, layer2 and sockopt.
2607	 * Then grab, release and grab again the WLOCK so we make
2608	 * sure the update is propagated and nobody will be in.
2609	 */
2610	(void)ipfw_attach_hooks(0 /* detach */);
2611	V_ip_fw_chk_ptr = NULL;
2612	V_ip_fw_ctl_ptr = NULL;
2613	IPFW_UH_WLOCK(chain);
2614	IPFW_UH_WUNLOCK(chain);
2615	IPFW_UH_WLOCK(chain);
2616
2617	IPFW_WLOCK(chain);
2618	IPFW_WUNLOCK(chain);
2619	IPFW_WLOCK(chain);
2620
2621	ipfw_dyn_uninit(0);	/* run the callout_drain */
2622	ipfw_destroy_tables(chain);
2623	reap = NULL;
2624	for (i = 0; i < chain->n_rules; i++) {
2625		rule = chain->map[i];
2626		rule->x_next = reap;
2627		reap = rule;
2628	}
2629	if (chain->map)
2630		free(chain->map, M_IPFW);
2631	IPFW_WUNLOCK(chain);
2632	IPFW_UH_WUNLOCK(chain);
2633	if (reap != NULL)
2634		ipfw_reap_rules(reap);
2635	IPFW_LOCK_DESTROY(chain);
2636	ipfw_dyn_uninit(1);	/* free the remaining parts */
2637	return 0;
2638}
2639
2640/*
2641 * Module event handler.
2642 * In general we have the choice of handling most of these events by the
2643 * event handler or by the (VNET_)SYS(UN)INIT handlers. I have chosen to
2644 * use the SYSINIT handlers as they are more capable of expressing the
2645 * flow of control during module and vnet operations, so this is just
2646 * a skeleton. Note there is no SYSINIT equivalent of the module
2647 * SHUTDOWN handler, but we don't have anything to do in that case anyhow.
2648 */
2649static int
2650ipfw_modevent(module_t mod, int type, void *unused)
2651{
2652	int err = 0;
2653
2654	switch (type) {
2655	case MOD_LOAD:
2656		/* Called once at module load or
2657	 	 * system boot if compiled in. */
2658		break;
2659	case MOD_QUIESCE:
2660		/* Called before unload. May veto unloading. */
2661		break;
2662	case MOD_UNLOAD:
2663		/* Called during unload. */
2664		break;
2665	case MOD_SHUTDOWN:
2666		/* Called during system shutdown. */
2667		break;
2668	default:
2669		err = EOPNOTSUPP;
2670		break;
2671	}
2672	return err;
2673}
2674
2675static moduledata_t ipfwmod = {
2676	"ipfw",
2677	ipfw_modevent,
2678	0
2679};
2680
2681/* Define startup order. */
2682#define	IPFW_SI_SUB_FIREWALL	SI_SUB_PROTO_IFATTACHDOMAIN
2683#define	IPFW_MODEVENT_ORDER	(SI_ORDER_ANY - 255) /* On boot slot in here. */
2684#define	IPFW_MODULE_ORDER	(IPFW_MODEVENT_ORDER + 1) /* A little later. */
2685#define	IPFW_VNET_ORDER		(IPFW_MODEVENT_ORDER + 2) /* Later still. */
2686
2687DECLARE_MODULE(ipfw, ipfwmod, IPFW_SI_SUB_FIREWALL, IPFW_MODEVENT_ORDER);
2688MODULE_VERSION(ipfw, 2);
2689/* should declare some dependencies here */
2690
2691/*
2692 * Starting up. Done in order after ipfwmod() has been called.
2693 * VNET_SYSINIT is also called for each existing vnet and each new vnet.
2694 */
2695SYSINIT(ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
2696	    ipfw_init, NULL);
2697VNET_SYSINIT(vnet_ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
2698	    vnet_ipfw_init, NULL);
2699
2700/*
2701 * Closing up shop. These are done in REVERSE ORDER, but still
2702 * after ipfwmod() has been called. Not called on reboot.
2703 * VNET_SYSUNINIT is also called for each exiting vnet as it exits.
2704 * or when the module is unloaded.
2705 */
2706SYSUNINIT(ipfw_destroy, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
2707	    ipfw_destroy, NULL);
2708VNET_SYSUNINIT(vnet_ipfw_uninit, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
2709	    vnet_ipfw_uninit, NULL);
2710/* end of file */
2711