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