xref: /freebsd/sys/netpfil/ipfw/ip_fw2.c (revision 2b15cb3d0922bd70ea592f0da9b4a5b167f4d53f)
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 					} else
1536 #endif /* !USERSPACE */
1537 					    break;
1538 				    }
1539 				    match = ipfw_lookup_table(chain,
1540 					cmd->arg1, key, &v);
1541 				    if (!match)
1542 					break;
1543 				    if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
1544 					match =
1545 					    ((ipfw_insn_u32 *)cmd)->d[0] == v;
1546 				    else
1547 					tablearg = v;
1548 				} else if (is_ipv6) {
1549 					uint32_t v = 0;
1550 					void *pkey = (cmd->opcode == O_IP_DST_LOOKUP) ?
1551 						&args->f_id.dst_ip6: &args->f_id.src_ip6;
1552 					match = ipfw_lookup_table_extended(chain,
1553 							cmd->arg1,
1554 							sizeof(struct in6_addr),
1555 							pkey, &v);
1556 					if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
1557 						match = ((ipfw_insn_u32 *)cmd)->d[0] == v;
1558 					if (match)
1559 						tablearg = v;
1560 				}
1561 				break;
1562 
1563 			case O_IP_FLOW_LOOKUP:
1564 				{
1565 					uint32_t v = 0;
1566 					match = ipfw_lookup_table_extended(chain,
1567 					    cmd->arg1, 0, &args->f_id, &v);
1568 					if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
1569 						match = ((ipfw_insn_u32 *)cmd)->d[0] == v;
1570 					if (match)
1571 						tablearg = v;
1572 				}
1573 				break;
1574 			case O_IP_SRC_MASK:
1575 			case O_IP_DST_MASK:
1576 				if (is_ipv4) {
1577 				    uint32_t a =
1578 					(cmd->opcode == O_IP_DST_MASK) ?
1579 					    dst_ip.s_addr : src_ip.s_addr;
1580 				    uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
1581 				    int i = cmdlen-1;
1582 
1583 				    for (; !match && i>0; i-= 2, p+= 2)
1584 					match = (p[0] == (a & p[1]));
1585 				}
1586 				break;
1587 
1588 			case O_IP_SRC_ME:
1589 				if (is_ipv4) {
1590 					struct ifnet *tif;
1591 
1592 					INADDR_TO_IFP(src_ip, tif);
1593 					match = (tif != NULL);
1594 					break;
1595 				}
1596 #ifdef INET6
1597 				/* FALLTHROUGH */
1598 			case O_IP6_SRC_ME:
1599 				match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
1600 #endif
1601 				break;
1602 
1603 			case O_IP_DST_SET:
1604 			case O_IP_SRC_SET:
1605 				if (is_ipv4) {
1606 					u_int32_t *d = (u_int32_t *)(cmd+1);
1607 					u_int32_t addr =
1608 					    cmd->opcode == O_IP_DST_SET ?
1609 						args->f_id.dst_ip :
1610 						args->f_id.src_ip;
1611 
1612 					    if (addr < d[0])
1613 						    break;
1614 					    addr -= d[0]; /* subtract base */
1615 					    match = (addr < cmd->arg1) &&
1616 						( d[ 1 + (addr>>5)] &
1617 						  (1<<(addr & 0x1f)) );
1618 				}
1619 				break;
1620 
1621 			case O_IP_DST:
1622 				match = is_ipv4 &&
1623 				    (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1624 				    dst_ip.s_addr);
1625 				break;
1626 
1627 			case O_IP_DST_ME:
1628 				if (is_ipv4) {
1629 					struct ifnet *tif;
1630 
1631 					INADDR_TO_IFP(dst_ip, tif);
1632 					match = (tif != NULL);
1633 					break;
1634 				}
1635 #ifdef INET6
1636 				/* FALLTHROUGH */
1637 			case O_IP6_DST_ME:
1638 				match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
1639 #endif
1640 				break;
1641 
1642 
1643 			case O_IP_SRCPORT:
1644 			case O_IP_DSTPORT:
1645 				/*
1646 				 * offset == 0 && proto != 0 is enough
1647 				 * to guarantee that we have a
1648 				 * packet with port info.
1649 				 */
1650 				if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
1651 				    && offset == 0) {
1652 					u_int16_t x =
1653 					    (cmd->opcode == O_IP_SRCPORT) ?
1654 						src_port : dst_port ;
1655 					u_int16_t *p =
1656 					    ((ipfw_insn_u16 *)cmd)->ports;
1657 					int i;
1658 
1659 					for (i = cmdlen - 1; !match && i>0;
1660 					    i--, p += 2)
1661 						match = (x>=p[0] && x<=p[1]);
1662 				}
1663 				break;
1664 
1665 			case O_ICMPTYPE:
1666 				match = (offset == 0 && proto==IPPROTO_ICMP &&
1667 				    icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
1668 				break;
1669 
1670 #ifdef INET6
1671 			case O_ICMP6TYPE:
1672 				match = is_ipv6 && offset == 0 &&
1673 				    proto==IPPROTO_ICMPV6 &&
1674 				    icmp6type_match(
1675 					ICMP6(ulp)->icmp6_type,
1676 					(ipfw_insn_u32 *)cmd);
1677 				break;
1678 #endif /* INET6 */
1679 
1680 			case O_IPOPT:
1681 				match = (is_ipv4 &&
1682 				    ipopts_match(ip, cmd) );
1683 				break;
1684 
1685 			case O_IPVER:
1686 				match = (is_ipv4 &&
1687 				    cmd->arg1 == ip->ip_v);
1688 				break;
1689 
1690 			case O_IPID:
1691 			case O_IPLEN:
1692 			case O_IPTTL:
1693 				if (is_ipv4) {	/* only for IP packets */
1694 				    uint16_t x;
1695 				    uint16_t *p;
1696 				    int i;
1697 
1698 				    if (cmd->opcode == O_IPLEN)
1699 					x = iplen;
1700 				    else if (cmd->opcode == O_IPTTL)
1701 					x = ip->ip_ttl;
1702 				    else /* must be IPID */
1703 					x = ntohs(ip->ip_id);
1704 				    if (cmdlen == 1) {
1705 					match = (cmd->arg1 == x);
1706 					break;
1707 				    }
1708 				    /* otherwise we have ranges */
1709 				    p = ((ipfw_insn_u16 *)cmd)->ports;
1710 				    i = cmdlen - 1;
1711 				    for (; !match && i>0; i--, p += 2)
1712 					match = (x >= p[0] && x <= p[1]);
1713 				}
1714 				break;
1715 
1716 			case O_IPPRECEDENCE:
1717 				match = (is_ipv4 &&
1718 				    (cmd->arg1 == (ip->ip_tos & 0xe0)) );
1719 				break;
1720 
1721 			case O_IPTOS:
1722 				match = (is_ipv4 &&
1723 				    flags_match(cmd, ip->ip_tos));
1724 				break;
1725 
1726 			case O_DSCP:
1727 			    {
1728 				uint32_t *p;
1729 				uint16_t x;
1730 
1731 				p = ((ipfw_insn_u32 *)cmd)->d;
1732 
1733 				if (is_ipv4)
1734 					x = ip->ip_tos >> 2;
1735 				else if (is_ipv6) {
1736 					uint8_t *v;
1737 					v = &((struct ip6_hdr *)ip)->ip6_vfc;
1738 					x = (*v & 0x0F) << 2;
1739 					v++;
1740 					x |= *v >> 6;
1741 				} else
1742 					break;
1743 
1744 				/* DSCP bitmask is stored as low_u32 high_u32 */
1745 				if (x > 32)
1746 					match = *(p + 1) & (1 << (x - 32));
1747 				else
1748 					match = *p & (1 << x);
1749 			    }
1750 				break;
1751 
1752 			case O_TCPDATALEN:
1753 				if (proto == IPPROTO_TCP && offset == 0) {
1754 				    struct tcphdr *tcp;
1755 				    uint16_t x;
1756 				    uint16_t *p;
1757 				    int i;
1758 
1759 				    tcp = TCP(ulp);
1760 				    x = iplen -
1761 					((ip->ip_hl + tcp->th_off) << 2);
1762 				    if (cmdlen == 1) {
1763 					match = (cmd->arg1 == x);
1764 					break;
1765 				    }
1766 				    /* otherwise we have ranges */
1767 				    p = ((ipfw_insn_u16 *)cmd)->ports;
1768 				    i = cmdlen - 1;
1769 				    for (; !match && i>0; i--, p += 2)
1770 					match = (x >= p[0] && x <= p[1]);
1771 				}
1772 				break;
1773 
1774 			case O_TCPFLAGS:
1775 				match = (proto == IPPROTO_TCP && offset == 0 &&
1776 				    flags_match(cmd, TCP(ulp)->th_flags));
1777 				break;
1778 
1779 			case O_TCPOPTS:
1780 				if (proto == IPPROTO_TCP && offset == 0 && ulp){
1781 					PULLUP_LEN(hlen, ulp,
1782 					    (TCP(ulp)->th_off << 2));
1783 					match = tcpopts_match(TCP(ulp), cmd);
1784 				}
1785 				break;
1786 
1787 			case O_TCPSEQ:
1788 				match = (proto == IPPROTO_TCP && offset == 0 &&
1789 				    ((ipfw_insn_u32 *)cmd)->d[0] ==
1790 					TCP(ulp)->th_seq);
1791 				break;
1792 
1793 			case O_TCPACK:
1794 				match = (proto == IPPROTO_TCP && offset == 0 &&
1795 				    ((ipfw_insn_u32 *)cmd)->d[0] ==
1796 					TCP(ulp)->th_ack);
1797 				break;
1798 
1799 			case O_TCPWIN:
1800 				if (proto == IPPROTO_TCP && offset == 0) {
1801 				    uint16_t x;
1802 				    uint16_t *p;
1803 				    int i;
1804 
1805 				    x = ntohs(TCP(ulp)->th_win);
1806 				    if (cmdlen == 1) {
1807 					match = (cmd->arg1 == x);
1808 					break;
1809 				    }
1810 				    /* Otherwise we have ranges. */
1811 				    p = ((ipfw_insn_u16 *)cmd)->ports;
1812 				    i = cmdlen - 1;
1813 				    for (; !match && i > 0; i--, p += 2)
1814 					match = (x >= p[0] && x <= p[1]);
1815 				}
1816 				break;
1817 
1818 			case O_ESTAB:
1819 				/* reject packets which have SYN only */
1820 				/* XXX should i also check for TH_ACK ? */
1821 				match = (proto == IPPROTO_TCP && offset == 0 &&
1822 				    (TCP(ulp)->th_flags &
1823 				     (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
1824 				break;
1825 
1826 			case O_ALTQ: {
1827 				struct pf_mtag *at;
1828 				struct m_tag *mtag;
1829 				ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
1830 
1831 				/*
1832 				 * ALTQ uses mbuf tags from another
1833 				 * packet filtering system - pf(4).
1834 				 * We allocate a tag in its format
1835 				 * and fill it in, pretending to be pf(4).
1836 				 */
1837 				match = 1;
1838 				at = pf_find_mtag(m);
1839 				if (at != NULL && at->qid != 0)
1840 					break;
1841 				mtag = m_tag_get(PACKET_TAG_PF,
1842 				    sizeof(struct pf_mtag), M_NOWAIT | M_ZERO);
1843 				if (mtag == NULL) {
1844 					/*
1845 					 * Let the packet fall back to the
1846 					 * default ALTQ.
1847 					 */
1848 					break;
1849 				}
1850 				m_tag_prepend(m, mtag);
1851 				at = (struct pf_mtag *)(mtag + 1);
1852 				at->qid = altq->qid;
1853 				at->hdr = ip;
1854 				break;
1855 			}
1856 
1857 			case O_LOG:
1858 				ipfw_log(chain, f, hlen, args, m,
1859 				    oif, offset | ip6f_mf, tablearg, ip);
1860 				match = 1;
1861 				break;
1862 
1863 			case O_PROB:
1864 				match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
1865 				break;
1866 
1867 			case O_VERREVPATH:
1868 				/* Outgoing packets automatically pass/match */
1869 				match = ((oif != NULL) ||
1870 				    (m->m_pkthdr.rcvif == NULL) ||
1871 				    (
1872 #ifdef INET6
1873 				    is_ipv6 ?
1874 					verify_path6(&(args->f_id.src_ip6),
1875 					    m->m_pkthdr.rcvif, args->f_id.fib) :
1876 #endif
1877 				    verify_path(src_ip, m->m_pkthdr.rcvif,
1878 				        args->f_id.fib)));
1879 				break;
1880 
1881 			case O_VERSRCREACH:
1882 				/* Outgoing packets automatically pass/match */
1883 				match = (hlen > 0 && ((oif != NULL) ||
1884 #ifdef INET6
1885 				    is_ipv6 ?
1886 				        verify_path6(&(args->f_id.src_ip6),
1887 				            NULL, args->f_id.fib) :
1888 #endif
1889 				    verify_path(src_ip, NULL, args->f_id.fib)));
1890 				break;
1891 
1892 			case O_ANTISPOOF:
1893 				/* Outgoing packets automatically pass/match */
1894 				if (oif == NULL && hlen > 0 &&
1895 				    (  (is_ipv4 && in_localaddr(src_ip))
1896 #ifdef INET6
1897 				    || (is_ipv6 &&
1898 				        in6_localaddr(&(args->f_id.src_ip6)))
1899 #endif
1900 				    ))
1901 					match =
1902 #ifdef INET6
1903 					    is_ipv6 ? verify_path6(
1904 					        &(args->f_id.src_ip6),
1905 					        m->m_pkthdr.rcvif,
1906 						args->f_id.fib) :
1907 #endif
1908 					    verify_path(src_ip,
1909 					    	m->m_pkthdr.rcvif,
1910 					        args->f_id.fib);
1911 				else
1912 					match = 1;
1913 				break;
1914 
1915 			case O_IPSEC:
1916 #ifdef IPSEC
1917 				match = (m_tag_find(m,
1918 				    PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
1919 #endif
1920 				/* otherwise no match */
1921 				break;
1922 
1923 #ifdef INET6
1924 			case O_IP6_SRC:
1925 				match = is_ipv6 &&
1926 				    IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
1927 				    &((ipfw_insn_ip6 *)cmd)->addr6);
1928 				break;
1929 
1930 			case O_IP6_DST:
1931 				match = is_ipv6 &&
1932 				IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
1933 				    &((ipfw_insn_ip6 *)cmd)->addr6);
1934 				break;
1935 			case O_IP6_SRC_MASK:
1936 			case O_IP6_DST_MASK:
1937 				if (is_ipv6) {
1938 					int i = cmdlen - 1;
1939 					struct in6_addr p;
1940 					struct in6_addr *d =
1941 					    &((ipfw_insn_ip6 *)cmd)->addr6;
1942 
1943 					for (; !match && i > 0; d += 2,
1944 					    i -= F_INSN_SIZE(struct in6_addr)
1945 					    * 2) {
1946 						p = (cmd->opcode ==
1947 						    O_IP6_SRC_MASK) ?
1948 						    args->f_id.src_ip6:
1949 						    args->f_id.dst_ip6;
1950 						APPLY_MASK(&p, &d[1]);
1951 						match =
1952 						    IN6_ARE_ADDR_EQUAL(&d[0],
1953 						    &p);
1954 					}
1955 				}
1956 				break;
1957 
1958 			case O_FLOW6ID:
1959 				match = is_ipv6 &&
1960 				    flow6id_match(args->f_id.flow_id6,
1961 				    (ipfw_insn_u32 *) cmd);
1962 				break;
1963 
1964 			case O_EXT_HDR:
1965 				match = is_ipv6 &&
1966 				    (ext_hd & ((ipfw_insn *) cmd)->arg1);
1967 				break;
1968 
1969 			case O_IP6:
1970 				match = is_ipv6;
1971 				break;
1972 #endif
1973 
1974 			case O_IP4:
1975 				match = is_ipv4;
1976 				break;
1977 
1978 			case O_TAG: {
1979 				struct m_tag *mtag;
1980 				uint32_t tag = TARG(cmd->arg1, tag);
1981 
1982 				/* Packet is already tagged with this tag? */
1983 				mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
1984 
1985 				/* We have `untag' action when F_NOT flag is
1986 				 * present. And we must remove this mtag from
1987 				 * mbuf and reset `match' to zero (`match' will
1988 				 * be inversed later).
1989 				 * Otherwise we should allocate new mtag and
1990 				 * push it into mbuf.
1991 				 */
1992 				if (cmd->len & F_NOT) { /* `untag' action */
1993 					if (mtag != NULL)
1994 						m_tag_delete(m, mtag);
1995 					match = 0;
1996 				} else {
1997 					if (mtag == NULL) {
1998 						mtag = m_tag_alloc( MTAG_IPFW,
1999 						    tag, 0, M_NOWAIT);
2000 						if (mtag != NULL)
2001 							m_tag_prepend(m, mtag);
2002 					}
2003 					match = 1;
2004 				}
2005 				break;
2006 			}
2007 
2008 			case O_FIB: /* try match the specified fib */
2009 				if (args->f_id.fib == cmd->arg1)
2010 					match = 1;
2011 				break;
2012 
2013 			case O_SOCKARG:	{
2014 #ifndef USERSPACE	/* not supported in userspace */
2015 				struct inpcb *inp = args->inp;
2016 				struct inpcbinfo *pi;
2017 
2018 				if (is_ipv6) /* XXX can we remove this ? */
2019 					break;
2020 
2021 				if (proto == IPPROTO_TCP)
2022 					pi = &V_tcbinfo;
2023 				else if (proto == IPPROTO_UDP)
2024 					pi = &V_udbinfo;
2025 				else
2026 					break;
2027 
2028 				/*
2029 				 * XXXRW: so_user_cookie should almost
2030 				 * certainly be inp_user_cookie?
2031 				 */
2032 
2033 				/* For incomming packet, lookup up the
2034 				inpcb using the src/dest ip/port tuple */
2035 				if (inp == NULL) {
2036 					inp = in_pcblookup(pi,
2037 						src_ip, htons(src_port),
2038 						dst_ip, htons(dst_port),
2039 						INPLOOKUP_RLOCKPCB, NULL);
2040 					if (inp != NULL) {
2041 						tablearg =
2042 						    inp->inp_socket->so_user_cookie;
2043 						if (tablearg)
2044 							match = 1;
2045 						INP_RUNLOCK(inp);
2046 					}
2047 				} else {
2048 					if (inp->inp_socket) {
2049 						tablearg =
2050 						    inp->inp_socket->so_user_cookie;
2051 						if (tablearg)
2052 							match = 1;
2053 					}
2054 				}
2055 #endif /* !USERSPACE */
2056 				break;
2057 			}
2058 
2059 			case O_TAGGED: {
2060 				struct m_tag *mtag;
2061 				uint32_t tag = TARG(cmd->arg1, tag);
2062 
2063 				if (cmdlen == 1) {
2064 					match = m_tag_locate(m, MTAG_IPFW,
2065 					    tag, NULL) != NULL;
2066 					break;
2067 				}
2068 
2069 				/* we have ranges */
2070 				for (mtag = m_tag_first(m);
2071 				    mtag != NULL && !match;
2072 				    mtag = m_tag_next(m, mtag)) {
2073 					uint16_t *p;
2074 					int i;
2075 
2076 					if (mtag->m_tag_cookie != MTAG_IPFW)
2077 						continue;
2078 
2079 					p = ((ipfw_insn_u16 *)cmd)->ports;
2080 					i = cmdlen - 1;
2081 					for(; !match && i > 0; i--, p += 2)
2082 						match =
2083 						    mtag->m_tag_id >= p[0] &&
2084 						    mtag->m_tag_id <= p[1];
2085 				}
2086 				break;
2087 			}
2088 
2089 			/*
2090 			 * The second set of opcodes represents 'actions',
2091 			 * i.e. the terminal part of a rule once the packet
2092 			 * matches all previous patterns.
2093 			 * Typically there is only one action for each rule,
2094 			 * and the opcode is stored at the end of the rule
2095 			 * (but there are exceptions -- see below).
2096 			 *
2097 			 * In general, here we set retval and terminate the
2098 			 * outer loop (would be a 'break 3' in some language,
2099 			 * but we need to set l=0, done=1)
2100 			 *
2101 			 * Exceptions:
2102 			 * O_COUNT and O_SKIPTO actions:
2103 			 *   instead of terminating, we jump to the next rule
2104 			 *   (setting l=0), or to the SKIPTO target (setting
2105 			 *   f/f_len, cmd and l as needed), respectively.
2106 			 *
2107 			 * O_TAG, O_LOG and O_ALTQ action parameters:
2108 			 *   perform some action and set match = 1;
2109 			 *
2110 			 * O_LIMIT and O_KEEP_STATE: these opcodes are
2111 			 *   not real 'actions', and are stored right
2112 			 *   before the 'action' part of the rule.
2113 			 *   These opcodes try to install an entry in the
2114 			 *   state tables; if successful, we continue with
2115 			 *   the next opcode (match=1; break;), otherwise
2116 			 *   the packet must be dropped (set retval,
2117 			 *   break loops with l=0, done=1)
2118 			 *
2119 			 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2120 			 *   cause a lookup of the state table, and a jump
2121 			 *   to the 'action' part of the parent rule
2122 			 *   if an entry is found, or
2123 			 *   (CHECK_STATE only) a jump to the next rule if
2124 			 *   the entry is not found.
2125 			 *   The result of the lookup is cached so that
2126 			 *   further instances of these opcodes become NOPs.
2127 			 *   The jump to the next rule is done by setting
2128 			 *   l=0, cmdlen=0.
2129 			 */
2130 			case O_LIMIT:
2131 			case O_KEEP_STATE:
2132 				if (ipfw_install_state(chain, f,
2133 				    (ipfw_insn_limit *)cmd, args, tablearg)) {
2134 					/* error or limit violation */
2135 					retval = IP_FW_DENY;
2136 					l = 0;	/* exit inner loop */
2137 					done = 1; /* exit outer loop */
2138 				}
2139 				match = 1;
2140 				break;
2141 
2142 			case O_PROBE_STATE:
2143 			case O_CHECK_STATE:
2144 				/*
2145 				 * dynamic rules are checked at the first
2146 				 * keep-state or check-state occurrence,
2147 				 * with the result being stored in dyn_dir.
2148 				 * The compiler introduces a PROBE_STATE
2149 				 * instruction for us when we have a
2150 				 * KEEP_STATE (because PROBE_STATE needs
2151 				 * to be run first).
2152 				 */
2153 				if (dyn_dir == MATCH_UNKNOWN &&
2154 				    (q = ipfw_lookup_dyn_rule(&args->f_id,
2155 				     &dyn_dir, proto == IPPROTO_TCP ?
2156 					TCP(ulp) : NULL))
2157 					!= NULL) {
2158 					/*
2159 					 * Found dynamic entry, update stats
2160 					 * and jump to the 'action' part of
2161 					 * the parent rule by setting
2162 					 * f, cmd, l and clearing cmdlen.
2163 					 */
2164 					IPFW_INC_DYN_COUNTER(q, pktlen);
2165 					/* XXX we would like to have f_pos
2166 					 * readily accessible in the dynamic
2167 				         * rule, instead of having to
2168 					 * lookup q->rule.
2169 					 */
2170 					f = q->rule;
2171 					f_pos = ipfw_find_rule(chain,
2172 						f->rulenum, f->id);
2173 					cmd = ACTION_PTR(f);
2174 					l = f->cmd_len - f->act_ofs;
2175 					ipfw_dyn_unlock(q);
2176 					cmdlen = 0;
2177 					match = 1;
2178 					break;
2179 				}
2180 				/*
2181 				 * Dynamic entry not found. If CHECK_STATE,
2182 				 * skip to next rule, if PROBE_STATE just
2183 				 * ignore and continue with next opcode.
2184 				 */
2185 				if (cmd->opcode == O_CHECK_STATE)
2186 					l = 0;	/* exit inner loop */
2187 				match = 1;
2188 				break;
2189 
2190 			case O_ACCEPT:
2191 				retval = 0;	/* accept */
2192 				l = 0;		/* exit inner loop */
2193 				done = 1;	/* exit outer loop */
2194 				break;
2195 
2196 			case O_PIPE:
2197 			case O_QUEUE:
2198 				set_match(args, f_pos, chain);
2199 				args->rule.info = TARG(cmd->arg1, pipe);
2200 				if (cmd->opcode == O_PIPE)
2201 					args->rule.info |= IPFW_IS_PIPE;
2202 				if (V_fw_one_pass)
2203 					args->rule.info |= IPFW_ONEPASS;
2204 				retval = IP_FW_DUMMYNET;
2205 				l = 0;          /* exit inner loop */
2206 				done = 1;       /* exit outer loop */
2207 				break;
2208 
2209 			case O_DIVERT:
2210 			case O_TEE:
2211 				if (args->eh) /* not on layer 2 */
2212 				    break;
2213 				/* otherwise this is terminal */
2214 				l = 0;		/* exit inner loop */
2215 				done = 1;	/* exit outer loop */
2216 				retval = (cmd->opcode == O_DIVERT) ?
2217 					IP_FW_DIVERT : IP_FW_TEE;
2218 				set_match(args, f_pos, chain);
2219 				args->rule.info = TARG(cmd->arg1, divert);
2220 				break;
2221 
2222 			case O_COUNT:
2223 				IPFW_INC_RULE_COUNTER(f, pktlen);
2224 				l = 0;		/* exit inner loop */
2225 				break;
2226 
2227 			case O_SKIPTO:
2228 			    IPFW_INC_RULE_COUNTER(f, pktlen);
2229 			    f_pos = JUMP(chain, f, cmd->arg1, tablearg, 0);
2230 			    /*
2231 			     * Skip disabled rules, and re-enter
2232 			     * the inner loop with the correct
2233 			     * f_pos, f, l and cmd.
2234 			     * Also clear cmdlen and skip_or
2235 			     */
2236 			    for (; f_pos < chain->n_rules - 1 &&
2237 				    (V_set_disable &
2238 				     (1 << chain->map[f_pos]->set));
2239 				    f_pos++)
2240 				;
2241 			    /* Re-enter the inner loop at the skipto rule. */
2242 			    f = chain->map[f_pos];
2243 			    l = f->cmd_len;
2244 			    cmd = f->cmd;
2245 			    match = 1;
2246 			    cmdlen = 0;
2247 			    skip_or = 0;
2248 			    continue;
2249 			    break;	/* not reached */
2250 
2251 			case O_CALLRETURN: {
2252 				/*
2253 				 * Implementation of `subroutine' call/return,
2254 				 * in the stack carried in an mbuf tag. This
2255 				 * is different from `skipto' in that any call
2256 				 * address is possible (`skipto' must prevent
2257 				 * backward jumps to avoid endless loops).
2258 				 * We have `return' action when F_NOT flag is
2259 				 * present. The `m_tag_id' field is used as
2260 				 * stack pointer.
2261 				 */
2262 				struct m_tag *mtag;
2263 				uint16_t jmpto, *stack;
2264 
2265 #define	IS_CALL		((cmd->len & F_NOT) == 0)
2266 #define	IS_RETURN	((cmd->len & F_NOT) != 0)
2267 				/*
2268 				 * Hand-rolled version of m_tag_locate() with
2269 				 * wildcard `type'.
2270 				 * If not already tagged, allocate new tag.
2271 				 */
2272 				mtag = m_tag_first(m);
2273 				while (mtag != NULL) {
2274 					if (mtag->m_tag_cookie ==
2275 					    MTAG_IPFW_CALL)
2276 						break;
2277 					mtag = m_tag_next(m, mtag);
2278 				}
2279 				if (mtag == NULL && IS_CALL) {
2280 					mtag = m_tag_alloc(MTAG_IPFW_CALL, 0,
2281 					    IPFW_CALLSTACK_SIZE *
2282 					    sizeof(uint16_t), M_NOWAIT);
2283 					if (mtag != NULL)
2284 						m_tag_prepend(m, mtag);
2285 				}
2286 
2287 				/*
2288 				 * On error both `call' and `return' just
2289 				 * continue with next rule.
2290 				 */
2291 				if (IS_RETURN && (mtag == NULL ||
2292 				    mtag->m_tag_id == 0)) {
2293 					l = 0;		/* exit inner loop */
2294 					break;
2295 				}
2296 				if (IS_CALL && (mtag == NULL ||
2297 				    mtag->m_tag_id >= IPFW_CALLSTACK_SIZE)) {
2298 					printf("ipfw: call stack error, "
2299 					    "go to next rule\n");
2300 					l = 0;		/* exit inner loop */
2301 					break;
2302 				}
2303 
2304 				IPFW_INC_RULE_COUNTER(f, pktlen);
2305 				stack = (uint16_t *)(mtag + 1);
2306 
2307 				/*
2308 				 * The `call' action may use cached f_pos
2309 				 * (in f->next_rule), whose version is written
2310 				 * in f->next_rule.
2311 				 * The `return' action, however, doesn't have
2312 				 * fixed jump address in cmd->arg1 and can't use
2313 				 * cache.
2314 				 */
2315 				if (IS_CALL) {
2316 					stack[mtag->m_tag_id] = f->rulenum;
2317 					mtag->m_tag_id++;
2318 			    		f_pos = JUMP(chain, f, cmd->arg1,
2319 					    tablearg, 1);
2320 				} else {	/* `return' action */
2321 					mtag->m_tag_id--;
2322 					jmpto = stack[mtag->m_tag_id] + 1;
2323 					f_pos = ipfw_find_rule(chain, jmpto, 0);
2324 				}
2325 
2326 				/*
2327 				 * Skip disabled rules, and re-enter
2328 				 * the inner loop with the correct
2329 				 * f_pos, f, l and cmd.
2330 				 * Also clear cmdlen and skip_or
2331 				 */
2332 				for (; f_pos < chain->n_rules - 1 &&
2333 				    (V_set_disable &
2334 				    (1 << chain->map[f_pos]->set)); f_pos++)
2335 					;
2336 				/* Re-enter the inner loop at the dest rule. */
2337 				f = chain->map[f_pos];
2338 				l = f->cmd_len;
2339 				cmd = f->cmd;
2340 				cmdlen = 0;
2341 				skip_or = 0;
2342 				continue;
2343 				break;	/* NOTREACHED */
2344 			}
2345 #undef IS_CALL
2346 #undef IS_RETURN
2347 
2348 			case O_REJECT:
2349 				/*
2350 				 * Drop the packet and send a reject notice
2351 				 * if the packet is not ICMP (or is an ICMP
2352 				 * query), and it is not multicast/broadcast.
2353 				 */
2354 				if (hlen > 0 && is_ipv4 && offset == 0 &&
2355 				    (proto != IPPROTO_ICMP ||
2356 				     is_icmp_query(ICMP(ulp))) &&
2357 				    !(m->m_flags & (M_BCAST|M_MCAST)) &&
2358 				    !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2359 					send_reject(args, cmd->arg1, iplen, ip);
2360 					m = args->m;
2361 				}
2362 				/* FALLTHROUGH */
2363 #ifdef INET6
2364 			case O_UNREACH6:
2365 				if (hlen > 0 && is_ipv6 &&
2366 				    ((offset & IP6F_OFF_MASK) == 0) &&
2367 				    (proto != IPPROTO_ICMPV6 ||
2368 				     (is_icmp6_query(icmp6_type) == 1)) &&
2369 				    !(m->m_flags & (M_BCAST|M_MCAST)) &&
2370 				    !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
2371 					send_reject6(
2372 					    args, cmd->arg1, hlen,
2373 					    (struct ip6_hdr *)ip);
2374 					m = args->m;
2375 				}
2376 				/* FALLTHROUGH */
2377 #endif
2378 			case O_DENY:
2379 				retval = IP_FW_DENY;
2380 				l = 0;		/* exit inner loop */
2381 				done = 1;	/* exit outer loop */
2382 				break;
2383 
2384 			case O_FORWARD_IP:
2385 				if (args->eh)	/* not valid on layer2 pkts */
2386 					break;
2387 				if (q == NULL || q->rule != f ||
2388 				    dyn_dir == MATCH_FORWARD) {
2389 				    struct sockaddr_in *sa;
2390 
2391 				    sa = &(((ipfw_insn_sa *)cmd)->sa);
2392 				    if (sa->sin_addr.s_addr == INADDR_ANY) {
2393 #ifdef INET6
2394 					/*
2395 					 * We use O_FORWARD_IP opcode for
2396 					 * fwd rule with tablearg, but tables
2397 					 * now support IPv6 addresses. And
2398 					 * when we are inspecting IPv6 packet,
2399 					 * we can use nh6 field from
2400 					 * table_value as next_hop6 address.
2401 					 */
2402 					if (is_ipv6) {
2403 						struct sockaddr_in6 *sa6;
2404 
2405 						sa6 = args->next_hop6 =
2406 						    &args->hopstore6;
2407 						sa6->sin6_family = AF_INET6;
2408 						sa6->sin6_len = sizeof(*sa6);
2409 						sa6->sin6_addr = TARG_VAL(
2410 						    chain, tablearg, nh6);
2411 						/*
2412 						 * Set sin6_scope_id only for
2413 						 * link-local unicast addresses.
2414 						 */
2415 						if (IN6_IS_ADDR_LINKLOCAL(
2416 						    &sa6->sin6_addr))
2417 							sa6->sin6_scope_id =
2418 							    TARG_VAL(chain,
2419 								tablearg,
2420 								zoneid);
2421 					} else
2422 #endif
2423 					{
2424 						sa = args->next_hop =
2425 						    &args->hopstore;
2426 						sa->sin_family = AF_INET;
2427 						sa->sin_len = sizeof(*sa);
2428 						sa->sin_addr.s_addr = htonl(
2429 						    TARG_VAL(chain, tablearg,
2430 						    nh4));
2431 					}
2432 				    } else {
2433 					args->next_hop = sa;
2434 				    }
2435 				}
2436 				retval = IP_FW_PASS;
2437 				l = 0;          /* exit inner loop */
2438 				done = 1;       /* exit outer loop */
2439 				break;
2440 
2441 #ifdef INET6
2442 			case O_FORWARD_IP6:
2443 				if (args->eh)	/* not valid on layer2 pkts */
2444 					break;
2445 				if (q == NULL || q->rule != f ||
2446 				    dyn_dir == MATCH_FORWARD) {
2447 					struct sockaddr_in6 *sin6;
2448 
2449 					sin6 = &(((ipfw_insn_sa6 *)cmd)->sa);
2450 					args->next_hop6 = sin6;
2451 				}
2452 				retval = IP_FW_PASS;
2453 				l = 0;		/* exit inner loop */
2454 				done = 1;	/* exit outer loop */
2455 				break;
2456 #endif
2457 
2458 			case O_NETGRAPH:
2459 			case O_NGTEE:
2460 				set_match(args, f_pos, chain);
2461 				args->rule.info = TARG(cmd->arg1, netgraph);
2462 				if (V_fw_one_pass)
2463 					args->rule.info |= IPFW_ONEPASS;
2464 				retval = (cmd->opcode == O_NETGRAPH) ?
2465 				    IP_FW_NETGRAPH : IP_FW_NGTEE;
2466 				l = 0;          /* exit inner loop */
2467 				done = 1;       /* exit outer loop */
2468 				break;
2469 
2470 			case O_SETFIB: {
2471 				uint32_t fib;
2472 
2473 				IPFW_INC_RULE_COUNTER(f, pktlen);
2474 				fib = TARG(cmd->arg1, fib) & 0x7FFFF;
2475 				if (fib >= rt_numfibs)
2476 					fib = 0;
2477 				M_SETFIB(m, fib);
2478 				args->f_id.fib = fib;
2479 				l = 0;		/* exit inner loop */
2480 				break;
2481 		        }
2482 
2483 			case O_SETDSCP: {
2484 				uint16_t code;
2485 
2486 				code = TARG(cmd->arg1, dscp) & 0x3F;
2487 				l = 0;		/* exit inner loop */
2488 				if (is_ipv4) {
2489 					uint16_t a;
2490 
2491 					a = ip->ip_tos;
2492 					ip->ip_tos = (code << 2) | (ip->ip_tos & 0x03);
2493 					a += ntohs(ip->ip_sum) - ip->ip_tos;
2494 					ip->ip_sum = htons(a);
2495 				} else if (is_ipv6) {
2496 					uint8_t *v;
2497 
2498 					v = &((struct ip6_hdr *)ip)->ip6_vfc;
2499 					*v = (*v & 0xF0) | (code >> 2);
2500 					v++;
2501 					*v = (*v & 0x3F) | ((code & 0x03) << 6);
2502 				} else
2503 					break;
2504 
2505 				IPFW_INC_RULE_COUNTER(f, pktlen);
2506 				break;
2507 			}
2508 
2509 			case O_NAT:
2510 				l = 0;          /* exit inner loop */
2511 				done = 1;       /* exit outer loop */
2512  				if (!IPFW_NAT_LOADED) {
2513 				    retval = IP_FW_DENY;
2514 				    break;
2515 				}
2516 
2517 				struct cfg_nat *t;
2518 				int nat_id;
2519 
2520 				set_match(args, f_pos, chain);
2521 				/* Check if this is 'global' nat rule */
2522 				if (cmd->arg1 == 0) {
2523 					retval = ipfw_nat_ptr(args, NULL, m);
2524 					break;
2525 				}
2526 				t = ((ipfw_insn_nat *)cmd)->nat;
2527 				if (t == NULL) {
2528 					nat_id = TARG(cmd->arg1, nat);
2529 					t = (*lookup_nat_ptr)(&chain->nat, nat_id);
2530 
2531 					if (t == NULL) {
2532 					    retval = IP_FW_DENY;
2533 					    break;
2534 					}
2535 					if (cmd->arg1 != IP_FW_TARG)
2536 					    ((ipfw_insn_nat *)cmd)->nat = t;
2537 				}
2538 				retval = ipfw_nat_ptr(args, t, m);
2539 				break;
2540 
2541 			case O_REASS: {
2542 				int ip_off;
2543 
2544 				IPFW_INC_RULE_COUNTER(f, pktlen);
2545 				l = 0;	/* in any case exit inner loop */
2546 				ip_off = ntohs(ip->ip_off);
2547 
2548 				/* if not fragmented, go to next rule */
2549 				if ((ip_off & (IP_MF | IP_OFFMASK)) == 0)
2550 				    break;
2551 
2552 				args->m = m = ip_reass(m);
2553 
2554 				/*
2555 				 * do IP header checksum fixup.
2556 				 */
2557 				if (m == NULL) { /* fragment got swallowed */
2558 				    retval = IP_FW_DENY;
2559 				} else { /* good, packet complete */
2560 				    int hlen;
2561 
2562 				    ip = mtod(m, struct ip *);
2563 				    hlen = ip->ip_hl << 2;
2564 				    ip->ip_sum = 0;
2565 				    if (hlen == sizeof(struct ip))
2566 					ip->ip_sum = in_cksum_hdr(ip);
2567 				    else
2568 					ip->ip_sum = in_cksum(m, hlen);
2569 				    retval = IP_FW_REASS;
2570 				    set_match(args, f_pos, chain);
2571 				}
2572 				done = 1;	/* exit outer loop */
2573 				break;
2574 			}
2575 
2576 			default:
2577 				panic("-- unknown opcode %d\n", cmd->opcode);
2578 			} /* end of switch() on opcodes */
2579 			/*
2580 			 * if we get here with l=0, then match is irrelevant.
2581 			 */
2582 
2583 			if (cmd->len & F_NOT)
2584 				match = !match;
2585 
2586 			if (match) {
2587 				if (cmd->len & F_OR)
2588 					skip_or = 1;
2589 			} else {
2590 				if (!(cmd->len & F_OR)) /* not an OR block, */
2591 					break;		/* try next rule    */
2592 			}
2593 
2594 		}	/* end of inner loop, scan opcodes */
2595 #undef PULLUP_LEN
2596 
2597 		if (done)
2598 			break;
2599 
2600 /* next_rule:; */	/* try next rule		*/
2601 
2602 	}		/* end of outer for, scan rules */
2603 
2604 	if (done) {
2605 		struct ip_fw *rule = chain->map[f_pos];
2606 		/* Update statistics */
2607 		IPFW_INC_RULE_COUNTER(rule, pktlen);
2608 	} else {
2609 		retval = IP_FW_DENY;
2610 		printf("ipfw: ouch!, skip past end of rules, denying packet\n");
2611 	}
2612 	IPFW_PF_RUNLOCK(chain);
2613 #ifdef __FreeBSD__
2614 	if (ucred_cache != NULL)
2615 		crfree(ucred_cache);
2616 #endif
2617 	return (retval);
2618 
2619 pullup_failed:
2620 	if (V_fw_verbose)
2621 		printf("ipfw: pullup failed\n");
2622 	return (IP_FW_DENY);
2623 }
2624 
2625 /*
2626  * Set maximum number of tables that can be used in given VNET ipfw instance.
2627  */
2628 #ifdef SYSCTL_NODE
2629 static int
2630 sysctl_ipfw_table_num(SYSCTL_HANDLER_ARGS)
2631 {
2632 	int error;
2633 	unsigned int ntables;
2634 
2635 	ntables = V_fw_tables_max;
2636 
2637 	error = sysctl_handle_int(oidp, &ntables, 0, req);
2638 	/* Read operation or some error */
2639 	if ((error != 0) || (req->newptr == NULL))
2640 		return (error);
2641 
2642 	return (ipfw_resize_tables(&V_layer3_chain, ntables));
2643 }
2644 
2645 /*
2646  * Switches table namespace between global and per-set.
2647  */
2648 static int
2649 sysctl_ipfw_tables_sets(SYSCTL_HANDLER_ARGS)
2650 {
2651 	int error;
2652 	unsigned int sets;
2653 
2654 	sets = V_fw_tables_sets;
2655 
2656 	error = sysctl_handle_int(oidp, &sets, 0, req);
2657 	/* Read operation or some error */
2658 	if ((error != 0) || (req->newptr == NULL))
2659 		return (error);
2660 
2661 	return (ipfw_switch_tables_namespace(&V_layer3_chain, sets));
2662 }
2663 #endif
2664 
2665 /*
2666  * Module and VNET glue
2667  */
2668 
2669 /*
2670  * Stuff that must be initialised only on boot or module load
2671  */
2672 static int
2673 ipfw_init(void)
2674 {
2675 	int error = 0;
2676 
2677 	/*
2678  	 * Only print out this stuff the first time around,
2679 	 * when called from the sysinit code.
2680 	 */
2681 	printf("ipfw2 "
2682 #ifdef INET6
2683 		"(+ipv6) "
2684 #endif
2685 		"initialized, divert %s, nat %s, "
2686 		"default to %s, logging ",
2687 #ifdef IPDIVERT
2688 		"enabled",
2689 #else
2690 		"loadable",
2691 #endif
2692 #ifdef IPFIREWALL_NAT
2693 		"enabled",
2694 #else
2695 		"loadable",
2696 #endif
2697 		default_to_accept ? "accept" : "deny");
2698 
2699 	/*
2700 	 * Note: V_xxx variables can be accessed here but the vnet specific
2701 	 * initializer may not have been called yet for the VIMAGE case.
2702 	 * Tuneables will have been processed. We will print out values for
2703 	 * the default vnet.
2704 	 * XXX This should all be rationalized AFTER 8.0
2705 	 */
2706 	if (V_fw_verbose == 0)
2707 		printf("disabled\n");
2708 	else if (V_verbose_limit == 0)
2709 		printf("unlimited\n");
2710 	else
2711 		printf("limited to %d packets/entry by default\n",
2712 		    V_verbose_limit);
2713 
2714 	/* Check user-supplied table count for validness */
2715 	if (default_fw_tables > IPFW_TABLES_MAX)
2716 	  default_fw_tables = IPFW_TABLES_MAX;
2717 
2718 	ipfw_init_sopt_handler();
2719 	ipfw_log_bpf(1); /* init */
2720 	ipfw_iface_init();
2721 	return (error);
2722 }
2723 
2724 /*
2725  * Called for the removal of the last instance only on module unload.
2726  */
2727 static void
2728 ipfw_destroy(void)
2729 {
2730 
2731 	ipfw_iface_destroy();
2732 	ipfw_log_bpf(0); /* uninit */
2733 	ipfw_destroy_sopt_handler();
2734 	printf("IP firewall unloaded\n");
2735 }
2736 
2737 /*
2738  * Stuff that must be initialized for every instance
2739  * (including the first of course).
2740  */
2741 static int
2742 vnet_ipfw_init(const void *unused)
2743 {
2744 	int error, first;
2745 	struct ip_fw *rule = NULL;
2746 	struct ip_fw_chain *chain;
2747 
2748 	chain = &V_layer3_chain;
2749 
2750 	first = IS_DEFAULT_VNET(curvnet) ? 1 : 0;
2751 
2752 	/* First set up some values that are compile time options */
2753 	V_autoinc_step = 100;	/* bounded to 1..1000 in add_rule() */
2754 	V_fw_deny_unknown_exthdrs = 1;
2755 #ifdef IPFIREWALL_VERBOSE
2756 	V_fw_verbose = 1;
2757 #endif
2758 #ifdef IPFIREWALL_VERBOSE_LIMIT
2759 	V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
2760 #endif
2761 #ifdef IPFIREWALL_NAT
2762 	LIST_INIT(&chain->nat);
2763 #endif
2764 
2765 	ipfw_init_counters();
2766 	/* insert the default rule and create the initial map */
2767 	chain->n_rules = 1;
2768 	chain->map = malloc(sizeof(struct ip_fw *), M_IPFW, M_WAITOK | M_ZERO);
2769 	rule = ipfw_alloc_rule(chain, sizeof(struct ip_fw));
2770 
2771 	/* Set initial number of tables */
2772 	V_fw_tables_max = default_fw_tables;
2773 	error = ipfw_init_tables(chain, first);
2774 	if (error) {
2775 		printf("ipfw2: setting up tables failed\n");
2776 		free(chain->map, M_IPFW);
2777 		free(rule, M_IPFW);
2778 		return (ENOSPC);
2779 	}
2780 
2781 	/* fill and insert the default rule */
2782 	rule->act_ofs = 0;
2783 	rule->rulenum = IPFW_DEFAULT_RULE;
2784 	rule->cmd_len = 1;
2785 	rule->set = RESVD_SET;
2786 	rule->cmd[0].len = 1;
2787 	rule->cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY;
2788 	chain->default_rule = chain->map[0] = rule;
2789 	chain->id = rule->id = 1;
2790 	/* Pre-calculate rules length for legacy dump format */
2791 	chain->static_len = sizeof(struct ip_fw_rule0);
2792 
2793 	IPFW_LOCK_INIT(chain);
2794 	ipfw_dyn_init(chain);
2795 #ifdef LINEAR_SKIPTO
2796 	ipfw_init_skipto_cache(chain);
2797 #endif
2798 
2799 	/* First set up some values that are compile time options */
2800 	V_ipfw_vnet_ready = 1;		/* Open for business */
2801 
2802 	/*
2803 	 * Hook the sockopt handler and pfil hooks for ipv4 and ipv6.
2804 	 * Even if the latter two fail we still keep the module alive
2805 	 * because the sockopt and layer2 paths are still useful.
2806 	 * ipfw[6]_hook return 0 on success, ENOENT on failure,
2807 	 * so we can ignore the exact return value and just set a flag.
2808 	 *
2809 	 * Note that V_fw[6]_enable are manipulated by a SYSCTL_PROC so
2810 	 * changes in the underlying (per-vnet) variables trigger
2811 	 * immediate hook()/unhook() calls.
2812 	 * In layer2 we have the same behaviour, except that V_ether_ipfw
2813 	 * is checked on each packet because there are no pfil hooks.
2814 	 */
2815 	V_ip_fw_ctl_ptr = ipfw_ctl3;
2816 	error = ipfw_attach_hooks(1);
2817 	return (error);
2818 }
2819 
2820 /*
2821  * Called for the removal of each instance.
2822  */
2823 static int
2824 vnet_ipfw_uninit(const void *unused)
2825 {
2826 	struct ip_fw *reap;
2827 	struct ip_fw_chain *chain = &V_layer3_chain;
2828 	int i, last;
2829 
2830 	V_ipfw_vnet_ready = 0; /* tell new callers to go away */
2831 	/*
2832 	 * disconnect from ipv4, ipv6, layer2 and sockopt.
2833 	 * Then grab, release and grab again the WLOCK so we make
2834 	 * sure the update is propagated and nobody will be in.
2835 	 */
2836 	(void)ipfw_attach_hooks(0 /* detach */);
2837 	V_ip_fw_ctl_ptr = NULL;
2838 
2839 	last = IS_DEFAULT_VNET(curvnet) ? 1 : 0;
2840 
2841 	IPFW_UH_WLOCK(chain);
2842 	IPFW_UH_WUNLOCK(chain);
2843 	IPFW_UH_WLOCK(chain);
2844 
2845 	IPFW_WLOCK(chain);
2846 	ipfw_dyn_uninit(0);	/* run the callout_drain */
2847 	IPFW_WUNLOCK(chain);
2848 
2849 	reap = NULL;
2850 	IPFW_WLOCK(chain);
2851 	for (i = 0; i < chain->n_rules; i++)
2852 		ipfw_reap_add(chain, &reap, chain->map[i]);
2853 	free(chain->map, M_IPFW);
2854 #ifdef LINEAR_SKIPTO
2855 	ipfw_destroy_skipto_cache(chain);
2856 #endif
2857 	IPFW_WUNLOCK(chain);
2858 	IPFW_UH_WUNLOCK(chain);
2859 	ipfw_destroy_tables(chain, last);
2860 	if (reap != NULL)
2861 		ipfw_reap_rules(reap);
2862 	vnet_ipfw_iface_destroy(chain);
2863 	IPFW_LOCK_DESTROY(chain);
2864 	ipfw_dyn_uninit(1);	/* free the remaining parts */
2865 	ipfw_destroy_counters();
2866 	return (0);
2867 }
2868 
2869 /*
2870  * Module event handler.
2871  * In general we have the choice of handling most of these events by the
2872  * event handler or by the (VNET_)SYS(UN)INIT handlers. I have chosen to
2873  * use the SYSINIT handlers as they are more capable of expressing the
2874  * flow of control during module and vnet operations, so this is just
2875  * a skeleton. Note there is no SYSINIT equivalent of the module
2876  * SHUTDOWN handler, but we don't have anything to do in that case anyhow.
2877  */
2878 static int
2879 ipfw_modevent(module_t mod, int type, void *unused)
2880 {
2881 	int err = 0;
2882 
2883 	switch (type) {
2884 	case MOD_LOAD:
2885 		/* Called once at module load or
2886 	 	 * system boot if compiled in. */
2887 		break;
2888 	case MOD_QUIESCE:
2889 		/* Called before unload. May veto unloading. */
2890 		break;
2891 	case MOD_UNLOAD:
2892 		/* Called during unload. */
2893 		break;
2894 	case MOD_SHUTDOWN:
2895 		/* Called during system shutdown. */
2896 		break;
2897 	default:
2898 		err = EOPNOTSUPP;
2899 		break;
2900 	}
2901 	return err;
2902 }
2903 
2904 static moduledata_t ipfwmod = {
2905 	"ipfw",
2906 	ipfw_modevent,
2907 	0
2908 };
2909 
2910 /* Define startup order. */
2911 #define	IPFW_SI_SUB_FIREWALL	SI_SUB_PROTO_IFATTACHDOMAIN
2912 #define	IPFW_MODEVENT_ORDER	(SI_ORDER_ANY - 255) /* On boot slot in here. */
2913 #define	IPFW_MODULE_ORDER	(IPFW_MODEVENT_ORDER + 1) /* A little later. */
2914 #define	IPFW_VNET_ORDER		(IPFW_MODEVENT_ORDER + 2) /* Later still. */
2915 
2916 DECLARE_MODULE(ipfw, ipfwmod, IPFW_SI_SUB_FIREWALL, IPFW_MODEVENT_ORDER);
2917 FEATURE(ipfw_ctl3, "ipfw new sockopt calls");
2918 MODULE_VERSION(ipfw, 3);
2919 /* should declare some dependencies here */
2920 
2921 /*
2922  * Starting up. Done in order after ipfwmod() has been called.
2923  * VNET_SYSINIT is also called for each existing vnet and each new vnet.
2924  */
2925 SYSINIT(ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
2926 	    ipfw_init, NULL);
2927 VNET_SYSINIT(vnet_ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
2928 	    vnet_ipfw_init, NULL);
2929 
2930 /*
2931  * Closing up shop. These are done in REVERSE ORDER, but still
2932  * after ipfwmod() has been called. Not called on reboot.
2933  * VNET_SYSUNINIT is also called for each exiting vnet as it exits.
2934  * or when the module is unloaded.
2935  */
2936 SYSUNINIT(ipfw_destroy, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
2937 	    ipfw_destroy, NULL);
2938 VNET_SYSUNINIT(vnet_ipfw_uninit, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
2939 	    vnet_ipfw_uninit, NULL);
2940 /* end of file */
2941