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