xref: /freebsd/sys/netpfil/ipfw/ip_fw2.c (revision 0a10f22a30d61a6f32777a236a82d461129538cc)
1 /*-
2  * Copyright (c) 2002-2009 Luigi Rizzo, Universita` di Pisa
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23  * SUCH DAMAGE.
24  */
25 
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
28 
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 #include "opt_ipsec.h"
41 
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 #include <sys/condvar.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/socket.h>
56 #include <sys/socketvar.h>
57 #include <sys/sysctl.h>
58 #include <sys/syslog.h>
59 #include <sys/ucred.h>
60 #include <net/ethernet.h> /* for ETHERTYPE_IP */
61 #include <net/if.h>
62 #include <net/route.h>
63 #include <net/pf_mtag.h>
64 #include <net/pfil.h>
65 #include <net/vnet.h>
66 
67 #include <netinet/in.h>
68 #include <netinet/in_var.h>
69 #include <netinet/in_pcb.h>
70 #include <netinet/ip.h>
71 #include <netinet/ip_var.h>
72 #include <netinet/ip_icmp.h>
73 #include <netinet/ip_fw.h>
74 #include <netinet/ip_carp.h>
75 #include <netinet/pim.h>
76 #include <netinet/tcp_var.h>
77 #include <netinet/udp.h>
78 #include <netinet/udp_var.h>
79 #include <netinet/sctp.h>
80 
81 #include <netinet/ip6.h>
82 #include <netinet/icmp6.h>
83 #ifdef INET6
84 #include <netinet6/in6_pcb.h>
85 #include <netinet6/scope6_var.h>
86 #include <netinet6/ip6_var.h>
87 #endif
88 
89 #include <netpfil/ipfw/ip_fw_private.h>
90 
91 #include <machine/in_cksum.h>	/* XXX for in_cksum */
92 
93 #ifdef MAC
94 #include <security/mac/mac_framework.h>
95 #endif
96 
97 /*
98  * static variables followed by global ones.
99  * All ipfw global variables are here.
100  */
101 
102 /* ipfw_vnet_ready controls when we are open for business */
103 static VNET_DEFINE(int, ipfw_vnet_ready) = 0;
104 #define	V_ipfw_vnet_ready	VNET(ipfw_vnet_ready)
105 
106 static VNET_DEFINE(int, fw_deny_unknown_exthdrs);
107 #define	V_fw_deny_unknown_exthdrs	VNET(fw_deny_unknown_exthdrs)
108 
109 static VNET_DEFINE(int, fw_permit_single_frag6) = 1;
110 #define	V_fw_permit_single_frag6	VNET(fw_permit_single_frag6)
111 
112 #ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
113 static int default_to_accept = 1;
114 #else
115 static int default_to_accept;
116 #endif
117 
118 VNET_DEFINE(int, autoinc_step);
119 VNET_DEFINE(int, fw_one_pass) = 1;
120 
121 VNET_DEFINE(unsigned int, fw_tables_max);
122 /* Use 128 tables by default */
123 static unsigned int default_fw_tables = IPFW_TABLES_DEFAULT;
124 
125 /*
126  * Each rule belongs to one of 32 different sets (0..31).
127  * The variable set_disable contains one bit per set.
128  * If the bit is set, all rules in the corresponding set
129  * are disabled. Set RESVD_SET(31) is reserved for the default rule
130  * and rules that are not deleted by the flush command,
131  * and CANNOT be disabled.
132  * Rules in set RESVD_SET can only be deleted individually.
133  */
134 VNET_DEFINE(u_int32_t, set_disable);
135 #define	V_set_disable			VNET(set_disable)
136 
137 VNET_DEFINE(int, fw_verbose);
138 /* counter for ipfw_log(NULL...) */
139 VNET_DEFINE(u_int64_t, norule_counter);
140 VNET_DEFINE(int, verbose_limit);
141 
142 /* layer3_chain contains the list of rules for layer 3 */
143 VNET_DEFINE(struct ip_fw_chain, layer3_chain);
144 
145 VNET_DEFINE(int, ipfw_nat_ready) = 0;
146 
147 ipfw_nat_t *ipfw_nat_ptr = NULL;
148 struct cfg_nat *(*lookup_nat_ptr)(struct nat_list *, int);
149 ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
150 ipfw_nat_cfg_t *ipfw_nat_del_ptr;
151 ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
152 ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
153 
154 #ifdef SYSCTL_NODE
155 uint32_t dummy_def = IPFW_DEFAULT_RULE;
156 static int sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS);
157 
158 SYSBEGIN(f3)
159 
160 SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
161 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
162     CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_one_pass), 0,
163     "Only do a single pass through ipfw when using dummynet(4)");
164 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step,
165     CTLFLAG_RW, &VNET_NAME(autoinc_step), 0,
166     "Rule number auto-increment step");
167 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose,
168     CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_verbose), 0,
169     "Log matches to ipfw rules");
170 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit,
171     CTLFLAG_RW, &VNET_NAME(verbose_limit), 0,
172     "Set upper limit of matches of ipfw rules logged");
173 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
174     &dummy_def, 0,
175     "The default/max possible rule number.");
176 SYSCTL_VNET_PROC(_net_inet_ip_fw, OID_AUTO, tables_max,
177     CTLTYPE_UINT|CTLFLAG_RW, 0, 0, sysctl_ipfw_table_num, "IU",
178     "Maximum number of tables");
179 SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, default_to_accept, CTLFLAG_RDTUN,
180     &default_to_accept, 0,
181     "Make the default rule accept all packets.");
182 TUNABLE_INT("net.inet.ip.fw.default_to_accept", &default_to_accept);
183 TUNABLE_INT("net.inet.ip.fw.tables_max", (int *)&default_fw_tables);
184 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, static_count,
185     CTLFLAG_RD, &VNET_NAME(layer3_chain.n_rules), 0,
186     "Number of static rules");
187 
188 #ifdef INET6
189 SYSCTL_DECL(_net_inet6_ip6);
190 SYSCTL_NODE(_net_inet6_ip6, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
191 SYSCTL_VNET_INT(_net_inet6_ip6_fw, OID_AUTO, deny_unknown_exthdrs,
192     CTLFLAG_RW | CTLFLAG_SECURE, &VNET_NAME(fw_deny_unknown_exthdrs), 0,
193     "Deny packets with unknown IPv6 Extension Headers");
194 SYSCTL_VNET_INT(_net_inet6_ip6_fw, OID_AUTO, permit_single_frag6,
195     CTLFLAG_RW | CTLFLAG_SECURE, &VNET_NAME(fw_permit_single_frag6), 0,
196     "Permit single packet IPv6 fragments");
197 #endif /* INET6 */
198 
199 SYSEND
200 
201 #endif /* SYSCTL_NODE */
202 
203 
204 /*
205  * Some macros used in the various matching options.
206  * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
207  * Other macros just cast void * into the appropriate type
208  */
209 #define	L3HDR(T, ip)	((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
210 #define	TCP(p)		((struct tcphdr *)(p))
211 #define	SCTP(p)		((struct sctphdr *)(p))
212 #define	UDP(p)		((struct udphdr *)(p))
213 #define	ICMP(p)		((struct icmphdr *)(p))
214 #define	ICMP6(p)	((struct icmp6_hdr *)(p))
215 
216 static __inline int
217 icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
218 {
219 	int type = icmp->icmp_type;
220 
221 	return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
222 }
223 
224 #define TT	( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
225     (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
226 
227 static int
228 is_icmp_query(struct icmphdr *icmp)
229 {
230 	int type = icmp->icmp_type;
231 
232 	return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
233 }
234 #undef TT
235 
236 /*
237  * The following checks use two arrays of 8 or 16 bits to store the
238  * bits that we want set or clear, respectively. They are in the
239  * low and high half of cmd->arg1 or cmd->d[0].
240  *
241  * We scan options and store the bits we find set. We succeed if
242  *
243  *	(want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
244  *
245  * The code is sometimes optimized not to store additional variables.
246  */
247 
248 static int
249 flags_match(ipfw_insn *cmd, u_int8_t bits)
250 {
251 	u_char want_clear;
252 	bits = ~bits;
253 
254 	if ( ((cmd->arg1 & 0xff) & bits) != 0)
255 		return 0; /* some bits we want set were clear */
256 	want_clear = (cmd->arg1 >> 8) & 0xff;
257 	if ( (want_clear & bits) != want_clear)
258 		return 0; /* some bits we want clear were set */
259 	return 1;
260 }
261 
262 static int
263 ipopts_match(struct ip *ip, ipfw_insn *cmd)
264 {
265 	int optlen, bits = 0;
266 	u_char *cp = (u_char *)(ip + 1);
267 	int x = (ip->ip_hl << 2) - sizeof (struct ip);
268 
269 	for (; x > 0; x -= optlen, cp += optlen) {
270 		int opt = cp[IPOPT_OPTVAL];
271 
272 		if (opt == IPOPT_EOL)
273 			break;
274 		if (opt == IPOPT_NOP)
275 			optlen = 1;
276 		else {
277 			optlen = cp[IPOPT_OLEN];
278 			if (optlen <= 0 || optlen > x)
279 				return 0; /* invalid or truncated */
280 		}
281 		switch (opt) {
282 
283 		default:
284 			break;
285 
286 		case IPOPT_LSRR:
287 			bits |= IP_FW_IPOPT_LSRR;
288 			break;
289 
290 		case IPOPT_SSRR:
291 			bits |= IP_FW_IPOPT_SSRR;
292 			break;
293 
294 		case IPOPT_RR:
295 			bits |= IP_FW_IPOPT_RR;
296 			break;
297 
298 		case IPOPT_TS:
299 			bits |= IP_FW_IPOPT_TS;
300 			break;
301 		}
302 	}
303 	return (flags_match(cmd, bits));
304 }
305 
306 static int
307 tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
308 {
309 	int optlen, bits = 0;
310 	u_char *cp = (u_char *)(tcp + 1);
311 	int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
312 
313 	for (; x > 0; x -= optlen, cp += optlen) {
314 		int opt = cp[0];
315 		if (opt == TCPOPT_EOL)
316 			break;
317 		if (opt == TCPOPT_NOP)
318 			optlen = 1;
319 		else {
320 			optlen = cp[1];
321 			if (optlen <= 0)
322 				break;
323 		}
324 
325 		switch (opt) {
326 
327 		default:
328 			break;
329 
330 		case TCPOPT_MAXSEG:
331 			bits |= IP_FW_TCPOPT_MSS;
332 			break;
333 
334 		case TCPOPT_WINDOW:
335 			bits |= IP_FW_TCPOPT_WINDOW;
336 			break;
337 
338 		case TCPOPT_SACK_PERMITTED:
339 		case TCPOPT_SACK:
340 			bits |= IP_FW_TCPOPT_SACK;
341 			break;
342 
343 		case TCPOPT_TIMESTAMP:
344 			bits |= IP_FW_TCPOPT_TS;
345 			break;
346 
347 		}
348 	}
349 	return (flags_match(cmd, bits));
350 }
351 
352 static int
353 iface_match(struct ifnet *ifp, ipfw_insn_if *cmd, struct ip_fw_chain *chain, uint32_t *tablearg)
354 {
355 	if (ifp == NULL)	/* no iface with this packet, match fails */
356 		return 0;
357 	/* Check by name or by IP address */
358 	if (cmd->name[0] != '\0') { /* match by name */
359 		if (cmd->name[0] == '\1') /* use tablearg to match */
360 			return ipfw_lookup_table_extended(chain, cmd->p.glob,
361 				ifp->if_xname, tablearg, IPFW_TABLE_INTERFACE);
362 		/* Check name */
363 		if (cmd->p.glob) {
364 			if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
365 				return(1);
366 		} else {
367 			if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
368 				return(1);
369 		}
370 	} else {
371 #ifdef __FreeBSD__	/* and OSX too ? */
372 		struct ifaddr *ia;
373 
374 		if_addr_rlock(ifp);
375 		TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
376 			if (ia->ifa_addr->sa_family != AF_INET)
377 				continue;
378 			if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
379 			    (ia->ifa_addr))->sin_addr.s_addr) {
380 				if_addr_runlock(ifp);
381 				return(1);	/* match */
382 			}
383 		}
384 		if_addr_runlock(ifp);
385 #endif /* __FreeBSD__ */
386 	}
387 	return(0);	/* no match, fail ... */
388 }
389 
390 /*
391  * The verify_path function checks if a route to the src exists and
392  * if it is reachable via ifp (when provided).
393  *
394  * The 'verrevpath' option checks that the interface that an IP packet
395  * arrives on is the same interface that traffic destined for the
396  * packet's source address would be routed out of.
397  * The 'versrcreach' option just checks that the source address is
398  * reachable via any route (except default) in the routing table.
399  * These two are a measure to block forged packets. This is also
400  * commonly known as "anti-spoofing" or Unicast Reverse Path
401  * Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
402  * is purposely reminiscent of the Cisco IOS command,
403  *
404  *   ip verify unicast reverse-path
405  *   ip verify unicast source reachable-via any
406  *
407  * which implements the same functionality. But note that the syntax
408  * is misleading, and the check may be performed on all IP packets
409  * whether unicast, multicast, or broadcast.
410  */
411 static int
412 verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
413 {
414 #ifndef __FreeBSD__
415 	return 0;
416 #else
417 	struct route ro;
418 	struct sockaddr_in *dst;
419 
420 	bzero(&ro, sizeof(ro));
421 
422 	dst = (struct sockaddr_in *)&(ro.ro_dst);
423 	dst->sin_family = AF_INET;
424 	dst->sin_len = sizeof(*dst);
425 	dst->sin_addr = src;
426 	in_rtalloc_ign(&ro, 0, fib);
427 
428 	if (ro.ro_rt == NULL)
429 		return 0;
430 
431 	/*
432 	 * If ifp is provided, check for equality with rtentry.
433 	 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
434 	 * in order to pass packets injected back by if_simloop():
435 	 * if useloopback == 1 routing entry (via lo0) for our own address
436 	 * may exist, so we need to handle routing assymetry.
437 	 */
438 	if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
439 		RTFREE(ro.ro_rt);
440 		return 0;
441 	}
442 
443 	/* if no ifp provided, check if rtentry is not default route */
444 	if (ifp == NULL &&
445 	     satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
446 		RTFREE(ro.ro_rt);
447 		return 0;
448 	}
449 
450 	/* or if this is a blackhole/reject route */
451 	if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
452 		RTFREE(ro.ro_rt);
453 		return 0;
454 	}
455 
456 	/* found valid route */
457 	RTFREE(ro.ro_rt);
458 	return 1;
459 #endif /* __FreeBSD__ */
460 }
461 
462 #ifdef INET6
463 /*
464  * ipv6 specific rules here...
465  */
466 static __inline int
467 icmp6type_match (int type, ipfw_insn_u32 *cmd)
468 {
469 	return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
470 }
471 
472 static int
473 flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
474 {
475 	int i;
476 	for (i=0; i <= cmd->o.arg1; ++i )
477 		if (curr_flow == cmd->d[i] )
478 			return 1;
479 	return 0;
480 }
481 
482 /* support for IP6_*_ME opcodes */
483 static int
484 search_ip6_addr_net (struct in6_addr * ip6_addr)
485 {
486 	struct ifnet *mdc;
487 	struct ifaddr *mdc2;
488 	struct in6_ifaddr *fdm;
489 	struct in6_addr copia;
490 
491 	TAILQ_FOREACH(mdc, &V_ifnet, if_link) {
492 		if_addr_rlock(mdc);
493 		TAILQ_FOREACH(mdc2, &mdc->if_addrhead, ifa_link) {
494 			if (mdc2->ifa_addr->sa_family == AF_INET6) {
495 				fdm = (struct in6_ifaddr *)mdc2;
496 				copia = fdm->ia_addr.sin6_addr;
497 				/* need for leaving scope_id in the sock_addr */
498 				in6_clearscope(&copia);
499 				if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia)) {
500 					if_addr_runlock(mdc);
501 					return 1;
502 				}
503 			}
504 		}
505 		if_addr_runlock(mdc);
506 	}
507 	return 0;
508 }
509 
510 static int
511 verify_path6(struct in6_addr *src, struct ifnet *ifp, u_int fib)
512 {
513 	struct route_in6 ro;
514 	struct sockaddr_in6 *dst;
515 
516 	bzero(&ro, sizeof(ro));
517 
518 	dst = (struct sockaddr_in6 * )&(ro.ro_dst);
519 	dst->sin6_family = AF_INET6;
520 	dst->sin6_len = sizeof(*dst);
521 	dst->sin6_addr = *src;
522 
523 	in6_rtalloc_ign(&ro, 0, fib);
524 	if (ro.ro_rt == NULL)
525 		return 0;
526 
527 	/*
528 	 * if ifp is provided, check for equality with rtentry
529 	 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
530 	 * to support the case of sending packets to an address of our own.
531 	 * (where the former interface is the first argument of if_simloop()
532 	 *  (=ifp), the latter is lo0)
533 	 */
534 	if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
535 		RTFREE(ro.ro_rt);
536 		return 0;
537 	}
538 
539 	/* if no ifp provided, check if rtentry is not default route */
540 	if (ifp == NULL &&
541 	    IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
542 		RTFREE(ro.ro_rt);
543 		return 0;
544 	}
545 
546 	/* or if this is a blackhole/reject route */
547 	if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
548 		RTFREE(ro.ro_rt);
549 		return 0;
550 	}
551 
552 	/* found valid route */
553 	RTFREE(ro.ro_rt);
554 	return 1;
555 
556 }
557 
558 static int
559 is_icmp6_query(int icmp6_type)
560 {
561 	if ((icmp6_type <= ICMP6_MAXTYPE) &&
562 	    (icmp6_type == ICMP6_ECHO_REQUEST ||
563 	    icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
564 	    icmp6_type == ICMP6_WRUREQUEST ||
565 	    icmp6_type == ICMP6_FQDN_QUERY ||
566 	    icmp6_type == ICMP6_NI_QUERY))
567 		return (1);
568 
569 	return (0);
570 }
571 
572 static void
573 send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
574 {
575 	struct mbuf *m;
576 
577 	m = args->m;
578 	if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
579 		struct tcphdr *tcp;
580 		tcp = (struct tcphdr *)((char *)ip6 + hlen);
581 
582 		if ((tcp->th_flags & TH_RST) == 0) {
583 			struct mbuf *m0;
584 			m0 = ipfw_send_pkt(args->m, &(args->f_id),
585 			    ntohl(tcp->th_seq), ntohl(tcp->th_ack),
586 			    tcp->th_flags | TH_RST);
587 			if (m0 != NULL)
588 				ip6_output(m0, NULL, NULL, 0, NULL, NULL,
589 				    NULL);
590 		}
591 		FREE_PKT(m);
592 	} else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
593 #if 0
594 		/*
595 		 * Unlike above, the mbufs need to line up with the ip6 hdr,
596 		 * as the contents are read. We need to m_adj() the
597 		 * needed amount.
598 		 * The mbuf will however be thrown away so we can adjust it.
599 		 * Remember we did an m_pullup on it already so we
600 		 * can make some assumptions about contiguousness.
601 		 */
602 		if (args->L3offset)
603 			m_adj(m, args->L3offset);
604 #endif
605 		icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
606 	} else
607 		FREE_PKT(m);
608 
609 	args->m = NULL;
610 }
611 
612 #endif /* INET6 */
613 
614 
615 /*
616  * sends a reject message, consuming the mbuf passed as an argument.
617  */
618 static void
619 send_reject(struct ip_fw_args *args, int code, int iplen, struct ip *ip)
620 {
621 
622 #if 0
623 	/* XXX When ip is not guaranteed to be at mtod() we will
624 	 * need to account for this */
625 	 * The mbuf will however be thrown away so we can adjust it.
626 	 * Remember we did an m_pullup on it already so we
627 	 * can make some assumptions about contiguousness.
628 	 */
629 	if (args->L3offset)
630 		m_adj(m, args->L3offset);
631 #endif
632 	if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
633 		icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
634 	} else if (args->f_id.proto == IPPROTO_TCP) {
635 		struct tcphdr *const tcp =
636 		    L3HDR(struct tcphdr, mtod(args->m, struct ip *));
637 		if ( (tcp->th_flags & TH_RST) == 0) {
638 			struct mbuf *m;
639 			m = ipfw_send_pkt(args->m, &(args->f_id),
640 				ntohl(tcp->th_seq), ntohl(tcp->th_ack),
641 				tcp->th_flags | TH_RST);
642 			if (m != NULL)
643 				ip_output(m, NULL, NULL, 0, NULL, NULL);
644 		}
645 		FREE_PKT(args->m);
646 	} else
647 		FREE_PKT(args->m);
648 	args->m = NULL;
649 }
650 
651 /*
652  * Support for uid/gid/jail lookup. These tests are expensive
653  * (because we may need to look into the list of active sockets)
654  * so we cache the results. ugid_lookupp is 0 if we have not
655  * yet done a lookup, 1 if we succeeded, and -1 if we tried
656  * and failed. The function always returns the match value.
657  * We could actually spare the variable and use *uc, setting
658  * it to '(void *)check_uidgid if we have no info, NULL if
659  * we tried and failed, or any other value if successful.
660  */
661 static int
662 check_uidgid(ipfw_insn_u32 *insn, struct ip_fw_args *args, int *ugid_lookupp,
663     struct ucred **uc)
664 {
665 #ifndef __FreeBSD__
666 	/* XXX */
667 	return cred_check(insn, proto, oif,
668 	    dst_ip, dst_port, src_ip, src_port,
669 	    (struct bsd_ucred *)uc, ugid_lookupp, ((struct mbuf *)inp)->m_skb);
670 #else  /* FreeBSD */
671 	struct in_addr src_ip, dst_ip;
672 	struct inpcbinfo *pi;
673 	struct ipfw_flow_id *id;
674 	struct inpcb *pcb, *inp;
675 	struct ifnet *oif;
676 	int lookupflags;
677 	int match;
678 
679 	id = &args->f_id;
680 	inp = args->inp;
681 	oif = args->oif;
682 
683 	/*
684 	 * Check to see if the UDP or TCP stack supplied us with
685 	 * the PCB. If so, rather then holding a lock and looking
686 	 * up the PCB, we can use the one that was supplied.
687 	 */
688 	if (inp && *ugid_lookupp == 0) {
689 		INP_LOCK_ASSERT(inp);
690 		if (inp->inp_socket != NULL) {
691 			*uc = crhold(inp->inp_cred);
692 			*ugid_lookupp = 1;
693 		} else
694 			*ugid_lookupp = -1;
695 	}
696 	/*
697 	 * If we have already been here and the packet has no
698 	 * PCB entry associated with it, then we can safely
699 	 * assume that this is a no match.
700 	 */
701 	if (*ugid_lookupp == -1)
702 		return (0);
703 	if (id->proto == IPPROTO_TCP) {
704 		lookupflags = 0;
705 		pi = &V_tcbinfo;
706 	} else if (id->proto == IPPROTO_UDP) {
707 		lookupflags = INPLOOKUP_WILDCARD;
708 		pi = &V_udbinfo;
709 	} else
710 		return 0;
711 	lookupflags |= INPLOOKUP_RLOCKPCB;
712 	match = 0;
713 	if (*ugid_lookupp == 0) {
714 		if (id->addr_type == 6) {
715 #ifdef INET6
716 			if (oif == NULL)
717 				pcb = in6_pcblookup_mbuf(pi,
718 				    &id->src_ip6, htons(id->src_port),
719 				    &id->dst_ip6, htons(id->dst_port),
720 				    lookupflags, oif, args->m);
721 			else
722 				pcb = in6_pcblookup_mbuf(pi,
723 				    &id->dst_ip6, htons(id->dst_port),
724 				    &id->src_ip6, htons(id->src_port),
725 				    lookupflags, oif, args->m);
726 #else
727 			*ugid_lookupp = -1;
728 			return (0);
729 #endif
730 		} else {
731 			src_ip.s_addr = htonl(id->src_ip);
732 			dst_ip.s_addr = htonl(id->dst_ip);
733 			if (oif == NULL)
734 				pcb = in_pcblookup_mbuf(pi,
735 				    src_ip, htons(id->src_port),
736 				    dst_ip, htons(id->dst_port),
737 				    lookupflags, oif, args->m);
738 			else
739 				pcb = in_pcblookup_mbuf(pi,
740 				    dst_ip, htons(id->dst_port),
741 				    src_ip, htons(id->src_port),
742 				    lookupflags, oif, args->m);
743 		}
744 		if (pcb != NULL) {
745 			INP_RLOCK_ASSERT(pcb);
746 			*uc = crhold(pcb->inp_cred);
747 			*ugid_lookupp = 1;
748 			INP_RUNLOCK(pcb);
749 		}
750 		if (*ugid_lookupp == 0) {
751 			/*
752 			 * We tried and failed, set the variable to -1
753 			 * so we will not try again on this packet.
754 			 */
755 			*ugid_lookupp = -1;
756 			return (0);
757 		}
758 	}
759 	if (insn->o.opcode == O_UID)
760 		match = ((*uc)->cr_uid == (uid_t)insn->d[0]);
761 	else if (insn->o.opcode == O_GID)
762 		match = groupmember((gid_t)insn->d[0], *uc);
763 	else if (insn->o.opcode == O_JAIL)
764 		match = ((*uc)->cr_prison->pr_id == (int)insn->d[0]);
765 	return (match);
766 #endif /* __FreeBSD__ */
767 }
768 
769 /*
770  * Helper function to set args with info on the rule after the matching
771  * one. slot is precise, whereas we guess rule_id as they are
772  * assigned sequentially.
773  */
774 static inline void
775 set_match(struct ip_fw_args *args, int slot,
776 	struct ip_fw_chain *chain)
777 {
778 	args->rule.chain_id = chain->id;
779 	args->rule.slot = slot + 1; /* we use 0 as a marker */
780 	args->rule.rule_id = 1 + chain->map[slot]->id;
781 	args->rule.rulenum = chain->map[slot]->rulenum;
782 }
783 
784 /*
785  * Helper function to enable cached rule lookups using
786  * x_next and next_rule fields in ipfw rule.
787  */
788 static int
789 jump_fast(struct ip_fw_chain *chain, struct ip_fw *f, int num,
790     int tablearg, int jump_backwards)
791 {
792 	int f_pos;
793 
794 	/* If possible use cached f_pos (in f->next_rule),
795 	 * whose version is written in f->next_rule
796 	 * (horrible hacks to avoid changing the ABI).
797 	 */
798 	if (num != IP_FW_TABLEARG && (uintptr_t)f->x_next == chain->id)
799 		f_pos = (uintptr_t)f->next_rule;
800 	else {
801 		int i = IP_FW_ARG_TABLEARG(num);
802 		/* make sure we do not jump backward */
803 		if (jump_backwards == 0 && i <= f->rulenum)
804 			i = f->rulenum + 1;
805 		f_pos = ipfw_find_rule(chain, i, 0);
806 		/* update the cache */
807 		if (num != IP_FW_TABLEARG) {
808 			f->next_rule = (void *)(uintptr_t)f_pos;
809 			f->x_next = (void *)(uintptr_t)chain->id;
810 		}
811 	}
812 
813 	return (f_pos);
814 }
815 
816 /*
817  * The main check routine for the firewall.
818  *
819  * All arguments are in args so we can modify them and return them
820  * back to the caller.
821  *
822  * Parameters:
823  *
824  *	args->m	(in/out) The packet; we set to NULL when/if we nuke it.
825  *		Starts with the IP header.
826  *	args->eh (in)	Mac header if present, NULL for layer3 packet.
827  *	args->L3offset	Number of bytes bypassed if we came from L2.
828  *			e.g. often sizeof(eh)  ** NOTYET **
829  *	args->oif	Outgoing interface, NULL if packet is incoming.
830  *		The incoming interface is in the mbuf. (in)
831  *	args->divert_rule (in/out)
832  *		Skip up to the first rule past this rule number;
833  *		upon return, non-zero port number for divert or tee.
834  *
835  *	args->rule	Pointer to the last matching rule (in/out)
836  *	args->next_hop	Socket we are forwarding to (out).
837  *	args->next_hop6	IPv6 next hop we are forwarding to (out).
838  *	args->f_id	Addresses grabbed from the packet (out)
839  * 	args->rule.info	a cookie depending on rule action
840  *
841  * Return value:
842  *
843  *	IP_FW_PASS	the packet must be accepted
844  *	IP_FW_DENY	the packet must be dropped
845  *	IP_FW_DIVERT	divert packet, port in m_tag
846  *	IP_FW_TEE	tee packet, port in m_tag
847  *	IP_FW_DUMMYNET	to dummynet, pipe in args->cookie
848  *	IP_FW_NETGRAPH	into netgraph, cookie args->cookie
849  *		args->rule contains the matching rule,
850  *		args->rule.info has additional information.
851  *
852  */
853 int
854 ipfw_chk(struct ip_fw_args *args)
855 {
856 
857 	/*
858 	 * Local variables holding state while processing a packet:
859 	 *
860 	 * IMPORTANT NOTE: to speed up the processing of rules, there
861 	 * are some assumption on the values of the variables, which
862 	 * are documented here. Should you change them, please check
863 	 * the implementation of the various instructions to make sure
864 	 * that they still work.
865 	 *
866 	 * args->eh	The MAC header. It is non-null for a layer2
867 	 *	packet, it is NULL for a layer-3 packet.
868 	 * **notyet**
869 	 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
870 	 *
871 	 * m | args->m	Pointer to the mbuf, as received from the caller.
872 	 *	It may change if ipfw_chk() does an m_pullup, or if it
873 	 *	consumes the packet because it calls send_reject().
874 	 *	XXX This has to change, so that ipfw_chk() never modifies
875 	 *	or consumes the buffer.
876 	 * ip	is the beginning of the ip(4 or 6) header.
877 	 *	Calculated by adding the L3offset to the start of data.
878 	 *	(Until we start using L3offset, the packet is
879 	 *	supposed to start with the ip header).
880 	 */
881 	struct mbuf *m = args->m;
882 	struct ip *ip = mtod(m, struct ip *);
883 
884 	/*
885 	 * For rules which contain uid/gid or jail constraints, cache
886 	 * a copy of the users credentials after the pcb lookup has been
887 	 * executed. This will speed up the processing of rules with
888 	 * these types of constraints, as well as decrease contention
889 	 * on pcb related locks.
890 	 */
891 #ifndef __FreeBSD__
892 	struct bsd_ucred ucred_cache;
893 #else
894 	struct ucred *ucred_cache = NULL;
895 #endif
896 	int ucred_lookup = 0;
897 
898 	/*
899 	 * oif | args->oif	If NULL, ipfw_chk has been called on the
900 	 *	inbound path (ether_input, ip_input).
901 	 *	If non-NULL, ipfw_chk has been called on the outbound path
902 	 *	(ether_output, ip_output).
903 	 */
904 	struct ifnet *oif = args->oif;
905 
906 	int f_pos = 0;		/* index of current rule in the array */
907 	int retval = 0;
908 
909 	/*
910 	 * hlen	The length of the IP header.
911 	 */
912 	u_int hlen = 0;		/* hlen >0 means we have an IP pkt */
913 
914 	/*
915 	 * offset	The offset of a fragment. offset != 0 means that
916 	 *	we have a fragment at this offset of an IPv4 packet.
917 	 *	offset == 0 means that (if this is an IPv4 packet)
918 	 *	this is the first or only fragment.
919 	 *	For IPv6 offset|ip6f_mf == 0 means there is no Fragment Header
920 	 *	or there is a single packet fragement (fragement header added
921 	 *	without needed).  We will treat a single packet fragment as if
922 	 *	there was no fragment header (or log/block depending on the
923 	 *	V_fw_permit_single_frag6 sysctl setting).
924 	 */
925 	u_short offset = 0;
926 	u_short ip6f_mf = 0;
927 
928 	/*
929 	 * Local copies of addresses. They are only valid if we have
930 	 * an IP packet.
931 	 *
932 	 * proto	The protocol. Set to 0 for non-ip packets,
933 	 *	or to the protocol read from the packet otherwise.
934 	 *	proto != 0 means that we have an IPv4 packet.
935 	 *
936 	 * src_port, dst_port	port numbers, in HOST format. Only
937 	 *	valid for TCP and UDP packets.
938 	 *
939 	 * src_ip, dst_ip	ip addresses, in NETWORK format.
940 	 *	Only valid for IPv4 packets.
941 	 */
942 	uint8_t proto;
943 	uint16_t src_port = 0, dst_port = 0;	/* NOTE: host format	*/
944 	struct in_addr src_ip, dst_ip;		/* NOTE: network format	*/
945 	uint16_t iplen=0;
946 	int pktlen;
947 	uint16_t	etype = 0;	/* Host order stored ether type */
948 
949 	/*
950 	 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
951 	 * 	MATCH_NONE when checked and not matched (q = NULL),
952 	 *	MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
953 	 */
954 	int dyn_dir = MATCH_UNKNOWN;
955 	ipfw_dyn_rule *q = NULL;
956 	struct ip_fw_chain *chain = &V_layer3_chain;
957 
958 	/*
959 	 * We store in ulp a pointer to the upper layer protocol header.
960 	 * In the ipv4 case this is easy to determine from the header,
961 	 * but for ipv6 we might have some additional headers in the middle.
962 	 * ulp is NULL if not found.
963 	 */
964 	void *ulp = NULL;		/* upper layer protocol pointer. */
965 
966 	/* XXX ipv6 variables */
967 	int is_ipv6 = 0;
968 	uint8_t	icmp6_type = 0;
969 	uint16_t ext_hd = 0;	/* bits vector for extension header filtering */
970 	/* end of ipv6 variables */
971 
972 	int is_ipv4 = 0;
973 
974 	int done = 0;		/* flag to exit the outer loop */
975 
976 	if (m->m_flags & M_SKIP_FIREWALL || (! V_ipfw_vnet_ready))
977 		return (IP_FW_PASS);	/* accept */
978 
979 	dst_ip.s_addr = 0;		/* make sure it is initialized */
980 	src_ip.s_addr = 0;		/* make sure it is initialized */
981 	pktlen = m->m_pkthdr.len;
982 	args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
983 	proto = args->f_id.proto = 0;	/* mark f_id invalid */
984 		/* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
985 
986 /*
987  * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
988  * then it sets p to point at the offset "len" in the mbuf. WARNING: the
989  * pointer might become stale after other pullups (but we never use it
990  * this way).
991  */
992 #define PULLUP_TO(_len, p, T)	PULLUP_LEN(_len, p, sizeof(T))
993 #define PULLUP_LEN(_len, p, T)					\
994 do {								\
995 	int x = (_len) + T;					\
996 	if ((m)->m_len < x) {					\
997 		args->m = m = m_pullup(m, x);			\
998 		if (m == NULL)					\
999 			goto pullup_failed;			\
1000 	}							\
1001 	p = (mtod(m, char *) + (_len));				\
1002 } while (0)
1003 
1004 	/*
1005 	 * if we have an ether header,
1006 	 */
1007 	if (args->eh)
1008 		etype = ntohs(args->eh->ether_type);
1009 
1010 	/* Identify IP packets and fill up variables. */
1011 	if (pktlen >= sizeof(struct ip6_hdr) &&
1012 	    (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
1013 		struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
1014 		is_ipv6 = 1;
1015 		args->f_id.addr_type = 6;
1016 		hlen = sizeof(struct ip6_hdr);
1017 		proto = ip6->ip6_nxt;
1018 
1019 		/* Search extension headers to find upper layer protocols */
1020 		while (ulp == NULL && offset == 0) {
1021 			switch (proto) {
1022 			case IPPROTO_ICMPV6:
1023 				PULLUP_TO(hlen, ulp, struct icmp6_hdr);
1024 				icmp6_type = ICMP6(ulp)->icmp6_type;
1025 				break;
1026 
1027 			case IPPROTO_TCP:
1028 				PULLUP_TO(hlen, ulp, struct tcphdr);
1029 				dst_port = TCP(ulp)->th_dport;
1030 				src_port = TCP(ulp)->th_sport;
1031 				/* save flags for dynamic rules */
1032 				args->f_id._flags = TCP(ulp)->th_flags;
1033 				break;
1034 
1035 			case IPPROTO_SCTP:
1036 				PULLUP_TO(hlen, ulp, struct sctphdr);
1037 				src_port = SCTP(ulp)->src_port;
1038 				dst_port = SCTP(ulp)->dest_port;
1039 				break;
1040 
1041 			case IPPROTO_UDP:
1042 				PULLUP_TO(hlen, ulp, struct udphdr);
1043 				dst_port = UDP(ulp)->uh_dport;
1044 				src_port = UDP(ulp)->uh_sport;
1045 				break;
1046 
1047 			case IPPROTO_HOPOPTS:	/* RFC 2460 */
1048 				PULLUP_TO(hlen, ulp, struct ip6_hbh);
1049 				ext_hd |= EXT_HOPOPTS;
1050 				hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1051 				proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1052 				ulp = NULL;
1053 				break;
1054 
1055 			case IPPROTO_ROUTING:	/* RFC 2460 */
1056 				PULLUP_TO(hlen, ulp, struct ip6_rthdr);
1057 				switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
1058 				case 0:
1059 					ext_hd |= EXT_RTHDR0;
1060 					break;
1061 				case 2:
1062 					ext_hd |= EXT_RTHDR2;
1063 					break;
1064 				default:
1065 					if (V_fw_verbose)
1066 						printf("IPFW2: IPV6 - Unknown "
1067 						    "Routing Header type(%d)\n",
1068 						    ((struct ip6_rthdr *)
1069 						    ulp)->ip6r_type);
1070 					if (V_fw_deny_unknown_exthdrs)
1071 					    return (IP_FW_DENY);
1072 					break;
1073 				}
1074 				ext_hd |= EXT_ROUTING;
1075 				hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
1076 				proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
1077 				ulp = NULL;
1078 				break;
1079 
1080 			case IPPROTO_FRAGMENT:	/* RFC 2460 */
1081 				PULLUP_TO(hlen, ulp, struct ip6_frag);
1082 				ext_hd |= EXT_FRAGMENT;
1083 				hlen += sizeof (struct ip6_frag);
1084 				proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
1085 				offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
1086 					IP6F_OFF_MASK;
1087 				ip6f_mf = ((struct ip6_frag *)ulp)->ip6f_offlg &
1088 					IP6F_MORE_FRAG;
1089 				if (V_fw_permit_single_frag6 == 0 &&
1090 				    offset == 0 && ip6f_mf == 0) {
1091 					if (V_fw_verbose)
1092 						printf("IPFW2: IPV6 - Invalid "
1093 						    "Fragment Header\n");
1094 					if (V_fw_deny_unknown_exthdrs)
1095 					    return (IP_FW_DENY);
1096 					break;
1097 				}
1098 				args->f_id.extra =
1099 				    ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
1100 				ulp = NULL;
1101 				break;
1102 
1103 			case IPPROTO_DSTOPTS:	/* RFC 2460 */
1104 				PULLUP_TO(hlen, ulp, struct ip6_hbh);
1105 				ext_hd |= EXT_DSTOPTS;
1106 				hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
1107 				proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
1108 				ulp = NULL;
1109 				break;
1110 
1111 			case IPPROTO_AH:	/* RFC 2402 */
1112 				PULLUP_TO(hlen, ulp, struct ip6_ext);
1113 				ext_hd |= EXT_AH;
1114 				hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
1115 				proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
1116 				ulp = NULL;
1117 				break;
1118 
1119 			case IPPROTO_ESP:	/* RFC 2406 */
1120 				PULLUP_TO(hlen, ulp, uint32_t);	/* SPI, Seq# */
1121 				/* Anything past Seq# is variable length and
1122 				 * data past this ext. header is encrypted. */
1123 				ext_hd |= EXT_ESP;
1124 				break;
1125 
1126 			case IPPROTO_NONE:	/* RFC 2460 */
1127 				/*
1128 				 * Packet ends here, and IPv6 header has
1129 				 * already been pulled up. If ip6e_len!=0
1130 				 * then octets must be ignored.
1131 				 */
1132 				ulp = ip; /* non-NULL to get out of loop. */
1133 				break;
1134 
1135 			case IPPROTO_OSPFIGP:
1136 				/* XXX OSPF header check? */
1137 				PULLUP_TO(hlen, ulp, struct ip6_ext);
1138 				break;
1139 
1140 			case IPPROTO_PIM:
1141 				/* XXX PIM header check? */
1142 				PULLUP_TO(hlen, ulp, struct pim);
1143 				break;
1144 
1145 			case IPPROTO_CARP:
1146 				PULLUP_TO(hlen, ulp, struct carp_header);
1147 				if (((struct carp_header *)ulp)->carp_version !=
1148 				    CARP_VERSION)
1149 					return (IP_FW_DENY);
1150 				if (((struct carp_header *)ulp)->carp_type !=
1151 				    CARP_ADVERTISEMENT)
1152 					return (IP_FW_DENY);
1153 				break;
1154 
1155 			case IPPROTO_IPV6:	/* RFC 2893 */
1156 				PULLUP_TO(hlen, ulp, struct ip6_hdr);
1157 				break;
1158 
1159 			case IPPROTO_IPV4:	/* RFC 2893 */
1160 				PULLUP_TO(hlen, ulp, struct ip);
1161 				break;
1162 
1163 			default:
1164 				if (V_fw_verbose)
1165 					printf("IPFW2: IPV6 - Unknown "
1166 					    "Extension Header(%d), ext_hd=%x\n",
1167 					     proto, ext_hd);
1168 				if (V_fw_deny_unknown_exthdrs)
1169 				    return (IP_FW_DENY);
1170 				PULLUP_TO(hlen, ulp, struct ip6_ext);
1171 				break;
1172 			} /*switch */
1173 		}
1174 		ip = mtod(m, struct ip *);
1175 		ip6 = (struct ip6_hdr *)ip;
1176 		args->f_id.src_ip6 = ip6->ip6_src;
1177 		args->f_id.dst_ip6 = ip6->ip6_dst;
1178 		args->f_id.src_ip = 0;
1179 		args->f_id.dst_ip = 0;
1180 		args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
1181 	} else if (pktlen >= sizeof(struct ip) &&
1182 	    (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
1183 	    	is_ipv4 = 1;
1184 		hlen = ip->ip_hl << 2;
1185 		args->f_id.addr_type = 4;
1186 
1187 		/*
1188 		 * Collect parameters into local variables for faster matching.
1189 		 */
1190 		proto = ip->ip_p;
1191 		src_ip = ip->ip_src;
1192 		dst_ip = ip->ip_dst;
1193 		offset = ntohs(ip->ip_off) & IP_OFFMASK;
1194 		iplen = ntohs(ip->ip_len);
1195 		pktlen = iplen < pktlen ? iplen : pktlen;
1196 
1197 		if (offset == 0) {
1198 			switch (proto) {
1199 			case IPPROTO_TCP:
1200 				PULLUP_TO(hlen, ulp, struct tcphdr);
1201 				dst_port = TCP(ulp)->th_dport;
1202 				src_port = TCP(ulp)->th_sport;
1203 				/* save flags for dynamic rules */
1204 				args->f_id._flags = TCP(ulp)->th_flags;
1205 				break;
1206 
1207 			case IPPROTO_SCTP:
1208 				PULLUP_TO(hlen, ulp, struct sctphdr);
1209 				src_port = SCTP(ulp)->src_port;
1210 				dst_port = SCTP(ulp)->dest_port;
1211 				break;
1212 
1213 			case IPPROTO_UDP:
1214 				PULLUP_TO(hlen, ulp, struct udphdr);
1215 				dst_port = UDP(ulp)->uh_dport;
1216 				src_port = UDP(ulp)->uh_sport;
1217 				break;
1218 
1219 			case IPPROTO_ICMP:
1220 				PULLUP_TO(hlen, ulp, struct icmphdr);
1221 				//args->f_id.flags = ICMP(ulp)->icmp_type;
1222 				break;
1223 
1224 			default:
1225 				break;
1226 			}
1227 		}
1228 
1229 		ip = mtod(m, struct ip *);
1230 		args->f_id.src_ip = ntohl(src_ip.s_addr);
1231 		args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1232 	}
1233 #undef PULLUP_TO
1234 	if (proto) { /* we may have port numbers, store them */
1235 		args->f_id.proto = proto;
1236 		args->f_id.src_port = src_port = ntohs(src_port);
1237 		args->f_id.dst_port = dst_port = ntohs(dst_port);
1238 	}
1239 
1240 	IPFW_PF_RLOCK(chain);
1241 	if (! V_ipfw_vnet_ready) { /* shutting down, leave NOW. */
1242 		IPFW_PF_RUNLOCK(chain);
1243 		return (IP_FW_PASS);	/* accept */
1244 	}
1245 	if (args->rule.slot) {
1246 		/*
1247 		 * Packet has already been tagged as a result of a previous
1248 		 * match on rule args->rule aka args->rule_id (PIPE, QUEUE,
1249 		 * REASS, NETGRAPH, DIVERT/TEE...)
1250 		 * Validate the slot and continue from the next one
1251 		 * if still present, otherwise do a lookup.
1252 		 */
1253 		f_pos = (args->rule.chain_id == chain->id) ?
1254 		    args->rule.slot :
1255 		    ipfw_find_rule(chain, args->rule.rulenum,
1256 			args->rule.rule_id);
1257 	} else {
1258 		f_pos = 0;
1259 	}
1260 
1261 	/*
1262 	 * Now scan the rules, and parse microinstructions for each rule.
1263 	 * We have two nested loops and an inner switch. Sometimes we
1264 	 * need to break out of one or both loops, or re-enter one of
1265 	 * the loops with updated variables. Loop variables are:
1266 	 *
1267 	 *	f_pos (outer loop) points to the current rule.
1268 	 *		On output it points to the matching rule.
1269 	 *	done (outer loop) is used as a flag to break the loop.
1270 	 *	l (inner loop)	residual length of current rule.
1271 	 *		cmd points to the current microinstruction.
1272 	 *
1273 	 * We break the inner loop by setting l=0 and possibly
1274 	 * cmdlen=0 if we don't want to advance cmd.
1275 	 * We break the outer loop by setting done=1
1276 	 * We can restart the inner loop by setting l>0 and f_pos, f, cmd
1277 	 * as needed.
1278 	 */
1279 	for (; f_pos < chain->n_rules; f_pos++) {
1280 		ipfw_insn *cmd;
1281 		uint32_t tablearg = 0;
1282 		int l, cmdlen, skip_or; /* skip rest of OR block */
1283 		struct ip_fw *f;
1284 
1285 		f = chain->map[f_pos];
1286 		if (V_set_disable & (1 << f->set) )
1287 			continue;
1288 
1289 		skip_or = 0;
1290 		for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
1291 		    l -= cmdlen, cmd += cmdlen) {
1292 			int match;
1293 
1294 			/*
1295 			 * check_body is a jump target used when we find a
1296 			 * CHECK_STATE, and need to jump to the body of
1297 			 * the target rule.
1298 			 */
1299 
1300 /* check_body: */
1301 			cmdlen = F_LEN(cmd);
1302 			/*
1303 			 * An OR block (insn_1 || .. || insn_n) has the
1304 			 * F_OR bit set in all but the last instruction.
1305 			 * The first match will set "skip_or", and cause
1306 			 * the following instructions to be skipped until
1307 			 * past the one with the F_OR bit clear.
1308 			 */
1309 			if (skip_or) {		/* skip this instruction */
1310 				if ((cmd->len & F_OR) == 0)
1311 					skip_or = 0;	/* next one is good */
1312 				continue;
1313 			}
1314 			match = 0; /* set to 1 if we succeed */
1315 
1316 			switch (cmd->opcode) {
1317 			/*
1318 			 * The first set of opcodes compares the packet's
1319 			 * fields with some pattern, setting 'match' if a
1320 			 * match is found. At the end of the loop there is
1321 			 * logic to deal with F_NOT and F_OR flags associated
1322 			 * with the opcode.
1323 			 */
1324 			case O_NOP:
1325 				match = 1;
1326 				break;
1327 
1328 			case O_FORWARD_MAC:
1329 				printf("ipfw: opcode %d unimplemented\n",
1330 				    cmd->opcode);
1331 				break;
1332 
1333 			case O_GID:
1334 			case O_UID:
1335 			case O_JAIL:
1336 				/*
1337 				 * We only check offset == 0 && proto != 0,
1338 				 * as this ensures that we have a
1339 				 * packet with the ports info.
1340 				 */
1341 				if (offset != 0)
1342 					break;
1343 				if (proto == IPPROTO_TCP ||
1344 				    proto == IPPROTO_UDP)
1345 					match = check_uidgid(
1346 						    (ipfw_insn_u32 *)cmd,
1347 						    args, &ucred_lookup,
1348 #ifdef __FreeBSD__
1349 						    &ucred_cache);
1350 #else
1351 						    (void *)&ucred_cache);
1352 #endif
1353 				break;
1354 
1355 			case O_RECV:
1356 				match = iface_match(m->m_pkthdr.rcvif,
1357 				    (ipfw_insn_if *)cmd, chain, &tablearg);
1358 				break;
1359 
1360 			case O_XMIT:
1361 				match = iface_match(oif, (ipfw_insn_if *)cmd,
1362 				    chain, &tablearg);
1363 				break;
1364 
1365 			case O_VIA:
1366 				match = iface_match(oif ? oif :
1367 				    m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd,
1368 				    chain, &tablearg);
1369 				break;
1370 
1371 			case O_MACADDR2:
1372 				if (args->eh != NULL) {	/* have MAC header */
1373 					u_int32_t *want = (u_int32_t *)
1374 						((ipfw_insn_mac *)cmd)->addr;
1375 					u_int32_t *mask = (u_int32_t *)
1376 						((ipfw_insn_mac *)cmd)->mask;
1377 					u_int32_t *hdr = (u_int32_t *)args->eh;
1378 
1379 					match =
1380 					    ( want[0] == (hdr[0] & mask[0]) &&
1381 					      want[1] == (hdr[1] & mask[1]) &&
1382 					      want[2] == (hdr[2] & mask[2]) );
1383 				}
1384 				break;
1385 
1386 			case O_MAC_TYPE:
1387 				if (args->eh != NULL) {
1388 					u_int16_t *p =
1389 					    ((ipfw_insn_u16 *)cmd)->ports;
1390 					int i;
1391 
1392 					for (i = cmdlen - 1; !match && i>0;
1393 					    i--, p += 2)
1394 						match = (etype >= p[0] &&
1395 						    etype <= p[1]);
1396 				}
1397 				break;
1398 
1399 			case O_FRAG:
1400 				match = (offset != 0);
1401 				break;
1402 
1403 			case O_IN:	/* "out" is "not in" */
1404 				match = (oif == NULL);
1405 				break;
1406 
1407 			case O_LAYER2:
1408 				match = (args->eh != NULL);
1409 				break;
1410 
1411 			case O_DIVERTED:
1412 			    {
1413 				/* For diverted packets, args->rule.info
1414 				 * contains the divert port (in host format)
1415 				 * reason and direction.
1416 				 */
1417 				uint32_t i = args->rule.info;
1418 				match = (i&IPFW_IS_MASK) == IPFW_IS_DIVERT &&
1419 				    cmd->arg1 & ((i & IPFW_INFO_IN) ? 1 : 2);
1420 			    }
1421 				break;
1422 
1423 			case O_PROTO:
1424 				/*
1425 				 * We do not allow an arg of 0 so the
1426 				 * check of "proto" only suffices.
1427 				 */
1428 				match = (proto == cmd->arg1);
1429 				break;
1430 
1431 			case O_IP_SRC:
1432 				match = is_ipv4 &&
1433 				    (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1434 				    src_ip.s_addr);
1435 				break;
1436 
1437 			case O_IP_SRC_LOOKUP:
1438 			case O_IP_DST_LOOKUP:
1439 				if (is_ipv4) {
1440 				    uint32_t key =
1441 					(cmd->opcode == O_IP_DST_LOOKUP) ?
1442 					    dst_ip.s_addr : src_ip.s_addr;
1443 				    uint32_t v = 0;
1444 
1445 				    if (cmdlen > F_INSN_SIZE(ipfw_insn_u32)) {
1446 					/* generic lookup. The key must be
1447 					 * in 32bit big-endian format.
1448 					 */
1449 					v = ((ipfw_insn_u32 *)cmd)->d[1];
1450 					if (v == 0)
1451 					    key = dst_ip.s_addr;
1452 					else if (v == 1)
1453 					    key = src_ip.s_addr;
1454 					else if (v == 6) /* dscp */
1455 					    key = (ip->ip_tos >> 2) & 0x3f;
1456 					else if (offset != 0)
1457 					    break;
1458 					else if (proto != IPPROTO_TCP &&
1459 						proto != IPPROTO_UDP)
1460 					    break;
1461 					else if (v == 2)
1462 					    key = htonl(dst_port);
1463 					else if (v == 3)
1464 					    key = htonl(src_port);
1465 					else if (v == 4 || v == 5) {
1466 					    check_uidgid(
1467 						(ipfw_insn_u32 *)cmd,
1468 						args, &ucred_lookup,
1469 #ifdef __FreeBSD__
1470 						&ucred_cache);
1471 					    if (v == 4 /* O_UID */)
1472 						key = ucred_cache->cr_uid;
1473 					    else if (v == 5 /* O_JAIL */)
1474 						key = ucred_cache->cr_prison->pr_id;
1475 #else /* !__FreeBSD__ */
1476 						(void *)&ucred_cache);
1477 					    if (v ==4 /* O_UID */)
1478 						key = ucred_cache.uid;
1479 					    else if (v == 5 /* O_JAIL */)
1480 						key = ucred_cache.xid;
1481 #endif /* !__FreeBSD__ */
1482 					    key = htonl(key);
1483 					} else
1484 					    break;
1485 				    }
1486 				    match = ipfw_lookup_table(chain,
1487 					cmd->arg1, key, &v);
1488 				    if (!match)
1489 					break;
1490 				    if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
1491 					match =
1492 					    ((ipfw_insn_u32 *)cmd)->d[0] == v;
1493 				    else
1494 					tablearg = v;
1495 				} else if (is_ipv6) {
1496 					uint32_t v = 0;
1497 					void *pkey = (cmd->opcode == O_IP_DST_LOOKUP) ?
1498 						&args->f_id.dst_ip6: &args->f_id.src_ip6;
1499 					match = ipfw_lookup_table_extended(chain,
1500 							cmd->arg1, pkey, &v,
1501 							IPFW_TABLE_CIDR);
1502 					if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
1503 						match = ((ipfw_insn_u32 *)cmd)->d[0] == v;
1504 					if (match)
1505 						tablearg = v;
1506 				}
1507 				break;
1508 
1509 			case O_IP_SRC_MASK:
1510 			case O_IP_DST_MASK:
1511 				if (is_ipv4) {
1512 				    uint32_t a =
1513 					(cmd->opcode == O_IP_DST_MASK) ?
1514 					    dst_ip.s_addr : src_ip.s_addr;
1515 				    uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
1516 				    int i = cmdlen-1;
1517 
1518 				    for (; !match && i>0; i-= 2, p+= 2)
1519 					match = (p[0] == (a & p[1]));
1520 				}
1521 				break;
1522 
1523 			case O_IP_SRC_ME:
1524 				if (is_ipv4) {
1525 					struct ifnet *tif;
1526 
1527 					INADDR_TO_IFP(src_ip, tif);
1528 					match = (tif != NULL);
1529 					break;
1530 				}
1531 #ifdef INET6
1532 				/* FALLTHROUGH */
1533 			case O_IP6_SRC_ME:
1534 				match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
1535 #endif
1536 				break;
1537 
1538 			case O_IP_DST_SET:
1539 			case O_IP_SRC_SET:
1540 				if (is_ipv4) {
1541 					u_int32_t *d = (u_int32_t *)(cmd+1);
1542 					u_int32_t addr =
1543 					    cmd->opcode == O_IP_DST_SET ?
1544 						args->f_id.dst_ip :
1545 						args->f_id.src_ip;
1546 
1547 					    if (addr < d[0])
1548 						    break;
1549 					    addr -= d[0]; /* subtract base */
1550 					    match = (addr < cmd->arg1) &&
1551 						( d[ 1 + (addr>>5)] &
1552 						  (1<<(addr & 0x1f)) );
1553 				}
1554 				break;
1555 
1556 			case O_IP_DST:
1557 				match = is_ipv4 &&
1558 				    (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1559 				    dst_ip.s_addr);
1560 				break;
1561 
1562 			case O_IP_DST_ME:
1563 				if (is_ipv4) {
1564 					struct ifnet *tif;
1565 
1566 					INADDR_TO_IFP(dst_ip, tif);
1567 					match = (tif != NULL);
1568 					break;
1569 				}
1570 #ifdef INET6
1571 				/* FALLTHROUGH */
1572 			case O_IP6_DST_ME:
1573 				match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
1574 #endif
1575 				break;
1576 
1577 
1578 			case O_IP_SRCPORT:
1579 			case O_IP_DSTPORT:
1580 				/*
1581 				 * offset == 0 && proto != 0 is enough
1582 				 * to guarantee that we have a
1583 				 * packet with port info.
1584 				 */
1585 				if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
1586 				    && offset == 0) {
1587 					u_int16_t x =
1588 					    (cmd->opcode == O_IP_SRCPORT) ?
1589 						src_port : dst_port ;
1590 					u_int16_t *p =
1591 					    ((ipfw_insn_u16 *)cmd)->ports;
1592 					int i;
1593 
1594 					for (i = cmdlen - 1; !match && i>0;
1595 					    i--, p += 2)
1596 						match = (x>=p[0] && x<=p[1]);
1597 				}
1598 				break;
1599 
1600 			case O_ICMPTYPE:
1601 				match = (offset == 0 && proto==IPPROTO_ICMP &&
1602 				    icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
1603 				break;
1604 
1605 #ifdef INET6
1606 			case O_ICMP6TYPE:
1607 				match = is_ipv6 && offset == 0 &&
1608 				    proto==IPPROTO_ICMPV6 &&
1609 				    icmp6type_match(
1610 					ICMP6(ulp)->icmp6_type,
1611 					(ipfw_insn_u32 *)cmd);
1612 				break;
1613 #endif /* INET6 */
1614 
1615 			case O_IPOPT:
1616 				match = (is_ipv4 &&
1617 				    ipopts_match(ip, cmd) );
1618 				break;
1619 
1620 			case O_IPVER:
1621 				match = (is_ipv4 &&
1622 				    cmd->arg1 == ip->ip_v);
1623 				break;
1624 
1625 			case O_IPID:
1626 			case O_IPLEN:
1627 			case O_IPTTL:
1628 				if (is_ipv4) {	/* only for IP packets */
1629 				    uint16_t x;
1630 				    uint16_t *p;
1631 				    int i;
1632 
1633 				    if (cmd->opcode == O_IPLEN)
1634 					x = iplen;
1635 				    else if (cmd->opcode == O_IPTTL)
1636 					x = ip->ip_ttl;
1637 				    else /* must be IPID */
1638 					x = ntohs(ip->ip_id);
1639 				    if (cmdlen == 1) {
1640 					match = (cmd->arg1 == x);
1641 					break;
1642 				    }
1643 				    /* otherwise we have ranges */
1644 				    p = ((ipfw_insn_u16 *)cmd)->ports;
1645 				    i = cmdlen - 1;
1646 				    for (; !match && i>0; i--, p += 2)
1647 					match = (x >= p[0] && x <= p[1]);
1648 				}
1649 				break;
1650 
1651 			case O_IPPRECEDENCE:
1652 				match = (is_ipv4 &&
1653 				    (cmd->arg1 == (ip->ip_tos & 0xe0)) );
1654 				break;
1655 
1656 			case O_IPTOS:
1657 				match = (is_ipv4 &&
1658 				    flags_match(cmd, ip->ip_tos));
1659 				break;
1660 
1661 			case O_DSCP:
1662 			    {
1663 				uint32_t *p;
1664 				uint16_t x;
1665 
1666 				p = ((ipfw_insn_u32 *)cmd)->d;
1667 
1668 				if (is_ipv4)
1669 					x = ip->ip_tos >> 2;
1670 				else if (is_ipv6) {
1671 					uint8_t *v;
1672 					v = &((struct ip6_hdr *)ip)->ip6_vfc;
1673 					x = (*v & 0x0F) << 2;
1674 					v++;
1675 					x |= *v >> 6;
1676 				} else
1677 					break;
1678 
1679 				/* DSCP bitmask is stored as low_u32 high_u32 */
1680 				if (x > 32)
1681 					match = *(p + 1) & (1 << (x - 32));
1682 				else
1683 					match = *p & (1 << x);
1684 			    }
1685 				break;
1686 
1687 			case O_TCPDATALEN:
1688 				if (proto == IPPROTO_TCP && offset == 0) {
1689 				    struct tcphdr *tcp;
1690 				    uint16_t x;
1691 				    uint16_t *p;
1692 				    int i;
1693 
1694 				    tcp = TCP(ulp);
1695 				    x = iplen -
1696 					((ip->ip_hl + tcp->th_off) << 2);
1697 				    if (cmdlen == 1) {
1698 					match = (cmd->arg1 == x);
1699 					break;
1700 				    }
1701 				    /* otherwise we have ranges */
1702 				    p = ((ipfw_insn_u16 *)cmd)->ports;
1703 				    i = cmdlen - 1;
1704 				    for (; !match && i>0; i--, p += 2)
1705 					match = (x >= p[0] && x <= p[1]);
1706 				}
1707 				break;
1708 
1709 			case O_TCPFLAGS:
1710 				match = (proto == IPPROTO_TCP && offset == 0 &&
1711 				    flags_match(cmd, TCP(ulp)->th_flags));
1712 				break;
1713 
1714 			case O_TCPOPTS:
1715 				PULLUP_LEN(hlen, ulp, (TCP(ulp)->th_off << 2));
1716 				match = (proto == IPPROTO_TCP && offset == 0 &&
1717 				    tcpopts_match(TCP(ulp), cmd));
1718 				break;
1719 
1720 			case O_TCPSEQ:
1721 				match = (proto == IPPROTO_TCP && offset == 0 &&
1722 				    ((ipfw_insn_u32 *)cmd)->d[0] ==
1723 					TCP(ulp)->th_seq);
1724 				break;
1725 
1726 			case O_TCPACK:
1727 				match = (proto == IPPROTO_TCP && offset == 0 &&
1728 				    ((ipfw_insn_u32 *)cmd)->d[0] ==
1729 					TCP(ulp)->th_ack);
1730 				break;
1731 
1732 			case O_TCPWIN:
1733 				if (proto == IPPROTO_TCP && offset == 0) {
1734 				    uint16_t x;
1735 				    uint16_t *p;
1736 				    int i;
1737 
1738 				    x = ntohs(TCP(ulp)->th_win);
1739 				    if (cmdlen == 1) {
1740 					match = (cmd->arg1 == x);
1741 					break;
1742 				    }
1743 				    /* Otherwise we have ranges. */
1744 				    p = ((ipfw_insn_u16 *)cmd)->ports;
1745 				    i = cmdlen - 1;
1746 				    for (; !match && i > 0; i--, p += 2)
1747 					match = (x >= p[0] && x <= p[1]);
1748 				}
1749 				break;
1750 
1751 			case O_ESTAB:
1752 				/* reject packets which have SYN only */
1753 				/* XXX should i also check for TH_ACK ? */
1754 				match = (proto == IPPROTO_TCP && offset == 0 &&
1755 				    (TCP(ulp)->th_flags &
1756 				     (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
1757 				break;
1758 
1759 			case O_ALTQ: {
1760 				struct pf_mtag *at;
1761 				struct m_tag *mtag;
1762 				ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
1763 
1764 				/*
1765 				 * ALTQ uses mbuf tags from another
1766 				 * packet filtering system - pf(4).
1767 				 * We allocate a tag in its format
1768 				 * and fill it in, pretending to be pf(4).
1769 				 */
1770 				match = 1;
1771 				at = pf_find_mtag(m);
1772 				if (at != NULL && at->qid != 0)
1773 					break;
1774 				mtag = m_tag_get(PACKET_TAG_PF,
1775 				    sizeof(struct pf_mtag), M_NOWAIT | M_ZERO);
1776 				if (mtag == NULL) {
1777 					/*
1778 					 * Let the packet fall back to the
1779 					 * default ALTQ.
1780 					 */
1781 					break;
1782 				}
1783 				m_tag_prepend(m, mtag);
1784 				at = (struct pf_mtag *)(mtag + 1);
1785 				at->qid = altq->qid;
1786 				at->hdr = ip;
1787 				break;
1788 			}
1789 
1790 			case O_LOG:
1791 				ipfw_log(f, hlen, args, m,
1792 				    oif, offset | ip6f_mf, tablearg, ip);
1793 				match = 1;
1794 				break;
1795 
1796 			case O_PROB:
1797 				match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
1798 				break;
1799 
1800 			case O_VERREVPATH:
1801 				/* Outgoing packets automatically pass/match */
1802 				match = ((oif != NULL) ||
1803 				    (m->m_pkthdr.rcvif == NULL) ||
1804 				    (
1805 #ifdef INET6
1806 				    is_ipv6 ?
1807 					verify_path6(&(args->f_id.src_ip6),
1808 					    m->m_pkthdr.rcvif, args->f_id.fib) :
1809 #endif
1810 				    verify_path(src_ip, m->m_pkthdr.rcvif,
1811 				        args->f_id.fib)));
1812 				break;
1813 
1814 			case O_VERSRCREACH:
1815 				/* Outgoing packets automatically pass/match */
1816 				match = (hlen > 0 && ((oif != NULL) ||
1817 #ifdef INET6
1818 				    is_ipv6 ?
1819 				        verify_path6(&(args->f_id.src_ip6),
1820 				            NULL, args->f_id.fib) :
1821 #endif
1822 				    verify_path(src_ip, NULL, args->f_id.fib)));
1823 				break;
1824 
1825 			case O_ANTISPOOF:
1826 				/* Outgoing packets automatically pass/match */
1827 				if (oif == NULL && hlen > 0 &&
1828 				    (  (is_ipv4 && in_localaddr(src_ip))
1829 #ifdef INET6
1830 				    || (is_ipv6 &&
1831 				        in6_localaddr(&(args->f_id.src_ip6)))
1832 #endif
1833 				    ))
1834 					match =
1835 #ifdef INET6
1836 					    is_ipv6 ? verify_path6(
1837 					        &(args->f_id.src_ip6),
1838 					        m->m_pkthdr.rcvif,
1839 						args->f_id.fib) :
1840 #endif
1841 					    verify_path(src_ip,
1842 					    	m->m_pkthdr.rcvif,
1843 					        args->f_id.fib);
1844 				else
1845 					match = 1;
1846 				break;
1847 
1848 			case O_IPSEC:
1849 #ifdef IPSEC
1850 				match = (m_tag_find(m,
1851 				    PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
1852 #endif
1853 				/* otherwise no match */
1854 				break;
1855 
1856 #ifdef INET6
1857 			case O_IP6_SRC:
1858 				match = is_ipv6 &&
1859 				    IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
1860 				    &((ipfw_insn_ip6 *)cmd)->addr6);
1861 				break;
1862 
1863 			case O_IP6_DST:
1864 				match = is_ipv6 &&
1865 				IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
1866 				    &((ipfw_insn_ip6 *)cmd)->addr6);
1867 				break;
1868 			case O_IP6_SRC_MASK:
1869 			case O_IP6_DST_MASK:
1870 				if (is_ipv6) {
1871 					int i = cmdlen - 1;
1872 					struct in6_addr p;
1873 					struct in6_addr *d =
1874 					    &((ipfw_insn_ip6 *)cmd)->addr6;
1875 
1876 					for (; !match && i > 0; d += 2,
1877 					    i -= F_INSN_SIZE(struct in6_addr)
1878 					    * 2) {
1879 						p = (cmd->opcode ==
1880 						    O_IP6_SRC_MASK) ?
1881 						    args->f_id.src_ip6:
1882 						    args->f_id.dst_ip6;
1883 						APPLY_MASK(&p, &d[1]);
1884 						match =
1885 						    IN6_ARE_ADDR_EQUAL(&d[0],
1886 						    &p);
1887 					}
1888 				}
1889 				break;
1890 
1891 			case O_FLOW6ID:
1892 				match = is_ipv6 &&
1893 				    flow6id_match(args->f_id.flow_id6,
1894 				    (ipfw_insn_u32 *) cmd);
1895 				break;
1896 
1897 			case O_EXT_HDR:
1898 				match = is_ipv6 &&
1899 				    (ext_hd & ((ipfw_insn *) cmd)->arg1);
1900 				break;
1901 
1902 			case O_IP6:
1903 				match = is_ipv6;
1904 				break;
1905 #endif
1906 
1907 			case O_IP4:
1908 				match = is_ipv4;
1909 				break;
1910 
1911 			case O_TAG: {
1912 				struct m_tag *mtag;
1913 				uint32_t tag = IP_FW_ARG_TABLEARG(cmd->arg1);
1914 
1915 				/* Packet is already tagged with this tag? */
1916 				mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
1917 
1918 				/* We have `untag' action when F_NOT flag is
1919 				 * present. And we must remove this mtag from
1920 				 * mbuf and reset `match' to zero (`match' will
1921 				 * be inversed later).
1922 				 * Otherwise we should allocate new mtag and
1923 				 * push it into mbuf.
1924 				 */
1925 				if (cmd->len & F_NOT) { /* `untag' action */
1926 					if (mtag != NULL)
1927 						m_tag_delete(m, mtag);
1928 					match = 0;
1929 				} else {
1930 					if (mtag == NULL) {
1931 						mtag = m_tag_alloc( MTAG_IPFW,
1932 						    tag, 0, M_NOWAIT);
1933 						if (mtag != NULL)
1934 							m_tag_prepend(m, mtag);
1935 					}
1936 					match = 1;
1937 				}
1938 				break;
1939 			}
1940 
1941 			case O_FIB: /* try match the specified fib */
1942 				if (args->f_id.fib == cmd->arg1)
1943 					match = 1;
1944 				break;
1945 
1946 			case O_SOCKARG:	{
1947 				struct inpcb *inp = args->inp;
1948 				struct inpcbinfo *pi;
1949 
1950 				if (is_ipv6) /* XXX can we remove this ? */
1951 					break;
1952 
1953 				if (proto == IPPROTO_TCP)
1954 					pi = &V_tcbinfo;
1955 				else if (proto == IPPROTO_UDP)
1956 					pi = &V_udbinfo;
1957 				else
1958 					break;
1959 
1960 				/*
1961 				 * XXXRW: so_user_cookie should almost
1962 				 * certainly be inp_user_cookie?
1963 				 */
1964 
1965 				/* For incomming packet, lookup up the
1966 				inpcb using the src/dest ip/port tuple */
1967 				if (inp == NULL) {
1968 					inp = in_pcblookup(pi,
1969 						src_ip, htons(src_port),
1970 						dst_ip, htons(dst_port),
1971 						INPLOOKUP_RLOCKPCB, NULL);
1972 					if (inp != NULL) {
1973 						tablearg =
1974 						    inp->inp_socket->so_user_cookie;
1975 						if (tablearg)
1976 							match = 1;
1977 						INP_RUNLOCK(inp);
1978 					}
1979 				} else {
1980 					if (inp->inp_socket) {
1981 						tablearg =
1982 						    inp->inp_socket->so_user_cookie;
1983 						if (tablearg)
1984 							match = 1;
1985 					}
1986 				}
1987 				break;
1988 			}
1989 
1990 			case O_TAGGED: {
1991 				struct m_tag *mtag;
1992 				uint32_t tag = IP_FW_ARG_TABLEARG(cmd->arg1);
1993 
1994 				if (cmdlen == 1) {
1995 					match = m_tag_locate(m, MTAG_IPFW,
1996 					    tag, NULL) != NULL;
1997 					break;
1998 				}
1999 
2000 				/* we have ranges */
2001 				for (mtag = m_tag_first(m);
2002 				    mtag != NULL && !match;
2003 				    mtag = m_tag_next(m, mtag)) {
2004 					uint16_t *p;
2005 					int i;
2006 
2007 					if (mtag->m_tag_cookie != MTAG_IPFW)
2008 						continue;
2009 
2010 					p = ((ipfw_insn_u16 *)cmd)->ports;
2011 					i = cmdlen - 1;
2012 					for(; !match && i > 0; i--, p += 2)
2013 						match =
2014 						    mtag->m_tag_id >= p[0] &&
2015 						    mtag->m_tag_id <= p[1];
2016 				}
2017 				break;
2018 			}
2019 
2020 			/*
2021 			 * The second set of opcodes represents 'actions',
2022 			 * i.e. the terminal part of a rule once the packet
2023 			 * matches all previous patterns.
2024 			 * Typically there is only one action for each rule,
2025 			 * and the opcode is stored at the end of the rule
2026 			 * (but there are exceptions -- see below).
2027 			 *
2028 			 * In general, here we set retval and terminate the
2029 			 * outer loop (would be a 'break 3' in some language,
2030 			 * but we need to set l=0, done=1)
2031 			 *
2032 			 * Exceptions:
2033 			 * O_COUNT and O_SKIPTO actions:
2034 			 *   instead of terminating, we jump to the next rule
2035 			 *   (setting l=0), or to the SKIPTO target (setting
2036 			 *   f/f_len, cmd and l as needed), respectively.
2037 			 *
2038 			 * O_TAG, O_LOG and O_ALTQ action parameters:
2039 			 *   perform some action and set match = 1;
2040 			 *
2041 			 * O_LIMIT and O_KEEP_STATE: these opcodes are
2042 			 *   not real 'actions', and are stored right
2043 			 *   before the 'action' part of the rule.
2044 			 *   These opcodes try to install an entry in the
2045 			 *   state tables; if successful, we continue with
2046 			 *   the next opcode (match=1; break;), otherwise
2047 			 *   the packet must be dropped (set retval,
2048 			 *   break loops with l=0, done=1)
2049 			 *
2050 			 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2051 			 *   cause a lookup of the state table, and a jump
2052 			 *   to the 'action' part of the parent rule
2053 			 *   if an entry is found, or
2054 			 *   (CHECK_STATE only) a jump to the next rule if
2055 			 *   the entry is not found.
2056 			 *   The result of the lookup is cached so that
2057 			 *   further instances of these opcodes become NOPs.
2058 			 *   The jump to the next rule is done by setting
2059 			 *   l=0, cmdlen=0.
2060 			 */
2061 			case O_LIMIT:
2062 			case O_KEEP_STATE:
2063 				if (ipfw_install_state(f,
2064 				    (ipfw_insn_limit *)cmd, args, tablearg)) {
2065 					/* error or limit violation */
2066 					retval = IP_FW_DENY;
2067 					l = 0;	/* exit inner loop */
2068 					done = 1; /* exit outer loop */
2069 				}
2070 				match = 1;
2071 				break;
2072 
2073 			case O_PROBE_STATE:
2074 			case O_CHECK_STATE:
2075 				/*
2076 				 * dynamic rules are checked at the first
2077 				 * keep-state or check-state occurrence,
2078 				 * with the result being stored in dyn_dir.
2079 				 * The compiler introduces a PROBE_STATE
2080 				 * instruction for us when we have a
2081 				 * KEEP_STATE (because PROBE_STATE needs
2082 				 * to be run first).
2083 				 */
2084 				if (dyn_dir == MATCH_UNKNOWN &&
2085 				    (q = ipfw_lookup_dyn_rule(&args->f_id,
2086 				     &dyn_dir, proto == IPPROTO_TCP ?
2087 					TCP(ulp) : NULL))
2088 					!= NULL) {
2089 					/*
2090 					 * Found dynamic entry, update stats
2091 					 * and jump to the 'action' part of
2092 					 * the parent rule by setting
2093 					 * f, cmd, l and clearing cmdlen.
2094 					 */
2095 					IPFW_INC_DYN_COUNTER(q, pktlen);
2096 					/* XXX we would like to have f_pos
2097 					 * readily accessible in the dynamic
2098 				         * rule, instead of having to
2099 					 * lookup q->rule.
2100 					 */
2101 					f = q->rule;
2102 					f_pos = ipfw_find_rule(chain,
2103 						f->rulenum, f->id);
2104 					cmd = ACTION_PTR(f);
2105 					l = f->cmd_len - f->act_ofs;
2106 					ipfw_dyn_unlock(q);
2107 					cmdlen = 0;
2108 					match = 1;
2109 					break;
2110 				}
2111 				/*
2112 				 * Dynamic entry not found. If CHECK_STATE,
2113 				 * skip to next rule, if PROBE_STATE just
2114 				 * ignore and continue with next opcode.
2115 				 */
2116 				if (cmd->opcode == O_CHECK_STATE)
2117 					l = 0;	/* exit inner loop */
2118 				match = 1;
2119 				break;
2120 
2121 			case O_ACCEPT:
2122 				retval = 0;	/* accept */
2123 				l = 0;		/* exit inner loop */
2124 				done = 1;	/* exit outer loop */
2125 				break;
2126 
2127 			case O_PIPE:
2128 			case O_QUEUE:
2129 				set_match(args, f_pos, chain);
2130 				args->rule.info = IP_FW_ARG_TABLEARG(cmd->arg1);
2131 				if (cmd->opcode == O_PIPE)
2132 					args->rule.info |= IPFW_IS_PIPE;
2133 				if (V_fw_one_pass)
2134 					args->rule.info |= IPFW_ONEPASS;
2135 				retval = IP_FW_DUMMYNET;
2136 				l = 0;          /* exit inner loop */
2137 				done = 1;       /* exit outer loop */
2138 				break;
2139 
2140 			case O_DIVERT:
2141 			case O_TEE:
2142 				if (args->eh) /* not on layer 2 */
2143 				    break;
2144 				/* otherwise this is terminal */
2145 				l = 0;		/* exit inner loop */
2146 				done = 1;	/* exit outer loop */
2147 				retval = (cmd->opcode == O_DIVERT) ?
2148 					IP_FW_DIVERT : IP_FW_TEE;
2149 				set_match(args, f_pos, chain);
2150 				args->rule.info = IP_FW_ARG_TABLEARG(cmd->arg1);
2151 				break;
2152 
2153 			case O_COUNT:
2154 				IPFW_INC_RULE_COUNTER(f, pktlen);
2155 				l = 0;		/* exit inner loop */
2156 				break;
2157 
2158 			case O_SKIPTO:
2159 			    IPFW_INC_RULE_COUNTER(f, pktlen);
2160 			    f_pos = jump_fast(chain, f, cmd->arg1, tablearg, 0);
2161 			    /*
2162 			     * Skip disabled rules, and re-enter
2163 			     * the inner loop with the correct
2164 			     * f_pos, f, l and cmd.
2165 			     * Also clear cmdlen and skip_or
2166 			     */
2167 			    for (; f_pos < chain->n_rules - 1 &&
2168 				    (V_set_disable &
2169 				     (1 << chain->map[f_pos]->set));
2170 				    f_pos++)
2171 				;
2172 			    /* Re-enter the inner loop at the skipto rule. */
2173 			    f = chain->map[f_pos];
2174 			    l = f->cmd_len;
2175 			    cmd = f->cmd;
2176 			    match = 1;
2177 			    cmdlen = 0;
2178 			    skip_or = 0;
2179 			    continue;
2180 			    break;	/* not reached */
2181 
2182 			case O_CALLRETURN: {
2183 				/*
2184 				 * Implementation of `subroutine' call/return,
2185 				 * in the stack carried in an mbuf tag. This
2186 				 * is different from `skipto' in that any call
2187 				 * address is possible (`skipto' must prevent
2188 				 * backward jumps to avoid endless loops).
2189 				 * We have `return' action when F_NOT flag is
2190 				 * present. The `m_tag_id' field is used as
2191 				 * stack pointer.
2192 				 */
2193 				struct m_tag *mtag;
2194 				uint16_t jmpto, *stack;
2195 
2196 #define	IS_CALL		((cmd->len & F_NOT) == 0)
2197 #define	IS_RETURN	((cmd->len & F_NOT) != 0)
2198 				/*
2199 				 * Hand-rolled version of m_tag_locate() with
2200 				 * wildcard `type'.
2201 				 * If not already tagged, allocate new tag.
2202 				 */
2203 				mtag = m_tag_first(m);
2204 				while (mtag != NULL) {
2205 					if (mtag->m_tag_cookie ==
2206 					    MTAG_IPFW_CALL)
2207 						break;
2208 					mtag = m_tag_next(m, mtag);
2209 				}
2210 				if (mtag == NULL && IS_CALL) {
2211 					mtag = m_tag_alloc(MTAG_IPFW_CALL, 0,
2212 					    IPFW_CALLSTACK_SIZE *
2213 					    sizeof(uint16_t), M_NOWAIT);
2214 					if (mtag != NULL)
2215 						m_tag_prepend(m, mtag);
2216 				}
2217 
2218 				/*
2219 				 * On error both `call' and `return' just
2220 				 * continue with next rule.
2221 				 */
2222 				if (IS_RETURN && (mtag == NULL ||
2223 				    mtag->m_tag_id == 0)) {
2224 					l = 0;		/* exit inner loop */
2225 					break;
2226 				}
2227 				if (IS_CALL && (mtag == NULL ||
2228 				    mtag->m_tag_id >= IPFW_CALLSTACK_SIZE)) {
2229 					printf("ipfw: call stack error, "
2230 					    "go to next rule\n");
2231 					l = 0;		/* exit inner loop */
2232 					break;
2233 				}
2234 
2235 				IPFW_INC_RULE_COUNTER(f, pktlen);
2236 				stack = (uint16_t *)(mtag + 1);
2237 
2238 				/*
2239 				 * The `call' action may use cached f_pos
2240 				 * (in f->next_rule), whose version is written
2241 				 * in f->next_rule.
2242 				 * The `return' action, however, doesn't have
2243 				 * fixed jump address in cmd->arg1 and can't use
2244 				 * cache.
2245 				 */
2246 				if (IS_CALL) {
2247 					stack[mtag->m_tag_id] = f->rulenum;
2248 					mtag->m_tag_id++;
2249 			    		f_pos = jump_fast(chain, f, cmd->arg1,
2250 					    tablearg, 1);
2251 				} else {	/* `return' action */
2252 					mtag->m_tag_id--;
2253 					jmpto = stack[mtag->m_tag_id] + 1;
2254 					f_pos = ipfw_find_rule(chain, jmpto, 0);
2255 				}
2256 
2257 				/*
2258 				 * Skip disabled rules, and re-enter
2259 				 * the inner loop with the correct
2260 				 * f_pos, f, l and cmd.
2261 				 * Also clear cmdlen and skip_or
2262 				 */
2263 				for (; f_pos < chain->n_rules - 1 &&
2264 				    (V_set_disable &
2265 				    (1 << chain->map[f_pos]->set)); f_pos++)
2266 					;
2267 				/* Re-enter the inner loop at the dest rule. */
2268 				f = chain->map[f_pos];
2269 				l = f->cmd_len;
2270 				cmd = f->cmd;
2271 				cmdlen = 0;
2272 				skip_or = 0;
2273 				continue;
2274 				break;	/* NOTREACHED */
2275 			}
2276 #undef IS_CALL
2277 #undef IS_RETURN
2278 
2279 			case O_REJECT:
2280 				/*
2281 				 * Drop the packet and send a reject notice
2282 				 * if the packet is not ICMP (or is an ICMP
2283 				 * query), and it is not multicast/broadcast.
2284 				 */
2285 				if (hlen > 0 && is_ipv4 && offset == 0 &&
2286 				    (proto != IPPROTO_ICMP ||
2287 				     is_icmp_query(ICMP(ulp))) &&
2288 				    !(m->m_flags & (M_BCAST|M_MCAST)) &&
2289 				    !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2290 					send_reject(args, cmd->arg1, iplen, ip);
2291 					m = args->m;
2292 				}
2293 				/* FALLTHROUGH */
2294 #ifdef INET6
2295 			case O_UNREACH6:
2296 				if (hlen > 0 && is_ipv6 &&
2297 				    ((offset & IP6F_OFF_MASK) == 0) &&
2298 				    (proto != IPPROTO_ICMPV6 ||
2299 				     (is_icmp6_query(icmp6_type) == 1)) &&
2300 				    !(m->m_flags & (M_BCAST|M_MCAST)) &&
2301 				    !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
2302 					send_reject6(
2303 					    args, cmd->arg1, hlen,
2304 					    (struct ip6_hdr *)ip);
2305 					m = args->m;
2306 				}
2307 				/* FALLTHROUGH */
2308 #endif
2309 			case O_DENY:
2310 				retval = IP_FW_DENY;
2311 				l = 0;		/* exit inner loop */
2312 				done = 1;	/* exit outer loop */
2313 				break;
2314 
2315 			case O_FORWARD_IP:
2316 				if (args->eh)	/* not valid on layer2 pkts */
2317 					break;
2318 				if (q == NULL || q->rule != f ||
2319 				    dyn_dir == MATCH_FORWARD) {
2320 				    struct sockaddr_in *sa;
2321 				    sa = &(((ipfw_insn_sa *)cmd)->sa);
2322 				    if (sa->sin_addr.s_addr == INADDR_ANY) {
2323 					bcopy(sa, &args->hopstore,
2324 							sizeof(*sa));
2325 					args->hopstore.sin_addr.s_addr =
2326 						    htonl(tablearg);
2327 					args->next_hop = &args->hopstore;
2328 				    } else {
2329 					args->next_hop = sa;
2330 				    }
2331 				}
2332 				retval = IP_FW_PASS;
2333 				l = 0;          /* exit inner loop */
2334 				done = 1;       /* exit outer loop */
2335 				break;
2336 
2337 #ifdef INET6
2338 			case O_FORWARD_IP6:
2339 				if (args->eh)	/* not valid on layer2 pkts */
2340 					break;
2341 				if (q == NULL || q->rule != f ||
2342 				    dyn_dir == MATCH_FORWARD) {
2343 					struct sockaddr_in6 *sin6;
2344 
2345 					sin6 = &(((ipfw_insn_sa6 *)cmd)->sa);
2346 					args->next_hop6 = sin6;
2347 				}
2348 				retval = IP_FW_PASS;
2349 				l = 0;		/* exit inner loop */
2350 				done = 1;	/* exit outer loop */
2351 				break;
2352 #endif
2353 
2354 			case O_NETGRAPH:
2355 			case O_NGTEE:
2356 				set_match(args, f_pos, chain);
2357 				args->rule.info = IP_FW_ARG_TABLEARG(cmd->arg1);
2358 				if (V_fw_one_pass)
2359 					args->rule.info |= IPFW_ONEPASS;
2360 				retval = (cmd->opcode == O_NETGRAPH) ?
2361 				    IP_FW_NETGRAPH : IP_FW_NGTEE;
2362 				l = 0;          /* exit inner loop */
2363 				done = 1;       /* exit outer loop */
2364 				break;
2365 
2366 			case O_SETFIB: {
2367 				uint32_t fib;
2368 
2369 				IPFW_INC_RULE_COUNTER(f, pktlen);
2370 				fib = IP_FW_ARG_TABLEARG(cmd->arg1);
2371 				if (fib >= rt_numfibs)
2372 					fib = 0;
2373 				M_SETFIB(m, fib);
2374 				args->f_id.fib = fib;
2375 				l = 0;		/* exit inner loop */
2376 				break;
2377 		        }
2378 
2379 			case O_SETDSCP: {
2380 				uint16_t code;
2381 
2382 				code = IP_FW_ARG_TABLEARG(cmd->arg1) & 0x3F;
2383 				l = 0;		/* exit inner loop */
2384 				if (is_ipv4) {
2385 					uint16_t a;
2386 
2387 					a = ip->ip_tos;
2388 					ip->ip_tos = (code << 2) | (ip->ip_tos & 0x03);
2389 					a += ntohs(ip->ip_sum) - ip->ip_tos;
2390 					ip->ip_sum = htons(a);
2391 				} else if (is_ipv6) {
2392 					uint8_t *v;
2393 
2394 					v = &((struct ip6_hdr *)ip)->ip6_vfc;
2395 					*v = (*v & 0xF0) | (code >> 2);
2396 					v++;
2397 					*v = (*v & 0x3F) | ((code & 0x03) << 6);
2398 				} else
2399 					break;
2400 
2401 				IPFW_INC_RULE_COUNTER(f, pktlen);
2402 				break;
2403 			}
2404 
2405 			case O_NAT:
2406  				if (!IPFW_NAT_LOADED) {
2407 				    retval = IP_FW_DENY;
2408 				} else {
2409 				    struct cfg_nat *t;
2410 				    int nat_id;
2411 
2412 				    set_match(args, f_pos, chain);
2413 				    /* Check if this is 'global' nat rule */
2414 				    if (cmd->arg1 == 0) {
2415 					    retval = ipfw_nat_ptr(args, NULL, m);
2416 					    l = 0;
2417 					    done = 1;
2418 					    break;
2419 				    }
2420 				    t = ((ipfw_insn_nat *)cmd)->nat;
2421 				    if (t == NULL) {
2422 					nat_id = IP_FW_ARG_TABLEARG(cmd->arg1);
2423 					t = (*lookup_nat_ptr)(&chain->nat, nat_id);
2424 
2425 					if (t == NULL) {
2426 					    retval = IP_FW_DENY;
2427 					    l = 0;	/* exit inner loop */
2428 					    done = 1;	/* exit outer loop */
2429 					    break;
2430 					}
2431 					if (cmd->arg1 != IP_FW_TABLEARG)
2432 					    ((ipfw_insn_nat *)cmd)->nat = t;
2433 				    }
2434 				    retval = ipfw_nat_ptr(args, t, m);
2435 				}
2436 				l = 0;          /* exit inner loop */
2437 				done = 1;       /* exit outer loop */
2438 				break;
2439 
2440 			case O_REASS: {
2441 				int ip_off;
2442 
2443 				IPFW_INC_RULE_COUNTER(f, pktlen);
2444 				l = 0;	/* in any case exit inner loop */
2445 				ip_off = ntohs(ip->ip_off);
2446 
2447 				/* if not fragmented, go to next rule */
2448 				if ((ip_off & (IP_MF | IP_OFFMASK)) == 0)
2449 				    break;
2450 
2451 				args->m = m = ip_reass(m);
2452 
2453 				/*
2454 				 * do IP header checksum fixup.
2455 				 */
2456 				if (m == NULL) { /* fragment got swallowed */
2457 				    retval = IP_FW_DENY;
2458 				} else { /* good, packet complete */
2459 				    int hlen;
2460 
2461 				    ip = mtod(m, struct ip *);
2462 				    hlen = ip->ip_hl << 2;
2463 				    ip->ip_sum = 0;
2464 				    if (hlen == sizeof(struct ip))
2465 					ip->ip_sum = in_cksum_hdr(ip);
2466 				    else
2467 					ip->ip_sum = in_cksum(m, hlen);
2468 				    retval = IP_FW_REASS;
2469 				    set_match(args, f_pos, chain);
2470 				}
2471 				done = 1;	/* exit outer loop */
2472 				break;
2473 			}
2474 
2475 			default:
2476 				panic("-- unknown opcode %d\n", cmd->opcode);
2477 			} /* end of switch() on opcodes */
2478 			/*
2479 			 * if we get here with l=0, then match is irrelevant.
2480 			 */
2481 
2482 			if (cmd->len & F_NOT)
2483 				match = !match;
2484 
2485 			if (match) {
2486 				if (cmd->len & F_OR)
2487 					skip_or = 1;
2488 			} else {
2489 				if (!(cmd->len & F_OR)) /* not an OR block, */
2490 					break;		/* try next rule    */
2491 			}
2492 
2493 		}	/* end of inner loop, scan opcodes */
2494 #undef PULLUP_LEN
2495 
2496 		if (done)
2497 			break;
2498 
2499 /* next_rule:; */	/* try next rule		*/
2500 
2501 	}		/* end of outer for, scan rules */
2502 
2503 	if (done) {
2504 		struct ip_fw *rule = chain->map[f_pos];
2505 		/* Update statistics */
2506 		IPFW_INC_RULE_COUNTER(rule, pktlen);
2507 	} else {
2508 		retval = IP_FW_DENY;
2509 		printf("ipfw: ouch!, skip past end of rules, denying packet\n");
2510 	}
2511 	IPFW_PF_RUNLOCK(chain);
2512 #ifdef __FreeBSD__
2513 	if (ucred_cache != NULL)
2514 		crfree(ucred_cache);
2515 #endif
2516 	return (retval);
2517 
2518 pullup_failed:
2519 	if (V_fw_verbose)
2520 		printf("ipfw: pullup failed\n");
2521 	return (IP_FW_DENY);
2522 }
2523 
2524 /*
2525  * Set maximum number of tables that can be used in given VNET ipfw instance.
2526  */
2527 #ifdef SYSCTL_NODE
2528 static int
2529 sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS)
2530 {
2531 	int error;
2532 	unsigned int ntables;
2533 
2534 	ntables = V_fw_tables_max;
2535 
2536 	error = sysctl_handle_int(oidp, &ntables, 0, req);
2537 	/* Read operation or some error */
2538 	if ((error != 0) || (req->newptr == NULL))
2539 		return (error);
2540 
2541 	return (ipfw_resize_tables(&V_layer3_chain, ntables));
2542 }
2543 #endif
2544 /*
2545  * Module and VNET glue
2546  */
2547 
2548 /*
2549  * Stuff that must be initialised only on boot or module load
2550  */
2551 static int
2552 ipfw_init(void)
2553 {
2554 	int error = 0;
2555 
2556 	/*
2557  	 * Only print out this stuff the first time around,
2558 	 * when called from the sysinit code.
2559 	 */
2560 	printf("ipfw2 "
2561 #ifdef INET6
2562 		"(+ipv6) "
2563 #endif
2564 		"initialized, divert %s, nat %s, "
2565 		"default to %s, logging ",
2566 #ifdef IPDIVERT
2567 		"enabled",
2568 #else
2569 		"loadable",
2570 #endif
2571 #ifdef IPFIREWALL_NAT
2572 		"enabled",
2573 #else
2574 		"loadable",
2575 #endif
2576 		default_to_accept ? "accept" : "deny");
2577 
2578 	/*
2579 	 * Note: V_xxx variables can be accessed here but the vnet specific
2580 	 * initializer may not have been called yet for the VIMAGE case.
2581 	 * Tuneables will have been processed. We will print out values for
2582 	 * the default vnet.
2583 	 * XXX This should all be rationalized AFTER 8.0
2584 	 */
2585 	if (V_fw_verbose == 0)
2586 		printf("disabled\n");
2587 	else if (V_verbose_limit == 0)
2588 		printf("unlimited\n");
2589 	else
2590 		printf("limited to %d packets/entry by default\n",
2591 		    V_verbose_limit);
2592 
2593 	/* Check user-supplied table count for validness */
2594 	if (default_fw_tables > IPFW_TABLES_MAX)
2595 	  default_fw_tables = IPFW_TABLES_MAX;
2596 
2597 	ipfw_log_bpf(1); /* init */
2598 	return (error);
2599 }
2600 
2601 /*
2602  * Called for the removal of the last instance only on module unload.
2603  */
2604 static void
2605 ipfw_destroy(void)
2606 {
2607 
2608 	ipfw_log_bpf(0); /* uninit */
2609 	printf("IP firewall unloaded\n");
2610 }
2611 
2612 /*
2613  * Stuff that must be initialized for every instance
2614  * (including the first of course).
2615  */
2616 static int
2617 vnet_ipfw_init(const void *unused)
2618 {
2619 	int error;
2620 	struct ip_fw *rule = NULL;
2621 	struct ip_fw_chain *chain;
2622 
2623 	chain = &V_layer3_chain;
2624 
2625 	/* First set up some values that are compile time options */
2626 	V_autoinc_step = 100;	/* bounded to 1..1000 in add_rule() */
2627 	V_fw_deny_unknown_exthdrs = 1;
2628 #ifdef IPFIREWALL_VERBOSE
2629 	V_fw_verbose = 1;
2630 #endif
2631 #ifdef IPFIREWALL_VERBOSE_LIMIT
2632 	V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
2633 #endif
2634 #ifdef IPFIREWALL_NAT
2635 	LIST_INIT(&chain->nat);
2636 #endif
2637 
2638 	/* insert the default rule and create the initial map */
2639 	chain->n_rules = 1;
2640 	chain->static_len = sizeof(struct ip_fw);
2641 	chain->map = malloc(sizeof(struct ip_fw *), M_IPFW, M_WAITOK | M_ZERO);
2642 	if (chain->map)
2643 		rule = malloc(chain->static_len, M_IPFW, M_WAITOK | M_ZERO);
2644 
2645 	/* Set initial number of tables */
2646 	V_fw_tables_max = default_fw_tables;
2647 	error = ipfw_init_tables(chain);
2648 	if (error) {
2649 		printf("ipfw2: setting up tables failed\n");
2650 		free(chain->map, M_IPFW);
2651 		free(rule, M_IPFW);
2652 		return (ENOSPC);
2653 	}
2654 
2655 	/* fill and insert the default rule */
2656 	rule->act_ofs = 0;
2657 	rule->rulenum = IPFW_DEFAULT_RULE;
2658 	rule->cmd_len = 1;
2659 	rule->set = RESVD_SET;
2660 	rule->cmd[0].len = 1;
2661 	rule->cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY;
2662 	chain->rules = chain->default_rule = chain->map[0] = rule;
2663 	chain->id = rule->id = 1;
2664 
2665 	IPFW_LOCK_INIT(chain);
2666 	ipfw_dyn_init(chain);
2667 
2668 	/* First set up some values that are compile time options */
2669 	V_ipfw_vnet_ready = 1;		/* Open for business */
2670 
2671 	/*
2672 	 * Hook the sockopt handler and pfil hooks for ipv4 and ipv6.
2673 	 * Even if the latter two fail we still keep the module alive
2674 	 * because the sockopt and layer2 paths are still useful.
2675 	 * ipfw[6]_hook return 0 on success, ENOENT on failure,
2676 	 * so we can ignore the exact return value and just set a flag.
2677 	 *
2678 	 * Note that V_fw[6]_enable are manipulated by a SYSCTL_PROC so
2679 	 * changes in the underlying (per-vnet) variables trigger
2680 	 * immediate hook()/unhook() calls.
2681 	 * In layer2 we have the same behaviour, except that V_ether_ipfw
2682 	 * is checked on each packet because there are no pfil hooks.
2683 	 */
2684 	V_ip_fw_ctl_ptr = ipfw_ctl;
2685 	error = ipfw_attach_hooks(1);
2686 	return (error);
2687 }
2688 
2689 /*
2690  * Called for the removal of each instance.
2691  */
2692 static int
2693 vnet_ipfw_uninit(const void *unused)
2694 {
2695 	struct ip_fw *reap, *rule;
2696 	struct ip_fw_chain *chain = &V_layer3_chain;
2697 	int i;
2698 
2699 	V_ipfw_vnet_ready = 0; /* tell new callers to go away */
2700 	/*
2701 	 * disconnect from ipv4, ipv6, layer2 and sockopt.
2702 	 * Then grab, release and grab again the WLOCK so we make
2703 	 * sure the update is propagated and nobody will be in.
2704 	 */
2705 	(void)ipfw_attach_hooks(0 /* detach */);
2706 	V_ip_fw_ctl_ptr = NULL;
2707 	IPFW_UH_WLOCK(chain);
2708 	IPFW_UH_WUNLOCK(chain);
2709 	IPFW_UH_WLOCK(chain);
2710 
2711 	IPFW_WLOCK(chain);
2712 	ipfw_dyn_uninit(0);	/* run the callout_drain */
2713 	IPFW_WUNLOCK(chain);
2714 
2715 	ipfw_destroy_tables(chain);
2716 	reap = NULL;
2717 	IPFW_WLOCK(chain);
2718 	for (i = 0; i < chain->n_rules; i++) {
2719 		rule = chain->map[i];
2720 		rule->x_next = reap;
2721 		reap = rule;
2722 	}
2723 	if (chain->map)
2724 		free(chain->map, M_IPFW);
2725 	IPFW_WUNLOCK(chain);
2726 	IPFW_UH_WUNLOCK(chain);
2727 	if (reap != NULL)
2728 		ipfw_reap_rules(reap);
2729 	IPFW_LOCK_DESTROY(chain);
2730 	ipfw_dyn_uninit(1);	/* free the remaining parts */
2731 	return 0;
2732 }
2733 
2734 /*
2735  * Module event handler.
2736  * In general we have the choice of handling most of these events by the
2737  * event handler or by the (VNET_)SYS(UN)INIT handlers. I have chosen to
2738  * use the SYSINIT handlers as they are more capable of expressing the
2739  * flow of control during module and vnet operations, so this is just
2740  * a skeleton. Note there is no SYSINIT equivalent of the module
2741  * SHUTDOWN handler, but we don't have anything to do in that case anyhow.
2742  */
2743 static int
2744 ipfw_modevent(module_t mod, int type, void *unused)
2745 {
2746 	int err = 0;
2747 
2748 	switch (type) {
2749 	case MOD_LOAD:
2750 		/* Called once at module load or
2751 	 	 * system boot if compiled in. */
2752 		break;
2753 	case MOD_QUIESCE:
2754 		/* Called before unload. May veto unloading. */
2755 		break;
2756 	case MOD_UNLOAD:
2757 		/* Called during unload. */
2758 		break;
2759 	case MOD_SHUTDOWN:
2760 		/* Called during system shutdown. */
2761 		break;
2762 	default:
2763 		err = EOPNOTSUPP;
2764 		break;
2765 	}
2766 	return err;
2767 }
2768 
2769 static moduledata_t ipfwmod = {
2770 	"ipfw",
2771 	ipfw_modevent,
2772 	0
2773 };
2774 
2775 /* Define startup order. */
2776 #define	IPFW_SI_SUB_FIREWALL	SI_SUB_PROTO_IFATTACHDOMAIN
2777 #define	IPFW_MODEVENT_ORDER	(SI_ORDER_ANY - 255) /* On boot slot in here. */
2778 #define	IPFW_MODULE_ORDER	(IPFW_MODEVENT_ORDER + 1) /* A little later. */
2779 #define	IPFW_VNET_ORDER		(IPFW_MODEVENT_ORDER + 2) /* Later still. */
2780 
2781 DECLARE_MODULE(ipfw, ipfwmod, IPFW_SI_SUB_FIREWALL, IPFW_MODEVENT_ORDER);
2782 MODULE_VERSION(ipfw, 2);
2783 /* should declare some dependencies here */
2784 
2785 /*
2786  * Starting up. Done in order after ipfwmod() has been called.
2787  * VNET_SYSINIT is also called for each existing vnet and each new vnet.
2788  */
2789 SYSINIT(ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
2790 	    ipfw_init, NULL);
2791 VNET_SYSINIT(vnet_ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
2792 	    vnet_ipfw_init, NULL);
2793 
2794 /*
2795  * Closing up shop. These are done in REVERSE ORDER, but still
2796  * after ipfwmod() has been called. Not called on reboot.
2797  * VNET_SYSUNINIT is also called for each exiting vnet as it exits.
2798  * or when the module is unloaded.
2799  */
2800 SYSUNINIT(ipfw_destroy, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
2801 	    ipfw_destroy, NULL);
2802 VNET_SYSUNINIT(vnet_ipfw_uninit, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
2803 	    vnet_ipfw_uninit, NULL);
2804 /* end of file */
2805