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