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