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