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