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