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