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