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