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