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