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