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