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