xref: /freebsd/sys/netpfil/ipfw/ip_fw2.c (revision 19fae0f66023a97a9b464b3beeeabb2081f575b3)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2002-2009 Luigi Rizzo, Universita` di Pisa
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD$");
30 
31 /*
32  * The FreeBSD IP packet firewall, main file
33  */
34 
35 #include "opt_ipfw.h"
36 #include "opt_ipdivert.h"
37 #include "opt_inet.h"
38 #ifndef INET
39 #error "IPFIREWALL requires INET"
40 #endif /* INET */
41 #include "opt_inet6.h"
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/condvar.h>
46 #include <sys/counter.h>
47 #include <sys/eventhandler.h>
48 #include <sys/malloc.h>
49 #include <sys/mbuf.h>
50 #include <sys/kernel.h>
51 #include <sys/lock.h>
52 #include <sys/jail.h>
53 #include <sys/module.h>
54 #include <sys/priv.h>
55 #include <sys/proc.h>
56 #include <sys/rwlock.h>
57 #include <sys/rmlock.h>
58 #include <sys/sdt.h>
59 #include <sys/socket.h>
60 #include <sys/socketvar.h>
61 #include <sys/sysctl.h>
62 #include <sys/syslog.h>
63 #include <sys/ucred.h>
64 #include <net/ethernet.h> /* for ETHERTYPE_IP */
65 #include <net/if.h>
66 #include <net/if_var.h>
67 #include <net/if_private.h>
68 #include <net/route.h>
69 #include <net/route/nhop.h>
70 #include <net/pfil.h>
71 #include <net/vnet.h>
72 #include <net/if_pfsync.h>
73 
74 #include <netpfil/pf/pf_mtag.h>
75 
76 #include <netinet/in.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_carp.h>
84 #include <netinet/pim.h>
85 #include <netinet/tcp_var.h>
86 #include <netinet/udp.h>
87 #include <netinet/udp_var.h>
88 #include <netinet/sctp.h>
89 #include <netinet/sctp_crc32.h>
90 #include <netinet/sctp_header.h>
91 
92 #include <netinet/ip6.h>
93 #include <netinet/icmp6.h>
94 #include <netinet/in_fib.h>
95 #ifdef INET6
96 #include <netinet6/in6_fib.h>
97 #include <netinet6/in6_pcb.h>
98 #include <netinet6/scope6_var.h>
99 #include <netinet6/ip6_var.h>
100 #endif
101 
102 #include <net/if_gre.h> /* for struct grehdr */
103 
104 #include <netpfil/ipfw/ip_fw_private.h>
105 
106 #include <machine/in_cksum.h>	/* XXX for in_cksum */
107 
108 #ifdef MAC
109 #include <security/mac/mac_framework.h>
110 #endif
111 
112 #define	IPFW_PROBE(probe, arg0, arg1, arg2, arg3, arg4, arg5)		\
113     SDT_PROBE6(ipfw, , , probe, arg0, arg1, arg2, arg3, arg4, arg5)
114 
115 SDT_PROVIDER_DEFINE(ipfw);
116 SDT_PROBE_DEFINE6(ipfw, , , rule__matched,
117     "int",			/* retval */
118     "int",			/* af */
119     "void *",			/* src addr */
120     "void *",			/* dst addr */
121     "struct ip_fw_args *",	/* args */
122     "struct ip_fw *"		/* rule */);
123 
124 /*
125  * static variables followed by global ones.
126  * All ipfw global variables are here.
127  */
128 
129 VNET_DEFINE_STATIC(int, fw_deny_unknown_exthdrs);
130 #define	V_fw_deny_unknown_exthdrs	VNET(fw_deny_unknown_exthdrs)
131 
132 VNET_DEFINE_STATIC(int, fw_permit_single_frag6) = 1;
133 #define	V_fw_permit_single_frag6	VNET(fw_permit_single_frag6)
134 
135 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
136 static int default_to_accept = 1;
137 #else
138 static int default_to_accept;
139 #endif
140 
141 VNET_DEFINE(int, autoinc_step);
142 VNET_DEFINE(int, fw_one_pass) = 1;
143 
144 VNET_DEFINE(unsigned int, fw_tables_max);
145 VNET_DEFINE(unsigned int, fw_tables_sets) = 0;	/* Don't use set-aware tables */
146 /* Use 128 tables by default */
147 static unsigned int default_fw_tables = IPFW_TABLES_DEFAULT;
148 
149 static int jump_lookup_pos(struct ip_fw_chain *chain, struct ip_fw *f, int num,
150     int tablearg, int jump_backwards);
151 #ifndef LINEAR_SKIPTO
152 static int jump_cached(struct ip_fw_chain *chain, struct ip_fw *f, int num,
153     int tablearg, int jump_backwards);
154 #define	JUMP(ch, f, num, targ, back)	jump_cached(ch, f, num, targ, back)
155 #else
156 #define	JUMP(ch, f, num, targ, back)	jump_lookup_pos(ch, f, num, targ, back)
157 #endif
158 
159 /*
160  * Each rule belongs to one of 32 different sets (0..31).
161  * The variable set_disable contains one bit per set.
162  * If the bit is set, all rules in the corresponding set
163  * are disabled. Set RESVD_SET(31) is reserved for the default rule
164  * and rules that are not deleted by the flush command,
165  * and CANNOT be disabled.
166  * Rules in set RESVD_SET can only be deleted individually.
167  */
168 VNET_DEFINE(u_int32_t, set_disable);
169 #define	V_set_disable			VNET(set_disable)
170 
171 VNET_DEFINE(int, fw_verbose);
172 /* counter for ipfw_log(NULL...) */
173 VNET_DEFINE(u_int64_t, norule_counter);
174 VNET_DEFINE(int, verbose_limit);
175 
176 /* layer3_chain contains the list of rules for layer 3 */
177 VNET_DEFINE(struct ip_fw_chain, layer3_chain);
178 
179 /* ipfw_vnet_ready controls when we are open for business */
180 VNET_DEFINE(int, ipfw_vnet_ready) = 0;
181 
182 VNET_DEFINE(int, ipfw_nat_ready) = 0;
183 
184 ipfw_nat_t *ipfw_nat_ptr = NULL;
185 struct cfg_nat *(*lookup_nat_ptr)(struct nat_list *, int);
186 ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
187 ipfw_nat_cfg_t *ipfw_nat_del_ptr;
188 ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
189 ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
190 
191 #ifdef SYSCTL_NODE
192 uint32_t dummy_def = IPFW_DEFAULT_RULE;
193 static int sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS);
194 static int sysctl_ipfw_tables_sets(SYSCTL_HANDLER_ARGS);
195 
196 SYSBEGIN(f3)
197 
198 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
199     "Firewall");
200 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
201     CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_one_pass), 0,
202     "Only do a single pass through ipfw when using dummynet(4)");
203 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step,
204     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(autoinc_step), 0,
205     "Rule number auto-increment step");
206 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
207     CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_verbose), 0,
208     "Log matches to ipfw rules");
209 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit,
210     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(verbose_limit), 0,
211     "Set upper limit of matches of ipfw rules logged");
212 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
213     &dummy_def, 0,
214     "The default/max possible rule number.");
215 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, tables_max,
216     CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
217     0, 0, sysctl_ipfw_table_num, "IU",
218     "Maximum number of concurrently used tables");
219 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, tables_sets,
220     CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW | CTLFLAG_MPSAFE,
221     0, 0, sysctl_ipfw_tables_sets, "IU",
222     "Use per-set namespace for tables");
223 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, default_to_accept, CTLFLAG_RDTUN,
224     &default_to_accept, 0,
225     "Make the default rule accept all packets.");
226 TUNABLE_INT("net.inet.ip.fw.tables_max", (int *)&default_fw_tables);
227 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count,
228     CTLFLAG_VNET | CTLFLAG_RD, &VNET_NAME(layer3_chain.n_rules), 0,
229     "Number of static rules");
230 
231 #ifdef INET6
232 SYSCTL_DECL(_net_inet6_ip6);
233 SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, fw, CTLFLAG_RW | CTLFLAG_MPSAFE, 0,
234     "Firewall");
235 SYSCTL_INT(_net_inet6_ip6_fw, OID_AUTO, deny_unknown_exthdrs,
236     CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
237     &VNET_NAME(fw_deny_unknown_exthdrs), 0,
238     "Deny packets with unknown IPv6 Extension Headers");
239 SYSCTL_INT(_net_inet6_ip6_fw, OID_AUTO, permit_single_frag6,
240     CTLFLAG_VNET | CTLFLAG_RW | CTLFLAG_SECURE,
241     &VNET_NAME(fw_permit_single_frag6), 0,
242     "Permit single packet IPv6 fragments");
243 #endif /* INET6 */
244 
245 SYSEND
246 
247 #endif /* SYSCTL_NODE */
248 
249 /*
250  * Some macros used in the various matching options.
251  * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
252  * Other macros just cast void * into the appropriate type
253  */
254 #define	L3HDR(T, ip)	((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
255 #define	TCP(p)		((struct tcphdr *)(p))
256 #define	SCTP(p)		((struct sctphdr *)(p))
257 #define	UDP(p)		((struct udphdr *)(p))
258 #define	ICMP(p)		((struct icmphdr *)(p))
259 #define	ICMP6(p)	((struct icmp6_hdr *)(p))
260 
261 static __inline int
262 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
263 {
264 	int type = icmp->icmp_type;
265 
266 	return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
267 }
268 
269 #define TT	( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
270     (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
271 
272 static int
273 is_icmp_query(struct icmphdr *icmp)
274 {
275 	int type = icmp->icmp_type;
276 
277 	return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
278 }
279 #undef TT
280 
281 /*
282  * The following checks use two arrays of 8 or 16 bits to store the
283  * bits that we want set or clear, respectively. They are in the
284  * low and high half of cmd->arg1 or cmd->d[0].
285  *
286  * We scan options and store the bits we find set. We succeed if
287  *
288  *	(want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
289  *
290  * The code is sometimes optimized not to store additional variables.
291  */
292 
293 static int
294 flags_match(ipfw_insn *cmd, u_int8_t bits)
295 {
296 	u_char want_clear;
297 	bits = ~bits;
298 
299 	if ( ((cmd->arg1 & 0xff) & bits) != 0)
300 		return 0; /* some bits we want set were clear */
301 	want_clear = (cmd->arg1 >> 8) & 0xff;
302 	if ( (want_clear & bits) != want_clear)
303 		return 0; /* some bits we want clear were set */
304 	return 1;
305 }
306 
307 static int
308 ipopts_match(struct ip *ip, ipfw_insn *cmd)
309 {
310 	int optlen, bits = 0;
311 	u_char *cp = (u_char *)(ip + 1);
312 	int x = (ip->ip_hl << 2) - sizeof (struct ip);
313 
314 	for (; x > 0; x -= optlen, cp += optlen) {
315 		int opt = cp[IPOPT_OPTVAL];
316 
317 		if (opt == IPOPT_EOL)
318 			break;
319 		if (opt == IPOPT_NOP)
320 			optlen = 1;
321 		else {
322 			optlen = cp[IPOPT_OLEN];
323 			if (optlen <= 0 || optlen > x)
324 				return 0; /* invalid or truncated */
325 		}
326 		switch (opt) {
327 		default:
328 			break;
329 
330 		case IPOPT_LSRR:
331 			bits |= IP_FW_IPOPT_LSRR;
332 			break;
333 
334 		case IPOPT_SSRR:
335 			bits |= IP_FW_IPOPT_SSRR;
336 			break;
337 
338 		case IPOPT_RR:
339 			bits |= IP_FW_IPOPT_RR;
340 			break;
341 
342 		case IPOPT_TS:
343 			bits |= IP_FW_IPOPT_TS;
344 			break;
345 		}
346 	}
347 	return (flags_match(cmd, bits));
348 }
349 
350 /*
351  * Parse TCP options. The logic copied from tcp_dooptions().
352  */
353 static int
354 tcpopts_parse(const struct tcphdr *tcp, uint16_t *mss)
355 {
356 	const u_char *cp = (const u_char *)(tcp + 1);
357 	int optlen, bits = 0;
358 	int cnt = (tcp->th_off << 2) - sizeof(struct tcphdr);
359 
360 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
361 		int opt = cp[0];
362 		if (opt == TCPOPT_EOL)
363 			break;
364 		if (opt == TCPOPT_NOP)
365 			optlen = 1;
366 		else {
367 			if (cnt < 2)
368 				break;
369 			optlen = cp[1];
370 			if (optlen < 2 || optlen > cnt)
371 				break;
372 		}
373 
374 		switch (opt) {
375 		default:
376 			break;
377 
378 		case TCPOPT_MAXSEG:
379 			if (optlen != TCPOLEN_MAXSEG)
380 				break;
381 			bits |= IP_FW_TCPOPT_MSS;
382 			if (mss != NULL)
383 				*mss = be16dec(cp + 2);
384 			break;
385 
386 		case TCPOPT_WINDOW:
387 			if (optlen == TCPOLEN_WINDOW)
388 				bits |= IP_FW_TCPOPT_WINDOW;
389 			break;
390 
391 		case TCPOPT_SACK_PERMITTED:
392 			if (optlen == TCPOLEN_SACK_PERMITTED)
393 				bits |= IP_FW_TCPOPT_SACK;
394 			break;
395 
396 		case TCPOPT_SACK:
397 			if (optlen > 2 && (optlen - 2) % TCPOLEN_SACK == 0)
398 				bits |= IP_FW_TCPOPT_SACK;
399 			break;
400 
401 		case TCPOPT_TIMESTAMP:
402 			if (optlen == TCPOLEN_TIMESTAMP)
403 				bits |= IP_FW_TCPOPT_TS;
404 			break;
405 		}
406 	}
407 	return (bits);
408 }
409 
410 static int
411 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
412 {
413 
414 	return (flags_match(cmd, tcpopts_parse(tcp, NULL)));
415 }
416 
417 static int
418 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd, struct ip_fw_chain *chain,
419     uint32_t *tablearg)
420 {
421 
422 	if (ifp == NULL)	/* no iface with this packet, match fails */
423 		return (0);
424 
425 	/* Check by name or by IP address */
426 	if (cmd->name[0] != '\0') { /* match by name */
427 		if (cmd->name[0] == '\1') /* use tablearg to match */
428 			return ipfw_lookup_table(chain, cmd->p.kidx, 0,
429 			    &ifp->if_index, tablearg);
430 		/* Check name */
431 		if (cmd->p.glob) {
432 			if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
433 				return(1);
434 		} else {
435 			if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
436 				return(1);
437 		}
438 	} else {
439 #if !defined(USERSPACE) && defined(__FreeBSD__)	/* and OSX too ? */
440 		struct ifaddr *ia;
441 
442 		NET_EPOCH_ASSERT();
443 
444 		CK_STAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
445 			if (ia->ifa_addr->sa_family != AF_INET)
446 				continue;
447 			if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
448 			    (ia->ifa_addr))->sin_addr.s_addr)
449 				return (1);	/* match */
450 		}
451 #endif /* __FreeBSD__ */
452 	}
453 	return(0);	/* no match, fail ... */
454 }
455 
456 /*
457  * The verify_path function checks if a route to the src exists and
458  * if it is reachable via ifp (when provided).
459  *
460  * The 'verrevpath' option checks that the interface that an IP packet
461  * arrives on is the same interface that traffic destined for the
462  * packet's source address would be routed out of.
463  * The 'versrcreach' option just checks that the source address is
464  * reachable via any route (except default) in the routing table.
465  * These two are a measure to block forged packets. This is also
466  * commonly known as "anti-spoofing" or Unicast Reverse Path
467  * Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
468  * is purposely reminiscent of the Cisco IOS command,
469  *
470  *   ip verify unicast reverse-path
471  *   ip verify unicast source reachable-via any
472  *
473  * which implements the same functionality. But note that the syntax
474  * is misleading, and the check may be performed on all IP packets
475  * whether unicast, multicast, or broadcast.
476  */
477 static int
478 verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
479 {
480 #if defined(USERSPACE) || !defined(__FreeBSD__)
481 	return 0;
482 #else
483 	struct nhop_object *nh;
484 
485 	nh = fib4_lookup(fib, src, 0, NHR_NONE, 0);
486 	if (nh == NULL)
487 		return (0);
488 
489 	/*
490 	 * If ifp is provided, check for equality with rtentry.
491 	 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
492 	 * in order to pass packets injected back by if_simloop():
493 	 * routing entry (via lo0) for our own address
494 	 * may exist, so we need to handle routing assymetry.
495 	 */
496 	if (ifp != NULL && ifp != nh->nh_aifp)
497 		return (0);
498 
499 	/* if no ifp provided, check if rtentry is not default route */
500 	if (ifp == NULL && (nh->nh_flags & NHF_DEFAULT) != 0)
501 		return (0);
502 
503 	/* or if this is a blackhole/reject route */
504 	if (ifp == NULL && (nh->nh_flags & (NHF_REJECT|NHF_BLACKHOLE)) != 0)
505 		return (0);
506 
507 	/* found valid route */
508 	return 1;
509 #endif /* __FreeBSD__ */
510 }
511 
512 /*
513  * Generate an SCTP packet containing an ABORT chunk. The verification tag
514  * is given by vtag. The T-bit is set in the ABORT chunk if and only if
515  * reflected is not 0.
516  */
517 
518 static struct mbuf *
519 ipfw_send_abort(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t vtag,
520     int reflected)
521 {
522 	struct mbuf *m;
523 	struct ip *ip;
524 #ifdef INET6
525 	struct ip6_hdr *ip6;
526 #endif
527 	struct sctphdr *sctp;
528 	struct sctp_chunkhdr *chunk;
529 	u_int16_t hlen, plen, tlen;
530 
531 	MGETHDR(m, M_NOWAIT, MT_DATA);
532 	if (m == NULL)
533 		return (NULL);
534 
535 	M_SETFIB(m, id->fib);
536 #ifdef MAC
537 	if (replyto != NULL)
538 		mac_netinet_firewall_reply(replyto, m);
539 	else
540 		mac_netinet_firewall_send(m);
541 #else
542 	(void)replyto;		/* don't warn about unused arg */
543 #endif
544 
545 	switch (id->addr_type) {
546 	case 4:
547 		hlen = sizeof(struct ip);
548 		break;
549 #ifdef INET6
550 	case 6:
551 		hlen = sizeof(struct ip6_hdr);
552 		break;
553 #endif
554 	default:
555 		/* XXX: log me?!? */
556 		FREE_PKT(m);
557 		return (NULL);
558 	}
559 	plen = sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr);
560 	tlen = hlen + plen;
561 	m->m_data += max_linkhdr;
562 	m->m_flags |= M_SKIP_FIREWALL;
563 	m->m_pkthdr.len = m->m_len = tlen;
564 	m->m_pkthdr.rcvif = NULL;
565 	bzero(m->m_data, tlen);
566 
567 	switch (id->addr_type) {
568 	case 4:
569 		ip = mtod(m, struct ip *);
570 
571 		ip->ip_v = 4;
572 		ip->ip_hl = sizeof(struct ip) >> 2;
573 		ip->ip_tos = IPTOS_LOWDELAY;
574 		ip->ip_len = htons(tlen);
575 		ip->ip_id = htons(0);
576 		ip->ip_off = htons(0);
577 		ip->ip_ttl = V_ip_defttl;
578 		ip->ip_p = IPPROTO_SCTP;
579 		ip->ip_sum = 0;
580 		ip->ip_src.s_addr = htonl(id->dst_ip);
581 		ip->ip_dst.s_addr = htonl(id->src_ip);
582 
583 		sctp = (struct sctphdr *)(ip + 1);
584 		break;
585 #ifdef INET6
586 	case 6:
587 		ip6 = mtod(m, struct ip6_hdr *);
588 
589 		ip6->ip6_vfc = IPV6_VERSION;
590 		ip6->ip6_plen = htons(plen);
591 		ip6->ip6_nxt = IPPROTO_SCTP;
592 		ip6->ip6_hlim = IPV6_DEFHLIM;
593 		ip6->ip6_src = id->dst_ip6;
594 		ip6->ip6_dst = id->src_ip6;
595 
596 		sctp = (struct sctphdr *)(ip6 + 1);
597 		break;
598 #endif
599 	}
600 
601 	sctp->src_port = htons(id->dst_port);
602 	sctp->dest_port = htons(id->src_port);
603 	sctp->v_tag = htonl(vtag);
604 	sctp->checksum = htonl(0);
605 
606 	chunk = (struct sctp_chunkhdr *)(sctp + 1);
607 	chunk->chunk_type = SCTP_ABORT_ASSOCIATION;
608 	chunk->chunk_flags = 0;
609 	if (reflected != 0) {
610 		chunk->chunk_flags |= SCTP_HAD_NO_TCB;
611 	}
612 	chunk->chunk_length = htons(sizeof(struct sctp_chunkhdr));
613 
614 	sctp->checksum = sctp_calculate_cksum(m, hlen);
615 
616 	return (m);
617 }
618 
619 /*
620  * Generate a TCP packet, containing either a RST or a keepalive.
621  * When flags & TH_RST, we are sending a RST packet, because of a
622  * "reset" action matched the packet.
623  * Otherwise we are sending a keepalive, and flags & TH_
624  * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
625  * so that MAC can label the reply appropriately.
626  */
627 struct mbuf *
628 ipfw_send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
629     u_int32_t ack, int flags)
630 {
631 	struct mbuf *m = NULL;		/* stupid compiler */
632 	struct ip *h = NULL;		/* stupid compiler */
633 #ifdef INET6
634 	struct ip6_hdr *h6 = NULL;
635 #endif
636 	struct tcphdr *th = NULL;
637 	int len, dir;
638 
639 	MGETHDR(m, M_NOWAIT, MT_DATA);
640 	if (m == NULL)
641 		return (NULL);
642 
643 	M_SETFIB(m, id->fib);
644 #ifdef MAC
645 	if (replyto != NULL)
646 		mac_netinet_firewall_reply(replyto, m);
647 	else
648 		mac_netinet_firewall_send(m);
649 #else
650 	(void)replyto;		/* don't warn about unused arg */
651 #endif
652 
653 	switch (id->addr_type) {
654 	case 4:
655 		len = sizeof(struct ip) + sizeof(struct tcphdr);
656 		break;
657 #ifdef INET6
658 	case 6:
659 		len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
660 		break;
661 #endif
662 	default:
663 		/* XXX: log me?!? */
664 		FREE_PKT(m);
665 		return (NULL);
666 	}
667 	dir = ((flags & (TH_SYN | TH_RST)) == TH_SYN);
668 
669 	m->m_data += max_linkhdr;
670 	m->m_flags |= M_SKIP_FIREWALL;
671 	m->m_pkthdr.len = m->m_len = len;
672 	m->m_pkthdr.rcvif = NULL;
673 	bzero(m->m_data, len);
674 
675 	switch (id->addr_type) {
676 	case 4:
677 		h = mtod(m, struct ip *);
678 
679 		/* prepare for checksum */
680 		h->ip_p = IPPROTO_TCP;
681 		h->ip_len = htons(sizeof(struct tcphdr));
682 		if (dir) {
683 			h->ip_src.s_addr = htonl(id->src_ip);
684 			h->ip_dst.s_addr = htonl(id->dst_ip);
685 		} else {
686 			h->ip_src.s_addr = htonl(id->dst_ip);
687 			h->ip_dst.s_addr = htonl(id->src_ip);
688 		}
689 
690 		th = (struct tcphdr *)(h + 1);
691 		break;
692 #ifdef INET6
693 	case 6:
694 		h6 = mtod(m, struct ip6_hdr *);
695 
696 		/* prepare for checksum */
697 		h6->ip6_nxt = IPPROTO_TCP;
698 		h6->ip6_plen = htons(sizeof(struct tcphdr));
699 		if (dir) {
700 			h6->ip6_src = id->src_ip6;
701 			h6->ip6_dst = id->dst_ip6;
702 		} else {
703 			h6->ip6_src = id->dst_ip6;
704 			h6->ip6_dst = id->src_ip6;
705 		}
706 
707 		th = (struct tcphdr *)(h6 + 1);
708 		break;
709 #endif
710 	}
711 
712 	if (dir) {
713 		th->th_sport = htons(id->src_port);
714 		th->th_dport = htons(id->dst_port);
715 	} else {
716 		th->th_sport = htons(id->dst_port);
717 		th->th_dport = htons(id->src_port);
718 	}
719 	th->th_off = sizeof(struct tcphdr) >> 2;
720 
721 	if (flags & TH_RST) {
722 		if (flags & TH_ACK) {
723 			th->th_seq = htonl(ack);
724 			th->th_flags = TH_RST;
725 		} else {
726 			if (flags & TH_SYN)
727 				seq++;
728 			th->th_ack = htonl(seq);
729 			th->th_flags = TH_RST | TH_ACK;
730 		}
731 	} else {
732 		/*
733 		 * Keepalive - use caller provided sequence numbers
734 		 */
735 		th->th_seq = htonl(seq);
736 		th->th_ack = htonl(ack);
737 		th->th_flags = TH_ACK;
738 	}
739 
740 	switch (id->addr_type) {
741 	case 4:
742 		th->th_sum = in_cksum(m, len);
743 
744 		/* finish the ip header */
745 		h->ip_v = 4;
746 		h->ip_hl = sizeof(*h) >> 2;
747 		h->ip_tos = IPTOS_LOWDELAY;
748 		h->ip_off = htons(0);
749 		h->ip_len = htons(len);
750 		h->ip_ttl = V_ip_defttl;
751 		h->ip_sum = 0;
752 		break;
753 #ifdef INET6
754 	case 6:
755 		th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(*h6),
756 		    sizeof(struct tcphdr));
757 
758 		/* finish the ip6 header */
759 		h6->ip6_vfc |= IPV6_VERSION;
760 		h6->ip6_hlim = IPV6_DEFHLIM;
761 		break;
762 #endif
763 	}
764 
765 	return (m);
766 }
767 
768 #ifdef INET6
769 /*
770  * ipv6 specific rules here...
771  */
772 static __inline int
773 icmp6type_match(int type, ipfw_insn_u32 *cmd)
774 {
775 	return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
776 }
777 
778 static int
779 flow6id_match(int curr_flow, ipfw_insn_u32 *cmd)
780 {
781 	int i;
782 	for (i=0; i <= cmd->o.arg1; ++i)
783 		if (curr_flow == cmd->d[i])
784 			return 1;
785 	return 0;
786 }
787 
788 /* support for IP6_*_ME opcodes */
789 static const struct in6_addr lla_mask = {{{
790 	0xff, 0xff, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff,
791 	0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff
792 }}};
793 
794 static int
795 ipfw_localip6(struct in6_addr *in6)
796 {
797 	struct rm_priotracker in6_ifa_tracker;
798 	struct in6_ifaddr *ia;
799 
800 	if (IN6_IS_ADDR_MULTICAST(in6))
801 		return (0);
802 
803 	if (!IN6_IS_ADDR_LINKLOCAL(in6))
804 		return (in6_localip(in6));
805 
806 	IN6_IFADDR_RLOCK(&in6_ifa_tracker);
807 	CK_STAILQ_FOREACH(ia, &V_in6_ifaddrhead, ia_link) {
808 		if (!IN6_IS_ADDR_LINKLOCAL(&ia->ia_addr.sin6_addr))
809 			continue;
810 		if (IN6_ARE_MASKED_ADDR_EQUAL(&ia->ia_addr.sin6_addr,
811 		    in6, &lla_mask)) {
812 			IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
813 			return (1);
814 		}
815 	}
816 	IN6_IFADDR_RUNLOCK(&in6_ifa_tracker);
817 	return (0);
818 }
819 
820 static int
821 verify_path6(struct in6_addr *src, struct ifnet *ifp, u_int fib)
822 {
823 	struct nhop_object *nh;
824 
825 	if (IN6_IS_SCOPE_LINKLOCAL(src))
826 		return (1);
827 
828 	nh = fib6_lookup(fib, src, 0, NHR_NONE, 0);
829 	if (nh == NULL)
830 		return (0);
831 
832 	/* If ifp is provided, check for equality with route table. */
833 	if (ifp != NULL && ifp != nh->nh_aifp)
834 		return (0);
835 
836 	/* if no ifp provided, check if rtentry is not default route */
837 	if (ifp == NULL && (nh->nh_flags & NHF_DEFAULT) != 0)
838 		return (0);
839 
840 	/* or if this is a blackhole/reject route */
841 	if (ifp == NULL && (nh->nh_flags & (NHF_REJECT|NHF_BLACKHOLE)) != 0)
842 		return (0);
843 
844 	/* found valid route */
845 	return 1;
846 }
847 
848 static int
849 is_icmp6_query(int icmp6_type)
850 {
851 	if ((icmp6_type <= ICMP6_MAXTYPE) &&
852 	    (icmp6_type == ICMP6_ECHO_REQUEST ||
853 	    icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
854 	    icmp6_type == ICMP6_WRUREQUEST ||
855 	    icmp6_type == ICMP6_FQDN_QUERY ||
856 	    icmp6_type == ICMP6_NI_QUERY))
857 		return (1);
858 
859 	return (0);
860 }
861 
862 static int
863 map_icmp_unreach(int code)
864 {
865 
866 	/* RFC 7915 p4.2 */
867 	switch (code) {
868 	case ICMP_UNREACH_NET:
869 	case ICMP_UNREACH_HOST:
870 	case ICMP_UNREACH_SRCFAIL:
871 	case ICMP_UNREACH_NET_UNKNOWN:
872 	case ICMP_UNREACH_HOST_UNKNOWN:
873 	case ICMP_UNREACH_TOSNET:
874 	case ICMP_UNREACH_TOSHOST:
875 		return (ICMP6_DST_UNREACH_NOROUTE);
876 	case ICMP_UNREACH_PORT:
877 		return (ICMP6_DST_UNREACH_NOPORT);
878 	default:
879 		/*
880 		 * Map the rest of codes into admit prohibited.
881 		 * XXX: unreach proto should be mapped into ICMPv6
882 		 * parameter problem, but we use only unreach type.
883 		 */
884 		return (ICMP6_DST_UNREACH_ADMIN);
885 	}
886 }
887 
888 static void
889 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
890 {
891 	struct mbuf *m;
892 
893 	m = args->m;
894 	if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
895 		struct tcphdr *tcp;
896 		tcp = (struct tcphdr *)((char *)ip6 + hlen);
897 
898 		if ((tcp->th_flags & TH_RST) == 0) {
899 			struct mbuf *m0;
900 			m0 = ipfw_send_pkt(args->m, &(args->f_id),
901 			    ntohl(tcp->th_seq), ntohl(tcp->th_ack),
902 			    tcp->th_flags | TH_RST);
903 			if (m0 != NULL)
904 				ip6_output(m0, NULL, NULL, 0, NULL, NULL,
905 				    NULL);
906 		}
907 		FREE_PKT(m);
908 	} else if (code == ICMP6_UNREACH_ABORT &&
909 	    args->f_id.proto == IPPROTO_SCTP) {
910 		struct mbuf *m0;
911 		struct sctphdr *sctp;
912 		u_int32_t v_tag;
913 		int reflected;
914 
915 		sctp = (struct sctphdr *)((char *)ip6 + hlen);
916 		reflected = 1;
917 		v_tag = ntohl(sctp->v_tag);
918 		/* Investigate the first chunk header if available */
919 		if (m->m_len >= hlen + sizeof(struct sctphdr) +
920 		    sizeof(struct sctp_chunkhdr)) {
921 			struct sctp_chunkhdr *chunk;
922 
923 			chunk = (struct sctp_chunkhdr *)(sctp + 1);
924 			switch (chunk->chunk_type) {
925 			case SCTP_INITIATION:
926 				/*
927 				 * Packets containing an INIT chunk MUST have
928 				 * a zero v-tag.
929 				 */
930 				if (v_tag != 0) {
931 					v_tag = 0;
932 					break;
933 				}
934 				/* INIT chunk MUST NOT be bundled */
935 				if (m->m_pkthdr.len >
936 				    hlen + sizeof(struct sctphdr) +
937 				    ntohs(chunk->chunk_length) + 3) {
938 					break;
939 				}
940 				/* Use the initiate tag if available */
941 				if ((m->m_len >= hlen + sizeof(struct sctphdr) +
942 				    sizeof(struct sctp_chunkhdr) +
943 				    offsetof(struct sctp_init, a_rwnd))) {
944 					struct sctp_init *init;
945 
946 					init = (struct sctp_init *)(chunk + 1);
947 					v_tag = ntohl(init->initiate_tag);
948 					reflected = 0;
949 				}
950 				break;
951 			case SCTP_ABORT_ASSOCIATION:
952 				/*
953 				 * If the packet contains an ABORT chunk, don't
954 				 * reply.
955 				 * XXX: We should search through all chunks,
956 				 * but do not do that to avoid attacks.
957 				 */
958 				v_tag = 0;
959 				break;
960 			}
961 		}
962 		if (v_tag == 0) {
963 			m0 = NULL;
964 		} else {
965 			m0 = ipfw_send_abort(args->m, &(args->f_id), v_tag,
966 			    reflected);
967 		}
968 		if (m0 != NULL)
969 			ip6_output(m0, NULL, NULL, 0, NULL, NULL, NULL);
970 		FREE_PKT(m);
971 	} else if (code != ICMP6_UNREACH_RST && code != ICMP6_UNREACH_ABORT) {
972 		/* Send an ICMPv6 unreach. */
973 #if 0
974 		/*
975 		 * Unlike above, the mbufs need to line up with the ip6 hdr,
976 		 * as the contents are read. We need to m_adj() the
977 		 * needed amount.
978 		 * The mbuf will however be thrown away so we can adjust it.
979 		 * Remember we did an m_pullup on it already so we
980 		 * can make some assumptions about contiguousness.
981 		 */
982 		if (args->L3offset)
983 			m_adj(m, args->L3offset);
984 #endif
985 		icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
986 	} else
987 		FREE_PKT(m);
988 
989 	args->m = NULL;
990 }
991 
992 #endif /* INET6 */
993 
994 /*
995  * sends a reject message, consuming the mbuf passed as an argument.
996  */
997 static void
998 send_reject(struct ip_fw_args *args, const ipfw_insn *cmd, int iplen,
999     struct ip *ip)
1000 {
1001 	int code, mtu;
1002 
1003 	code = cmd->arg1;
1004 	if (code == ICMP_UNREACH_NEEDFRAG &&
1005 	    cmd->len == F_INSN_SIZE(ipfw_insn_u16))
1006 		mtu = ((const ipfw_insn_u16 *)cmd)->ports[0];
1007 	else
1008 		mtu = 0;
1009 
1010 #if 0
1011 	/* XXX When ip is not guaranteed to be at mtod() we will
1012 	 * need to account for this */
1013 	 * The mbuf will however be thrown away so we can adjust it.
1014 	 * Remember we did an m_pullup on it already so we
1015 	 * can make some assumptions about contiguousness.
1016 	 */
1017 	if (args->L3offset)
1018 		m_adj(m, args->L3offset);
1019 #endif
1020 	if (code != ICMP_REJECT_RST && code != ICMP_REJECT_ABORT) {
1021 		/* Send an ICMP unreach */
1022 		icmp_error(args->m, ICMP_UNREACH, code, 0L, mtu);
1023 	} else if (code == ICMP_REJECT_RST && args->f_id.proto == IPPROTO_TCP) {
1024 		struct tcphdr *const tcp =
1025 		    L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1026 		if ( (tcp->th_flags & TH_RST) == 0) {
1027 			struct mbuf *m;
1028 			m = ipfw_send_pkt(args->m, &(args->f_id),
1029 				ntohl(tcp->th_seq), ntohl(tcp->th_ack),
1030 				tcp->th_flags | TH_RST);
1031 			if (m != NULL)
1032 				ip_output(m, NULL, NULL, 0, NULL, NULL);
1033 		}
1034 		FREE_PKT(args->m);
1035 	} else if (code == ICMP_REJECT_ABORT &&
1036 	    args->f_id.proto == IPPROTO_SCTP) {
1037 		struct mbuf *m;
1038 		struct sctphdr *sctp;
1039 		struct sctp_chunkhdr *chunk;
1040 		struct sctp_init *init;
1041 		u_int32_t v_tag;
1042 		int reflected;
1043 
1044 		sctp = L3HDR(struct sctphdr, mtod(args->m, struct ip *));
1045 		reflected = 1;
1046 		v_tag = ntohl(sctp->v_tag);
1047 		if (iplen >= (ip->ip_hl << 2) + sizeof(struct sctphdr) +
1048 		    sizeof(struct sctp_chunkhdr)) {
1049 			/* Look at the first chunk header if available */
1050 			chunk = (struct sctp_chunkhdr *)(sctp + 1);
1051 			switch (chunk->chunk_type) {
1052 			case SCTP_INITIATION:
1053 				/*
1054 				 * Packets containing an INIT chunk MUST have
1055 				 * a zero v-tag.
1056 				 */
1057 				if (v_tag != 0) {
1058 					v_tag = 0;
1059 					break;
1060 				}
1061 				/* INIT chunk MUST NOT be bundled */
1062 				if (iplen >
1063 				    (ip->ip_hl << 2) + sizeof(struct sctphdr) +
1064 				    ntohs(chunk->chunk_length) + 3) {
1065 					break;
1066 				}
1067 				/* Use the initiate tag if available */
1068 				if ((iplen >= (ip->ip_hl << 2) +
1069 				    sizeof(struct sctphdr) +
1070 				    sizeof(struct sctp_chunkhdr) +
1071 				    offsetof(struct sctp_init, a_rwnd))) {
1072 					init = (struct sctp_init *)(chunk + 1);
1073 					v_tag = ntohl(init->initiate_tag);
1074 					reflected = 0;
1075 				}
1076 				break;
1077 			case SCTP_ABORT_ASSOCIATION:
1078 				/*
1079 				 * If the packet contains an ABORT chunk, don't
1080 				 * reply.
1081 				 * XXX: We should search through all chunks,
1082 				 * but do not do that to avoid attacks.
1083 				 */
1084 				v_tag = 0;
1085 				break;
1086 			}
1087 		}
1088 		if (v_tag == 0) {
1089 			m = NULL;
1090 		} else {
1091 			m = ipfw_send_abort(args->m, &(args->f_id), v_tag,
1092 			    reflected);
1093 		}
1094 		if (m != NULL)
1095 			ip_output(m, NULL, NULL, 0, NULL, NULL);
1096 		FREE_PKT(args->m);
1097 	} else
1098 		FREE_PKT(args->m);
1099 	args->m = NULL;
1100 }
1101 
1102 /*
1103  * Support for uid/gid/jail lookup. These tests are expensive
1104  * (because we may need to look into the list of active sockets)
1105  * so we cache the results. ugid_lookupp is 0 if we have not
1106  * yet done a lookup, 1 if we succeeded, and -1 if we tried
1107  * and failed. The function always returns the match value.
1108  * We could actually spare the variable and use *uc, setting
1109  * it to '(void *)check_uidgid if we have no info, NULL if
1110  * we tried and failed, or any other value if successful.
1111  */
1112 static int
1113 check_uidgid(ipfw_insn_u32 *insn, struct ip_fw_args *args, int *ugid_lookupp,
1114     struct ucred **uc)
1115 {
1116 #if defined(USERSPACE)
1117 	return 0;	// not supported in userspace
1118 #else
1119 #ifndef __FreeBSD__
1120 	/* XXX */
1121 	return cred_check(insn, proto, oif,
1122 	    dst_ip, dst_port, src_ip, src_port,
1123 	    (struct bsd_ucred *)uc, ugid_lookupp, ((struct mbuf *)inp)->m_skb);
1124 #else  /* FreeBSD */
1125 	struct in_addr src_ip, dst_ip;
1126 	struct inpcbinfo *pi;
1127 	struct ipfw_flow_id *id;
1128 	struct inpcb *pcb, *inp;
1129 	int lookupflags;
1130 	int match;
1131 
1132 	id = &args->f_id;
1133 	inp = args->inp;
1134 
1135 	/*
1136 	 * Check to see if the UDP or TCP stack supplied us with
1137 	 * the PCB. If so, rather then holding a lock and looking
1138 	 * up the PCB, we can use the one that was supplied.
1139 	 */
1140 	if (inp && *ugid_lookupp == 0) {
1141 		INP_LOCK_ASSERT(inp);
1142 		if (inp->inp_socket != NULL) {
1143 			*uc = crhold(inp->inp_cred);
1144 			*ugid_lookupp = 1;
1145 		} else
1146 			*ugid_lookupp = -1;
1147 	}
1148 	/*
1149 	 * If we have already been here and the packet has no
1150 	 * PCB entry associated with it, then we can safely
1151 	 * assume that this is a no match.
1152 	 */
1153 	if (*ugid_lookupp == -1)
1154 		return (0);
1155 	if (id->proto == IPPROTO_TCP) {
1156 		lookupflags = 0;
1157 		pi = &V_tcbinfo;
1158 	} else if (id->proto == IPPROTO_UDP) {
1159 		lookupflags = INPLOOKUP_WILDCARD;
1160 		pi = &V_udbinfo;
1161 	} else if (id->proto == IPPROTO_UDPLITE) {
1162 		lookupflags = INPLOOKUP_WILDCARD;
1163 		pi = &V_ulitecbinfo;
1164 	} else
1165 		return 0;
1166 	lookupflags |= INPLOOKUP_RLOCKPCB;
1167 	match = 0;
1168 	if (*ugid_lookupp == 0) {
1169 		if (id->addr_type == 6) {
1170 #ifdef INET6
1171 			if (args->flags & IPFW_ARGS_IN)
1172 				pcb = in6_pcblookup_mbuf(pi,
1173 				    &id->src_ip6, htons(id->src_port),
1174 				    &id->dst_ip6, htons(id->dst_port),
1175 				    lookupflags, NULL, args->m);
1176 			else
1177 				pcb = in6_pcblookup_mbuf(pi,
1178 				    &id->dst_ip6, htons(id->dst_port),
1179 				    &id->src_ip6, htons(id->src_port),
1180 				    lookupflags, args->ifp, args->m);
1181 #else
1182 			*ugid_lookupp = -1;
1183 			return (0);
1184 #endif
1185 		} else {
1186 			src_ip.s_addr = htonl(id->src_ip);
1187 			dst_ip.s_addr = htonl(id->dst_ip);
1188 			if (args->flags & IPFW_ARGS_IN)
1189 				pcb = in_pcblookup_mbuf(pi,
1190 				    src_ip, htons(id->src_port),
1191 				    dst_ip, htons(id->dst_port),
1192 				    lookupflags, NULL, args->m);
1193 			else
1194 				pcb = in_pcblookup_mbuf(pi,
1195 				    dst_ip, htons(id->dst_port),
1196 				    src_ip, htons(id->src_port),
1197 				    lookupflags, args->ifp, args->m);
1198 		}
1199 		if (pcb != NULL) {
1200 			INP_RLOCK_ASSERT(pcb);
1201 			*uc = crhold(pcb->inp_cred);
1202 			*ugid_lookupp = 1;
1203 			INP_RUNLOCK(pcb);
1204 		}
1205 		if (*ugid_lookupp == 0) {
1206 			/*
1207 			 * We tried and failed, set the variable to -1
1208 			 * so we will not try again on this packet.
1209 			 */
1210 			*ugid_lookupp = -1;
1211 			return (0);
1212 		}
1213 	}
1214 	if (insn->o.opcode == O_UID)
1215 		match = ((*uc)->cr_uid == (uid_t)insn->d[0]);
1216 	else if (insn->o.opcode == O_GID)
1217 		match = groupmember((gid_t)insn->d[0], *uc);
1218 	else if (insn->o.opcode == O_JAIL)
1219 		match = ((*uc)->cr_prison->pr_id == (int)insn->d[0]);
1220 	return (match);
1221 #endif /* __FreeBSD__ */
1222 #endif /* not supported in userspace */
1223 }
1224 
1225 /*
1226  * Helper function to set args with info on the rule after the matching
1227  * one. slot is precise, whereas we guess rule_id as they are
1228  * assigned sequentially.
1229  */
1230 static inline void
1231 set_match(struct ip_fw_args *args, int slot,
1232 	struct ip_fw_chain *chain)
1233 {
1234 	args->rule.chain_id = chain->id;
1235 	args->rule.slot = slot + 1; /* we use 0 as a marker */
1236 	args->rule.rule_id = 1 + chain->map[slot]->id;
1237 	args->rule.rulenum = chain->map[slot]->rulenum;
1238 	args->flags |= IPFW_ARGS_REF;
1239 }
1240 
1241 static int
1242 jump_lookup_pos(struct ip_fw_chain *chain, struct ip_fw *f, int num,
1243     int tablearg, int jump_backwards)
1244 {
1245 	int f_pos, i;
1246 
1247 	i = IP_FW_ARG_TABLEARG(chain, num, skipto);
1248 	/* make sure we do not jump backward */
1249 	if (jump_backwards == 0 && i <= f->rulenum)
1250 		i = f->rulenum + 1;
1251 
1252 #ifndef LINEAR_SKIPTO
1253 	if (chain->idxmap != NULL)
1254 		f_pos = chain->idxmap[i];
1255 	else
1256 		f_pos = ipfw_find_rule(chain, i, 0);
1257 #else
1258 	f_pos = chain->idxmap[i];
1259 #endif /* LINEAR_SKIPTO */
1260 
1261 	return (f_pos);
1262 }
1263 
1264 
1265 #ifndef LINEAR_SKIPTO
1266 /*
1267  * Helper function to enable cached rule lookups using
1268  * cache.id and cache.pos fields in ipfw rule.
1269  */
1270 static int
1271 jump_cached(struct ip_fw_chain *chain, struct ip_fw *f, int num,
1272     int tablearg, int jump_backwards)
1273 {
1274 	int f_pos;
1275 
1276 	/* Can't use cache with IP_FW_TARG */
1277 	if (num == IP_FW_TARG)
1278 		return jump_lookup_pos(chain, f, num, tablearg, jump_backwards);
1279 
1280 	/*
1281 	 * If possible use cached f_pos (in f->cache.pos),
1282 	 * whose version is written in f->cache.id (horrible hacks
1283 	 * to avoid changing the ABI).
1284 	 *
1285 	 * Multiple threads can execute the same rule simultaneously,
1286 	 * we need to ensure that cache.pos is updated before cache.id.
1287 	 */
1288 
1289 #ifdef __LP64__
1290 	struct ip_fw_jump_cache cache;
1291 
1292 	cache.raw_value = f->cache.raw_value;
1293 	if (cache.id == chain->id)
1294 		return (cache.pos);
1295 
1296 	f_pos = jump_lookup_pos(chain, f, num, tablearg, jump_backwards);
1297 
1298 	cache.pos = f_pos;
1299 	cache.id = chain->id;
1300 	f->cache.raw_value = cache.raw_value;
1301 #else
1302 	if (f->cache.id == chain->id) {
1303 		/* Load pos after id */
1304 		atomic_thread_fence_acq();
1305 		return (f->cache.pos);
1306 	}
1307 
1308 	f_pos = jump_lookup_pos(chain, f, num, tablearg, jump_backwards);
1309 
1310 	f->cache.pos = f_pos;
1311 	/* Store id after pos */
1312 	atomic_thread_fence_rel();
1313 	f->cache.id = chain->id;
1314 #endif /* !__LP64__ */
1315 	return (f_pos);
1316 }
1317 #endif /* !LINEAR_SKIPTO */
1318 
1319 #define	TARG(k, f)	IP_FW_ARG_TABLEARG(chain, k, f)
1320 /*
1321  * The main check routine for the firewall.
1322  *
1323  * All arguments are in args so we can modify them and return them
1324  * back to the caller.
1325  *
1326  * Parameters:
1327  *
1328  *	args->m	(in/out) The packet; we set to NULL when/if we nuke it.
1329  *		Starts with the IP header.
1330  *	args->L3offset	Number of bytes bypassed if we came from L2.
1331  *			e.g. often sizeof(eh)  ** NOTYET **
1332  *	args->ifp	Incoming or outgoing interface.
1333  *	args->divert_rule (in/out)
1334  *		Skip up to the first rule past this rule number;
1335  *		upon return, non-zero port number for divert or tee.
1336  *
1337  *	args->rule	Pointer to the last matching rule (in/out)
1338  *	args->next_hop	Socket we are forwarding to (out).
1339  *	args->next_hop6	IPv6 next hop we are forwarding to (out).
1340  *	args->f_id	Addresses grabbed from the packet (out)
1341  * 	args->rule.info	a cookie depending on rule action
1342  *
1343  * Return value:
1344  *
1345  *	IP_FW_PASS	the packet must be accepted
1346  *	IP_FW_DENY	the packet must be dropped
1347  *	IP_FW_DIVERT	divert packet, port in m_tag
1348  *	IP_FW_TEE	tee packet, port in m_tag
1349  *	IP_FW_DUMMYNET	to dummynet, pipe in args->cookie
1350  *	IP_FW_NETGRAPH	into netgraph, cookie args->cookie
1351  *		args->rule contains the matching rule,
1352  *		args->rule.info has additional information.
1353  *
1354  */
1355 int
1356 ipfw_chk(struct ip_fw_args *args)
1357 {
1358 
1359 	/*
1360 	 * Local variables holding state while processing a packet:
1361 	 *
1362 	 * IMPORTANT NOTE: to speed up the processing of rules, there
1363 	 * are some assumption on the values of the variables, which
1364 	 * are documented here. Should you change them, please check
1365 	 * the implementation of the various instructions to make sure
1366 	 * that they still work.
1367 	 *
1368 	 * m | args->m	Pointer to the mbuf, as received from the caller.
1369 	 *	It may change if ipfw_chk() does an m_pullup, or if it
1370 	 *	consumes the packet because it calls send_reject().
1371 	 *	XXX This has to change, so that ipfw_chk() never modifies
1372 	 *	or consumes the buffer.
1373 	 *	OR
1374 	 * args->mem	Pointer to contigous memory chunk.
1375 	 * ip	Is the beginning of the ip(4 or 6) header.
1376 	 * eh	Ethernet header in case if input is Layer2.
1377 	 */
1378 	struct mbuf *m;
1379 	struct ip *ip;
1380 	struct ether_header *eh;
1381 
1382 	/*
1383 	 * For rules which contain uid/gid or jail constraints, cache
1384 	 * a copy of the users credentials after the pcb lookup has been
1385 	 * executed. This will speed up the processing of rules with
1386 	 * these types of constraints, as well as decrease contention
1387 	 * on pcb related locks.
1388 	 */
1389 #ifndef __FreeBSD__
1390 	struct bsd_ucred ucred_cache;
1391 #else
1392 	struct ucred *ucred_cache = NULL;
1393 #endif
1394 	int ucred_lookup = 0;
1395 	int f_pos = 0;		/* index of current rule in the array */
1396 	int retval = 0;
1397 	struct ifnet *oif, *iif;
1398 
1399 	/*
1400 	 * hlen	The length of the IP header.
1401 	 */
1402 	u_int hlen = 0;		/* hlen >0 means we have an IP pkt */
1403 
1404 	/*
1405 	 * offset	The offset of a fragment. offset != 0 means that
1406 	 *	we have a fragment at this offset of an IPv4 packet.
1407 	 *	offset == 0 means that (if this is an IPv4 packet)
1408 	 *	this is the first or only fragment.
1409 	 *	For IPv6 offset|ip6f_mf == 0 means there is no Fragment Header
1410 	 *	or there is a single packet fragment (fragment header added
1411 	 *	without needed).  We will treat a single packet fragment as if
1412 	 *	there was no fragment header (or log/block depending on the
1413 	 *	V_fw_permit_single_frag6 sysctl setting).
1414 	 */
1415 	u_short offset = 0;
1416 	u_short ip6f_mf = 0;
1417 
1418 	/*
1419 	 * Local copies of addresses. They are only valid if we have
1420 	 * an IP packet.
1421 	 *
1422 	 * proto	The protocol. Set to 0 for non-ip packets,
1423 	 *	or to the protocol read from the packet otherwise.
1424 	 *	proto != 0 means that we have an IPv4 packet.
1425 	 *
1426 	 * src_port, dst_port	port numbers, in HOST format. Only
1427 	 *	valid for TCP and UDP packets.
1428 	 *
1429 	 * src_ip, dst_ip	ip addresses, in NETWORK format.
1430 	 *	Only valid for IPv4 packets.
1431 	 */
1432 	uint8_t proto;
1433 	uint16_t src_port, dst_port;		/* NOTE: host format	*/
1434 	struct in_addr src_ip, dst_ip;		/* NOTE: network format	*/
1435 	int iplen = 0;
1436 	int pktlen;
1437 
1438 	struct ipfw_dyn_info dyn_info;
1439 	struct ip_fw *q = NULL;
1440 	struct ip_fw_chain *chain = &V_layer3_chain;
1441 
1442 	/*
1443 	 * We store in ulp a pointer to the upper layer protocol header.
1444 	 * In the ipv4 case this is easy to determine from the header,
1445 	 * but for ipv6 we might have some additional headers in the middle.
1446 	 * ulp is NULL if not found.
1447 	 */
1448 	void *ulp = NULL;		/* upper layer protocol pointer. */
1449 
1450 	/* XXX ipv6 variables */
1451 	int is_ipv6 = 0;
1452 #ifdef INET6
1453 	uint8_t	icmp6_type = 0;
1454 #endif
1455 	uint16_t ext_hd = 0;	/* bits vector for extension header filtering */
1456 	/* end of ipv6 variables */
1457 
1458 	int is_ipv4 = 0;
1459 
1460 	int done = 0;		/* flag to exit the outer loop */
1461 	IPFW_RLOCK_TRACKER;
1462 	bool mem;
1463 
1464 	if ((mem = (args->flags & IPFW_ARGS_LENMASK))) {
1465 		if (args->flags & IPFW_ARGS_ETHER) {
1466 			eh = (struct ether_header *)args->mem;
1467 			if (eh->ether_type == htons(ETHERTYPE_VLAN))
1468 				ip = (struct ip *)
1469 				    ((struct ether_vlan_header *)eh + 1);
1470 			else
1471 				ip = (struct ip *)(eh + 1);
1472 		} else {
1473 			eh = NULL;
1474 			ip = (struct ip *)args->mem;
1475 		}
1476 		pktlen = IPFW_ARGS_LENGTH(args->flags);
1477 		args->f_id.fib = args->ifp->if_fib;	/* best guess */
1478 	} else {
1479 		m = args->m;
1480 		if (m->m_flags & M_SKIP_FIREWALL || (! V_ipfw_vnet_ready))
1481 			return (IP_FW_PASS);	/* accept */
1482 		if (args->flags & IPFW_ARGS_ETHER) {
1483 	                /* We need some amount of data to be contiguous. */
1484 			if (m->m_len < min(m->m_pkthdr.len, max_protohdr) &&
1485 			    (args->m = m = m_pullup(m, min(m->m_pkthdr.len,
1486 			    max_protohdr))) == NULL)
1487 				goto pullup_failed;
1488 			eh = mtod(m, struct ether_header *);
1489 			ip = (struct ip *)(eh + 1);
1490 		} else {
1491 			eh = NULL;
1492 			ip = mtod(m, struct ip *);
1493 		}
1494 		pktlen = m->m_pkthdr.len;
1495 		args->f_id.fib = M_GETFIB(m); /* mbuf not altered */
1496 	}
1497 
1498 	dst_ip.s_addr = 0;		/* make sure it is initialized */
1499 	src_ip.s_addr = 0;		/* make sure it is initialized */
1500 	src_port = dst_port = 0;
1501 
1502 	DYN_INFO_INIT(&dyn_info);
1503 /*
1504  * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
1505  * then it sets p to point at the offset "len" in the mbuf. WARNING: the
1506  * pointer might become stale after other pullups (but we never use it
1507  * this way).
1508  */
1509 #define	PULLUP_TO(_len, p, T)	PULLUP_LEN(_len, p, sizeof(T))
1510 #define	EHLEN	(eh != NULL ? ((char *)ip - (char *)eh) : 0)
1511 #define	_PULLUP_LOCKED(_len, p, T, unlock)			\
1512 do {								\
1513 	int x = (_len) + T + EHLEN;				\
1514 	if (mem) {						\
1515 		if (__predict_false(pktlen < x)) {		\
1516 			unlock;					\
1517 			goto pullup_failed;			\
1518 		}						\
1519 		p = (char *)args->mem + (_len) + EHLEN;		\
1520 	} else {						\
1521 		if (__predict_false((m)->m_len < x)) {		\
1522 			args->m = m = m_pullup(m, x);		\
1523 			if (m == NULL) {			\
1524 				unlock;				\
1525 				goto pullup_failed;		\
1526 			}					\
1527 		}						\
1528 		p = mtod(m, char *) + (_len) + EHLEN;		\
1529 	}							\
1530 } while (0)
1531 
1532 #define	PULLUP_LEN(_len, p, T)	_PULLUP_LOCKED(_len, p, T, )
1533 #define	PULLUP_LEN_LOCKED(_len, p, T)	\
1534     _PULLUP_LOCKED(_len, p, T, IPFW_PF_RUNLOCK(chain));	\
1535     UPDATE_POINTERS()
1536 /*
1537  * In case pointers got stale after pullups, update them.
1538  */
1539 #define	UPDATE_POINTERS()					\
1540 do {								\
1541 	if (!mem) {						\
1542 		if (eh != NULL) {				\
1543 			eh = mtod(m, struct ether_header *);	\
1544 			ip = (struct ip *)(eh + 1);		\
1545 		} else						\
1546 			ip = mtod(m, struct ip *);		\
1547 		args->m = m;					\
1548 	}							\
1549 } while (0)
1550 
1551 	/* Identify IP packets and fill up variables. */
1552 	if (pktlen >= sizeof(struct ip6_hdr) &&
1553 	    (eh == NULL || eh->ether_type == htons(ETHERTYPE_IPV6)) &&
1554 	    ip->ip_v == 6) {
1555 		struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
1556 
1557 		is_ipv6 = 1;
1558 		args->flags |= IPFW_ARGS_IP6;
1559 		hlen = sizeof(struct ip6_hdr);
1560 		proto = ip6->ip6_nxt;
1561 		/* Search extension headers to find upper layer protocols */
1562 		while (ulp == NULL && offset == 0) {
1563 			switch (proto) {
1564 			case IPPROTO_ICMPV6:
1565 				PULLUP_TO(hlen, ulp, struct icmp6_hdr);
1566 #ifdef INET6
1567 				icmp6_type = ICMP6(ulp)->icmp6_type;
1568 #endif
1569 				break;
1570 
1571 			case IPPROTO_TCP:
1572 				PULLUP_TO(hlen, ulp, struct tcphdr);
1573 				dst_port = TCP(ulp)->th_dport;
1574 				src_port = TCP(ulp)->th_sport;
1575 				/* save flags for dynamic rules */
1576 				args->f_id._flags = TCP(ulp)->th_flags;
1577 				break;
1578 
1579 			case IPPROTO_SCTP:
1580 				if (pktlen >= hlen + sizeof(struct sctphdr) +
1581 				    sizeof(struct sctp_chunkhdr) +
1582 				    offsetof(struct sctp_init, a_rwnd))
1583 					PULLUP_LEN(hlen, ulp,
1584 					    sizeof(struct sctphdr) +
1585 					    sizeof(struct sctp_chunkhdr) +
1586 					    offsetof(struct sctp_init, a_rwnd));
1587 				else if (pktlen >= hlen + sizeof(struct sctphdr))
1588 					PULLUP_LEN(hlen, ulp, pktlen - hlen);
1589 				else
1590 					PULLUP_LEN(hlen, ulp,
1591 					    sizeof(struct sctphdr));
1592 				src_port = SCTP(ulp)->src_port;
1593 				dst_port = SCTP(ulp)->dest_port;
1594 				break;
1595 
1596 			case IPPROTO_UDP:
1597 			case IPPROTO_UDPLITE:
1598 				PULLUP_TO(hlen, ulp, struct udphdr);
1599 				dst_port = UDP(ulp)->uh_dport;
1600 				src_port = UDP(ulp)->uh_sport;
1601 				break;
1602 
1603 			case IPPROTO_HOPOPTS:	/* RFC 2460 */
1604 				PULLUP_TO(hlen, ulp, struct ip6_hbh);
1605 				ext_hd |= EXT_HOPOPTS;
1606 				hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1607 				proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1608 				ulp = NULL;
1609 				break;
1610 
1611 			case IPPROTO_ROUTING:	/* RFC 2460 */
1612 				PULLUP_TO(hlen, ulp, struct ip6_rthdr);
1613 				switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
1614 				case 0:
1615 					ext_hd |= EXT_RTHDR0;
1616 					break;
1617 				case 2:
1618 					ext_hd |= EXT_RTHDR2;
1619 					break;
1620 				default:
1621 					if (V_fw_verbose)
1622 						printf("IPFW2: IPV6 - Unknown "
1623 						    "Routing Header type(%d)\n",
1624 						    ((struct ip6_rthdr *)
1625 						    ulp)->ip6r_type);
1626 					if (V_fw_deny_unknown_exthdrs)
1627 					    return (IP_FW_DENY);
1628 					break;
1629 				}
1630 				ext_hd |= EXT_ROUTING;
1631 				hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
1632 				proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
1633 				ulp = NULL;
1634 				break;
1635 
1636 			case IPPROTO_FRAGMENT:	/* RFC 2460 */
1637 				PULLUP_TO(hlen, ulp, struct ip6_frag);
1638 				ext_hd |= EXT_FRAGMENT;
1639 				hlen += sizeof (struct ip6_frag);
1640 				proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
1641 				offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
1642 					IP6F_OFF_MASK;
1643 				ip6f_mf = ((struct ip6_frag *)ulp)->ip6f_offlg &
1644 					IP6F_MORE_FRAG;
1645 				if (V_fw_permit_single_frag6 == 0 &&
1646 				    offset == 0 && ip6f_mf == 0) {
1647 					if (V_fw_verbose)
1648 						printf("IPFW2: IPV6 - Invalid "
1649 						    "Fragment Header\n");
1650 					if (V_fw_deny_unknown_exthdrs)
1651 					    return (IP_FW_DENY);
1652 					break;
1653 				}
1654 				args->f_id.extra =
1655 				    ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
1656 				ulp = NULL;
1657 				break;
1658 
1659 			case IPPROTO_DSTOPTS:	/* RFC 2460 */
1660 				PULLUP_TO(hlen, ulp, struct ip6_hbh);
1661 				ext_hd |= EXT_DSTOPTS;
1662 				hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1663 				proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1664 				ulp = NULL;
1665 				break;
1666 
1667 			case IPPROTO_AH:	/* RFC 2402 */
1668 				PULLUP_TO(hlen, ulp, struct ip6_ext);
1669 				ext_hd |= EXT_AH;
1670 				hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
1671 				proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
1672 				ulp = NULL;
1673 				break;
1674 
1675 			case IPPROTO_ESP:	/* RFC 2406 */
1676 				PULLUP_TO(hlen, ulp, uint32_t);	/* SPI, Seq# */
1677 				/* Anything past Seq# is variable length and
1678 				 * data past this ext. header is encrypted. */
1679 				ext_hd |= EXT_ESP;
1680 				break;
1681 
1682 			case IPPROTO_NONE:	/* RFC 2460 */
1683 				/*
1684 				 * Packet ends here, and IPv6 header has
1685 				 * already been pulled up. If ip6e_len!=0
1686 				 * then octets must be ignored.
1687 				 */
1688 				ulp = ip; /* non-NULL to get out of loop. */
1689 				break;
1690 
1691 			case IPPROTO_OSPFIGP:
1692 				/* XXX OSPF header check? */
1693 				PULLUP_TO(hlen, ulp, struct ip6_ext);
1694 				break;
1695 
1696 			case IPPROTO_PIM:
1697 				/* XXX PIM header check? */
1698 				PULLUP_TO(hlen, ulp, struct pim);
1699 				break;
1700 
1701 			case IPPROTO_GRE:	/* RFC 1701 */
1702 				/* XXX GRE header check? */
1703 				PULLUP_TO(hlen, ulp, struct grehdr);
1704 				break;
1705 
1706 			case IPPROTO_CARP:
1707 				PULLUP_TO(hlen, ulp, offsetof(
1708 				    struct carp_header, carp_counter));
1709 				if (CARP_ADVERTISEMENT !=
1710 				    ((struct carp_header *)ulp)->carp_type)
1711 					return (IP_FW_DENY);
1712 				break;
1713 
1714 			case IPPROTO_IPV6:	/* RFC 2893 */
1715 				PULLUP_TO(hlen, ulp, struct ip6_hdr);
1716 				break;
1717 
1718 			case IPPROTO_IPV4:	/* RFC 2893 */
1719 				PULLUP_TO(hlen, ulp, struct ip);
1720 				break;
1721 
1722 			case IPPROTO_PFSYNC:
1723 				PULLUP_TO(hlen, ulp, struct pfsync_header);
1724 				break;
1725 
1726 			default:
1727 				if (V_fw_verbose)
1728 					printf("IPFW2: IPV6 - Unknown "
1729 					    "Extension Header(%d), ext_hd=%x\n",
1730 					     proto, ext_hd);
1731 				if (V_fw_deny_unknown_exthdrs)
1732 				    return (IP_FW_DENY);
1733 				PULLUP_TO(hlen, ulp, struct ip6_ext);
1734 				break;
1735 			} /*switch */
1736 		}
1737 		UPDATE_POINTERS();
1738 		ip6 = (struct ip6_hdr *)ip;
1739 		args->f_id.addr_type = 6;
1740 		args->f_id.src_ip6 = ip6->ip6_src;
1741 		args->f_id.dst_ip6 = ip6->ip6_dst;
1742 		args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
1743 		iplen = ntohs(ip6->ip6_plen) + sizeof(*ip6);
1744 	} else if (pktlen >= sizeof(struct ip) &&
1745 	    (eh == NULL || eh->ether_type == htons(ETHERTYPE_IP)) &&
1746 	    ip->ip_v == 4) {
1747 		is_ipv4 = 1;
1748 		args->flags |= IPFW_ARGS_IP4;
1749 		hlen = ip->ip_hl << 2;
1750 		/*
1751 		 * Collect parameters into local variables for faster
1752 		 * matching.
1753 		 */
1754 		proto = ip->ip_p;
1755 		src_ip = ip->ip_src;
1756 		dst_ip = ip->ip_dst;
1757 		offset = ntohs(ip->ip_off) & IP_OFFMASK;
1758 		iplen = ntohs(ip->ip_len);
1759 
1760 		if (offset == 0) {
1761 			switch (proto) {
1762 			case IPPROTO_TCP:
1763 				PULLUP_TO(hlen, ulp, struct tcphdr);
1764 				dst_port = TCP(ulp)->th_dport;
1765 				src_port = TCP(ulp)->th_sport;
1766 				/* save flags for dynamic rules */
1767 				args->f_id._flags = TCP(ulp)->th_flags;
1768 				break;
1769 
1770 			case IPPROTO_SCTP:
1771 				if (pktlen >= hlen + sizeof(struct sctphdr) +
1772 				    sizeof(struct sctp_chunkhdr) +
1773 				    offsetof(struct sctp_init, a_rwnd))
1774 					PULLUP_LEN(hlen, ulp,
1775 					    sizeof(struct sctphdr) +
1776 					    sizeof(struct sctp_chunkhdr) +
1777 					    offsetof(struct sctp_init, a_rwnd));
1778 				else if (pktlen >= hlen + sizeof(struct sctphdr))
1779 					PULLUP_LEN(hlen, ulp, pktlen - hlen);
1780 				else
1781 					PULLUP_LEN(hlen, ulp,
1782 					    sizeof(struct sctphdr));
1783 				src_port = SCTP(ulp)->src_port;
1784 				dst_port = SCTP(ulp)->dest_port;
1785 				break;
1786 
1787 			case IPPROTO_UDP:
1788 			case IPPROTO_UDPLITE:
1789 				PULLUP_TO(hlen, ulp, struct udphdr);
1790 				dst_port = UDP(ulp)->uh_dport;
1791 				src_port = UDP(ulp)->uh_sport;
1792 				break;
1793 
1794 			case IPPROTO_ICMP:
1795 				PULLUP_TO(hlen, ulp, struct icmphdr);
1796 				//args->f_id.flags = ICMP(ulp)->icmp_type;
1797 				break;
1798 
1799 			default:
1800 				break;
1801 			}
1802 		} else {
1803 			if (offset == 1 && proto == IPPROTO_TCP) {
1804 				/* RFC 3128 */
1805 				goto pullup_failed;
1806 			}
1807 		}
1808 
1809 		UPDATE_POINTERS();
1810 		args->f_id.addr_type = 4;
1811 		args->f_id.src_ip = ntohl(src_ip.s_addr);
1812 		args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1813 	} else {
1814 		proto = 0;
1815 		dst_ip.s_addr = src_ip.s_addr = 0;
1816 
1817 		args->f_id.addr_type = 1; /* XXX */
1818 	}
1819 #undef PULLUP_TO
1820 	pktlen = iplen < pktlen ? iplen: pktlen;
1821 
1822 	/* Properly initialize the rest of f_id */
1823 	args->f_id.proto = proto;
1824 	args->f_id.src_port = src_port = ntohs(src_port);
1825 	args->f_id.dst_port = dst_port = ntohs(dst_port);
1826 
1827 	IPFW_PF_RLOCK(chain);
1828 	if (! V_ipfw_vnet_ready) { /* shutting down, leave NOW. */
1829 		IPFW_PF_RUNLOCK(chain);
1830 		return (IP_FW_PASS);	/* accept */
1831 	}
1832 	if (args->flags & IPFW_ARGS_REF) {
1833 		/*
1834 		 * Packet has already been tagged as a result of a previous
1835 		 * match on rule args->rule aka args->rule_id (PIPE, QUEUE,
1836 		 * REASS, NETGRAPH, DIVERT/TEE...)
1837 		 * Validate the slot and continue from the next one
1838 		 * if still present, otherwise do a lookup.
1839 		 */
1840 		f_pos = (args->rule.chain_id == chain->id) ?
1841 		    args->rule.slot :
1842 		    ipfw_find_rule(chain, args->rule.rulenum,
1843 			args->rule.rule_id);
1844 	} else {
1845 		f_pos = 0;
1846 	}
1847 
1848 	if (args->flags & IPFW_ARGS_IN) {
1849 		iif = args->ifp;
1850 		oif = NULL;
1851 	} else {
1852 		MPASS(args->flags & IPFW_ARGS_OUT);
1853 		iif = mem ? NULL : m_rcvif(m);
1854 		oif = args->ifp;
1855 	}
1856 
1857 	/*
1858 	 * Now scan the rules, and parse microinstructions for each rule.
1859 	 * We have two nested loops and an inner switch. Sometimes we
1860 	 * need to break out of one or both loops, or re-enter one of
1861 	 * the loops with updated variables. Loop variables are:
1862 	 *
1863 	 *	f_pos (outer loop) points to the current rule.
1864 	 *		On output it points to the matching rule.
1865 	 *	done (outer loop) is used as a flag to break the loop.
1866 	 *	l (inner loop)	residual length of current rule.
1867 	 *		cmd points to the current microinstruction.
1868 	 *
1869 	 * We break the inner loop by setting l=0 and possibly
1870 	 * cmdlen=0 if we don't want to advance cmd.
1871 	 * We break the outer loop by setting done=1
1872 	 * We can restart the inner loop by setting l>0 and f_pos, f, cmd
1873 	 * as needed.
1874 	 */
1875 	for (; f_pos < chain->n_rules; f_pos++) {
1876 		ipfw_insn *cmd;
1877 		uint32_t tablearg = 0;
1878 		int l, cmdlen, skip_or; /* skip rest of OR block */
1879 		struct ip_fw *f;
1880 
1881 		f = chain->map[f_pos];
1882 		if (V_set_disable & (1 << f->set) )
1883 			continue;
1884 
1885 		skip_or = 0;
1886 		for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
1887 		    l -= cmdlen, cmd += cmdlen) {
1888 			int match;
1889 
1890 			/*
1891 			 * check_body is a jump target used when we find a
1892 			 * CHECK_STATE, and need to jump to the body of
1893 			 * the target rule.
1894 			 */
1895 
1896 /* check_body: */
1897 			cmdlen = F_LEN(cmd);
1898 			/*
1899 			 * An OR block (insn_1 || .. || insn_n) has the
1900 			 * F_OR bit set in all but the last instruction.
1901 			 * The first match will set "skip_or", and cause
1902 			 * the following instructions to be skipped until
1903 			 * past the one with the F_OR bit clear.
1904 			 */
1905 			if (skip_or) {		/* skip this instruction */
1906 				if ((cmd->len & F_OR) == 0)
1907 					skip_or = 0;	/* next one is good */
1908 				continue;
1909 			}
1910 			match = 0; /* set to 1 if we succeed */
1911 
1912 			switch (cmd->opcode) {
1913 			/*
1914 			 * The first set of opcodes compares the packet's
1915 			 * fields with some pattern, setting 'match' if a
1916 			 * match is found. At the end of the loop there is
1917 			 * logic to deal with F_NOT and F_OR flags associated
1918 			 * with the opcode.
1919 			 */
1920 			case O_NOP:
1921 				match = 1;
1922 				break;
1923 
1924 			case O_FORWARD_MAC:
1925 				printf("ipfw: opcode %d unimplemented\n",
1926 				    cmd->opcode);
1927 				break;
1928 
1929 			case O_GID:
1930 			case O_UID:
1931 			case O_JAIL:
1932 				/*
1933 				 * We only check offset == 0 && proto != 0,
1934 				 * as this ensures that we have a
1935 				 * packet with the ports info.
1936 				 */
1937 				if (offset != 0)
1938 					break;
1939 				if (proto == IPPROTO_TCP ||
1940 				    proto == IPPROTO_UDP ||
1941 				    proto == IPPROTO_UDPLITE)
1942 					match = check_uidgid(
1943 						    (ipfw_insn_u32 *)cmd,
1944 						    args, &ucred_lookup,
1945 #ifdef __FreeBSD__
1946 						    &ucred_cache);
1947 #else
1948 						    (void *)&ucred_cache);
1949 #endif
1950 				break;
1951 
1952 			case O_RECV:
1953 				match = iface_match(iif, (ipfw_insn_if *)cmd,
1954 				    chain, &tablearg);
1955 				break;
1956 
1957 			case O_XMIT:
1958 				match = iface_match(oif, (ipfw_insn_if *)cmd,
1959 				    chain, &tablearg);
1960 				break;
1961 
1962 			case O_VIA:
1963 				match = iface_match(args->ifp,
1964 				    (ipfw_insn_if *)cmd, chain, &tablearg);
1965 				break;
1966 
1967 			case O_MACADDR2:
1968 				if (args->flags & IPFW_ARGS_ETHER) {
1969 					u_int32_t *want = (u_int32_t *)
1970 						((ipfw_insn_mac *)cmd)->addr;
1971 					u_int32_t *mask = (u_int32_t *)
1972 						((ipfw_insn_mac *)cmd)->mask;
1973 					u_int32_t *hdr = (u_int32_t *)eh;
1974 
1975 					match =
1976 					    ( want[0] == (hdr[0] & mask[0]) &&
1977 					      want[1] == (hdr[1] & mask[1]) &&
1978 					      want[2] == (hdr[2] & mask[2]) );
1979 				}
1980 				break;
1981 
1982 			case O_MAC_TYPE:
1983 				if (args->flags & IPFW_ARGS_ETHER) {
1984 					u_int16_t *p =
1985 					    ((ipfw_insn_u16 *)cmd)->ports;
1986 					int i;
1987 
1988 					for (i = cmdlen - 1; !match && i>0;
1989 					    i--, p += 2)
1990 						match =
1991 						    (ntohs(eh->ether_type) >=
1992 						    p[0] &&
1993 						    ntohs(eh->ether_type) <=
1994 						    p[1]);
1995 				}
1996 				break;
1997 
1998 			case O_FRAG:
1999 				if (is_ipv4) {
2000 					/*
2001 					 * Since flags_match() works with
2002 					 * uint8_t we pack ip_off into 8 bits.
2003 					 * For this match offset is a boolean.
2004 					 */
2005 					match = flags_match(cmd,
2006 					    ((ntohs(ip->ip_off) & ~IP_OFFMASK)
2007 					    >> 8) | (offset != 0));
2008 				} else {
2009 					/*
2010 					 * Compatibility: historically bare
2011 					 * "frag" would match IPv6 fragments.
2012 					 */
2013 					match = (cmd->arg1 == 0x1 &&
2014 					    (offset != 0));
2015 				}
2016 				break;
2017 
2018 			case O_IN:	/* "out" is "not in" */
2019 				match = (oif == NULL);
2020 				break;
2021 
2022 			case O_LAYER2:
2023 				match = (args->flags & IPFW_ARGS_ETHER);
2024 				break;
2025 
2026 			case O_DIVERTED:
2027 				if ((args->flags & IPFW_ARGS_REF) == 0)
2028 					break;
2029 				/*
2030 				 * For diverted packets, args->rule.info
2031 				 * contains the divert port (in host format)
2032 				 * reason and direction.
2033 				 */
2034 				match = ((args->rule.info & IPFW_IS_MASK) ==
2035 				    IPFW_IS_DIVERT) && (
2036 				    ((args->rule.info & IPFW_INFO_IN) ?
2037 					1: 2) & cmd->arg1);
2038 				break;
2039 
2040 			case O_PROTO:
2041 				/*
2042 				 * We do not allow an arg of 0 so the
2043 				 * check of "proto" only suffices.
2044 				 */
2045 				match = (proto == cmd->arg1);
2046 				break;
2047 
2048 			case O_IP_SRC:
2049 				match = is_ipv4 &&
2050 				    (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2051 				    src_ip.s_addr);
2052 				break;
2053 
2054 			case O_IP_DST_LOOKUP:
2055 			{
2056 				if (cmdlen > F_INSN_SIZE(ipfw_insn_u32)) {
2057 					void *pkey;
2058 					uint32_t vidx, key;
2059 					uint16_t keylen = 0; /* zero if can't match the packet */
2060 
2061 					/* Determine lookup key type */
2062 					vidx = ((ipfw_insn_u32 *)cmd)->d[1];
2063 					switch (vidx) {
2064 					case LOOKUP_DST_IP:
2065 					case LOOKUP_SRC_IP:
2066 						/* Need IP frame */
2067 						if (is_ipv6 == 0 && is_ipv4 == 0)
2068 							break;
2069 						if (vidx == LOOKUP_DST_IP)
2070 							pkey = is_ipv6 ?
2071 								(void *)&args->f_id.dst_ip6:
2072 								(void *)&dst_ip;
2073 						else
2074 							pkey = is_ipv6 ?
2075 								(void *)&args->f_id.src_ip6:
2076 								(void *)&src_ip;
2077 						keylen = is_ipv6 ?
2078 							sizeof(struct in6_addr):
2079 							sizeof(in_addr_t);
2080 						break;
2081 					case LOOKUP_DST_PORT:
2082 					case LOOKUP_SRC_PORT:
2083 						/* Need IP frame */
2084 						if (is_ipv6 == 0 && is_ipv4 == 0)
2085 							break;
2086 						/* Skip fragments */
2087 						if (offset != 0)
2088 							break;
2089 						/* Skip proto without ports */
2090 						if (proto != IPPROTO_TCP &&
2091 							proto != IPPROTO_UDP &&
2092 							proto != IPPROTO_UDPLITE &&
2093 							proto != IPPROTO_SCTP)
2094 							break;
2095 						key = vidx == LOOKUP_DST_PORT ?
2096 							dst_port:
2097 							src_port;
2098 						pkey = &key;
2099 						keylen = sizeof(key);
2100 						break;
2101 					case LOOKUP_UID:
2102 					case LOOKUP_JAIL:
2103 						check_uidgid(
2104 						    (ipfw_insn_u32 *)cmd,
2105 						    args, &ucred_lookup,
2106 						    &ucred_cache);
2107 						key = vidx == LOOKUP_UID ?
2108 							ucred_cache->cr_uid:
2109 							ucred_cache->cr_prison->pr_id;
2110 						pkey = &key;
2111 						keylen = sizeof(key);
2112 						break;
2113 					case LOOKUP_DSCP:
2114 						/* Need IP frame */
2115 						if (is_ipv6 == 0 && is_ipv4 == 0)
2116 							break;
2117 						if (is_ipv6)
2118 							key = IPV6_DSCP(
2119 							    (struct ip6_hdr *)ip) >> 2;
2120 						else
2121 							key = ip->ip_tos >> 2;
2122 						pkey = &key;
2123 						keylen = sizeof(key);
2124 						break;
2125 					case LOOKUP_DST_MAC:
2126 					case LOOKUP_SRC_MAC:
2127 						/* Need ether frame */
2128 						if ((args->flags & IPFW_ARGS_ETHER) == 0)
2129 							break;
2130 						pkey = vidx == LOOKUP_DST_MAC ?
2131 							eh->ether_dhost:
2132 							eh->ether_shost;
2133 						keylen = ETHER_ADDR_LEN;
2134 						break;
2135 					case LOOKUP_MARK:
2136 						key = args->rule.pkt_mark;
2137 						pkey = &key;
2138 						keylen = sizeof(key);
2139 						break;
2140 					}
2141 					if (keylen == 0)
2142 						break;
2143 					match = ipfw_lookup_table(chain,
2144 					    cmd->arg1, keylen, pkey, &vidx);
2145 					if (!match)
2146 						break;
2147 					tablearg = vidx;
2148 					break;
2149 				}
2150 				/* cmdlen =< F_INSN_SIZE(ipfw_insn_u32) */
2151 				/* FALLTHROUGH */
2152 			}
2153 			case O_IP_SRC_LOOKUP:
2154 			{
2155 				void *pkey;
2156 				uint32_t vidx;
2157 				uint16_t keylen;
2158 
2159 				if (is_ipv4) {
2160 					keylen = sizeof(in_addr_t);
2161 					if (cmd->opcode == O_IP_DST_LOOKUP)
2162 						pkey = &dst_ip;
2163 					else
2164 						pkey = &src_ip;
2165 				} else if (is_ipv6) {
2166 					keylen = sizeof(struct in6_addr);
2167 					if (cmd->opcode == O_IP_DST_LOOKUP)
2168 						pkey = &args->f_id.dst_ip6;
2169 					else
2170 						pkey = &args->f_id.src_ip6;
2171 				} else
2172 					break;
2173 				match = ipfw_lookup_table(chain, cmd->arg1,
2174 				    keylen, pkey, &vidx);
2175 				if (!match)
2176 					break;
2177 				if (cmdlen == F_INSN_SIZE(ipfw_insn_u32)) {
2178 					match = ((ipfw_insn_u32 *)cmd)->d[0] ==
2179 					    TARG_VAL(chain, vidx, tag);
2180 					if (!match)
2181 						break;
2182 				}
2183 				tablearg = vidx;
2184 				break;
2185 			}
2186 
2187 			case O_MAC_SRC_LOOKUP:
2188 			case O_MAC_DST_LOOKUP:
2189 			{
2190 				void *pkey;
2191 				uint32_t vidx;
2192 				uint16_t keylen = ETHER_ADDR_LEN;
2193 
2194 				/* Need ether frame */
2195 				if ((args->flags & IPFW_ARGS_ETHER) == 0)
2196 					break;
2197 
2198 				if (cmd->opcode == O_MAC_DST_LOOKUP)
2199 					pkey = eh->ether_dhost;
2200 				else
2201 					pkey = eh->ether_shost;
2202 
2203 				match = ipfw_lookup_table(chain, cmd->arg1,
2204 				    keylen, pkey, &vidx);
2205 				if (!match)
2206 					break;
2207 				if (cmdlen == F_INSN_SIZE(ipfw_insn_u32)) {
2208 					match = ((ipfw_insn_u32 *)cmd)->d[0] ==
2209 					    TARG_VAL(chain, vidx, tag);
2210 					if (!match)
2211 						break;
2212 				}
2213 				tablearg = vidx;
2214 				break;
2215 			}
2216 
2217 			case O_IP_FLOW_LOOKUP:
2218 				{
2219 					uint32_t v = 0;
2220 					match = ipfw_lookup_table(chain,
2221 					    cmd->arg1, 0, &args->f_id, &v);
2222 					if (!match)
2223 						break;
2224 					if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
2225 						match = ((ipfw_insn_u32 *)cmd)->d[0] ==
2226 						    TARG_VAL(chain, v, tag);
2227 					if (match)
2228 						tablearg = v;
2229 				}
2230 				break;
2231 			case O_IP_SRC_MASK:
2232 			case O_IP_DST_MASK:
2233 				if (is_ipv4) {
2234 				    uint32_t a =
2235 					(cmd->opcode == O_IP_DST_MASK) ?
2236 					    dst_ip.s_addr : src_ip.s_addr;
2237 				    uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
2238 				    int i = cmdlen-1;
2239 
2240 				    for (; !match && i>0; i-= 2, p+= 2)
2241 					match = (p[0] == (a & p[1]));
2242 				}
2243 				break;
2244 
2245 			case O_IP_SRC_ME:
2246 				if (is_ipv4) {
2247 					match = in_localip(src_ip);
2248 					break;
2249 				}
2250 #ifdef INET6
2251 				/* FALLTHROUGH */
2252 			case O_IP6_SRC_ME:
2253 				match = is_ipv6 &&
2254 				    ipfw_localip6(&args->f_id.src_ip6);
2255 #endif
2256 				break;
2257 
2258 			case O_IP_DST_SET:
2259 			case O_IP_SRC_SET:
2260 				if (is_ipv4) {
2261 					u_int32_t *d = (u_int32_t *)(cmd+1);
2262 					u_int32_t addr =
2263 					    cmd->opcode == O_IP_DST_SET ?
2264 						args->f_id.dst_ip :
2265 						args->f_id.src_ip;
2266 
2267 					    if (addr < d[0])
2268 						    break;
2269 					    addr -= d[0]; /* subtract base */
2270 					    match = (addr < cmd->arg1) &&
2271 						( d[ 1 + (addr>>5)] &
2272 						  (1<<(addr & 0x1f)) );
2273 				}
2274 				break;
2275 
2276 			case O_IP_DST:
2277 				match = is_ipv4 &&
2278 				    (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2279 				    dst_ip.s_addr);
2280 				break;
2281 
2282 			case O_IP_DST_ME:
2283 				if (is_ipv4) {
2284 					match = in_localip(dst_ip);
2285 					break;
2286 				}
2287 #ifdef INET6
2288 				/* FALLTHROUGH */
2289 			case O_IP6_DST_ME:
2290 				match = is_ipv6 &&
2291 				    ipfw_localip6(&args->f_id.dst_ip6);
2292 #endif
2293 				break;
2294 
2295 			case O_IP_SRCPORT:
2296 			case O_IP_DSTPORT:
2297 				/*
2298 				 * offset == 0 && proto != 0 is enough
2299 				 * to guarantee that we have a
2300 				 * packet with port info.
2301 				 */
2302 				if ((proto == IPPROTO_UDP ||
2303 				    proto == IPPROTO_UDPLITE ||
2304 				    proto == IPPROTO_TCP ||
2305 				    proto == IPPROTO_SCTP) && offset == 0) {
2306 					u_int16_t x =
2307 					    (cmd->opcode == O_IP_SRCPORT) ?
2308 						src_port : dst_port ;
2309 					u_int16_t *p =
2310 					    ((ipfw_insn_u16 *)cmd)->ports;
2311 					int i;
2312 
2313 					for (i = cmdlen - 1; !match && i>0;
2314 					    i--, p += 2)
2315 						match = (x>=p[0] && x<=p[1]);
2316 				}
2317 				break;
2318 
2319 			case O_ICMPTYPE:
2320 				match = (offset == 0 && proto==IPPROTO_ICMP &&
2321 				    icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
2322 				break;
2323 
2324 #ifdef INET6
2325 			case O_ICMP6TYPE:
2326 				match = is_ipv6 && offset == 0 &&
2327 				    proto==IPPROTO_ICMPV6 &&
2328 				    icmp6type_match(
2329 					ICMP6(ulp)->icmp6_type,
2330 					(ipfw_insn_u32 *)cmd);
2331 				break;
2332 #endif /* INET6 */
2333 
2334 			case O_IPOPT:
2335 				match = (is_ipv4 &&
2336 				    ipopts_match(ip, cmd) );
2337 				break;
2338 
2339 			case O_IPVER:
2340 				match = ((is_ipv4 || is_ipv6) &&
2341 				    cmd->arg1 == ip->ip_v);
2342 				break;
2343 
2344 			case O_IPID:
2345 			case O_IPTTL:
2346 				if (!is_ipv4)
2347 					break;
2348 			case O_IPLEN:
2349 				{	/* only for IP packets */
2350 				    uint16_t x;
2351 				    uint16_t *p;
2352 				    int i;
2353 
2354 				    if (cmd->opcode == O_IPLEN)
2355 					x = iplen;
2356 				    else if (cmd->opcode == O_IPTTL)
2357 					x = ip->ip_ttl;
2358 				    else /* must be IPID */
2359 					x = ntohs(ip->ip_id);
2360 				    if (cmdlen == 1) {
2361 					match = (cmd->arg1 == x);
2362 					break;
2363 				    }
2364 				    /* otherwise we have ranges */
2365 				    p = ((ipfw_insn_u16 *)cmd)->ports;
2366 				    i = cmdlen - 1;
2367 				    for (; !match && i>0; i--, p += 2)
2368 					match = (x >= p[0] && x <= p[1]);
2369 				}
2370 				break;
2371 
2372 			case O_IPPRECEDENCE:
2373 				match = (is_ipv4 &&
2374 				    (cmd->arg1 == (ip->ip_tos & 0xe0)) );
2375 				break;
2376 
2377 			case O_IPTOS:
2378 				match = (is_ipv4 &&
2379 				    flags_match(cmd, ip->ip_tos));
2380 				break;
2381 
2382 			case O_DSCP:
2383 			    {
2384 				uint32_t *p;
2385 				uint16_t x;
2386 
2387 				p = ((ipfw_insn_u32 *)cmd)->d;
2388 
2389 				if (is_ipv4)
2390 					x = ip->ip_tos >> 2;
2391 				else if (is_ipv6) {
2392 					x = IPV6_DSCP(
2393 					    (struct ip6_hdr *)ip) >> 2;
2394 					x &= 0x3f;
2395 				} else
2396 					break;
2397 
2398 				/* DSCP bitmask is stored as low_u32 high_u32 */
2399 				if (x >= 32)
2400 					match = *(p + 1) & (1 << (x - 32));
2401 				else
2402 					match = *p & (1 << x);
2403 			    }
2404 				break;
2405 
2406 			case O_TCPDATALEN:
2407 				if (proto == IPPROTO_TCP && offset == 0) {
2408 				    struct tcphdr *tcp;
2409 				    uint16_t x;
2410 				    uint16_t *p;
2411 				    int i;
2412 #ifdef INET6
2413 				    if (is_ipv6) {
2414 					    struct ip6_hdr *ip6;
2415 
2416 					    ip6 = (struct ip6_hdr *)ip;
2417 					    if (ip6->ip6_plen == 0) {
2418 						    /*
2419 						     * Jumbo payload is not
2420 						     * supported by this
2421 						     * opcode.
2422 						     */
2423 						    break;
2424 					    }
2425 					    x = iplen - hlen;
2426 				    } else
2427 #endif /* INET6 */
2428 					    x = iplen - (ip->ip_hl << 2);
2429 				    tcp = TCP(ulp);
2430 				    x -= tcp->th_off << 2;
2431 				    if (cmdlen == 1) {
2432 					match = (cmd->arg1 == x);
2433 					break;
2434 				    }
2435 				    /* otherwise we have ranges */
2436 				    p = ((ipfw_insn_u16 *)cmd)->ports;
2437 				    i = cmdlen - 1;
2438 				    for (; !match && i>0; i--, p += 2)
2439 					match = (x >= p[0] && x <= p[1]);
2440 				}
2441 				break;
2442 
2443 			case O_TCPFLAGS:
2444 				match = (proto == IPPROTO_TCP && offset == 0 &&
2445 				    flags_match(cmd, TCP(ulp)->th_flags));
2446 				break;
2447 
2448 			case O_TCPOPTS:
2449 				if (proto == IPPROTO_TCP && offset == 0 && ulp){
2450 					PULLUP_LEN_LOCKED(hlen, ulp,
2451 					    (TCP(ulp)->th_off << 2));
2452 					match = tcpopts_match(TCP(ulp), cmd);
2453 				}
2454 				break;
2455 
2456 			case O_TCPSEQ:
2457 				match = (proto == IPPROTO_TCP && offset == 0 &&
2458 				    ((ipfw_insn_u32 *)cmd)->d[0] ==
2459 					TCP(ulp)->th_seq);
2460 				break;
2461 
2462 			case O_TCPACK:
2463 				match = (proto == IPPROTO_TCP && offset == 0 &&
2464 				    ((ipfw_insn_u32 *)cmd)->d[0] ==
2465 					TCP(ulp)->th_ack);
2466 				break;
2467 
2468 			case O_TCPMSS:
2469 				if (proto == IPPROTO_TCP &&
2470 				    (args->f_id._flags & TH_SYN) != 0 &&
2471 				    ulp != NULL) {
2472 					uint16_t mss, *p;
2473 					int i;
2474 
2475 					PULLUP_LEN_LOCKED(hlen, ulp,
2476 					    (TCP(ulp)->th_off << 2));
2477 					if ((tcpopts_parse(TCP(ulp), &mss) &
2478 					    IP_FW_TCPOPT_MSS) == 0)
2479 						break;
2480 					if (cmdlen == 1) {
2481 						match = (cmd->arg1 == mss);
2482 						break;
2483 					}
2484 					/* Otherwise we have ranges. */
2485 					p = ((ipfw_insn_u16 *)cmd)->ports;
2486 					i = cmdlen - 1;
2487 					for (; !match && i > 0; i--, p += 2)
2488 						match = (mss >= p[0] &&
2489 						    mss <= p[1]);
2490 				}
2491 				break;
2492 
2493 			case O_TCPWIN:
2494 				if (proto == IPPROTO_TCP && offset == 0) {
2495 				    uint16_t x;
2496 				    uint16_t *p;
2497 				    int i;
2498 
2499 				    x = ntohs(TCP(ulp)->th_win);
2500 				    if (cmdlen == 1) {
2501 					match = (cmd->arg1 == x);
2502 					break;
2503 				    }
2504 				    /* Otherwise we have ranges. */
2505 				    p = ((ipfw_insn_u16 *)cmd)->ports;
2506 				    i = cmdlen - 1;
2507 				    for (; !match && i > 0; i--, p += 2)
2508 					match = (x >= p[0] && x <= p[1]);
2509 				}
2510 				break;
2511 
2512 			case O_ESTAB:
2513 				/* reject packets which have SYN only */
2514 				/* XXX should i also check for TH_ACK ? */
2515 				match = (proto == IPPROTO_TCP && offset == 0 &&
2516 				    (TCP(ulp)->th_flags &
2517 				     (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2518 				break;
2519 
2520 			case O_ALTQ: {
2521 				struct pf_mtag *at;
2522 				struct m_tag *mtag;
2523 				ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
2524 
2525 				/*
2526 				 * ALTQ uses mbuf tags from another
2527 				 * packet filtering system - pf(4).
2528 				 * We allocate a tag in its format
2529 				 * and fill it in, pretending to be pf(4).
2530 				 */
2531 				match = 1;
2532 				at = pf_find_mtag(m);
2533 				if (at != NULL && at->qid != 0)
2534 					break;
2535 				mtag = m_tag_get(PACKET_TAG_PF,
2536 				    sizeof(struct pf_mtag), M_NOWAIT | M_ZERO);
2537 				if (mtag == NULL) {
2538 					/*
2539 					 * Let the packet fall back to the
2540 					 * default ALTQ.
2541 					 */
2542 					break;
2543 				}
2544 				m_tag_prepend(m, mtag);
2545 				at = (struct pf_mtag *)(mtag + 1);
2546 				at->qid = altq->qid;
2547 				at->hdr = ip;
2548 				break;
2549 			}
2550 
2551 			case O_LOG:
2552 				ipfw_log(chain, f, hlen, args,
2553 				    offset | ip6f_mf, tablearg, ip);
2554 				match = 1;
2555 				break;
2556 
2557 			case O_PROB:
2558 				match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
2559 				break;
2560 
2561 			case O_VERREVPATH:
2562 				/* Outgoing packets automatically pass/match */
2563 				match = (args->flags & IPFW_ARGS_OUT ||
2564 				    (
2565 #ifdef INET6
2566 				    is_ipv6 ?
2567 					verify_path6(&(args->f_id.src_ip6),
2568 					    iif, args->f_id.fib) :
2569 #endif
2570 				    verify_path(src_ip, iif, args->f_id.fib)));
2571 				break;
2572 
2573 			case O_VERSRCREACH:
2574 				/* Outgoing packets automatically pass/match */
2575 				match = (hlen > 0 && ((oif != NULL) || (
2576 #ifdef INET6
2577 				    is_ipv6 ?
2578 				        verify_path6(&(args->f_id.src_ip6),
2579 				            NULL, args->f_id.fib) :
2580 #endif
2581 				    verify_path(src_ip, NULL, args->f_id.fib))));
2582 				break;
2583 
2584 			case O_ANTISPOOF:
2585 				/* Outgoing packets automatically pass/match */
2586 				if (oif == NULL && hlen > 0 &&
2587 				    (  (is_ipv4 && in_localaddr(src_ip))
2588 #ifdef INET6
2589 				    || (is_ipv6 &&
2590 				        in6_localaddr(&(args->f_id.src_ip6)))
2591 #endif
2592 				    ))
2593 					match =
2594 #ifdef INET6
2595 					    is_ipv6 ? verify_path6(
2596 					        &(args->f_id.src_ip6), iif,
2597 						args->f_id.fib) :
2598 #endif
2599 					    verify_path(src_ip, iif,
2600 					        args->f_id.fib);
2601 				else
2602 					match = 1;
2603 				break;
2604 
2605 			case O_IPSEC:
2606 				match = (m_tag_find(m,
2607 				    PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
2608 				/* otherwise no match */
2609 				break;
2610 
2611 #ifdef INET6
2612 			case O_IP6_SRC:
2613 				match = is_ipv6 &&
2614 				    IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
2615 				    &((ipfw_insn_ip6 *)cmd)->addr6);
2616 				break;
2617 
2618 			case O_IP6_DST:
2619 				match = is_ipv6 &&
2620 				IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
2621 				    &((ipfw_insn_ip6 *)cmd)->addr6);
2622 				break;
2623 			case O_IP6_SRC_MASK:
2624 			case O_IP6_DST_MASK:
2625 				if (is_ipv6) {
2626 					int i = cmdlen - 1;
2627 					struct in6_addr p;
2628 					struct in6_addr *d =
2629 					    &((ipfw_insn_ip6 *)cmd)->addr6;
2630 
2631 					for (; !match && i > 0; d += 2,
2632 					    i -= F_INSN_SIZE(struct in6_addr)
2633 					    * 2) {
2634 						p = (cmd->opcode ==
2635 						    O_IP6_SRC_MASK) ?
2636 						    args->f_id.src_ip6:
2637 						    args->f_id.dst_ip6;
2638 						APPLY_MASK(&p, &d[1]);
2639 						match =
2640 						    IN6_ARE_ADDR_EQUAL(&d[0],
2641 						    &p);
2642 					}
2643 				}
2644 				break;
2645 
2646 			case O_FLOW6ID:
2647 				match = is_ipv6 &&
2648 				    flow6id_match(args->f_id.flow_id6,
2649 				    (ipfw_insn_u32 *) cmd);
2650 				break;
2651 
2652 			case O_EXT_HDR:
2653 				match = is_ipv6 &&
2654 				    (ext_hd & ((ipfw_insn *) cmd)->arg1);
2655 				break;
2656 
2657 			case O_IP6:
2658 				match = is_ipv6;
2659 				break;
2660 #endif
2661 
2662 			case O_IP4:
2663 				match = is_ipv4;
2664 				break;
2665 
2666 			case O_TAG: {
2667 				struct m_tag *mtag;
2668 				uint32_t tag = TARG(cmd->arg1, tag);
2669 
2670 				/* Packet is already tagged with this tag? */
2671 				mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
2672 
2673 				/* We have `untag' action when F_NOT flag is
2674 				 * present. And we must remove this mtag from
2675 				 * mbuf and reset `match' to zero (`match' will
2676 				 * be inversed later).
2677 				 * Otherwise we should allocate new mtag and
2678 				 * push it into mbuf.
2679 				 */
2680 				if (cmd->len & F_NOT) { /* `untag' action */
2681 					if (mtag != NULL)
2682 						m_tag_delete(m, mtag);
2683 					match = 0;
2684 				} else {
2685 					if (mtag == NULL) {
2686 						mtag = m_tag_alloc( MTAG_IPFW,
2687 						    tag, 0, M_NOWAIT);
2688 						if (mtag != NULL)
2689 							m_tag_prepend(m, mtag);
2690 					}
2691 					match = 1;
2692 				}
2693 				break;
2694 			}
2695 
2696 			case O_FIB: /* try match the specified fib */
2697 				if (args->f_id.fib == cmd->arg1)
2698 					match = 1;
2699 				break;
2700 
2701 			case O_SOCKARG:	{
2702 #ifndef USERSPACE	/* not supported in userspace */
2703 				struct inpcb *inp = args->inp;
2704 				struct inpcbinfo *pi;
2705 				bool inp_locked = false;
2706 
2707 				if (proto == IPPROTO_TCP)
2708 					pi = &V_tcbinfo;
2709 				else if (proto == IPPROTO_UDP)
2710 					pi = &V_udbinfo;
2711 				else if (proto == IPPROTO_UDPLITE)
2712 					pi = &V_ulitecbinfo;
2713 				else
2714 					break;
2715 
2716 				/*
2717 				 * XXXRW: so_user_cookie should almost
2718 				 * certainly be inp_user_cookie?
2719 				 */
2720 
2721 				/*
2722 				 * For incoming packet lookup the inpcb
2723 				 * using the src/dest ip/port tuple.
2724 				 */
2725 				if (is_ipv4 && inp == NULL) {
2726 					inp = in_pcblookup(pi,
2727 					    src_ip, htons(src_port),
2728 					    dst_ip, htons(dst_port),
2729 					    INPLOOKUP_RLOCKPCB, NULL);
2730 					inp_locked = true;
2731 				}
2732 #ifdef INET6
2733 				if (is_ipv6 && inp == NULL) {
2734 					inp = in6_pcblookup(pi,
2735 					    &args->f_id.src_ip6,
2736 					    htons(src_port),
2737 					    &args->f_id.dst_ip6,
2738 					    htons(dst_port),
2739 					    INPLOOKUP_RLOCKPCB, NULL);
2740 					inp_locked = true;
2741 				}
2742 #endif /* INET6 */
2743 				if (inp != NULL) {
2744 					if (inp->inp_socket) {
2745 						tablearg =
2746 						    inp->inp_socket->so_user_cookie;
2747 						if (tablearg)
2748 							match = 1;
2749 					}
2750 					if (inp_locked)
2751 						INP_RUNLOCK(inp);
2752 				}
2753 #endif /* !USERSPACE */
2754 				break;
2755 			}
2756 
2757 			case O_TAGGED: {
2758 				struct m_tag *mtag;
2759 				uint32_t tag = TARG(cmd->arg1, tag);
2760 
2761 				if (cmdlen == 1) {
2762 					match = m_tag_locate(m, MTAG_IPFW,
2763 					    tag, NULL) != NULL;
2764 					break;
2765 				}
2766 
2767 				/* we have ranges */
2768 				for (mtag = m_tag_first(m);
2769 				    mtag != NULL && !match;
2770 				    mtag = m_tag_next(m, mtag)) {
2771 					uint16_t *p;
2772 					int i;
2773 
2774 					if (mtag->m_tag_cookie != MTAG_IPFW)
2775 						continue;
2776 
2777 					p = ((ipfw_insn_u16 *)cmd)->ports;
2778 					i = cmdlen - 1;
2779 					for(; !match && i > 0; i--, p += 2)
2780 						match =
2781 						    mtag->m_tag_id >= p[0] &&
2782 						    mtag->m_tag_id <= p[1];
2783 				}
2784 				break;
2785 			}
2786 
2787 			case O_MARK: {
2788 				uint32_t mark;
2789 				if (cmd->arg1 == IP_FW_TARG)
2790 					mark = TARG_VAL(chain, tablearg, mark);
2791 				else
2792 					mark = ((ipfw_insn_u32 *)cmd)->d[0];
2793 				match =
2794 				    (args->rule.pkt_mark &
2795 				    ((ipfw_insn_u32 *)cmd)->d[1]) ==
2796 				    (mark & ((ipfw_insn_u32 *)cmd)->d[1]);
2797 				break;
2798 			}
2799 
2800 			/*
2801 			 * The second set of opcodes represents 'actions',
2802 			 * i.e. the terminal part of a rule once the packet
2803 			 * matches all previous patterns.
2804 			 * Typically there is only one action for each rule,
2805 			 * and the opcode is stored at the end of the rule
2806 			 * (but there are exceptions -- see below).
2807 			 *
2808 			 * In general, here we set retval and terminate the
2809 			 * outer loop (would be a 'break 3' in some language,
2810 			 * but we need to set l=0, done=1)
2811 			 *
2812 			 * Exceptions:
2813 			 * O_COUNT and O_SKIPTO actions:
2814 			 *   instead of terminating, we jump to the next rule
2815 			 *   (setting l=0), or to the SKIPTO target (setting
2816 			 *   f/f_len, cmd and l as needed), respectively.
2817 			 *
2818 			 * O_TAG, O_LOG and O_ALTQ action parameters:
2819 			 *   perform some action and set match = 1;
2820 			 *
2821 			 * O_LIMIT and O_KEEP_STATE: these opcodes are
2822 			 *   not real 'actions', and are stored right
2823 			 *   before the 'action' part of the rule (one
2824 			 *   exception is O_SKIP_ACTION which could be
2825 			 *   between these opcodes and 'action' one).
2826 			 *   These opcodes try to install an entry in the
2827 			 *   state tables; if successful, we continue with
2828 			 *   the next opcode (match=1; break;), otherwise
2829 			 *   the packet must be dropped (set retval,
2830 			 *   break loops with l=0, done=1)
2831 			 *
2832 			 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2833 			 *   cause a lookup of the state table, and a jump
2834 			 *   to the 'action' part of the parent rule
2835 			 *   if an entry is found, or
2836 			 *   (CHECK_STATE only) a jump to the next rule if
2837 			 *   the entry is not found.
2838 			 *   The result of the lookup is cached so that
2839 			 *   further instances of these opcodes become NOPs.
2840 			 *   The jump to the next rule is done by setting
2841 			 *   l=0, cmdlen=0.
2842 			 *
2843 			 * O_SKIP_ACTION: this opcode is not a real 'action'
2844 			 *  either, and is stored right before the 'action'
2845 			 *  part of the rule, right after the O_KEEP_STATE
2846 			 *  opcode. It causes match failure so the real
2847 			 *  'action' could be executed only if the rule
2848 			 *  is checked via dynamic rule from the state
2849 			 *  table, as in such case execution starts
2850 			 *  from the true 'action' opcode directly.
2851 			 *
2852 			 */
2853 			case O_LIMIT:
2854 			case O_KEEP_STATE:
2855 				if (ipfw_dyn_install_state(chain, f,
2856 				    (ipfw_insn_limit *)cmd, args, ulp,
2857 				    pktlen, &dyn_info, tablearg)) {
2858 					/* error or limit violation */
2859 					retval = IP_FW_DENY;
2860 					l = 0;	/* exit inner loop */
2861 					done = 1; /* exit outer loop */
2862 				}
2863 				match = 1;
2864 				break;
2865 
2866 			case O_PROBE_STATE:
2867 			case O_CHECK_STATE:
2868 				/*
2869 				 * dynamic rules are checked at the first
2870 				 * keep-state or check-state occurrence,
2871 				 * with the result being stored in dyn_info.
2872 				 * The compiler introduces a PROBE_STATE
2873 				 * instruction for us when we have a
2874 				 * KEEP_STATE (because PROBE_STATE needs
2875 				 * to be run first).
2876 				 */
2877 				if (DYN_LOOKUP_NEEDED(&dyn_info, cmd) &&
2878 				    (q = ipfw_dyn_lookup_state(args, ulp,
2879 				    pktlen, cmd, &dyn_info)) != NULL) {
2880 					/*
2881 					 * Found dynamic entry, jump to the
2882 					 * 'action' part of the parent rule
2883 					 * by setting f, cmd, l and clearing
2884 					 * cmdlen.
2885 					 */
2886 					f = q;
2887 					f_pos = dyn_info.f_pos;
2888 					cmd = ACTION_PTR(f);
2889 					l = f->cmd_len - f->act_ofs;
2890 					cmdlen = 0;
2891 					match = 1;
2892 					break;
2893 				}
2894 				/*
2895 				 * Dynamic entry not found. If CHECK_STATE,
2896 				 * skip to next rule, if PROBE_STATE just
2897 				 * ignore and continue with next opcode.
2898 				 */
2899 				if (cmd->opcode == O_CHECK_STATE)
2900 					l = 0;	/* exit inner loop */
2901 				match = 1;
2902 				break;
2903 
2904 			case O_SKIP_ACTION:
2905 				match = 0;	/* skip to the next rule */
2906 				l = 0;		/* exit inner loop */
2907 				break;
2908 
2909 			case O_ACCEPT:
2910 				retval = 0;	/* accept */
2911 				l = 0;		/* exit inner loop */
2912 				done = 1;	/* exit outer loop */
2913 				break;
2914 
2915 			case O_PIPE:
2916 			case O_QUEUE:
2917 				set_match(args, f_pos, chain);
2918 				args->rule.info = TARG(cmd->arg1, pipe);
2919 				if (cmd->opcode == O_PIPE)
2920 					args->rule.info |= IPFW_IS_PIPE;
2921 				if (V_fw_one_pass)
2922 					args->rule.info |= IPFW_ONEPASS;
2923 				retval = IP_FW_DUMMYNET;
2924 				l = 0;          /* exit inner loop */
2925 				done = 1;       /* exit outer loop */
2926 				break;
2927 
2928 			case O_DIVERT:
2929 			case O_TEE:
2930 				if (args->flags & IPFW_ARGS_ETHER)
2931 					break;	/* not on layer 2 */
2932 				/* otherwise this is terminal */
2933 				l = 0;		/* exit inner loop */
2934 				done = 1;	/* exit outer loop */
2935 				retval = (cmd->opcode == O_DIVERT) ?
2936 					IP_FW_DIVERT : IP_FW_TEE;
2937 				set_match(args, f_pos, chain);
2938 				args->rule.info = TARG(cmd->arg1, divert);
2939 				break;
2940 
2941 			case O_COUNT:
2942 				IPFW_INC_RULE_COUNTER(f, pktlen);
2943 				l = 0;		/* exit inner loop */
2944 				break;
2945 
2946 			case O_SKIPTO:
2947 			    IPFW_INC_RULE_COUNTER(f, pktlen);
2948 			    f_pos = JUMP(chain, f, cmd->arg1, tablearg, 0);
2949 			    /*
2950 			     * Skip disabled rules, and re-enter
2951 			     * the inner loop with the correct
2952 			     * f_pos, f, l and cmd.
2953 			     * Also clear cmdlen and skip_or
2954 			     */
2955 			    for (; f_pos < chain->n_rules - 1 &&
2956 				    (V_set_disable &
2957 				     (1 << chain->map[f_pos]->set));
2958 				    f_pos++)
2959 				;
2960 			    /* Re-enter the inner loop at the skipto rule. */
2961 			    f = chain->map[f_pos];
2962 			    l = f->cmd_len;
2963 			    cmd = f->cmd;
2964 			    match = 1;
2965 			    cmdlen = 0;
2966 			    skip_or = 0;
2967 			    continue;
2968 			    break;	/* not reached */
2969 
2970 			case O_CALLRETURN: {
2971 				/*
2972 				 * Implementation of `subroutine' call/return,
2973 				 * in the stack carried in an mbuf tag. This
2974 				 * is different from `skipto' in that any call
2975 				 * address is possible (`skipto' must prevent
2976 				 * backward jumps to avoid endless loops).
2977 				 * We have `return' action when F_NOT flag is
2978 				 * present. The `m_tag_id' field is used as
2979 				 * stack pointer.
2980 				 */
2981 				struct m_tag *mtag;
2982 				uint16_t jmpto, *stack;
2983 
2984 #define	IS_CALL		((cmd->len & F_NOT) == 0)
2985 #define	IS_RETURN	((cmd->len & F_NOT) != 0)
2986 				/*
2987 				 * Hand-rolled version of m_tag_locate() with
2988 				 * wildcard `type'.
2989 				 * If not already tagged, allocate new tag.
2990 				 */
2991 				mtag = m_tag_first(m);
2992 				while (mtag != NULL) {
2993 					if (mtag->m_tag_cookie ==
2994 					    MTAG_IPFW_CALL)
2995 						break;
2996 					mtag = m_tag_next(m, mtag);
2997 				}
2998 				if (mtag == NULL && IS_CALL) {
2999 					mtag = m_tag_alloc(MTAG_IPFW_CALL, 0,
3000 					    IPFW_CALLSTACK_SIZE *
3001 					    sizeof(uint16_t), M_NOWAIT);
3002 					if (mtag != NULL)
3003 						m_tag_prepend(m, mtag);
3004 				}
3005 
3006 				/*
3007 				 * On error both `call' and `return' just
3008 				 * continue with next rule.
3009 				 */
3010 				if (IS_RETURN && (mtag == NULL ||
3011 				    mtag->m_tag_id == 0)) {
3012 					l = 0;		/* exit inner loop */
3013 					break;
3014 				}
3015 				if (IS_CALL && (mtag == NULL ||
3016 				    mtag->m_tag_id >= IPFW_CALLSTACK_SIZE)) {
3017 					printf("ipfw: call stack error, "
3018 					    "go to next rule\n");
3019 					l = 0;		/* exit inner loop */
3020 					break;
3021 				}
3022 
3023 				IPFW_INC_RULE_COUNTER(f, pktlen);
3024 				stack = (uint16_t *)(mtag + 1);
3025 
3026 				/*
3027 				 * The `call' action may use cached f_pos
3028 				 * (in f->next_rule), whose version is written
3029 				 * in f->next_rule.
3030 				 * The `return' action, however, doesn't have
3031 				 * fixed jump address in cmd->arg1 and can't use
3032 				 * cache.
3033 				 */
3034 				if (IS_CALL) {
3035 					stack[mtag->m_tag_id] = f->rulenum;
3036 					mtag->m_tag_id++;
3037 			    		f_pos = JUMP(chain, f, cmd->arg1,
3038 					    tablearg, 1);
3039 				} else {	/* `return' action */
3040 					mtag->m_tag_id--;
3041 					jmpto = stack[mtag->m_tag_id] + 1;
3042 					f_pos = ipfw_find_rule(chain, jmpto, 0);
3043 				}
3044 
3045 				/*
3046 				 * Skip disabled rules, and re-enter
3047 				 * the inner loop with the correct
3048 				 * f_pos, f, l and cmd.
3049 				 * Also clear cmdlen and skip_or
3050 				 */
3051 				for (; f_pos < chain->n_rules - 1 &&
3052 				    (V_set_disable &
3053 				    (1 << chain->map[f_pos]->set)); f_pos++)
3054 					;
3055 				/* Re-enter the inner loop at the dest rule. */
3056 				f = chain->map[f_pos];
3057 				l = f->cmd_len;
3058 				cmd = f->cmd;
3059 				cmdlen = 0;
3060 				skip_or = 0;
3061 				continue;
3062 				break;	/* NOTREACHED */
3063 			}
3064 #undef IS_CALL
3065 #undef IS_RETURN
3066 
3067 			case O_REJECT:
3068 				/*
3069 				 * Drop the packet and send a reject notice
3070 				 * if the packet is not ICMP (or is an ICMP
3071 				 * query), and it is not multicast/broadcast.
3072 				 */
3073 				if (hlen > 0 && is_ipv4 && offset == 0 &&
3074 				    (proto != IPPROTO_ICMP ||
3075 				     is_icmp_query(ICMP(ulp))) &&
3076 				    !(m->m_flags & (M_BCAST|M_MCAST)) &&
3077 				    !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
3078 					send_reject(args, cmd, iplen, ip);
3079 					m = args->m;
3080 				}
3081 				/* FALLTHROUGH */
3082 #ifdef INET6
3083 			case O_UNREACH6:
3084 				if (hlen > 0 && is_ipv6 &&
3085 				    ((offset & IP6F_OFF_MASK) == 0) &&
3086 				    (proto != IPPROTO_ICMPV6 ||
3087 				     (is_icmp6_query(icmp6_type) == 1)) &&
3088 				    !(m->m_flags & (M_BCAST|M_MCAST)) &&
3089 				    !IN6_IS_ADDR_MULTICAST(
3090 					&args->f_id.dst_ip6)) {
3091 					send_reject6(args,
3092 					    cmd->opcode == O_REJECT ?
3093 					    map_icmp_unreach(cmd->arg1):
3094 					    cmd->arg1, hlen,
3095 					    (struct ip6_hdr *)ip);
3096 					m = args->m;
3097 				}
3098 				/* FALLTHROUGH */
3099 #endif
3100 			case O_DENY:
3101 				retval = IP_FW_DENY;
3102 				l = 0;		/* exit inner loop */
3103 				done = 1;	/* exit outer loop */
3104 				break;
3105 
3106 			case O_FORWARD_IP:
3107 				if (args->flags & IPFW_ARGS_ETHER)
3108 					break;	/* not valid on layer2 pkts */
3109 				if (q != f ||
3110 				    dyn_info.direction == MATCH_FORWARD) {
3111 				    struct sockaddr_in *sa;
3112 
3113 				    sa = &(((ipfw_insn_sa *)cmd)->sa);
3114 				    if (sa->sin_addr.s_addr == INADDR_ANY) {
3115 #ifdef INET6
3116 					/*
3117 					 * We use O_FORWARD_IP opcode for
3118 					 * fwd rule with tablearg, but tables
3119 					 * now support IPv6 addresses. And
3120 					 * when we are inspecting IPv6 packet,
3121 					 * we can use nh6 field from
3122 					 * table_value as next_hop6 address.
3123 					 */
3124 					if (is_ipv6) {
3125 						struct ip_fw_nh6 *nh6;
3126 
3127 						args->flags |= IPFW_ARGS_NH6;
3128 						nh6 = &args->hopstore6;
3129 						nh6->sin6_addr = TARG_VAL(
3130 						    chain, tablearg, nh6);
3131 						nh6->sin6_port = sa->sin_port;
3132 						nh6->sin6_scope_id = TARG_VAL(
3133 						    chain, tablearg, zoneid);
3134 					} else
3135 #endif
3136 					{
3137 						args->flags |= IPFW_ARGS_NH4;
3138 						args->hopstore.sin_port =
3139 						    sa->sin_port;
3140 						sa = &args->hopstore;
3141 						sa->sin_family = AF_INET;
3142 						sa->sin_len = sizeof(*sa);
3143 						sa->sin_addr.s_addr = htonl(
3144 						    TARG_VAL(chain, tablearg,
3145 						    nh4));
3146 					}
3147 				    } else {
3148 					    args->flags |= IPFW_ARGS_NH4PTR;
3149 					    args->next_hop = sa;
3150 				    }
3151 				}
3152 				retval = IP_FW_PASS;
3153 				l = 0;          /* exit inner loop */
3154 				done = 1;       /* exit outer loop */
3155 				break;
3156 
3157 #ifdef INET6
3158 			case O_FORWARD_IP6:
3159 				if (args->flags & IPFW_ARGS_ETHER)
3160 					break;	/* not valid on layer2 pkts */
3161 				if (q != f ||
3162 				    dyn_info.direction == MATCH_FORWARD) {
3163 					struct sockaddr_in6 *sin6;
3164 
3165 					sin6 = &(((ipfw_insn_sa6 *)cmd)->sa);
3166 					args->flags |= IPFW_ARGS_NH6PTR;
3167 					args->next_hop6 = sin6;
3168 				}
3169 				retval = IP_FW_PASS;
3170 				l = 0;		/* exit inner loop */
3171 				done = 1;	/* exit outer loop */
3172 				break;
3173 #endif
3174 
3175 			case O_NETGRAPH:
3176 			case O_NGTEE:
3177 				set_match(args, f_pos, chain);
3178 				args->rule.info = TARG(cmd->arg1, netgraph);
3179 				if (V_fw_one_pass)
3180 					args->rule.info |= IPFW_ONEPASS;
3181 				retval = (cmd->opcode == O_NETGRAPH) ?
3182 				    IP_FW_NETGRAPH : IP_FW_NGTEE;
3183 				l = 0;          /* exit inner loop */
3184 				done = 1;       /* exit outer loop */
3185 				break;
3186 
3187 			case O_SETFIB: {
3188 				uint32_t fib;
3189 
3190 				IPFW_INC_RULE_COUNTER(f, pktlen);
3191 				fib = TARG(cmd->arg1, fib) & 0x7FFF;
3192 				if (fib >= rt_numfibs)
3193 					fib = 0;
3194 				M_SETFIB(m, fib);
3195 				args->f_id.fib = fib; /* XXX */
3196 				l = 0;		/* exit inner loop */
3197 				break;
3198 		        }
3199 
3200 			case O_SETDSCP: {
3201 				uint16_t code;
3202 
3203 				code = TARG(cmd->arg1, dscp) & 0x3F;
3204 				l = 0;		/* exit inner loop */
3205 				if (is_ipv4) {
3206 					uint16_t old;
3207 
3208 					old = *(uint16_t *)ip;
3209 					ip->ip_tos = (code << 2) |
3210 					    (ip->ip_tos & 0x03);
3211 					ip->ip_sum = cksum_adjust(ip->ip_sum,
3212 					    old, *(uint16_t *)ip);
3213 				} else if (is_ipv6) {
3214 					/* update cached value */
3215 					args->f_id.flow_id6 =
3216 					    ntohl(*(uint32_t *)ip) & ~0x0FC00000;
3217 					args->f_id.flow_id6 |= code << 22;
3218 
3219 					*((uint32_t *)ip) =
3220 					    htonl(args->f_id.flow_id6);
3221 				} else
3222 					break;
3223 
3224 				IPFW_INC_RULE_COUNTER(f, pktlen);
3225 				break;
3226 			}
3227 
3228 			case O_NAT:
3229 				l = 0;          /* exit inner loop */
3230 				done = 1;       /* exit outer loop */
3231 				/*
3232 				 * Ensure that we do not invoke NAT handler for
3233 				 * non IPv4 packets. Libalias expects only IPv4.
3234 				 */
3235 				if (!is_ipv4 || !IPFW_NAT_LOADED) {
3236 				    retval = IP_FW_DENY;
3237 				    break;
3238 				}
3239 
3240 				struct cfg_nat *t;
3241 				int nat_id;
3242 
3243 				args->rule.info = 0;
3244 				set_match(args, f_pos, chain);
3245 				/* Check if this is 'global' nat rule */
3246 				if (cmd->arg1 == IP_FW_NAT44_GLOBAL) {
3247 					retval = ipfw_nat_ptr(args, NULL, m);
3248 					break;
3249 				}
3250 				t = ((ipfw_insn_nat *)cmd)->nat;
3251 				if (t == NULL) {
3252 					nat_id = TARG(cmd->arg1, nat);
3253 					t = (*lookup_nat_ptr)(&chain->nat, nat_id);
3254 
3255 					if (t == NULL) {
3256 					    retval = IP_FW_DENY;
3257 					    break;
3258 					}
3259 					if (cmd->arg1 != IP_FW_TARG)
3260 					    ((ipfw_insn_nat *)cmd)->nat = t;
3261 				}
3262 				retval = ipfw_nat_ptr(args, t, m);
3263 				break;
3264 
3265 			case O_REASS: {
3266 				int ip_off;
3267 
3268 				l = 0;	/* in any case exit inner loop */
3269 				if (is_ipv6) /* IPv6 is not supported yet */
3270 					break;
3271 				IPFW_INC_RULE_COUNTER(f, pktlen);
3272 				ip_off = ntohs(ip->ip_off);
3273 
3274 				/* if not fragmented, go to next rule */
3275 				if ((ip_off & (IP_MF | IP_OFFMASK)) == 0)
3276 				    break;
3277 
3278 				args->m = m = ip_reass(m);
3279 
3280 				/*
3281 				 * do IP header checksum fixup.
3282 				 */
3283 				if (m == NULL) { /* fragment got swallowed */
3284 				    retval = IP_FW_DENY;
3285 				} else { /* good, packet complete */
3286 				    int hlen;
3287 
3288 				    ip = mtod(m, struct ip *);
3289 				    hlen = ip->ip_hl << 2;
3290 				    ip->ip_sum = 0;
3291 				    if (hlen == sizeof(struct ip))
3292 					ip->ip_sum = in_cksum_hdr(ip);
3293 				    else
3294 					ip->ip_sum = in_cksum(m, hlen);
3295 				    retval = IP_FW_REASS;
3296 				    args->rule.info = 0;
3297 				    set_match(args, f_pos, chain);
3298 				}
3299 				done = 1;	/* exit outer loop */
3300 				break;
3301 			}
3302 
3303 			case O_SETMARK: {
3304 				l = 0;		/* exit inner loop */
3305 				args->rule.pkt_mark = (
3306 				    (cmd->arg1 == IP_FW_TARG) ?
3307 				    TARG_VAL(chain, tablearg, mark) :
3308 				    ((ipfw_insn_u32 *)cmd)->d[0]);
3309 
3310 				IPFW_INC_RULE_COUNTER(f, pktlen);
3311 				break;
3312 			}
3313 
3314 			case O_EXTERNAL_ACTION:
3315 				l = 0; /* in any case exit inner loop */
3316 				retval = ipfw_run_eaction(chain, args,
3317 				    cmd, &done);
3318 				/*
3319 				 * If both @retval and @done are zero,
3320 				 * consider this as rule matching and
3321 				 * update counters.
3322 				 */
3323 				if (retval == 0 && done == 0) {
3324 					IPFW_INC_RULE_COUNTER(f, pktlen);
3325 					/*
3326 					 * Reset the result of the last
3327 					 * dynamic state lookup.
3328 					 * External action can change
3329 					 * @args content, and it may be
3330 					 * used for new state lookup later.
3331 					 */
3332 					DYN_INFO_INIT(&dyn_info);
3333 				}
3334 				break;
3335 
3336 			default:
3337 				panic("-- unknown opcode %d\n", cmd->opcode);
3338 			} /* end of switch() on opcodes */
3339 			/*
3340 			 * if we get here with l=0, then match is irrelevant.
3341 			 */
3342 
3343 			if (cmd->len & F_NOT)
3344 				match = !match;
3345 
3346 			if (match) {
3347 				if (cmd->len & F_OR)
3348 					skip_or = 1;
3349 			} else {
3350 				if (!(cmd->len & F_OR)) /* not an OR block, */
3351 					break;		/* try next rule    */
3352 			}
3353 
3354 		}	/* end of inner loop, scan opcodes */
3355 #undef PULLUP_LEN
3356 #undef PULLUP_LEN_LOCKED
3357 
3358 		if (done)
3359 			break;
3360 
3361 /* next_rule:; */	/* try next rule		*/
3362 
3363 	}		/* end of outer for, scan rules */
3364 
3365 	if (done) {
3366 		struct ip_fw *rule = chain->map[f_pos];
3367 		/* Update statistics */
3368 		IPFW_INC_RULE_COUNTER(rule, pktlen);
3369 		IPFW_PROBE(rule__matched, retval,
3370 		    is_ipv4 ? AF_INET : AF_INET6,
3371 		    is_ipv4 ? (uintptr_t)&src_ip :
3372 		        (uintptr_t)&args->f_id.src_ip6,
3373 		    is_ipv4 ? (uintptr_t)&dst_ip :
3374 		        (uintptr_t)&args->f_id.dst_ip6,
3375 		    args, rule);
3376 	} else {
3377 		retval = IP_FW_DENY;
3378 		printf("ipfw: ouch!, skip past end of rules, denying packet\n");
3379 	}
3380 	IPFW_PF_RUNLOCK(chain);
3381 #ifdef __FreeBSD__
3382 	if (ucred_cache != NULL)
3383 		crfree(ucred_cache);
3384 #endif
3385 	return (retval);
3386 
3387 pullup_failed:
3388 	if (V_fw_verbose)
3389 		printf("ipfw: pullup failed\n");
3390 	return (IP_FW_DENY);
3391 }
3392 
3393 /*
3394  * Set maximum number of tables that can be used in given VNET ipfw instance.
3395  */
3396 #ifdef SYSCTL_NODE
3397 static int
3398 sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS)
3399 {
3400 	int error;
3401 	unsigned int ntables;
3402 
3403 	ntables = V_fw_tables_max;
3404 
3405 	error = sysctl_handle_int(oidp, &ntables, 0, req);
3406 	/* Read operation or some error */
3407 	if ((error != 0) || (req->newptr == NULL))
3408 		return (error);
3409 
3410 	return (ipfw_resize_tables(&V_layer3_chain, ntables));
3411 }
3412 
3413 /*
3414  * Switches table namespace between global and per-set.
3415  */
3416 static int
3417 sysctl_ipfw_tables_sets(SYSCTL_HANDLER_ARGS)
3418 {
3419 	int error;
3420 	unsigned int sets;
3421 
3422 	sets = V_fw_tables_sets;
3423 
3424 	error = sysctl_handle_int(oidp, &sets, 0, req);
3425 	/* Read operation or some error */
3426 	if ((error != 0) || (req->newptr == NULL))
3427 		return (error);
3428 
3429 	return (ipfw_switch_tables_namespace(&V_layer3_chain, sets));
3430 }
3431 #endif
3432 
3433 /*
3434  * Module and VNET glue
3435  */
3436 
3437 /*
3438  * Stuff that must be initialised only on boot or module load
3439  */
3440 static int
3441 ipfw_init(void)
3442 {
3443 	int error = 0;
3444 
3445 	/*
3446  	 * Only print out this stuff the first time around,
3447 	 * when called from the sysinit code.
3448 	 */
3449 	printf("ipfw2 "
3450 #ifdef INET6
3451 		"(+ipv6) "
3452 #endif
3453 		"initialized, divert %s, nat %s, "
3454 		"default to %s, logging ",
3455 #ifdef IPDIVERT
3456 		"enabled",
3457 #else
3458 		"loadable",
3459 #endif
3460 #ifdef IPFIREWALL_NAT
3461 		"enabled",
3462 #else
3463 		"loadable",
3464 #endif
3465 		default_to_accept ? "accept" : "deny");
3466 
3467 	/*
3468 	 * Note: V_xxx variables can be accessed here but the vnet specific
3469 	 * initializer may not have been called yet for the VIMAGE case.
3470 	 * Tuneables will have been processed. We will print out values for
3471 	 * the default vnet.
3472 	 * XXX This should all be rationalized AFTER 8.0
3473 	 */
3474 	if (V_fw_verbose == 0)
3475 		printf("disabled\n");
3476 	else if (V_verbose_limit == 0)
3477 		printf("unlimited\n");
3478 	else
3479 		printf("limited to %d packets/entry by default\n",
3480 		    V_verbose_limit);
3481 
3482 	/* Check user-supplied table count for validness */
3483 	if (default_fw_tables > IPFW_TABLES_MAX)
3484 	  default_fw_tables = IPFW_TABLES_MAX;
3485 
3486 	ipfw_init_sopt_handler();
3487 	ipfw_init_obj_rewriter();
3488 	ipfw_iface_init();
3489 	return (error);
3490 }
3491 
3492 /*
3493  * Called for the removal of the last instance only on module unload.
3494  */
3495 static void
3496 ipfw_destroy(void)
3497 {
3498 
3499 	ipfw_iface_destroy();
3500 	ipfw_destroy_sopt_handler();
3501 	ipfw_destroy_obj_rewriter();
3502 	printf("IP firewall unloaded\n");
3503 }
3504 
3505 /*
3506  * Stuff that must be initialized for every instance
3507  * (including the first of course).
3508  */
3509 static int
3510 vnet_ipfw_init(const void *unused)
3511 {
3512 	int error, first;
3513 	struct ip_fw *rule = NULL;
3514 	struct ip_fw_chain *chain;
3515 
3516 	chain = &V_layer3_chain;
3517 
3518 	first = IS_DEFAULT_VNET(curvnet) ? 1 : 0;
3519 
3520 	/* First set up some values that are compile time options */
3521 	V_autoinc_step = 100;	/* bounded to 1..1000 in add_rule() */
3522 	V_fw_deny_unknown_exthdrs = 1;
3523 #ifdef IPFIREWALL_VERBOSE
3524 	V_fw_verbose = 1;
3525 #endif
3526 #ifdef IPFIREWALL_VERBOSE_LIMIT
3527 	V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
3528 #endif
3529 #ifdef IPFIREWALL_NAT
3530 	LIST_INIT(&chain->nat);
3531 #endif
3532 
3533 	/* Init shared services hash table */
3534 	ipfw_init_srv(chain);
3535 
3536 	ipfw_init_counters();
3537 	/* Set initial number of tables */
3538 	V_fw_tables_max = default_fw_tables;
3539 	error = ipfw_init_tables(chain, first);
3540 	if (error) {
3541 		printf("ipfw2: setting up tables failed\n");
3542 		free(chain->map, M_IPFW);
3543 		free(rule, M_IPFW);
3544 		return (ENOSPC);
3545 	}
3546 
3547 	IPFW_LOCK_INIT(chain);
3548 
3549 	/* fill and insert the default rule */
3550 	rule = ipfw_alloc_rule(chain, sizeof(struct ip_fw));
3551 	rule->flags |= IPFW_RULE_NOOPT;
3552 	rule->cmd_len = 1;
3553 	rule->cmd[0].len = 1;
3554 	rule->cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY;
3555 	chain->default_rule = rule;
3556 	ipfw_add_protected_rule(chain, rule, 0);
3557 
3558 	ipfw_dyn_init(chain);
3559 	ipfw_eaction_init(chain, first);
3560 #ifdef LINEAR_SKIPTO
3561 	ipfw_init_skipto_cache(chain);
3562 #endif
3563 	ipfw_bpf_init(first);
3564 
3565 	/* First set up some values that are compile time options */
3566 	V_ipfw_vnet_ready = 1;		/* Open for business */
3567 
3568 	/*
3569 	 * Hook the sockopt handler and pfil hooks for ipv4 and ipv6.
3570 	 * Even if the latter two fail we still keep the module alive
3571 	 * because the sockopt and layer2 paths are still useful.
3572 	 * ipfw[6]_hook return 0 on success, ENOENT on failure,
3573 	 * so we can ignore the exact return value and just set a flag.
3574 	 *
3575 	 * Note that V_fw[6]_enable are manipulated by a SYSCTL_PROC so
3576 	 * changes in the underlying (per-vnet) variables trigger
3577 	 * immediate hook()/unhook() calls.
3578 	 * In layer2 we have the same behaviour, except that V_ether_ipfw
3579 	 * is checked on each packet because there are no pfil hooks.
3580 	 */
3581 	V_ip_fw_ctl_ptr = ipfw_ctl3;
3582 	error = ipfw_attach_hooks();
3583 	return (error);
3584 }
3585 
3586 /*
3587  * Called for the removal of each instance.
3588  */
3589 static int
3590 vnet_ipfw_uninit(const void *unused)
3591 {
3592 	struct ip_fw *reap;
3593 	struct ip_fw_chain *chain = &V_layer3_chain;
3594 	int i, last;
3595 
3596 	V_ipfw_vnet_ready = 0; /* tell new callers to go away */
3597 	/*
3598 	 * disconnect from ipv4, ipv6, layer2 and sockopt.
3599 	 * Then grab, release and grab again the WLOCK so we make
3600 	 * sure the update is propagated and nobody will be in.
3601 	 */
3602 	ipfw_detach_hooks();
3603 	V_ip_fw_ctl_ptr = NULL;
3604 
3605 	last = IS_DEFAULT_VNET(curvnet) ? 1 : 0;
3606 
3607 	IPFW_UH_WLOCK(chain);
3608 	IPFW_UH_WUNLOCK(chain);
3609 
3610 	ipfw_dyn_uninit(0);	/* run the callout_drain */
3611 
3612 	IPFW_UH_WLOCK(chain);
3613 
3614 	reap = NULL;
3615 	IPFW_WLOCK(chain);
3616 	for (i = 0; i < chain->n_rules; i++)
3617 		ipfw_reap_add(chain, &reap, chain->map[i]);
3618 	free(chain->map, M_IPFW);
3619 #ifdef LINEAR_SKIPTO
3620 	ipfw_destroy_skipto_cache(chain);
3621 #endif
3622 	IPFW_WUNLOCK(chain);
3623 	IPFW_UH_WUNLOCK(chain);
3624 	ipfw_destroy_tables(chain, last);
3625 	ipfw_eaction_uninit(chain, last);
3626 	if (reap != NULL)
3627 		ipfw_reap_rules(reap);
3628 	vnet_ipfw_iface_destroy(chain);
3629 	ipfw_destroy_srv(chain);
3630 	IPFW_LOCK_DESTROY(chain);
3631 	ipfw_dyn_uninit(1);	/* free the remaining parts */
3632 	ipfw_destroy_counters();
3633 	ipfw_bpf_uninit(last);
3634 	return (0);
3635 }
3636 
3637 /*
3638  * Module event handler.
3639  * In general we have the choice of handling most of these events by the
3640  * event handler or by the (VNET_)SYS(UN)INIT handlers. I have chosen to
3641  * use the SYSINIT handlers as they are more capable of expressing the
3642  * flow of control during module and vnet operations, so this is just
3643  * a skeleton. Note there is no SYSINIT equivalent of the module
3644  * SHUTDOWN handler, but we don't have anything to do in that case anyhow.
3645  */
3646 static int
3647 ipfw_modevent(module_t mod, int type, void *unused)
3648 {
3649 	int err = 0;
3650 
3651 	switch (type) {
3652 	case MOD_LOAD:
3653 		/* Called once at module load or
3654 	 	 * system boot if compiled in. */
3655 		break;
3656 	case MOD_QUIESCE:
3657 		/* Called before unload. May veto unloading. */
3658 		break;
3659 	case MOD_UNLOAD:
3660 		/* Called during unload. */
3661 		break;
3662 	case MOD_SHUTDOWN:
3663 		/* Called during system shutdown. */
3664 		break;
3665 	default:
3666 		err = EOPNOTSUPP;
3667 		break;
3668 	}
3669 	return err;
3670 }
3671 
3672 static moduledata_t ipfwmod = {
3673 	"ipfw",
3674 	ipfw_modevent,
3675 	0
3676 };
3677 
3678 /* Define startup order. */
3679 #define	IPFW_SI_SUB_FIREWALL	SI_SUB_PROTO_FIREWALL
3680 #define	IPFW_MODEVENT_ORDER	(SI_ORDER_ANY - 255) /* On boot slot in here. */
3681 #define	IPFW_MODULE_ORDER	(IPFW_MODEVENT_ORDER + 1) /* A little later. */
3682 #define	IPFW_VNET_ORDER		(IPFW_MODEVENT_ORDER + 2) /* Later still. */
3683 
3684 DECLARE_MODULE(ipfw, ipfwmod, IPFW_SI_SUB_FIREWALL, IPFW_MODEVENT_ORDER);
3685 FEATURE(ipfw_ctl3, "ipfw new sockopt calls");
3686 MODULE_VERSION(ipfw, 3);
3687 /* should declare some dependencies here */
3688 
3689 /*
3690  * Starting up. Done in order after ipfwmod() has been called.
3691  * VNET_SYSINIT is also called for each existing vnet and each new vnet.
3692  */
3693 SYSINIT(ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
3694 	    ipfw_init, NULL);
3695 VNET_SYSINIT(vnet_ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
3696 	    vnet_ipfw_init, NULL);
3697 
3698 /*
3699  * Closing up shop. These are done in REVERSE ORDER, but still
3700  * after ipfwmod() has been called. Not called on reboot.
3701  * VNET_SYSUNINIT is also called for each exiting vnet as it exits.
3702  * or when the module is unloaded.
3703  */
3704 SYSUNINIT(ipfw_destroy, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
3705 	    ipfw_destroy, NULL);
3706 VNET_SYSUNINIT(vnet_ipfw_uninit, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
3707 	    vnet_ipfw_uninit, NULL);
3708 /* end of file */
3709