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