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