ip_fw2.c revision 183606
1/*-
2 * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 *    notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 *    notice, this list of conditions and the following disclaimer in the
11 *    documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23 * SUCH DAMAGE.
24 */
25
26#include <sys/cdefs.h>
27__FBSDID("$FreeBSD: head/sys/netinet/ip_fw2.c 183606 2008-10-04 15:06:34Z bz $");
28
29#define        DEB(x)
30#define        DDB(x) x
31
32/*
33 * Implement IP packet firewall (new version)
34 */
35
36#if !defined(KLD_MODULE)
37#include "opt_ipfw.h"
38#include "opt_ipdivert.h"
39#include "opt_ipdn.h"
40#include "opt_inet.h"
41#ifndef INET
42#error IPFIREWALL requires INET.
43#endif /* INET */
44#endif
45#include "opt_inet6.h"
46#include "opt_ipsec.h"
47#include "opt_mac.h"
48
49#include <sys/param.h>
50#include <sys/systm.h>
51#include <sys/condvar.h>
52#include <sys/eventhandler.h>
53#include <sys/malloc.h>
54#include <sys/mbuf.h>
55#include <sys/kernel.h>
56#include <sys/lock.h>
57#include <sys/jail.h>
58#include <sys/module.h>
59#include <sys/priv.h>
60#include <sys/proc.h>
61#include <sys/rwlock.h>
62#include <sys/socket.h>
63#include <sys/socketvar.h>
64#include <sys/sysctl.h>
65#include <sys/syslog.h>
66#include <sys/ucred.h>
67#include <sys/vimage.h>
68#include <net/if.h>
69#include <net/radix.h>
70#include <net/route.h>
71#include <net/pf_mtag.h>
72
73#define	IPFW_INTERNAL	/* Access to protected data structures in ip_fw.h. */
74
75#include <netinet/in.h>
76#include <netinet/in_systm.h>
77#include <netinet/in_var.h>
78#include <netinet/in_pcb.h>
79#include <netinet/ip.h>
80#include <netinet/ip_var.h>
81#include <netinet/ip_icmp.h>
82#include <netinet/ip_fw.h>
83#include <netinet/ip_divert.h>
84#include <netinet/ip_dummynet.h>
85#include <netinet/ip_carp.h>
86#include <netinet/pim.h>
87#include <netinet/tcp.h>
88#include <netinet/tcp_timer.h>
89#include <netinet/tcp_var.h>
90#include <netinet/tcpip.h>
91#include <netinet/udp.h>
92#include <netinet/udp_var.h>
93#include <netinet/sctp.h>
94#include <netgraph/ng_ipfw.h>
95
96#include <altq/if_altq.h>
97
98#include <netinet/ip6.h>
99#include <netinet/icmp6.h>
100#ifdef INET6
101#include <netinet6/scope6_var.h>
102#endif
103
104#include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
105
106#include <machine/in_cksum.h>	/* XXX for in_cksum */
107
108#include <security/mac/mac_framework.h>
109
110/*
111 * set_disable contains one bit per set value (0..31).
112 * If the bit is set, all rules with the corresponding set
113 * are disabled. Set RESVD_SET(31) is reserved for the default rule
114 * and rules that are not deleted by the flush command,
115 * and CANNOT be disabled.
116 * Rules in set RESVD_SET can only be deleted explicitly.
117 */
118static u_int32_t set_disable;
119
120static int fw_verbose;
121static int verbose_limit;
122
123static struct callout ipfw_timeout;
124static uma_zone_t ipfw_dyn_rule_zone;
125
126/*
127 * Data structure to cache our ucred related
128 * information. This structure only gets used if
129 * the user specified UID/GID based constraints in
130 * a firewall rule.
131 */
132struct ip_fw_ugid {
133	gid_t		fw_groups[NGROUPS];
134	int		fw_ngroups;
135	uid_t		fw_uid;
136	int		fw_prid;
137};
138
139/*
140 * list of rules for layer 3
141 */
142struct ip_fw_chain layer3_chain;
143
144MALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
145MALLOC_DEFINE(M_IPFW_TBL, "ipfw_tbl", "IpFw tables");
146#define IPFW_NAT_LOADED (ipfw_nat_ptr != NULL)
147ipfw_nat_t *ipfw_nat_ptr = NULL;
148ipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
149ipfw_nat_cfg_t *ipfw_nat_del_ptr;
150ipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
151ipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
152
153struct table_entry {
154	struct radix_node	rn[2];
155	struct sockaddr_in	addr, mask;
156	u_int32_t		value;
157};
158
159static int fw_debug = 1;
160static int autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
161
162extern int ipfw_chg_hook(SYSCTL_HANDLER_ARGS);
163
164#ifdef SYSCTL_NODE
165SYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
166SYSCTL_V_PROC(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, enable,
167    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, fw_enable, 0,
168    ipfw_chg_hook, "I", "Enable ipfw");
169SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, autoinc_step,
170    CTLFLAG_RW, autoinc_step, 0, "Rule number autincrement step");
171SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, one_pass,
172    CTLFLAG_RW | CTLFLAG_SECURE3, fw_one_pass, 0,
173    "Only do a single pass through ipfw when using dummynet(4)");
174SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
175    fw_debug, 0, "Enable printing of debug ip_fw statements");
176SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, verbose,
177    CTLFLAG_RW | CTLFLAG_SECURE3,
178    fw_verbose, 0, "Log matches to ipfw rules");
179SYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
180    &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
181SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
182    NULL, IPFW_DEFAULT_RULE, "The default/max possible rule number.");
183SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, tables_max, CTLFLAG_RD,
184    NULL, IPFW_TABLES_MAX, "The maximum number of tables.");
185
186/*
187 * Description of dynamic rules.
188 *
189 * Dynamic rules are stored in lists accessed through a hash table
190 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
191 * be modified through the sysctl variable dyn_buckets which is
192 * updated when the table becomes empty.
193 *
194 * XXX currently there is only one list, ipfw_dyn.
195 *
196 * When a packet is received, its address fields are first masked
197 * with the mask defined for the rule, then hashed, then matched
198 * against the entries in the corresponding list.
199 * Dynamic rules can be used for different purposes:
200 *  + stateful rules;
201 *  + enforcing limits on the number of sessions;
202 *  + in-kernel NAT (not implemented yet)
203 *
204 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
205 * measured in seconds and depending on the flags.
206 *
207 * The total number of dynamic rules is stored in dyn_count.
208 * The max number of dynamic rules is dyn_max. When we reach
209 * the maximum number of rules we do not create anymore. This is
210 * done to avoid consuming too much memory, but also too much
211 * time when searching on each packet (ideally, we should try instead
212 * to put a limit on the length of the list on each bucket...).
213 *
214 * Each dynamic rule holds a pointer to the parent ipfw rule so
215 * we know what action to perform. Dynamic rules are removed when
216 * the parent rule is deleted. XXX we should make them survive.
217 *
218 * There are some limitations with dynamic rules -- we do not
219 * obey the 'randomized match', and we do not do multiple
220 * passes through the firewall. XXX check the latter!!!
221 */
222static ipfw_dyn_rule **ipfw_dyn_v = NULL;
223static u_int32_t dyn_buckets = 256; /* must be power of 2 */
224static u_int32_t curr_dyn_buckets = 256; /* must be power of 2 */
225
226static struct mtx ipfw_dyn_mtx;		/* mutex guarding dynamic rules */
227#define	IPFW_DYN_LOCK_INIT() \
228	mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
229#define	IPFW_DYN_LOCK_DESTROY()	mtx_destroy(&ipfw_dyn_mtx)
230#define	IPFW_DYN_LOCK()		mtx_lock(&ipfw_dyn_mtx)
231#define	IPFW_DYN_UNLOCK()	mtx_unlock(&ipfw_dyn_mtx)
232#define	IPFW_DYN_LOCK_ASSERT()	mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
233
234/*
235 * Timeouts for various events in handing dynamic rules.
236 */
237static u_int32_t dyn_ack_lifetime = 300;
238static u_int32_t dyn_syn_lifetime = 20;
239static u_int32_t dyn_fin_lifetime = 1;
240static u_int32_t dyn_rst_lifetime = 1;
241static u_int32_t dyn_udp_lifetime = 10;
242static u_int32_t dyn_short_lifetime = 5;
243
244/*
245 * Keepalives are sent if dyn_keepalive is set. They are sent every
246 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
247 * seconds of lifetime of a rule.
248 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
249 * than dyn_keepalive_period.
250 */
251
252static u_int32_t dyn_keepalive_interval = 20;
253static u_int32_t dyn_keepalive_period = 5;
254static u_int32_t dyn_keepalive = 1;	/* do send keepalives */
255
256static u_int32_t static_count;	/* # of static rules */
257static u_int32_t static_len;	/* size in bytes of static rules */
258static u_int32_t dyn_count;		/* # of dynamic rules */
259static u_int32_t dyn_max = 4096;	/* max # of dynamic rules */
260
261SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, dyn_buckets,
262    CTLFLAG_RW, dyn_buckets, 0, "Number of dyn. buckets");
263SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, curr_dyn_buckets,
264    CTLFLAG_RD, curr_dyn_buckets, 0, "Current Number of dyn. buckets");
265SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, dyn_count,
266    CTLFLAG_RD, dyn_count, 0, "Number of dyn. rules");
267SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, dyn_max,
268    CTLFLAG_RW, dyn_max, 0, "Max number of dyn. rules");
269SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, static_count,
270    CTLFLAG_RD, static_count, 0, "Number of static rules");
271SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime,
272    CTLFLAG_RW, dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
273SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime,
274    CTLFLAG_RW, dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
275SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
276    CTLFLAG_RW, dyn_fin_lifetime, 0, "Lifetime of dyn. rules for fin");
277SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
278    CTLFLAG_RW, dyn_rst_lifetime, 0, "Lifetime of dyn. rules for rst");
279SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime,
280    CTLFLAG_RW, dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
281SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, dyn_short_lifetime,
282    CTLFLAG_RW, dyn_short_lifetime, 0,
283    "Lifetime of dyn. rules for other situations");
284SYSCTL_V_INT(V_NET, vnet_ipfw, _net_inet_ip_fw, OID_AUTO, dyn_keepalive,
285    CTLFLAG_RW, dyn_keepalive, 0, "Enable keepalives for dyn. rules");
286
287
288#ifdef INET6
289/*
290 * IPv6 specific variables
291 */
292SYSCTL_DECL(_net_inet6_ip6);
293
294static struct sysctl_ctx_list ip6_fw_sysctl_ctx;
295static struct sysctl_oid *ip6_fw_sysctl_tree;
296#endif /* INET6 */
297#endif /* SYSCTL_NODE */
298
299static int fw_deny_unknown_exthdrs = 1;
300
301
302/*
303 * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
304 * Other macros just cast void * into the appropriate type
305 */
306#define	L3HDR(T, ip)	((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
307#define	TCP(p)		((struct tcphdr *)(p))
308#define	SCTP(p)		((struct sctphdr *)(p))
309#define	UDP(p)		((struct udphdr *)(p))
310#define	ICMP(p)		((struct icmphdr *)(p))
311#define	ICMP6(p)	((struct icmp6_hdr *)(p))
312
313static __inline int
314icmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
315{
316	int type = icmp->icmp_type;
317
318	return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
319}
320
321#define TT	( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
322    (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
323
324static int
325is_icmp_query(struct icmphdr *icmp)
326{
327	int type = icmp->icmp_type;
328
329	return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
330}
331#undef TT
332
333/*
334 * The following checks use two arrays of 8 or 16 bits to store the
335 * bits that we want set or clear, respectively. They are in the
336 * low and high half of cmd->arg1 or cmd->d[0].
337 *
338 * We scan options and store the bits we find set. We succeed if
339 *
340 *	(want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
341 *
342 * The code is sometimes optimized not to store additional variables.
343 */
344
345static int
346flags_match(ipfw_insn *cmd, u_int8_t bits)
347{
348	u_char want_clear;
349	bits = ~bits;
350
351	if ( ((cmd->arg1 & 0xff) & bits) != 0)
352		return 0; /* some bits we want set were clear */
353	want_clear = (cmd->arg1 >> 8) & 0xff;
354	if ( (want_clear & bits) != want_clear)
355		return 0; /* some bits we want clear were set */
356	return 1;
357}
358
359static int
360ipopts_match(struct ip *ip, ipfw_insn *cmd)
361{
362	int optlen, bits = 0;
363	u_char *cp = (u_char *)(ip + 1);
364	int x = (ip->ip_hl << 2) - sizeof (struct ip);
365
366	for (; x > 0; x -= optlen, cp += optlen) {
367		int opt = cp[IPOPT_OPTVAL];
368
369		if (opt == IPOPT_EOL)
370			break;
371		if (opt == IPOPT_NOP)
372			optlen = 1;
373		else {
374			optlen = cp[IPOPT_OLEN];
375			if (optlen <= 0 || optlen > x)
376				return 0; /* invalid or truncated */
377		}
378		switch (opt) {
379
380		default:
381			break;
382
383		case IPOPT_LSRR:
384			bits |= IP_FW_IPOPT_LSRR;
385			break;
386
387		case IPOPT_SSRR:
388			bits |= IP_FW_IPOPT_SSRR;
389			break;
390
391		case IPOPT_RR:
392			bits |= IP_FW_IPOPT_RR;
393			break;
394
395		case IPOPT_TS:
396			bits |= IP_FW_IPOPT_TS;
397			break;
398		}
399	}
400	return (flags_match(cmd, bits));
401}
402
403static int
404tcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
405{
406	int optlen, bits = 0;
407	u_char *cp = (u_char *)(tcp + 1);
408	int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
409
410	for (; x > 0; x -= optlen, cp += optlen) {
411		int opt = cp[0];
412		if (opt == TCPOPT_EOL)
413			break;
414		if (opt == TCPOPT_NOP)
415			optlen = 1;
416		else {
417			optlen = cp[1];
418			if (optlen <= 0)
419				break;
420		}
421
422		switch (opt) {
423
424		default:
425			break;
426
427		case TCPOPT_MAXSEG:
428			bits |= IP_FW_TCPOPT_MSS;
429			break;
430
431		case TCPOPT_WINDOW:
432			bits |= IP_FW_TCPOPT_WINDOW;
433			break;
434
435		case TCPOPT_SACK_PERMITTED:
436		case TCPOPT_SACK:
437			bits |= IP_FW_TCPOPT_SACK;
438			break;
439
440		case TCPOPT_TIMESTAMP:
441			bits |= IP_FW_TCPOPT_TS;
442			break;
443
444		}
445	}
446	return (flags_match(cmd, bits));
447}
448
449static int
450iface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
451{
452	if (ifp == NULL)	/* no iface with this packet, match fails */
453		return 0;
454	/* Check by name or by IP address */
455	if (cmd->name[0] != '\0') { /* match by name */
456		/* Check name */
457		if (cmd->p.glob) {
458			if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
459				return(1);
460		} else {
461			if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
462				return(1);
463		}
464	} else {
465		struct ifaddr *ia;
466
467		/* XXX lock? */
468		TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
469			if (ia->ifa_addr->sa_family != AF_INET)
470				continue;
471			if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
472			    (ia->ifa_addr))->sin_addr.s_addr)
473				return(1);	/* match */
474		}
475	}
476	return(0);	/* no match, fail ... */
477}
478
479/*
480 * The verify_path function checks if a route to the src exists and
481 * if it is reachable via ifp (when provided).
482 *
483 * The 'verrevpath' option checks that the interface that an IP packet
484 * arrives on is the same interface that traffic destined for the
485 * packet's source address would be routed out of.  The 'versrcreach'
486 * option just checks that the source address is reachable via any route
487 * (except default) in the routing table.  These two are a measure to block
488 * forged packets.  This is also commonly known as "anti-spoofing" or Unicast
489 * Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
490 * is purposely reminiscent of the Cisco IOS command,
491 *
492 *   ip verify unicast reverse-path
493 *   ip verify unicast source reachable-via any
494 *
495 * which implements the same functionality. But note that syntax is
496 * misleading. The check may be performed on all IP packets whether unicast,
497 * multicast, or broadcast.
498 */
499static int
500verify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
501{
502	struct route ro;
503	struct sockaddr_in *dst;
504
505	bzero(&ro, sizeof(ro));
506
507	dst = (struct sockaddr_in *)&(ro.ro_dst);
508	dst->sin_family = AF_INET;
509	dst->sin_len = sizeof(*dst);
510	dst->sin_addr = src;
511	in_rtalloc_ign(&ro, RTF_CLONING, fib);
512
513	if (ro.ro_rt == NULL)
514		return 0;
515
516	/*
517	 * If ifp is provided, check for equality with rtentry.
518	 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
519	 * in order to pass packets injected back by if_simloop():
520	 * if useloopback == 1 routing entry (via lo0) for our own address
521	 * may exist, so we need to handle routing assymetry.
522	 */
523	if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
524		RTFREE(ro.ro_rt);
525		return 0;
526	}
527
528	/* if no ifp provided, check if rtentry is not default route */
529	if (ifp == NULL &&
530	     satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
531		RTFREE(ro.ro_rt);
532		return 0;
533	}
534
535	/* or if this is a blackhole/reject route */
536	if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
537		RTFREE(ro.ro_rt);
538		return 0;
539	}
540
541	/* found valid route */
542	RTFREE(ro.ro_rt);
543	return 1;
544}
545
546#ifdef INET6
547/*
548 * ipv6 specific rules here...
549 */
550static __inline int
551icmp6type_match (int type, ipfw_insn_u32 *cmd)
552{
553	return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
554}
555
556static int
557flow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
558{
559	int i;
560	for (i=0; i <= cmd->o.arg1; ++i )
561		if (curr_flow == cmd->d[i] )
562			return 1;
563	return 0;
564}
565
566/* support for IP6_*_ME opcodes */
567static int
568search_ip6_addr_net (struct in6_addr * ip6_addr)
569{
570	INIT_VNET_NET(curvnet);
571	struct ifnet *mdc;
572	struct ifaddr *mdc2;
573	struct in6_ifaddr *fdm;
574	struct in6_addr copia;
575
576	TAILQ_FOREACH(mdc, &V_ifnet, if_link)
577		TAILQ_FOREACH(mdc2, &mdc->if_addrlist, ifa_list) {
578			if (mdc2->ifa_addr->sa_family == AF_INET6) {
579				fdm = (struct in6_ifaddr *)mdc2;
580				copia = fdm->ia_addr.sin6_addr;
581				/* need for leaving scope_id in the sock_addr */
582				in6_clearscope(&copia);
583				if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia))
584					return 1;
585			}
586		}
587	return 0;
588}
589
590static int
591verify_path6(struct in6_addr *src, struct ifnet *ifp)
592{
593	struct route_in6 ro;
594	struct sockaddr_in6 *dst;
595
596	bzero(&ro, sizeof(ro));
597
598	dst = (struct sockaddr_in6 * )&(ro.ro_dst);
599	dst->sin6_family = AF_INET6;
600	dst->sin6_len = sizeof(*dst);
601	dst->sin6_addr = *src;
602	/* XXX MRT 0 for ipv6 at this time */
603	rtalloc_ign((struct route *)&ro, RTF_CLONING);
604
605	if (ro.ro_rt == NULL)
606		return 0;
607
608	/*
609	 * if ifp is provided, check for equality with rtentry
610	 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
611	 * to support the case of sending packets to an address of our own.
612	 * (where the former interface is the first argument of if_simloop()
613	 *  (=ifp), the latter is lo0)
614	 */
615	if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
616		RTFREE(ro.ro_rt);
617		return 0;
618	}
619
620	/* if no ifp provided, check if rtentry is not default route */
621	if (ifp == NULL &&
622	    IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
623		RTFREE(ro.ro_rt);
624		return 0;
625	}
626
627	/* or if this is a blackhole/reject route */
628	if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
629		RTFREE(ro.ro_rt);
630		return 0;
631	}
632
633	/* found valid route */
634	RTFREE(ro.ro_rt);
635	return 1;
636
637}
638static __inline int
639hash_packet6(struct ipfw_flow_id *id)
640{
641	u_int32_t i;
642	i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
643	    (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
644	    (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
645	    (id->src_ip6.__u6_addr.__u6_addr32[3]) ^
646	    (id->dst_port) ^ (id->src_port);
647	return i;
648}
649
650static int
651is_icmp6_query(int icmp6_type)
652{
653	if ((icmp6_type <= ICMP6_MAXTYPE) &&
654	    (icmp6_type == ICMP6_ECHO_REQUEST ||
655	    icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
656	    icmp6_type == ICMP6_WRUREQUEST ||
657	    icmp6_type == ICMP6_FQDN_QUERY ||
658	    icmp6_type == ICMP6_NI_QUERY))
659		return (1);
660
661	return (0);
662}
663
664static void
665send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
666{
667	struct mbuf *m;
668
669	m = args->m;
670	if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
671		struct tcphdr *tcp;
672		tcp_seq ack, seq;
673		int flags;
674		struct {
675			struct ip6_hdr ip6;
676			struct tcphdr th;
677		} ti;
678		tcp = (struct tcphdr *)((char *)ip6 + hlen);
679
680		if ((tcp->th_flags & TH_RST) != 0) {
681			m_freem(m);
682			args->m = NULL;
683			return;
684		}
685
686		ti.ip6 = *ip6;
687		ti.th = *tcp;
688		ti.th.th_seq = ntohl(ti.th.th_seq);
689		ti.th.th_ack = ntohl(ti.th.th_ack);
690		ti.ip6.ip6_nxt = IPPROTO_TCP;
691
692		if (ti.th.th_flags & TH_ACK) {
693			ack = 0;
694			seq = ti.th.th_ack;
695			flags = TH_RST;
696		} else {
697			ack = ti.th.th_seq;
698			if ((m->m_flags & M_PKTHDR) != 0) {
699				/*
700				 * total new data to ACK is:
701				 * total packet length,
702				 * minus the header length,
703				 * minus the tcp header length.
704				 */
705				ack += m->m_pkthdr.len - hlen
706					- (ti.th.th_off << 2);
707			} else if (ip6->ip6_plen) {
708				ack += ntohs(ip6->ip6_plen) + sizeof(*ip6) -
709				    hlen - (ti.th.th_off << 2);
710			} else {
711				m_freem(m);
712				return;
713			}
714			if (tcp->th_flags & TH_SYN)
715				ack++;
716			seq = 0;
717			flags = TH_RST|TH_ACK;
718		}
719		bcopy(&ti, ip6, sizeof(ti));
720		/*
721		 * m is only used to recycle the mbuf
722		 * The data in it is never read so we don't need
723		 * to correct the offsets or anything
724		 */
725		tcp_respond(NULL, ip6, tcp, m, ack, seq, flags);
726	} else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
727#if 0
728		/*
729		 * Unlike above, the mbufs need to line up with the ip6 hdr,
730		 * as the contents are read. We need to m_adj() the
731		 * needed amount.
732		 * The mbuf will however be thrown away so we can adjust it.
733		 * Remember we did an m_pullup on it already so we
734		 * can make some assumptions about contiguousness.
735		 */
736		if (args->L3offset)
737			m_adj(m, args->L3offset);
738#endif
739		icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
740	} else
741		m_freem(m);
742
743	args->m = NULL;
744}
745
746#endif /* INET6 */
747
748static u_int64_t norule_counter;	/* counter for ipfw_log(NULL...) */
749
750#define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
751#define SNP(buf) buf, sizeof(buf)
752
753/*
754 * We enter here when we have a rule with O_LOG.
755 * XXX this function alone takes about 2Kbytes of code!
756 */
757static void
758ipfw_log(struct ip_fw *f, u_int hlen, struct ip_fw_args *args,
759    struct mbuf *m, struct ifnet *oif, u_short offset, uint32_t tablearg,
760    struct ip *ip)
761{
762	INIT_VNET_IPFW(curvnet);
763	struct ether_header *eh = args->eh;
764	char *action;
765	int limit_reached = 0;
766	char action2[40], proto[128], fragment[32];
767
768	fragment[0] = '\0';
769	proto[0] = '\0';
770
771	if (f == NULL) {	/* bogus pkt */
772		if (V_verbose_limit != 0 && V_norule_counter >= V_verbose_limit)
773			return;
774		V_norule_counter++;
775		if (V_norule_counter == V_verbose_limit)
776			limit_reached = V_verbose_limit;
777		action = "Refuse";
778	} else {	/* O_LOG is the first action, find the real one */
779		ipfw_insn *cmd = ACTION_PTR(f);
780		ipfw_insn_log *l = (ipfw_insn_log *)cmd;
781
782		if (l->max_log != 0 && l->log_left == 0)
783			return;
784		l->log_left--;
785		if (l->log_left == 0)
786			limit_reached = l->max_log;
787		cmd += F_LEN(cmd);	/* point to first action */
788		if (cmd->opcode == O_ALTQ) {
789			ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
790
791			snprintf(SNPARGS(action2, 0), "Altq %d",
792				altq->qid);
793			cmd += F_LEN(cmd);
794		}
795		if (cmd->opcode == O_PROB)
796			cmd += F_LEN(cmd);
797
798		if (cmd->opcode == O_TAG)
799			cmd += F_LEN(cmd);
800
801		action = action2;
802		switch (cmd->opcode) {
803		case O_DENY:
804			action = "Deny";
805			break;
806
807		case O_REJECT:
808			if (cmd->arg1==ICMP_REJECT_RST)
809				action = "Reset";
810			else if (cmd->arg1==ICMP_UNREACH_HOST)
811				action = "Reject";
812			else
813				snprintf(SNPARGS(action2, 0), "Unreach %d",
814					cmd->arg1);
815			break;
816
817		case O_UNREACH6:
818			if (cmd->arg1==ICMP6_UNREACH_RST)
819				action = "Reset";
820			else
821				snprintf(SNPARGS(action2, 0), "Unreach %d",
822					cmd->arg1);
823			break;
824
825		case O_ACCEPT:
826			action = "Accept";
827			break;
828		case O_COUNT:
829			action = "Count";
830			break;
831		case O_DIVERT:
832			snprintf(SNPARGS(action2, 0), "Divert %d",
833				cmd->arg1);
834			break;
835		case O_TEE:
836			snprintf(SNPARGS(action2, 0), "Tee %d",
837				cmd->arg1);
838			break;
839		case O_SETFIB:
840			snprintf(SNPARGS(action2, 0), "SetFib %d",
841				cmd->arg1);
842			break;
843		case O_SKIPTO:
844			snprintf(SNPARGS(action2, 0), "SkipTo %d",
845				cmd->arg1);
846			break;
847		case O_PIPE:
848			snprintf(SNPARGS(action2, 0), "Pipe %d",
849				cmd->arg1);
850			break;
851		case O_QUEUE:
852			snprintf(SNPARGS(action2, 0), "Queue %d",
853				cmd->arg1);
854			break;
855		case O_FORWARD_IP: {
856			ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
857			int len;
858			struct in_addr dummyaddr;
859			if (sa->sa.sin_addr.s_addr == INADDR_ANY)
860				dummyaddr.s_addr = htonl(tablearg);
861			else
862				dummyaddr.s_addr = sa->sa.sin_addr.s_addr;
863
864			len = snprintf(SNPARGS(action2, 0), "Forward to %s",
865				inet_ntoa(dummyaddr));
866
867			if (sa->sa.sin_port)
868				snprintf(SNPARGS(action2, len), ":%d",
869				    sa->sa.sin_port);
870			}
871			break;
872		case O_NETGRAPH:
873			snprintf(SNPARGS(action2, 0), "Netgraph %d",
874				cmd->arg1);
875			break;
876		case O_NGTEE:
877			snprintf(SNPARGS(action2, 0), "Ngtee %d",
878				cmd->arg1);
879			break;
880		case O_NAT:
881			action = "Nat";
882 			break;
883		default:
884			action = "UNKNOWN";
885			break;
886		}
887	}
888
889	if (hlen == 0) {	/* non-ip */
890		snprintf(SNPARGS(proto, 0), "MAC");
891
892	} else {
893		int len;
894		char src[48], dst[48];
895		struct icmphdr *icmp;
896		struct tcphdr *tcp;
897		struct udphdr *udp;
898#ifdef INET6
899		struct ip6_hdr *ip6 = NULL;
900		struct icmp6_hdr *icmp6;
901#endif
902		src[0] = '\0';
903		dst[0] = '\0';
904#ifdef INET6
905		if (IS_IP6_FLOW_ID(&(args->f_id))) {
906			char ip6buf[INET6_ADDRSTRLEN];
907			snprintf(src, sizeof(src), "[%s]",
908			    ip6_sprintf(ip6buf, &args->f_id.src_ip6));
909			snprintf(dst, sizeof(dst), "[%s]",
910			    ip6_sprintf(ip6buf, &args->f_id.dst_ip6));
911
912			ip6 = (struct ip6_hdr *)ip;
913			tcp = (struct tcphdr *)(((char *)ip) + hlen);
914			udp = (struct udphdr *)(((char *)ip) + hlen);
915		} else
916#endif
917		{
918			tcp = L3HDR(struct tcphdr, ip);
919			udp = L3HDR(struct udphdr, ip);
920
921			inet_ntoa_r(ip->ip_src, src);
922			inet_ntoa_r(ip->ip_dst, dst);
923		}
924
925		switch (args->f_id.proto) {
926		case IPPROTO_TCP:
927			len = snprintf(SNPARGS(proto, 0), "TCP %s", src);
928			if (offset == 0)
929				snprintf(SNPARGS(proto, len), ":%d %s:%d",
930				    ntohs(tcp->th_sport),
931				    dst,
932				    ntohs(tcp->th_dport));
933			else
934				snprintf(SNPARGS(proto, len), " %s", dst);
935			break;
936
937		case IPPROTO_UDP:
938			len = snprintf(SNPARGS(proto, 0), "UDP %s", src);
939			if (offset == 0)
940				snprintf(SNPARGS(proto, len), ":%d %s:%d",
941				    ntohs(udp->uh_sport),
942				    dst,
943				    ntohs(udp->uh_dport));
944			else
945				snprintf(SNPARGS(proto, len), " %s", dst);
946			break;
947
948		case IPPROTO_ICMP:
949			icmp = L3HDR(struct icmphdr, ip);
950			if (offset == 0)
951				len = snprintf(SNPARGS(proto, 0),
952				    "ICMP:%u.%u ",
953				    icmp->icmp_type, icmp->icmp_code);
954			else
955				len = snprintf(SNPARGS(proto, 0), "ICMP ");
956			len += snprintf(SNPARGS(proto, len), "%s", src);
957			snprintf(SNPARGS(proto, len), " %s", dst);
958			break;
959#ifdef INET6
960		case IPPROTO_ICMPV6:
961			icmp6 = (struct icmp6_hdr *)(((char *)ip) + hlen);
962			if (offset == 0)
963				len = snprintf(SNPARGS(proto, 0),
964				    "ICMPv6:%u.%u ",
965				    icmp6->icmp6_type, icmp6->icmp6_code);
966			else
967				len = snprintf(SNPARGS(proto, 0), "ICMPv6 ");
968			len += snprintf(SNPARGS(proto, len), "%s", src);
969			snprintf(SNPARGS(proto, len), " %s", dst);
970			break;
971#endif
972		default:
973			len = snprintf(SNPARGS(proto, 0), "P:%d %s",
974			    args->f_id.proto, src);
975			snprintf(SNPARGS(proto, len), " %s", dst);
976			break;
977		}
978
979#ifdef INET6
980		if (IS_IP6_FLOW_ID(&(args->f_id))) {
981			if (offset & (IP6F_OFF_MASK | IP6F_MORE_FRAG))
982				snprintf(SNPARGS(fragment, 0),
983				    " (frag %08x:%d@%d%s)",
984				    args->f_id.frag_id6,
985				    ntohs(ip6->ip6_plen) - hlen,
986				    ntohs(offset & IP6F_OFF_MASK) << 3,
987				    (offset & IP6F_MORE_FRAG) ? "+" : "");
988		} else
989#endif
990		{
991			int ip_off, ip_len;
992			if (eh != NULL) { /* layer 2 packets are as on the wire */
993				ip_off = ntohs(ip->ip_off);
994				ip_len = ntohs(ip->ip_len);
995			} else {
996				ip_off = ip->ip_off;
997				ip_len = ip->ip_len;
998			}
999			if (ip_off & (IP_MF | IP_OFFMASK))
1000				snprintf(SNPARGS(fragment, 0),
1001				    " (frag %d:%d@%d%s)",
1002				    ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
1003				    offset << 3,
1004				    (ip_off & IP_MF) ? "+" : "");
1005		}
1006	}
1007	if (oif || m->m_pkthdr.rcvif)
1008		log(LOG_SECURITY | LOG_INFO,
1009		    "ipfw: %d %s %s %s via %s%s\n",
1010		    f ? f->rulenum : -1,
1011		    action, proto, oif ? "out" : "in",
1012		    oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
1013		    fragment);
1014	else
1015		log(LOG_SECURITY | LOG_INFO,
1016		    "ipfw: %d %s %s [no if info]%s\n",
1017		    f ? f->rulenum : -1,
1018		    action, proto, fragment);
1019	if (limit_reached)
1020		log(LOG_SECURITY | LOG_NOTICE,
1021		    "ipfw: limit %d reached on entry %d\n",
1022		    limit_reached, f ? f->rulenum : -1);
1023}
1024
1025/*
1026 * IMPORTANT: the hash function for dynamic rules must be commutative
1027 * in source and destination (ip,port), because rules are bidirectional
1028 * and we want to find both in the same bucket.
1029 */
1030static __inline int
1031hash_packet(struct ipfw_flow_id *id)
1032{
1033	INIT_VNET_IPFW(curvnet);
1034	u_int32_t i;
1035
1036#ifdef INET6
1037	if (IS_IP6_FLOW_ID(id))
1038		i = hash_packet6(id);
1039	else
1040#endif /* INET6 */
1041	i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
1042	i &= (V_curr_dyn_buckets - 1);
1043	return i;
1044}
1045
1046/**
1047 * unlink a dynamic rule from a chain. prev is a pointer to
1048 * the previous one, q is a pointer to the rule to delete,
1049 * head is a pointer to the head of the queue.
1050 * Modifies q and potentially also head.
1051 */
1052#define UNLINK_DYN_RULE(prev, head, q) {				\
1053	ipfw_dyn_rule *old_q = q;					\
1054									\
1055	/* remove a refcount to the parent */				\
1056	if (q->dyn_type == O_LIMIT)					\
1057		q->parent->count--;					\
1058	DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
1059		(q->id.src_ip), (q->id.src_port),			\
1060		(q->id.dst_ip), (q->id.dst_port), V_dyn_count-1 ); )	\
1061	if (prev != NULL)						\
1062		prev->next = q = q->next;				\
1063	else								\
1064		head = q = q->next;					\
1065	V_dyn_count--;							\
1066	uma_zfree(ipfw_dyn_rule_zone, old_q); }
1067
1068#define TIME_LEQ(a,b)       ((int)((a)-(b)) <= 0)
1069
1070/**
1071 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
1072 *
1073 * If keep_me == NULL, rules are deleted even if not expired,
1074 * otherwise only expired rules are removed.
1075 *
1076 * The value of the second parameter is also used to point to identify
1077 * a rule we absolutely do not want to remove (e.g. because we are
1078 * holding a reference to it -- this is the case with O_LIMIT_PARENT
1079 * rules). The pointer is only used for comparison, so any non-null
1080 * value will do.
1081 */
1082static void
1083remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
1084{
1085	INIT_VNET_IPFW(curvnet);
1086	static u_int32_t last_remove = 0;
1087
1088#define FORCE (keep_me == NULL)
1089
1090	ipfw_dyn_rule *prev, *q;
1091	int i, pass = 0, max_pass = 0;
1092
1093	IPFW_DYN_LOCK_ASSERT();
1094
1095	if (V_ipfw_dyn_v == NULL || V_dyn_count == 0)
1096		return;
1097	/* do not expire more than once per second, it is useless */
1098	if (!FORCE && last_remove == time_uptime)
1099		return;
1100	last_remove = time_uptime;
1101
1102	/*
1103	 * because O_LIMIT refer to parent rules, during the first pass only
1104	 * remove child and mark any pending LIMIT_PARENT, and remove
1105	 * them in a second pass.
1106	 */
1107next_pass:
1108	for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
1109		for (prev=NULL, q = V_ipfw_dyn_v[i] ; q ; ) {
1110			/*
1111			 * Logic can become complex here, so we split tests.
1112			 */
1113			if (q == keep_me)
1114				goto next;
1115			if (rule != NULL && rule != q->rule)
1116				goto next; /* not the one we are looking for */
1117			if (q->dyn_type == O_LIMIT_PARENT) {
1118				/*
1119				 * handle parent in the second pass,
1120				 * record we need one.
1121				 */
1122				max_pass = 1;
1123				if (pass == 0)
1124					goto next;
1125				if (FORCE && q->count != 0 ) {
1126					/* XXX should not happen! */
1127					printf("ipfw: OUCH! cannot remove rule,"
1128					     " count %d\n", q->count);
1129				}
1130			} else {
1131				if (!FORCE &&
1132				    !TIME_LEQ( q->expire, time_uptime ))
1133					goto next;
1134			}
1135             if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
1136                     UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
1137                     continue;
1138             }
1139next:
1140			prev=q;
1141			q=q->next;
1142		}
1143	}
1144	if (pass++ < max_pass)
1145		goto next_pass;
1146}
1147
1148
1149/**
1150 * lookup a dynamic rule.
1151 */
1152static ipfw_dyn_rule *
1153lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
1154    struct tcphdr *tcp)
1155{
1156	INIT_VNET_IPFW(curvnet);
1157	/*
1158	 * stateful ipfw extensions.
1159	 * Lookup into dynamic session queue
1160	 */
1161#define MATCH_REVERSE	0
1162#define MATCH_FORWARD	1
1163#define MATCH_NONE	2
1164#define MATCH_UNKNOWN	3
1165	int i, dir = MATCH_NONE;
1166	ipfw_dyn_rule *prev, *q=NULL;
1167
1168	IPFW_DYN_LOCK_ASSERT();
1169
1170	if (V_ipfw_dyn_v == NULL)
1171		goto done;	/* not found */
1172	i = hash_packet( pkt );
1173	for (prev=NULL, q = V_ipfw_dyn_v[i] ; q != NULL ; ) {
1174		if (q->dyn_type == O_LIMIT_PARENT && q->count)
1175			goto next;
1176		if (TIME_LEQ( q->expire, time_uptime)) { /* expire entry */
1177			UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
1178			continue;
1179		}
1180		if (pkt->proto == q->id.proto &&
1181		    q->dyn_type != O_LIMIT_PARENT) {
1182			if (IS_IP6_FLOW_ID(pkt)) {
1183			    if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1184				&(q->id.src_ip6)) &&
1185			    IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1186				&(q->id.dst_ip6)) &&
1187			    pkt->src_port == q->id.src_port &&
1188			    pkt->dst_port == q->id.dst_port ) {
1189				dir = MATCH_FORWARD;
1190				break;
1191			    }
1192			    if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1193				    &(q->id.dst_ip6)) &&
1194				IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1195				    &(q->id.src_ip6)) &&
1196				pkt->src_port == q->id.dst_port &&
1197				pkt->dst_port == q->id.src_port ) {
1198				    dir = MATCH_REVERSE;
1199				    break;
1200			    }
1201			} else {
1202			    if (pkt->src_ip == q->id.src_ip &&
1203				pkt->dst_ip == q->id.dst_ip &&
1204				pkt->src_port == q->id.src_port &&
1205				pkt->dst_port == q->id.dst_port ) {
1206				    dir = MATCH_FORWARD;
1207				    break;
1208			    }
1209			    if (pkt->src_ip == q->id.dst_ip &&
1210				pkt->dst_ip == q->id.src_ip &&
1211				pkt->src_port == q->id.dst_port &&
1212				pkt->dst_port == q->id.src_port ) {
1213				    dir = MATCH_REVERSE;
1214				    break;
1215			    }
1216			}
1217		}
1218next:
1219		prev = q;
1220		q = q->next;
1221	}
1222	if (q == NULL)
1223		goto done; /* q = NULL, not found */
1224
1225	if ( prev != NULL) { /* found and not in front */
1226		prev->next = q->next;
1227		q->next = V_ipfw_dyn_v[i];
1228		V_ipfw_dyn_v[i] = q;
1229	}
1230	if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1231		u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1232
1233#define BOTH_SYN	(TH_SYN | (TH_SYN << 8))
1234#define BOTH_FIN	(TH_FIN | (TH_FIN << 8))
1235		q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1236		switch (q->state) {
1237		case TH_SYN:				/* opening */
1238			q->expire = time_uptime + V_dyn_syn_lifetime;
1239			break;
1240
1241		case BOTH_SYN:			/* move to established */
1242		case BOTH_SYN | TH_FIN :	/* one side tries to close */
1243		case BOTH_SYN | (TH_FIN << 8) :
1244 			if (tcp) {
1245#define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
1246			    u_int32_t ack = ntohl(tcp->th_ack);
1247			    if (dir == MATCH_FORWARD) {
1248				if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
1249				    q->ack_fwd = ack;
1250				else { /* ignore out-of-sequence */
1251				    break;
1252				}
1253			    } else {
1254				if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
1255				    q->ack_rev = ack;
1256				else { /* ignore out-of-sequence */
1257				    break;
1258				}
1259			    }
1260			}
1261			q->expire = time_uptime + V_dyn_ack_lifetime;
1262			break;
1263
1264		case BOTH_SYN | BOTH_FIN:	/* both sides closed */
1265			if (V_dyn_fin_lifetime >= V_dyn_keepalive_period)
1266				V_dyn_fin_lifetime = V_dyn_keepalive_period - 1;
1267			q->expire = time_uptime + V_dyn_fin_lifetime;
1268			break;
1269
1270		default:
1271#if 0
1272			/*
1273			 * reset or some invalid combination, but can also
1274			 * occur if we use keep-state the wrong way.
1275			 */
1276			if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
1277				printf("invalid state: 0x%x\n", q->state);
1278#endif
1279			if (V_dyn_rst_lifetime >= V_dyn_keepalive_period)
1280				V_dyn_rst_lifetime = V_dyn_keepalive_period - 1;
1281			q->expire = time_uptime + V_dyn_rst_lifetime;
1282			break;
1283		}
1284	} else if (pkt->proto == IPPROTO_UDP) {
1285		q->expire = time_uptime + V_dyn_udp_lifetime;
1286	} else {
1287		/* other protocols */
1288		q->expire = time_uptime + V_dyn_short_lifetime;
1289	}
1290done:
1291	if (match_direction)
1292		*match_direction = dir;
1293	return q;
1294}
1295
1296static ipfw_dyn_rule *
1297lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
1298    struct tcphdr *tcp)
1299{
1300	ipfw_dyn_rule *q;
1301
1302	IPFW_DYN_LOCK();
1303	q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
1304	if (q == NULL)
1305		IPFW_DYN_UNLOCK();
1306	/* NB: return table locked when q is not NULL */
1307	return q;
1308}
1309
1310static void
1311realloc_dynamic_table(void)
1312{
1313	INIT_VNET_IPFW(curvnet);
1314	IPFW_DYN_LOCK_ASSERT();
1315
1316	/*
1317	 * Try reallocation, make sure we have a power of 2 and do
1318	 * not allow more than 64k entries. In case of overflow,
1319	 * default to 1024.
1320	 */
1321
1322	if (V_dyn_buckets > 65536)
1323		V_dyn_buckets = 1024;
1324	if ((V_dyn_buckets & (V_dyn_buckets-1)) != 0) { /* not a power of 2 */
1325		V_dyn_buckets = V_curr_dyn_buckets; /* reset */
1326		return;
1327	}
1328	V_curr_dyn_buckets = V_dyn_buckets;
1329	if (V_ipfw_dyn_v != NULL)
1330		free(V_ipfw_dyn_v, M_IPFW);
1331	for (;;) {
1332		V_ipfw_dyn_v = malloc(V_curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1333		       M_IPFW, M_NOWAIT | M_ZERO);
1334		if (V_ipfw_dyn_v != NULL || V_curr_dyn_buckets <= 2)
1335			break;
1336		V_curr_dyn_buckets /= 2;
1337	}
1338}
1339
1340/**
1341 * Install state of type 'type' for a dynamic session.
1342 * The hash table contains two type of rules:
1343 * - regular rules (O_KEEP_STATE)
1344 * - rules for sessions with limited number of sess per user
1345 *   (O_LIMIT). When they are created, the parent is
1346 *   increased by 1, and decreased on delete. In this case,
1347 *   the third parameter is the parent rule and not the chain.
1348 * - "parent" rules for the above (O_LIMIT_PARENT).
1349 */
1350static ipfw_dyn_rule *
1351add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
1352{
1353	INIT_VNET_IPFW(curvnet);
1354	ipfw_dyn_rule *r;
1355	int i;
1356
1357	IPFW_DYN_LOCK_ASSERT();
1358
1359	if (V_ipfw_dyn_v == NULL ||
1360	    (V_dyn_count == 0 && V_dyn_buckets != V_curr_dyn_buckets)) {
1361		realloc_dynamic_table();
1362		if (V_ipfw_dyn_v == NULL)
1363			return NULL; /* failed ! */
1364	}
1365	i = hash_packet(id);
1366
1367	r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
1368	if (r == NULL) {
1369		printf ("ipfw: sorry cannot allocate state\n");
1370		return NULL;
1371	}
1372
1373	/* increase refcount on parent, and set pointer */
1374	if (dyn_type == O_LIMIT) {
1375		ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1376		if ( parent->dyn_type != O_LIMIT_PARENT)
1377			panic("invalid parent");
1378		parent->count++;
1379		r->parent = parent;
1380		rule = parent->rule;
1381	}
1382
1383	r->id = *id;
1384	r->expire = time_uptime + V_dyn_syn_lifetime;
1385	r->rule = rule;
1386	r->dyn_type = dyn_type;
1387	r->pcnt = r->bcnt = 0;
1388	r->count = 0;
1389
1390	r->bucket = i;
1391	r->next = V_ipfw_dyn_v[i];
1392	V_ipfw_dyn_v[i] = r;
1393	V_dyn_count++;
1394	DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1395	   dyn_type,
1396	   (r->id.src_ip), (r->id.src_port),
1397	   (r->id.dst_ip), (r->id.dst_port),
1398	   V_dyn_count ); )
1399	return r;
1400}
1401
1402/**
1403 * lookup dynamic parent rule using pkt and rule as search keys.
1404 * If the lookup fails, then install one.
1405 */
1406static ipfw_dyn_rule *
1407lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1408{
1409	INIT_VNET_IPFW(curvnet);
1410	ipfw_dyn_rule *q;
1411	int i;
1412
1413	IPFW_DYN_LOCK_ASSERT();
1414
1415	if (V_ipfw_dyn_v) {
1416		int is_v6 = IS_IP6_FLOW_ID(pkt);
1417		i = hash_packet( pkt );
1418		for (q = V_ipfw_dyn_v[i] ; q != NULL ; q=q->next)
1419			if (q->dyn_type == O_LIMIT_PARENT &&
1420			    rule== q->rule &&
1421			    pkt->proto == q->id.proto &&
1422			    pkt->src_port == q->id.src_port &&
1423			    pkt->dst_port == q->id.dst_port &&
1424			    (
1425				(is_v6 &&
1426				 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1427					&(q->id.src_ip6)) &&
1428				 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1429					&(q->id.dst_ip6))) ||
1430				(!is_v6 &&
1431				 pkt->src_ip == q->id.src_ip &&
1432				 pkt->dst_ip == q->id.dst_ip)
1433			    )
1434			) {
1435				q->expire = time_uptime + V_dyn_short_lifetime;
1436				DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
1437				return q;
1438			}
1439	}
1440	return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1441}
1442
1443/**
1444 * Install dynamic state for rule type cmd->o.opcode
1445 *
1446 * Returns 1 (failure) if state is not installed because of errors or because
1447 * session limitations are enforced.
1448 */
1449static int
1450install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1451    struct ip_fw_args *args, uint32_t tablearg)
1452{
1453	INIT_VNET_IPFW(curvnet);
1454	static int last_log;
1455	ipfw_dyn_rule *q;
1456	struct in_addr da;
1457	char src[48], dst[48];
1458
1459	src[0] = '\0';
1460	dst[0] = '\0';
1461
1462	DEB(
1463	printf("ipfw: %s: type %d 0x%08x %u -> 0x%08x %u\n",
1464	    __func__, cmd->o.opcode,
1465	    (args->f_id.src_ip), (args->f_id.src_port),
1466	    (args->f_id.dst_ip), (args->f_id.dst_port));
1467	)
1468
1469	IPFW_DYN_LOCK();
1470
1471	q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1472
1473	if (q != NULL) {	/* should never occur */
1474		if (last_log != time_uptime) {
1475			last_log = time_uptime;
1476			printf("ipfw: %s: entry already present, done\n",
1477			    __func__);
1478		}
1479		IPFW_DYN_UNLOCK();
1480		return (0);
1481	}
1482
1483	if (V_dyn_count >= V_dyn_max)
1484		/* Run out of slots, try to remove any expired rule. */
1485		remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1486
1487	if (V_dyn_count >= V_dyn_max) {
1488		if (last_log != time_uptime) {
1489			last_log = time_uptime;
1490			printf("ipfw: %s: Too many dynamic rules\n", __func__);
1491		}
1492		IPFW_DYN_UNLOCK();
1493		return (1);	/* cannot install, notify caller */
1494	}
1495
1496	switch (cmd->o.opcode) {
1497	case O_KEEP_STATE:	/* bidir rule */
1498		add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1499		break;
1500
1501	case O_LIMIT: {		/* limit number of sessions */
1502		struct ipfw_flow_id id;
1503		ipfw_dyn_rule *parent;
1504		uint32_t conn_limit;
1505		uint16_t limit_mask = cmd->limit_mask;
1506
1507		conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ?
1508		    tablearg : cmd->conn_limit;
1509
1510		DEB(
1511		if (cmd->conn_limit == IP_FW_TABLEARG)
1512			printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
1513			    "(tablearg)\n", __func__, conn_limit);
1514		else
1515			printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
1516			    __func__, conn_limit);
1517		)
1518
1519		id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
1520		id.proto = args->f_id.proto;
1521		id.addr_type = args->f_id.addr_type;
1522		id.fib = M_GETFIB(args->m);
1523
1524		if (IS_IP6_FLOW_ID (&(args->f_id))) {
1525			if (limit_mask & DYN_SRC_ADDR)
1526				id.src_ip6 = args->f_id.src_ip6;
1527			if (limit_mask & DYN_DST_ADDR)
1528				id.dst_ip6 = args->f_id.dst_ip6;
1529		} else {
1530			if (limit_mask & DYN_SRC_ADDR)
1531				id.src_ip = args->f_id.src_ip;
1532			if (limit_mask & DYN_DST_ADDR)
1533				id.dst_ip = args->f_id.dst_ip;
1534		}
1535		if (limit_mask & DYN_SRC_PORT)
1536			id.src_port = args->f_id.src_port;
1537		if (limit_mask & DYN_DST_PORT)
1538			id.dst_port = args->f_id.dst_port;
1539		if ((parent = lookup_dyn_parent(&id, rule)) == NULL) {
1540			printf("ipfw: %s: add parent failed\n", __func__);
1541			IPFW_DYN_UNLOCK();
1542			return (1);
1543		}
1544
1545		if (parent->count >= conn_limit) {
1546			/* See if we can remove some expired rule. */
1547			remove_dyn_rule(rule, parent);
1548			if (parent->count >= conn_limit) {
1549				if (V_fw_verbose && last_log != time_uptime) {
1550					last_log = time_uptime;
1551#ifdef INET6
1552					/*
1553					 * XXX IPv6 flows are not
1554					 * supported yet.
1555					 */
1556					if (IS_IP6_FLOW_ID(&(args->f_id))) {
1557						char ip6buf[INET6_ADDRSTRLEN];
1558						snprintf(src, sizeof(src),
1559						    "[%s]", ip6_sprintf(ip6buf,
1560							&args->f_id.src_ip6));
1561						snprintf(dst, sizeof(dst),
1562						    "[%s]", ip6_sprintf(ip6buf,
1563							&args->f_id.dst_ip6));
1564					} else
1565#endif
1566					{
1567						da.s_addr =
1568						    htonl(args->f_id.src_ip);
1569						inet_ntoa_r(da, src);
1570						da.s_addr =
1571						    htonl(args->f_id.dst_ip);
1572						inet_ntoa_r(da, dst);
1573					}
1574					log(LOG_SECURITY | LOG_DEBUG,
1575					    "ipfw: %d %s %s:%u -> %s:%u, %s\n",
1576					    parent->rule->rulenum,
1577					    "drop session",
1578					    src, (args->f_id.src_port),
1579					    dst, (args->f_id.dst_port),
1580					    "too many entries");
1581				}
1582				IPFW_DYN_UNLOCK();
1583				return (1);
1584			}
1585		}
1586		add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1587		break;
1588	}
1589	default:
1590		printf("ipfw: %s: unknown dynamic rule type %u\n",
1591		    __func__, cmd->o.opcode);
1592		IPFW_DYN_UNLOCK();
1593		return (1);
1594	}
1595
1596	/* XXX just set lifetime */
1597	lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1598
1599	IPFW_DYN_UNLOCK();
1600	return (0);
1601}
1602
1603/*
1604 * Generate a TCP packet, containing either a RST or a keepalive.
1605 * When flags & TH_RST, we are sending a RST packet, because of a
1606 * "reset" action matched the packet.
1607 * Otherwise we are sending a keepalive, and flags & TH_
1608 * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
1609 * so that MAC can label the reply appropriately.
1610 */
1611static struct mbuf *
1612send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
1613    u_int32_t ack, int flags)
1614{
1615	INIT_VNET_INET(curvnet);
1616	struct mbuf *m;
1617	struct ip *ip;
1618	struct tcphdr *tcp;
1619
1620	MGETHDR(m, M_DONTWAIT, MT_DATA);
1621	if (m == 0)
1622		return (NULL);
1623	m->m_pkthdr.rcvif = (struct ifnet *)0;
1624
1625	M_SETFIB(m, id->fib);
1626#ifdef MAC
1627	if (replyto != NULL)
1628		mac_netinet_firewall_reply(replyto, m);
1629	else
1630		mac_netinet_firewall_send(m);
1631#else
1632	(void)replyto;		/* don't warn about unused arg */
1633#endif
1634
1635	m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1636	m->m_data += max_linkhdr;
1637
1638	ip = mtod(m, struct ip *);
1639	bzero(ip, m->m_len);
1640	tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1641	ip->ip_p = IPPROTO_TCP;
1642	tcp->th_off = 5;
1643	/*
1644	 * Assume we are sending a RST (or a keepalive in the reverse
1645	 * direction), swap src and destination addresses and ports.
1646	 */
1647	ip->ip_src.s_addr = htonl(id->dst_ip);
1648	ip->ip_dst.s_addr = htonl(id->src_ip);
1649	tcp->th_sport = htons(id->dst_port);
1650	tcp->th_dport = htons(id->src_port);
1651	if (flags & TH_RST) {	/* we are sending a RST */
1652		if (flags & TH_ACK) {
1653			tcp->th_seq = htonl(ack);
1654			tcp->th_ack = htonl(0);
1655			tcp->th_flags = TH_RST;
1656		} else {
1657			if (flags & TH_SYN)
1658				seq++;
1659			tcp->th_seq = htonl(0);
1660			tcp->th_ack = htonl(seq);
1661			tcp->th_flags = TH_RST | TH_ACK;
1662		}
1663	} else {
1664		/*
1665		 * We are sending a keepalive. flags & TH_SYN determines
1666		 * the direction, forward if set, reverse if clear.
1667		 * NOTE: seq and ack are always assumed to be correct
1668		 * as set by the caller. This may be confusing...
1669		 */
1670		if (flags & TH_SYN) {
1671			/*
1672			 * we have to rewrite the correct addresses!
1673			 */
1674			ip->ip_dst.s_addr = htonl(id->dst_ip);
1675			ip->ip_src.s_addr = htonl(id->src_ip);
1676			tcp->th_dport = htons(id->dst_port);
1677			tcp->th_sport = htons(id->src_port);
1678		}
1679		tcp->th_seq = htonl(seq);
1680		tcp->th_ack = htonl(ack);
1681		tcp->th_flags = TH_ACK;
1682	}
1683	/*
1684	 * set ip_len to the payload size so we can compute
1685	 * the tcp checksum on the pseudoheader
1686	 * XXX check this, could save a couple of words ?
1687	 */
1688	ip->ip_len = htons(sizeof(struct tcphdr));
1689	tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1690	/*
1691	 * now fill fields left out earlier
1692	 */
1693	ip->ip_ttl = V_ip_defttl;
1694	ip->ip_len = m->m_pkthdr.len;
1695	m->m_flags |= M_SKIP_FIREWALL;
1696	return (m);
1697}
1698
1699/*
1700 * sends a reject message, consuming the mbuf passed as an argument.
1701 */
1702static void
1703send_reject(struct ip_fw_args *args, int code, int ip_len, struct ip *ip)
1704{
1705
1706#if 0
1707	/* XXX When ip is not guaranteed to be at mtod() we will
1708	 * need to account for this */
1709	 * The mbuf will however be thrown away so we can adjust it.
1710	 * Remember we did an m_pullup on it already so we
1711	 * can make some assumptions about contiguousness.
1712	 */
1713	if (args->L3offset)
1714		m_adj(m, args->L3offset);
1715#endif
1716	if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1717		/* We need the IP header in host order for icmp_error(). */
1718		if (args->eh != NULL) {
1719			ip->ip_len = ntohs(ip->ip_len);
1720			ip->ip_off = ntohs(ip->ip_off);
1721		}
1722		icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1723	} else if (args->f_id.proto == IPPROTO_TCP) {
1724		struct tcphdr *const tcp =
1725		    L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1726		if ( (tcp->th_flags & TH_RST) == 0) {
1727			struct mbuf *m;
1728			m = send_pkt(args->m, &(args->f_id),
1729				ntohl(tcp->th_seq), ntohl(tcp->th_ack),
1730				tcp->th_flags | TH_RST);
1731			if (m != NULL)
1732				ip_output(m, NULL, NULL, 0, NULL, NULL);
1733		}
1734		m_freem(args->m);
1735	} else
1736		m_freem(args->m);
1737	args->m = NULL;
1738}
1739
1740/**
1741 *
1742 * Given an ip_fw *, lookup_next_rule will return a pointer
1743 * to the next rule, which can be either the jump
1744 * target (for skipto instructions) or the next one in the list (in
1745 * all other cases including a missing jump target).
1746 * The result is also written in the "next_rule" field of the rule.
1747 * Backward jumps are not allowed, so start looking from the next
1748 * rule...
1749 *
1750 * This never returns NULL -- in case we do not have an exact match,
1751 * the next rule is returned. When the ruleset is changed,
1752 * pointers are flushed so we are always correct.
1753 */
1754
1755static struct ip_fw *
1756lookup_next_rule(struct ip_fw *me, u_int32_t tablearg)
1757{
1758	struct ip_fw *rule = NULL;
1759	ipfw_insn *cmd;
1760	u_int16_t	rulenum;
1761
1762	/* look for action, in case it is a skipto */
1763	cmd = ACTION_PTR(me);
1764	if (cmd->opcode == O_LOG)
1765		cmd += F_LEN(cmd);
1766	if (cmd->opcode == O_ALTQ)
1767		cmd += F_LEN(cmd);
1768	if (cmd->opcode == O_TAG)
1769		cmd += F_LEN(cmd);
1770	if (cmd->opcode == O_SKIPTO ) {
1771		if (tablearg != 0) {
1772			rulenum = (u_int16_t)tablearg;
1773		} else {
1774			rulenum = cmd->arg1;
1775		}
1776		for (rule = me->next; rule ; rule = rule->next) {
1777			if (rule->rulenum >= rulenum) {
1778				break;
1779			}
1780		}
1781	}
1782	if (rule == NULL)			/* failure or not a skipto */
1783		rule = me->next;
1784	me->next_rule = rule;
1785	return rule;
1786}
1787
1788static int
1789add_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1790    uint8_t mlen, uint32_t value)
1791{
1792	INIT_VNET_IPFW(curvnet);
1793	struct radix_node_head *rnh;
1794	struct table_entry *ent;
1795
1796	if (tbl >= IPFW_TABLES_MAX)
1797		return (EINVAL);
1798	rnh = ch->tables[tbl];
1799	ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO);
1800	if (ent == NULL)
1801		return (ENOMEM);
1802	ent->value = value;
1803	ent->addr.sin_len = ent->mask.sin_len = 8;
1804	ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1805	ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr;
1806	IPFW_WLOCK(&V_layer3_chain);
1807	if (rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent) ==
1808	    NULL) {
1809		IPFW_WUNLOCK(&V_layer3_chain);
1810		free(ent, M_IPFW_TBL);
1811		return (EEXIST);
1812	}
1813	IPFW_WUNLOCK(&V_layer3_chain);
1814	return (0);
1815}
1816
1817static int
1818del_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1819    uint8_t mlen)
1820{
1821	struct radix_node_head *rnh;
1822	struct table_entry *ent;
1823	struct sockaddr_in sa, mask;
1824
1825	if (tbl >= IPFW_TABLES_MAX)
1826		return (EINVAL);
1827	rnh = ch->tables[tbl];
1828	sa.sin_len = mask.sin_len = 8;
1829	mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1830	sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr;
1831	IPFW_WLOCK(ch);
1832	ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh);
1833	if (ent == NULL) {
1834		IPFW_WUNLOCK(ch);
1835		return (ESRCH);
1836	}
1837	IPFW_WUNLOCK(ch);
1838	free(ent, M_IPFW_TBL);
1839	return (0);
1840}
1841
1842static int
1843flush_table_entry(struct radix_node *rn, void *arg)
1844{
1845	struct radix_node_head * const rnh = arg;
1846	struct table_entry *ent;
1847
1848	ent = (struct table_entry *)
1849	    rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh);
1850	if (ent != NULL)
1851		free(ent, M_IPFW_TBL);
1852	return (0);
1853}
1854
1855static int
1856flush_table(struct ip_fw_chain *ch, uint16_t tbl)
1857{
1858	struct radix_node_head *rnh;
1859
1860	IPFW_WLOCK_ASSERT(ch);
1861
1862	if (tbl >= IPFW_TABLES_MAX)
1863		return (EINVAL);
1864	rnh = ch->tables[tbl];
1865	KASSERT(rnh != NULL, ("NULL IPFW table"));
1866	rnh->rnh_walktree(rnh, flush_table_entry, rnh);
1867	return (0);
1868}
1869
1870static void
1871flush_tables(struct ip_fw_chain *ch)
1872{
1873	uint16_t tbl;
1874
1875	IPFW_WLOCK_ASSERT(ch);
1876
1877	for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++)
1878		flush_table(ch, tbl);
1879}
1880
1881static int
1882init_tables(struct ip_fw_chain *ch)
1883{
1884	int i;
1885	uint16_t j;
1886
1887	for (i = 0; i < IPFW_TABLES_MAX; i++) {
1888		if (!rn_inithead((void **)&ch->tables[i], 32)) {
1889			for (j = 0; j < i; j++) {
1890				(void) flush_table(ch, j);
1891			}
1892			return (ENOMEM);
1893		}
1894	}
1895	return (0);
1896}
1897
1898static int
1899lookup_table(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1900    uint32_t *val)
1901{
1902	struct radix_node_head *rnh;
1903	struct table_entry *ent;
1904	struct sockaddr_in sa;
1905
1906	if (tbl >= IPFW_TABLES_MAX)
1907		return (0);
1908	rnh = ch->tables[tbl];
1909	sa.sin_len = 8;
1910	sa.sin_addr.s_addr = addr;
1911	ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh));
1912	if (ent != NULL) {
1913		*val = ent->value;
1914		return (1);
1915	}
1916	return (0);
1917}
1918
1919static int
1920count_table_entry(struct radix_node *rn, void *arg)
1921{
1922	u_int32_t * const cnt = arg;
1923
1924	(*cnt)++;
1925	return (0);
1926}
1927
1928static int
1929count_table(struct ip_fw_chain *ch, uint32_t tbl, uint32_t *cnt)
1930{
1931	struct radix_node_head *rnh;
1932
1933	if (tbl >= IPFW_TABLES_MAX)
1934		return (EINVAL);
1935	rnh = ch->tables[tbl];
1936	*cnt = 0;
1937	rnh->rnh_walktree(rnh, count_table_entry, cnt);
1938	return (0);
1939}
1940
1941static int
1942dump_table_entry(struct radix_node *rn, void *arg)
1943{
1944	struct table_entry * const n = (struct table_entry *)rn;
1945	ipfw_table * const tbl = arg;
1946	ipfw_table_entry *ent;
1947
1948	if (tbl->cnt == tbl->size)
1949		return (1);
1950	ent = &tbl->ent[tbl->cnt];
1951	ent->tbl = tbl->tbl;
1952	if (in_nullhost(n->mask.sin_addr))
1953		ent->masklen = 0;
1954	else
1955		ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr));
1956	ent->addr = n->addr.sin_addr.s_addr;
1957	ent->value = n->value;
1958	tbl->cnt++;
1959	return (0);
1960}
1961
1962static int
1963dump_table(struct ip_fw_chain *ch, ipfw_table *tbl)
1964{
1965	struct radix_node_head *rnh;
1966
1967	if (tbl->tbl >= IPFW_TABLES_MAX)
1968		return (EINVAL);
1969	rnh = ch->tables[tbl->tbl];
1970	tbl->cnt = 0;
1971	rnh->rnh_walktree(rnh, dump_table_entry, tbl);
1972	return (0);
1973}
1974
1975static void
1976fill_ugid_cache(struct inpcb *inp, struct ip_fw_ugid *ugp)
1977{
1978	struct ucred *cr;
1979
1980	cr = inp->inp_cred;
1981	ugp->fw_prid = jailed(cr) ? cr->cr_prison->pr_id : -1;
1982	ugp->fw_uid = cr->cr_uid;
1983	ugp->fw_ngroups = cr->cr_ngroups;
1984	bcopy(cr->cr_groups, ugp->fw_groups, sizeof(ugp->fw_groups));
1985}
1986
1987static int
1988check_uidgid(ipfw_insn_u32 *insn, int proto, struct ifnet *oif,
1989    struct in_addr dst_ip, u_int16_t dst_port, struct in_addr src_ip,
1990    u_int16_t src_port, struct ip_fw_ugid *ugp, int *ugid_lookupp,
1991    struct inpcb *inp)
1992{
1993	INIT_VNET_INET(curvnet);
1994	struct inpcbinfo *pi;
1995	int wildcard;
1996	struct inpcb *pcb;
1997	int match;
1998	gid_t *gp;
1999
2000	/*
2001	 * Check to see if the UDP or TCP stack supplied us with
2002	 * the PCB. If so, rather then holding a lock and looking
2003	 * up the PCB, we can use the one that was supplied.
2004	 */
2005	if (inp && *ugid_lookupp == 0) {
2006		INP_LOCK_ASSERT(inp);
2007		if (inp->inp_socket != NULL) {
2008			fill_ugid_cache(inp, ugp);
2009			*ugid_lookupp = 1;
2010		} else
2011			*ugid_lookupp = -1;
2012	}
2013	/*
2014	 * If we have already been here and the packet has no
2015	 * PCB entry associated with it, then we can safely
2016	 * assume that this is a no match.
2017	 */
2018	if (*ugid_lookupp == -1)
2019		return (0);
2020	if (proto == IPPROTO_TCP) {
2021		wildcard = 0;
2022		pi = &V_tcbinfo;
2023	} else if (proto == IPPROTO_UDP) {
2024		wildcard = INPLOOKUP_WILDCARD;
2025		pi = &V_udbinfo;
2026	} else
2027		return 0;
2028	match = 0;
2029	if (*ugid_lookupp == 0) {
2030		INP_INFO_RLOCK(pi);
2031		pcb =  (oif) ?
2032			in_pcblookup_hash(pi,
2033				dst_ip, htons(dst_port),
2034				src_ip, htons(src_port),
2035				wildcard, oif) :
2036			in_pcblookup_hash(pi,
2037				src_ip, htons(src_port),
2038				dst_ip, htons(dst_port),
2039				wildcard, NULL);
2040		if (pcb != NULL) {
2041			fill_ugid_cache(pcb, ugp);
2042			*ugid_lookupp = 1;
2043		}
2044		INP_INFO_RUNLOCK(pi);
2045		if (*ugid_lookupp == 0) {
2046			/*
2047			 * If the lookup did not yield any results, there
2048			 * is no sense in coming back and trying again. So
2049			 * we can set lookup to -1 and ensure that we wont
2050			 * bother the pcb system again.
2051			 */
2052			*ugid_lookupp = -1;
2053			return (0);
2054		}
2055	}
2056	if (insn->o.opcode == O_UID)
2057		match = (ugp->fw_uid == (uid_t)insn->d[0]);
2058	else if (insn->o.opcode == O_GID) {
2059		for (gp = ugp->fw_groups;
2060			gp < &ugp->fw_groups[ugp->fw_ngroups]; gp++)
2061			if (*gp == (gid_t)insn->d[0]) {
2062				match = 1;
2063				break;
2064			}
2065	} else if (insn->o.opcode == O_JAIL)
2066		match = (ugp->fw_prid == (int)insn->d[0]);
2067	return match;
2068}
2069
2070/*
2071 * The main check routine for the firewall.
2072 *
2073 * All arguments are in args so we can modify them and return them
2074 * back to the caller.
2075 *
2076 * Parameters:
2077 *
2078 *	args->m	(in/out) The packet; we set to NULL when/if we nuke it.
2079 *		Starts with the IP header.
2080 *	args->eh (in)	Mac header if present, or NULL for layer3 packet.
2081 *	args->L3offset	Number of bytes bypassed if we came from L2.
2082 *			e.g. often sizeof(eh)  ** NOTYET **
2083 *	args->oif	Outgoing interface, or NULL if packet is incoming.
2084 *		The incoming interface is in the mbuf. (in)
2085 *	args->divert_rule (in/out)
2086 *		Skip up to the first rule past this rule number;
2087 *		upon return, non-zero port number for divert or tee.
2088 *
2089 *	args->rule	Pointer to the last matching rule (in/out)
2090 *	args->next_hop	Socket we are forwarding to (out).
2091 *	args->f_id	Addresses grabbed from the packet (out)
2092 * 	args->cookie	a cookie depending on rule action
2093 *
2094 * Return value:
2095 *
2096 *	IP_FW_PASS	the packet must be accepted
2097 *	IP_FW_DENY	the packet must be dropped
2098 *	IP_FW_DIVERT	divert packet, port in m_tag
2099 *	IP_FW_TEE	tee packet, port in m_tag
2100 *	IP_FW_DUMMYNET	to dummynet, pipe in args->cookie
2101 *	IP_FW_NETGRAPH	into netgraph, cookie args->cookie
2102 *
2103 */
2104int
2105ipfw_chk(struct ip_fw_args *args)
2106{
2107	INIT_VNET_INET(curvnet);
2108	INIT_VNET_IPFW(curvnet);
2109
2110	/*
2111	 * Local variables holding state during the processing of a packet:
2112	 *
2113	 * IMPORTANT NOTE: to speed up the processing of rules, there
2114	 * are some assumption on the values of the variables, which
2115	 * are documented here. Should you change them, please check
2116	 * the implementation of the various instructions to make sure
2117	 * that they still work.
2118	 *
2119	 * args->eh	The MAC header. It is non-null for a layer2
2120	 *	packet, it is NULL for a layer-3 packet.
2121	 * **notyet**
2122	 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
2123	 *
2124	 * m | args->m	Pointer to the mbuf, as received from the caller.
2125	 *	It may change if ipfw_chk() does an m_pullup, or if it
2126	 *	consumes the packet because it calls send_reject().
2127	 *	XXX This has to change, so that ipfw_chk() never modifies
2128	 *	or consumes the buffer.
2129	 * ip	is the beginning of the ip(4 or 6) header.
2130	 *	Calculated by adding the L3offset to the start of data.
2131	 *	(Until we start using L3offset, the packet is
2132	 *	supposed to start with the ip header).
2133	 */
2134	struct mbuf *m = args->m;
2135	struct ip *ip = mtod(m, struct ip *);
2136
2137	/*
2138	 * For rules which contain uid/gid or jail constraints, cache
2139	 * a copy of the users credentials after the pcb lookup has been
2140	 * executed. This will speed up the processing of rules with
2141	 * these types of constraints, as well as decrease contention
2142	 * on pcb related locks.
2143	 */
2144	struct ip_fw_ugid fw_ugid_cache;
2145	int ugid_lookup = 0;
2146
2147	/*
2148	 * divinput_flags	If non-zero, set to the IP_FW_DIVERT_*_FLAG
2149	 *	associated with a packet input on a divert socket.  This
2150	 *	will allow to distinguish traffic and its direction when
2151	 *	it originates from a divert socket.
2152	 */
2153	u_int divinput_flags = 0;
2154
2155	/*
2156	 * oif | args->oif	If NULL, ipfw_chk has been called on the
2157	 *	inbound path (ether_input, ip_input).
2158	 *	If non-NULL, ipfw_chk has been called on the outbound path
2159	 *	(ether_output, ip_output).
2160	 */
2161	struct ifnet *oif = args->oif;
2162
2163	struct ip_fw *f = NULL;		/* matching rule */
2164	int retval = 0;
2165
2166	/*
2167	 * hlen	The length of the IP header.
2168	 */
2169	u_int hlen = 0;		/* hlen >0 means we have an IP pkt */
2170
2171	/*
2172	 * offset	The offset of a fragment. offset != 0 means that
2173	 *	we have a fragment at this offset of an IPv4 packet.
2174	 *	offset == 0 means that (if this is an IPv4 packet)
2175	 *	this is the first or only fragment.
2176	 *	For IPv6 offset == 0 means there is no Fragment Header.
2177	 *	If offset != 0 for IPv6 always use correct mask to
2178	 *	get the correct offset because we add IP6F_MORE_FRAG
2179	 *	to be able to dectect the first fragment which would
2180	 *	otherwise have offset = 0.
2181	 */
2182	u_short offset = 0;
2183
2184	/*
2185	 * Local copies of addresses. They are only valid if we have
2186	 * an IP packet.
2187	 *
2188	 * proto	The protocol. Set to 0 for non-ip packets,
2189	 *	or to the protocol read from the packet otherwise.
2190	 *	proto != 0 means that we have an IPv4 packet.
2191	 *
2192	 * src_port, dst_port	port numbers, in HOST format. Only
2193	 *	valid for TCP and UDP packets.
2194	 *
2195	 * src_ip, dst_ip	ip addresses, in NETWORK format.
2196	 *	Only valid for IPv4 packets.
2197	 */
2198	u_int8_t proto;
2199	u_int16_t src_port = 0, dst_port = 0;	/* NOTE: host format	*/
2200	struct in_addr src_ip, dst_ip;		/* NOTE: network format	*/
2201	u_int16_t ip_len=0;
2202	int pktlen;
2203	u_int16_t	etype = 0;	/* Host order stored ether type */
2204
2205	/*
2206	 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
2207	 * 	MATCH_NONE when checked and not matched (q = NULL),
2208	 *	MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
2209	 */
2210	int dyn_dir = MATCH_UNKNOWN;
2211	ipfw_dyn_rule *q = NULL;
2212	struct ip_fw_chain *chain = &V_layer3_chain;
2213	struct m_tag *mtag;
2214
2215	/*
2216	 * We store in ulp a pointer to the upper layer protocol header.
2217	 * In the ipv4 case this is easy to determine from the header,
2218	 * but for ipv6 we might have some additional headers in the middle.
2219	 * ulp is NULL if not found.
2220	 */
2221	void *ulp = NULL;		/* upper layer protocol pointer. */
2222	/* XXX ipv6 variables */
2223	int is_ipv6 = 0;
2224	u_int16_t ext_hd = 0;	/* bits vector for extension header filtering */
2225	/* end of ipv6 variables */
2226	int is_ipv4 = 0;
2227
2228	if (m->m_flags & M_SKIP_FIREWALL)
2229		return (IP_FW_PASS);	/* accept */
2230
2231	pktlen = m->m_pkthdr.len;
2232	args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
2233	proto = args->f_id.proto = 0;	/* mark f_id invalid */
2234		/* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
2235
2236/*
2237 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
2238 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
2239 * pointer might become stale after other pullups (but we never use it
2240 * this way).
2241 */
2242#define PULLUP_TO(len, p, T)						\
2243do {									\
2244	int x = (len) + sizeof(T);					\
2245	if ((m)->m_len < x) {						\
2246		args->m = m = m_pullup(m, x);				\
2247		if (m == NULL)						\
2248			goto pullup_failed;				\
2249	}								\
2250	p = (mtod(m, char *) + (len));					\
2251} while (0)
2252
2253	/*
2254	 * if we have an ether header,
2255	 */
2256	if (args->eh)
2257		etype = ntohs(args->eh->ether_type);
2258
2259	/* Identify IP packets and fill up variables. */
2260	if (pktlen >= sizeof(struct ip6_hdr) &&
2261	    (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
2262		struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
2263		is_ipv6 = 1;
2264		args->f_id.addr_type = 6;
2265		hlen = sizeof(struct ip6_hdr);
2266		proto = ip6->ip6_nxt;
2267
2268		/* Search extension headers to find upper layer protocols */
2269		while (ulp == NULL) {
2270			switch (proto) {
2271			case IPPROTO_ICMPV6:
2272				PULLUP_TO(hlen, ulp, struct icmp6_hdr);
2273				args->f_id.flags = ICMP6(ulp)->icmp6_type;
2274				break;
2275
2276			case IPPROTO_TCP:
2277				PULLUP_TO(hlen, ulp, struct tcphdr);
2278				dst_port = TCP(ulp)->th_dport;
2279				src_port = TCP(ulp)->th_sport;
2280				args->f_id.flags = TCP(ulp)->th_flags;
2281				break;
2282
2283			case IPPROTO_SCTP:
2284				PULLUP_TO(hlen, ulp, struct sctphdr);
2285				src_port = SCTP(ulp)->src_port;
2286				dst_port = SCTP(ulp)->dest_port;
2287				break;
2288
2289			case IPPROTO_UDP:
2290				PULLUP_TO(hlen, ulp, struct udphdr);
2291				dst_port = UDP(ulp)->uh_dport;
2292				src_port = UDP(ulp)->uh_sport;
2293				break;
2294
2295			case IPPROTO_HOPOPTS:	/* RFC 2460 */
2296				PULLUP_TO(hlen, ulp, struct ip6_hbh);
2297				ext_hd |= EXT_HOPOPTS;
2298				hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2299				proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2300				ulp = NULL;
2301				break;
2302
2303			case IPPROTO_ROUTING:	/* RFC 2460 */
2304				PULLUP_TO(hlen, ulp, struct ip6_rthdr);
2305				switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
2306				case 0:
2307					ext_hd |= EXT_RTHDR0;
2308					break;
2309				case 2:
2310					ext_hd |= EXT_RTHDR2;
2311					break;
2312				default:
2313					printf("IPFW2: IPV6 - Unknown Routing "
2314					    "Header type(%d)\n",
2315					    ((struct ip6_rthdr *)ulp)->ip6r_type);
2316					if (V_fw_deny_unknown_exthdrs)
2317					    return (IP_FW_DENY);
2318					break;
2319				}
2320				ext_hd |= EXT_ROUTING;
2321				hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
2322				proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
2323				ulp = NULL;
2324				break;
2325
2326			case IPPROTO_FRAGMENT:	/* RFC 2460 */
2327				PULLUP_TO(hlen, ulp, struct ip6_frag);
2328				ext_hd |= EXT_FRAGMENT;
2329				hlen += sizeof (struct ip6_frag);
2330				proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
2331				offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
2332					IP6F_OFF_MASK;
2333				/* Add IP6F_MORE_FRAG for offset of first
2334				 * fragment to be != 0. */
2335				offset |= ((struct ip6_frag *)ulp)->ip6f_offlg &
2336					IP6F_MORE_FRAG;
2337				if (offset == 0) {
2338					printf("IPFW2: IPV6 - Invalid Fragment "
2339					    "Header\n");
2340					if (V_fw_deny_unknown_exthdrs)
2341					    return (IP_FW_DENY);
2342					break;
2343				}
2344				args->f_id.frag_id6 =
2345				    ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
2346				ulp = NULL;
2347				break;
2348
2349			case IPPROTO_DSTOPTS:	/* RFC 2460 */
2350				PULLUP_TO(hlen, ulp, struct ip6_hbh);
2351				ext_hd |= EXT_DSTOPTS;
2352				hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2353				proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2354				ulp = NULL;
2355				break;
2356
2357			case IPPROTO_AH:	/* RFC 2402 */
2358				PULLUP_TO(hlen, ulp, struct ip6_ext);
2359				ext_hd |= EXT_AH;
2360				hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
2361				proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
2362				ulp = NULL;
2363				break;
2364
2365			case IPPROTO_ESP:	/* RFC 2406 */
2366				PULLUP_TO(hlen, ulp, uint32_t);	/* SPI, Seq# */
2367				/* Anything past Seq# is variable length and
2368				 * data past this ext. header is encrypted. */
2369				ext_hd |= EXT_ESP;
2370				break;
2371
2372			case IPPROTO_NONE:	/* RFC 2460 */
2373				/*
2374				 * Packet ends here, and IPv6 header has
2375				 * already been pulled up. If ip6e_len!=0
2376				 * then octets must be ignored.
2377				 */
2378				ulp = ip; /* non-NULL to get out of loop. */
2379				break;
2380
2381			case IPPROTO_OSPFIGP:
2382				/* XXX OSPF header check? */
2383				PULLUP_TO(hlen, ulp, struct ip6_ext);
2384				break;
2385
2386			case IPPROTO_PIM:
2387				/* XXX PIM header check? */
2388				PULLUP_TO(hlen, ulp, struct pim);
2389				break;
2390
2391			case IPPROTO_CARP:
2392				PULLUP_TO(hlen, ulp, struct carp_header);
2393				if (((struct carp_header *)ulp)->carp_version !=
2394				    CARP_VERSION)
2395					return (IP_FW_DENY);
2396				if (((struct carp_header *)ulp)->carp_type !=
2397				    CARP_ADVERTISEMENT)
2398					return (IP_FW_DENY);
2399				break;
2400
2401			case IPPROTO_IPV6:	/* RFC 2893 */
2402				PULLUP_TO(hlen, ulp, struct ip6_hdr);
2403				break;
2404
2405			case IPPROTO_IPV4:	/* RFC 2893 */
2406				PULLUP_TO(hlen, ulp, struct ip);
2407				break;
2408
2409			default:
2410				printf("IPFW2: IPV6 - Unknown Extension "
2411				    "Header(%d), ext_hd=%x\n", proto, ext_hd);
2412				if (V_fw_deny_unknown_exthdrs)
2413				    return (IP_FW_DENY);
2414				PULLUP_TO(hlen, ulp, struct ip6_ext);
2415				break;
2416			} /*switch */
2417		}
2418		ip = mtod(m, struct ip *);
2419		ip6 = (struct ip6_hdr *)ip;
2420		args->f_id.src_ip6 = ip6->ip6_src;
2421		args->f_id.dst_ip6 = ip6->ip6_dst;
2422		args->f_id.src_ip = 0;
2423		args->f_id.dst_ip = 0;
2424		args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
2425	} else if (pktlen >= sizeof(struct ip) &&
2426	    (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
2427	    	is_ipv4 = 1;
2428		hlen = ip->ip_hl << 2;
2429		args->f_id.addr_type = 4;
2430
2431		/*
2432		 * Collect parameters into local variables for faster matching.
2433		 */
2434		proto = ip->ip_p;
2435		src_ip = ip->ip_src;
2436		dst_ip = ip->ip_dst;
2437		if (args->eh != NULL) { /* layer 2 packets are as on the wire */
2438			offset = ntohs(ip->ip_off) & IP_OFFMASK;
2439			ip_len = ntohs(ip->ip_len);
2440		} else {
2441			offset = ip->ip_off & IP_OFFMASK;
2442			ip_len = ip->ip_len;
2443		}
2444		pktlen = ip_len < pktlen ? ip_len : pktlen;
2445
2446		if (offset == 0) {
2447			switch (proto) {
2448			case IPPROTO_TCP:
2449				PULLUP_TO(hlen, ulp, struct tcphdr);
2450				dst_port = TCP(ulp)->th_dport;
2451				src_port = TCP(ulp)->th_sport;
2452				args->f_id.flags = TCP(ulp)->th_flags;
2453				break;
2454
2455			case IPPROTO_UDP:
2456				PULLUP_TO(hlen, ulp, struct udphdr);
2457				dst_port = UDP(ulp)->uh_dport;
2458				src_port = UDP(ulp)->uh_sport;
2459				break;
2460
2461			case IPPROTO_ICMP:
2462				PULLUP_TO(hlen, ulp, struct icmphdr);
2463				args->f_id.flags = ICMP(ulp)->icmp_type;
2464				break;
2465
2466			default:
2467				break;
2468			}
2469		}
2470
2471		ip = mtod(m, struct ip *);
2472		args->f_id.src_ip = ntohl(src_ip.s_addr);
2473		args->f_id.dst_ip = ntohl(dst_ip.s_addr);
2474	}
2475#undef PULLUP_TO
2476	if (proto) { /* we may have port numbers, store them */
2477		args->f_id.proto = proto;
2478		args->f_id.src_port = src_port = ntohs(src_port);
2479		args->f_id.dst_port = dst_port = ntohs(dst_port);
2480	}
2481
2482	IPFW_RLOCK(chain);
2483	mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
2484	if (args->rule) {
2485		/*
2486		 * Packet has already been tagged. Look for the next rule
2487		 * to restart processing.
2488		 *
2489		 * If fw_one_pass != 0 then just accept it.
2490		 * XXX should not happen here, but optimized out in
2491		 * the caller.
2492		 */
2493		if (V_fw_one_pass) {
2494			IPFW_RUNLOCK(chain);
2495			return (IP_FW_PASS);
2496		}
2497
2498		f = args->rule->next_rule;
2499		if (f == NULL)
2500			f = lookup_next_rule(args->rule, 0);
2501	} else {
2502		/*
2503		 * Find the starting rule. It can be either the first
2504		 * one, or the one after divert_rule if asked so.
2505		 */
2506		int skipto = mtag ? divert_cookie(mtag) : 0;
2507
2508		f = chain->rules;
2509		if (args->eh == NULL && skipto != 0) {
2510			if (skipto >= IPFW_DEFAULT_RULE) {
2511				IPFW_RUNLOCK(chain);
2512				return (IP_FW_DENY); /* invalid */
2513			}
2514			while (f && f->rulenum <= skipto)
2515				f = f->next;
2516			if (f == NULL) {	/* drop packet */
2517				IPFW_RUNLOCK(chain);
2518				return (IP_FW_DENY);
2519			}
2520		}
2521	}
2522	/* reset divert rule to avoid confusion later */
2523	if (mtag) {
2524		divinput_flags = divert_info(mtag) &
2525		    (IP_FW_DIVERT_OUTPUT_FLAG | IP_FW_DIVERT_LOOPBACK_FLAG);
2526		m_tag_delete(m, mtag);
2527	}
2528
2529	/*
2530	 * Now scan the rules, and parse microinstructions for each rule.
2531	 */
2532	for (; f; f = f->next) {
2533		ipfw_insn *cmd;
2534		uint32_t tablearg = 0;
2535		int l, cmdlen, skip_or; /* skip rest of OR block */
2536
2537again:
2538		if (V_set_disable & (1 << f->set) )
2539			continue;
2540
2541		skip_or = 0;
2542		for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
2543		    l -= cmdlen, cmd += cmdlen) {
2544			int match;
2545
2546			/*
2547			 * check_body is a jump target used when we find a
2548			 * CHECK_STATE, and need to jump to the body of
2549			 * the target rule.
2550			 */
2551
2552check_body:
2553			cmdlen = F_LEN(cmd);
2554			/*
2555			 * An OR block (insn_1 || .. || insn_n) has the
2556			 * F_OR bit set in all but the last instruction.
2557			 * The first match will set "skip_or", and cause
2558			 * the following instructions to be skipped until
2559			 * past the one with the F_OR bit clear.
2560			 */
2561			if (skip_or) {		/* skip this instruction */
2562				if ((cmd->len & F_OR) == 0)
2563					skip_or = 0;	/* next one is good */
2564				continue;
2565			}
2566			match = 0; /* set to 1 if we succeed */
2567
2568			switch (cmd->opcode) {
2569			/*
2570			 * The first set of opcodes compares the packet's
2571			 * fields with some pattern, setting 'match' if a
2572			 * match is found. At the end of the loop there is
2573			 * logic to deal with F_NOT and F_OR flags associated
2574			 * with the opcode.
2575			 */
2576			case O_NOP:
2577				match = 1;
2578				break;
2579
2580			case O_FORWARD_MAC:
2581				printf("ipfw: opcode %d unimplemented\n",
2582				    cmd->opcode);
2583				break;
2584
2585			case O_GID:
2586			case O_UID:
2587			case O_JAIL:
2588				/*
2589				 * We only check offset == 0 && proto != 0,
2590				 * as this ensures that we have a
2591				 * packet with the ports info.
2592				 */
2593				if (offset!=0)
2594					break;
2595				if (is_ipv6) /* XXX to be fixed later */
2596					break;
2597				if (proto == IPPROTO_TCP ||
2598				    proto == IPPROTO_UDP)
2599					match = check_uidgid(
2600						    (ipfw_insn_u32 *)cmd,
2601						    proto, oif,
2602						    dst_ip, dst_port,
2603						    src_ip, src_port, &fw_ugid_cache,
2604						    &ugid_lookup, args->inp);
2605				break;
2606
2607			case O_RECV:
2608				match = iface_match(m->m_pkthdr.rcvif,
2609				    (ipfw_insn_if *)cmd);
2610				break;
2611
2612			case O_XMIT:
2613				match = iface_match(oif, (ipfw_insn_if *)cmd);
2614				break;
2615
2616			case O_VIA:
2617				match = iface_match(oif ? oif :
2618				    m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
2619				break;
2620
2621			case O_MACADDR2:
2622				if (args->eh != NULL) {	/* have MAC header */
2623					u_int32_t *want = (u_int32_t *)
2624						((ipfw_insn_mac *)cmd)->addr;
2625					u_int32_t *mask = (u_int32_t *)
2626						((ipfw_insn_mac *)cmd)->mask;
2627					u_int32_t *hdr = (u_int32_t *)args->eh;
2628
2629					match =
2630					    ( want[0] == (hdr[0] & mask[0]) &&
2631					      want[1] == (hdr[1] & mask[1]) &&
2632					      want[2] == (hdr[2] & mask[2]) );
2633				}
2634				break;
2635
2636			case O_MAC_TYPE:
2637				if (args->eh != NULL) {
2638					u_int16_t *p =
2639					    ((ipfw_insn_u16 *)cmd)->ports;
2640					int i;
2641
2642					for (i = cmdlen - 1; !match && i>0;
2643					    i--, p += 2)
2644						match = (etype >= p[0] &&
2645						    etype <= p[1]);
2646				}
2647				break;
2648
2649			case O_FRAG:
2650				match = (offset != 0);
2651				break;
2652
2653			case O_IN:	/* "out" is "not in" */
2654				match = (oif == NULL);
2655				break;
2656
2657			case O_LAYER2:
2658				match = (args->eh != NULL);
2659				break;
2660
2661			case O_DIVERTED:
2662				match = (cmd->arg1 & 1 && divinput_flags &
2663				    IP_FW_DIVERT_LOOPBACK_FLAG) ||
2664					(cmd->arg1 & 2 && divinput_flags &
2665				    IP_FW_DIVERT_OUTPUT_FLAG);
2666				break;
2667
2668			case O_PROTO:
2669				/*
2670				 * We do not allow an arg of 0 so the
2671				 * check of "proto" only suffices.
2672				 */
2673				match = (proto == cmd->arg1);
2674				break;
2675
2676			case O_IP_SRC:
2677				match = is_ipv4 &&
2678				    (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2679				    src_ip.s_addr);
2680				break;
2681
2682			case O_IP_SRC_LOOKUP:
2683			case O_IP_DST_LOOKUP:
2684				if (is_ipv4) {
2685				    uint32_t a =
2686					(cmd->opcode == O_IP_DST_LOOKUP) ?
2687					    dst_ip.s_addr : src_ip.s_addr;
2688				    uint32_t v;
2689
2690				    match = lookup_table(chain, cmd->arg1, a,
2691					&v);
2692				    if (!match)
2693					break;
2694				    if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
2695					match =
2696					    ((ipfw_insn_u32 *)cmd)->d[0] == v;
2697				    else
2698					tablearg = v;
2699				}
2700				break;
2701
2702			case O_IP_SRC_MASK:
2703			case O_IP_DST_MASK:
2704				if (is_ipv4) {
2705				    uint32_t a =
2706					(cmd->opcode == O_IP_DST_MASK) ?
2707					    dst_ip.s_addr : src_ip.s_addr;
2708				    uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
2709				    int i = cmdlen-1;
2710
2711				    for (; !match && i>0; i-= 2, p+= 2)
2712					match = (p[0] == (a & p[1]));
2713				}
2714				break;
2715
2716			case O_IP_SRC_ME:
2717				if (is_ipv4) {
2718					struct ifnet *tif;
2719
2720					INADDR_TO_IFP(src_ip, tif);
2721					match = (tif != NULL);
2722				}
2723				break;
2724
2725			case O_IP_DST_SET:
2726			case O_IP_SRC_SET:
2727				if (is_ipv4) {
2728					u_int32_t *d = (u_int32_t *)(cmd+1);
2729					u_int32_t addr =
2730					    cmd->opcode == O_IP_DST_SET ?
2731						args->f_id.dst_ip :
2732						args->f_id.src_ip;
2733
2734					    if (addr < d[0])
2735						    break;
2736					    addr -= d[0]; /* subtract base */
2737					    match = (addr < cmd->arg1) &&
2738						( d[ 1 + (addr>>5)] &
2739						  (1<<(addr & 0x1f)) );
2740				}
2741				break;
2742
2743			case O_IP_DST:
2744				match = is_ipv4 &&
2745				    (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2746				    dst_ip.s_addr);
2747				break;
2748
2749			case O_IP_DST_ME:
2750				if (is_ipv4) {
2751					struct ifnet *tif;
2752
2753					INADDR_TO_IFP(dst_ip, tif);
2754					match = (tif != NULL);
2755				}
2756				break;
2757
2758			case O_IP_SRCPORT:
2759			case O_IP_DSTPORT:
2760				/*
2761				 * offset == 0 && proto != 0 is enough
2762				 * to guarantee that we have a
2763				 * packet with port info.
2764				 */
2765				if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2766				    && offset == 0) {
2767					u_int16_t x =
2768					    (cmd->opcode == O_IP_SRCPORT) ?
2769						src_port : dst_port ;
2770					u_int16_t *p =
2771					    ((ipfw_insn_u16 *)cmd)->ports;
2772					int i;
2773
2774					for (i = cmdlen - 1; !match && i>0;
2775					    i--, p += 2)
2776						match = (x>=p[0] && x<=p[1]);
2777				}
2778				break;
2779
2780			case O_ICMPTYPE:
2781				match = (offset == 0 && proto==IPPROTO_ICMP &&
2782				    icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
2783				break;
2784
2785#ifdef INET6
2786			case O_ICMP6TYPE:
2787				match = is_ipv6 && offset == 0 &&
2788				    proto==IPPROTO_ICMPV6 &&
2789				    icmp6type_match(
2790					ICMP6(ulp)->icmp6_type,
2791					(ipfw_insn_u32 *)cmd);
2792				break;
2793#endif /* INET6 */
2794
2795			case O_IPOPT:
2796				match = (is_ipv4 &&
2797				    ipopts_match(ip, cmd) );
2798				break;
2799
2800			case O_IPVER:
2801				match = (is_ipv4 &&
2802				    cmd->arg1 == ip->ip_v);
2803				break;
2804
2805			case O_IPID:
2806			case O_IPLEN:
2807			case O_IPTTL:
2808				if (is_ipv4) {	/* only for IP packets */
2809				    uint16_t x;
2810				    uint16_t *p;
2811				    int i;
2812
2813				    if (cmd->opcode == O_IPLEN)
2814					x = ip_len;
2815				    else if (cmd->opcode == O_IPTTL)
2816					x = ip->ip_ttl;
2817				    else /* must be IPID */
2818					x = ntohs(ip->ip_id);
2819				    if (cmdlen == 1) {
2820					match = (cmd->arg1 == x);
2821					break;
2822				    }
2823				    /* otherwise we have ranges */
2824				    p = ((ipfw_insn_u16 *)cmd)->ports;
2825				    i = cmdlen - 1;
2826				    for (; !match && i>0; i--, p += 2)
2827					match = (x >= p[0] && x <= p[1]);
2828				}
2829				break;
2830
2831			case O_IPPRECEDENCE:
2832				match = (is_ipv4 &&
2833				    (cmd->arg1 == (ip->ip_tos & 0xe0)) );
2834				break;
2835
2836			case O_IPTOS:
2837				match = (is_ipv4 &&
2838				    flags_match(cmd, ip->ip_tos));
2839				break;
2840
2841			case O_TCPDATALEN:
2842				if (proto == IPPROTO_TCP && offset == 0) {
2843				    struct tcphdr *tcp;
2844				    uint16_t x;
2845				    uint16_t *p;
2846				    int i;
2847
2848				    tcp = TCP(ulp);
2849				    x = ip_len -
2850					((ip->ip_hl + tcp->th_off) << 2);
2851				    if (cmdlen == 1) {
2852					match = (cmd->arg1 == x);
2853					break;
2854				    }
2855				    /* otherwise we have ranges */
2856				    p = ((ipfw_insn_u16 *)cmd)->ports;
2857				    i = cmdlen - 1;
2858				    for (; !match && i>0; i--, p += 2)
2859					match = (x >= p[0] && x <= p[1]);
2860				}
2861				break;
2862
2863			case O_TCPFLAGS:
2864				match = (proto == IPPROTO_TCP && offset == 0 &&
2865				    flags_match(cmd, TCP(ulp)->th_flags));
2866				break;
2867
2868			case O_TCPOPTS:
2869				match = (proto == IPPROTO_TCP && offset == 0 &&
2870				    tcpopts_match(TCP(ulp), cmd));
2871				break;
2872
2873			case O_TCPSEQ:
2874				match = (proto == IPPROTO_TCP && offset == 0 &&
2875				    ((ipfw_insn_u32 *)cmd)->d[0] ==
2876					TCP(ulp)->th_seq);
2877				break;
2878
2879			case O_TCPACK:
2880				match = (proto == IPPROTO_TCP && offset == 0 &&
2881				    ((ipfw_insn_u32 *)cmd)->d[0] ==
2882					TCP(ulp)->th_ack);
2883				break;
2884
2885			case O_TCPWIN:
2886				match = (proto == IPPROTO_TCP && offset == 0 &&
2887				    cmd->arg1 == TCP(ulp)->th_win);
2888				break;
2889
2890			case O_ESTAB:
2891				/* reject packets which have SYN only */
2892				/* XXX should i also check for TH_ACK ? */
2893				match = (proto == IPPROTO_TCP && offset == 0 &&
2894				    (TCP(ulp)->th_flags &
2895				     (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2896				break;
2897
2898			case O_ALTQ: {
2899				struct pf_mtag *at;
2900				ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
2901
2902				match = 1;
2903				at = pf_find_mtag(m);
2904				if (at != NULL && at->qid != 0)
2905					break;
2906				at = pf_get_mtag(m);
2907				if (at == NULL) {
2908					/*
2909					 * Let the packet fall back to the
2910					 * default ALTQ.
2911					 */
2912					break;
2913				}
2914				at->qid = altq->qid;
2915				if (is_ipv4)
2916					at->af = AF_INET;
2917				else
2918					at->af = AF_LINK;
2919				at->hdr = ip;
2920				break;
2921			}
2922
2923			case O_LOG:
2924				if (V_fw_verbose)
2925					ipfw_log(f, hlen, args, m,
2926					    oif, offset, tablearg, ip);
2927				match = 1;
2928				break;
2929
2930			case O_PROB:
2931				match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
2932				break;
2933
2934			case O_VERREVPATH:
2935				/* Outgoing packets automatically pass/match */
2936				match = ((oif != NULL) ||
2937				    (m->m_pkthdr.rcvif == NULL) ||
2938				    (
2939#ifdef INET6
2940				    is_ipv6 ?
2941					verify_path6(&(args->f_id.src_ip6),
2942					    m->m_pkthdr.rcvif) :
2943#endif
2944				    verify_path(src_ip, m->m_pkthdr.rcvif,
2945				        args->f_id.fib)));
2946				break;
2947
2948			case O_VERSRCREACH:
2949				/* Outgoing packets automatically pass/match */
2950				match = (hlen > 0 && ((oif != NULL) ||
2951#ifdef INET6
2952				    is_ipv6 ?
2953				        verify_path6(&(args->f_id.src_ip6),
2954				            NULL) :
2955#endif
2956				    verify_path(src_ip, NULL, args->f_id.fib)));
2957				break;
2958
2959			case O_ANTISPOOF:
2960				/* Outgoing packets automatically pass/match */
2961				if (oif == NULL && hlen > 0 &&
2962				    (  (is_ipv4 && in_localaddr(src_ip))
2963#ifdef INET6
2964				    || (is_ipv6 &&
2965				        in6_localaddr(&(args->f_id.src_ip6)))
2966#endif
2967				    ))
2968					match =
2969#ifdef INET6
2970					    is_ipv6 ? verify_path6(
2971					        &(args->f_id.src_ip6),
2972					        m->m_pkthdr.rcvif) :
2973#endif
2974					    verify_path(src_ip,
2975					    	m->m_pkthdr.rcvif,
2976					        args->f_id.fib);
2977				else
2978					match = 1;
2979				break;
2980
2981			case O_IPSEC:
2982#ifdef IPSEC
2983				match = (m_tag_find(m,
2984				    PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
2985#endif
2986				/* otherwise no match */
2987				break;
2988
2989#ifdef INET6
2990			case O_IP6_SRC:
2991				match = is_ipv6 &&
2992				    IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
2993				    &((ipfw_insn_ip6 *)cmd)->addr6);
2994				break;
2995
2996			case O_IP6_DST:
2997				match = is_ipv6 &&
2998				IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
2999				    &((ipfw_insn_ip6 *)cmd)->addr6);
3000				break;
3001			case O_IP6_SRC_MASK:
3002			case O_IP6_DST_MASK:
3003				if (is_ipv6) {
3004					int i = cmdlen - 1;
3005					struct in6_addr p;
3006					struct in6_addr *d =
3007					    &((ipfw_insn_ip6 *)cmd)->addr6;
3008
3009					for (; !match && i > 0; d += 2,
3010					    i -= F_INSN_SIZE(struct in6_addr)
3011					    * 2) {
3012						p = (cmd->opcode ==
3013						    O_IP6_SRC_MASK) ?
3014						    args->f_id.src_ip6:
3015						    args->f_id.dst_ip6;
3016						APPLY_MASK(&p, &d[1]);
3017						match =
3018						    IN6_ARE_ADDR_EQUAL(&d[0],
3019						    &p);
3020					}
3021				}
3022				break;
3023
3024			case O_IP6_SRC_ME:
3025				match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
3026				break;
3027
3028			case O_IP6_DST_ME:
3029				match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
3030				break;
3031
3032			case O_FLOW6ID:
3033				match = is_ipv6 &&
3034				    flow6id_match(args->f_id.flow_id6,
3035				    (ipfw_insn_u32 *) cmd);
3036				break;
3037
3038			case O_EXT_HDR:
3039				match = is_ipv6 &&
3040				    (ext_hd & ((ipfw_insn *) cmd)->arg1);
3041				break;
3042
3043			case O_IP6:
3044				match = is_ipv6;
3045				break;
3046#endif
3047
3048			case O_IP4:
3049				match = is_ipv4;
3050				break;
3051
3052			case O_TAG: {
3053				uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3054				    tablearg : cmd->arg1;
3055
3056				/* Packet is already tagged with this tag? */
3057				mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
3058
3059				/* We have `untag' action when F_NOT flag is
3060				 * present. And we must remove this mtag from
3061				 * mbuf and reset `match' to zero (`match' will
3062				 * be inversed later).
3063				 * Otherwise we should allocate new mtag and
3064				 * push it into mbuf.
3065				 */
3066				if (cmd->len & F_NOT) { /* `untag' action */
3067					if (mtag != NULL)
3068						m_tag_delete(m, mtag);
3069				} else if (mtag == NULL) {
3070					if ((mtag = m_tag_alloc(MTAG_IPFW,
3071					    tag, 0, M_NOWAIT)) != NULL)
3072						m_tag_prepend(m, mtag);
3073				}
3074				match = (cmd->len & F_NOT) ? 0: 1;
3075				break;
3076			}
3077
3078			case O_FIB: /* try match the specified fib */
3079				if (args->f_id.fib == cmd->arg1)
3080					match = 1;
3081				break;
3082
3083			case O_TAGGED: {
3084				uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3085				    tablearg : cmd->arg1;
3086
3087				if (cmdlen == 1) {
3088					match = m_tag_locate(m, MTAG_IPFW,
3089					    tag, NULL) != NULL;
3090					break;
3091				}
3092
3093				/* we have ranges */
3094				for (mtag = m_tag_first(m);
3095				    mtag != NULL && !match;
3096				    mtag = m_tag_next(m, mtag)) {
3097					uint16_t *p;
3098					int i;
3099
3100					if (mtag->m_tag_cookie != MTAG_IPFW)
3101						continue;
3102
3103					p = ((ipfw_insn_u16 *)cmd)->ports;
3104					i = cmdlen - 1;
3105					for(; !match && i > 0; i--, p += 2)
3106						match =
3107						    mtag->m_tag_id >= p[0] &&
3108						    mtag->m_tag_id <= p[1];
3109				}
3110				break;
3111			}
3112
3113			/*
3114			 * The second set of opcodes represents 'actions',
3115			 * i.e. the terminal part of a rule once the packet
3116			 * matches all previous patterns.
3117			 * Typically there is only one action for each rule,
3118			 * and the opcode is stored at the end of the rule
3119			 * (but there are exceptions -- see below).
3120			 *
3121			 * In general, here we set retval and terminate the
3122			 * outer loop (would be a 'break 3' in some language,
3123			 * but we need to do a 'goto done').
3124			 *
3125			 * Exceptions:
3126			 * O_COUNT and O_SKIPTO actions:
3127			 *   instead of terminating, we jump to the next rule
3128			 *   ('goto next_rule', equivalent to a 'break 2'),
3129			 *   or to the SKIPTO target ('goto again' after
3130			 *   having set f, cmd and l), respectively.
3131			 *
3132			 * O_TAG, O_LOG and O_ALTQ action parameters:
3133			 *   perform some action and set match = 1;
3134			 *
3135			 * O_LIMIT and O_KEEP_STATE: these opcodes are
3136			 *   not real 'actions', and are stored right
3137			 *   before the 'action' part of the rule.
3138			 *   These opcodes try to install an entry in the
3139			 *   state tables; if successful, we continue with
3140			 *   the next opcode (match=1; break;), otherwise
3141			 *   the packet *   must be dropped
3142			 *   ('goto done' after setting retval);
3143			 *
3144			 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
3145			 *   cause a lookup of the state table, and a jump
3146			 *   to the 'action' part of the parent rule
3147			 *   ('goto check_body') if an entry is found, or
3148			 *   (CHECK_STATE only) a jump to the next rule if
3149			 *   the entry is not found ('goto next_rule').
3150			 *   The result of the lookup is cached to make
3151			 *   further instances of these opcodes are
3152			 *   effectively NOPs.
3153			 */
3154			case O_LIMIT:
3155			case O_KEEP_STATE:
3156				if (install_state(f,
3157				    (ipfw_insn_limit *)cmd, args, tablearg)) {
3158					retval = IP_FW_DENY;
3159					goto done; /* error/limit violation */
3160				}
3161				match = 1;
3162				break;
3163
3164			case O_PROBE_STATE:
3165			case O_CHECK_STATE:
3166				/*
3167				 * dynamic rules are checked at the first
3168				 * keep-state or check-state occurrence,
3169				 * with the result being stored in dyn_dir.
3170				 * The compiler introduces a PROBE_STATE
3171				 * instruction for us when we have a
3172				 * KEEP_STATE (because PROBE_STATE needs
3173				 * to be run first).
3174				 */
3175				if (dyn_dir == MATCH_UNKNOWN &&
3176				    (q = lookup_dyn_rule(&args->f_id,
3177				     &dyn_dir, proto == IPPROTO_TCP ?
3178					TCP(ulp) : NULL))
3179					!= NULL) {
3180					/*
3181					 * Found dynamic entry, update stats
3182					 * and jump to the 'action' part of
3183					 * the parent rule.
3184					 */
3185					q->pcnt++;
3186					q->bcnt += pktlen;
3187					f = q->rule;
3188					cmd = ACTION_PTR(f);
3189					l = f->cmd_len - f->act_ofs;
3190					IPFW_DYN_UNLOCK();
3191					goto check_body;
3192				}
3193				/*
3194				 * Dynamic entry not found. If CHECK_STATE,
3195				 * skip to next rule, if PROBE_STATE just
3196				 * ignore and continue with next opcode.
3197				 */
3198				if (cmd->opcode == O_CHECK_STATE)
3199					goto next_rule;
3200				match = 1;
3201				break;
3202
3203			case O_ACCEPT:
3204				retval = 0;	/* accept */
3205				goto done;
3206
3207			case O_PIPE:
3208			case O_QUEUE:
3209				args->rule = f; /* report matching rule */
3210				if (cmd->arg1 == IP_FW_TABLEARG)
3211					args->cookie = tablearg;
3212				else
3213					args->cookie = cmd->arg1;
3214				retval = IP_FW_DUMMYNET;
3215				goto done;
3216
3217			case O_DIVERT:
3218			case O_TEE: {
3219				struct divert_tag *dt;
3220
3221				if (args->eh) /* not on layer 2 */
3222					break;
3223				mtag = m_tag_get(PACKET_TAG_DIVERT,
3224						sizeof(struct divert_tag),
3225						M_NOWAIT);
3226				if (mtag == NULL) {
3227					/* XXX statistic */
3228					/* drop packet */
3229					IPFW_RUNLOCK(chain);
3230					return (IP_FW_DENY);
3231				}
3232				dt = (struct divert_tag *)(mtag+1);
3233				dt->cookie = f->rulenum;
3234				if (cmd->arg1 == IP_FW_TABLEARG)
3235					dt->info = tablearg;
3236				else
3237					dt->info = cmd->arg1;
3238				m_tag_prepend(m, mtag);
3239				retval = (cmd->opcode == O_DIVERT) ?
3240				    IP_FW_DIVERT : IP_FW_TEE;
3241				goto done;
3242			}
3243			case O_COUNT:
3244			case O_SKIPTO:
3245				f->pcnt++;	/* update stats */
3246				f->bcnt += pktlen;
3247				f->timestamp = time_uptime;
3248				if (cmd->opcode == O_COUNT)
3249					goto next_rule;
3250				/* handle skipto */
3251				if (cmd->arg1 == IP_FW_TABLEARG) {
3252					f = lookup_next_rule(f, tablearg);
3253				} else {
3254					if (f->next_rule == NULL)
3255						lookup_next_rule(f, 0);
3256					f = f->next_rule;
3257				}
3258				goto again;
3259
3260			case O_REJECT:
3261				/*
3262				 * Drop the packet and send a reject notice
3263				 * if the packet is not ICMP (or is an ICMP
3264				 * query), and it is not multicast/broadcast.
3265				 */
3266				if (hlen > 0 && is_ipv4 && offset == 0 &&
3267				    (proto != IPPROTO_ICMP ||
3268				     is_icmp_query(ICMP(ulp))) &&
3269				    !(m->m_flags & (M_BCAST|M_MCAST)) &&
3270				    !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
3271					send_reject(args, cmd->arg1, ip_len, ip);
3272					m = args->m;
3273				}
3274				/* FALLTHROUGH */
3275#ifdef INET6
3276			case O_UNREACH6:
3277				if (hlen > 0 && is_ipv6 &&
3278				    ((offset & IP6F_OFF_MASK) == 0) &&
3279				    (proto != IPPROTO_ICMPV6 ||
3280				     (is_icmp6_query(args->f_id.flags) == 1)) &&
3281				    !(m->m_flags & (M_BCAST|M_MCAST)) &&
3282				    !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
3283					send_reject6(
3284					    args, cmd->arg1, hlen,
3285					    (struct ip6_hdr *)ip);
3286					m = args->m;
3287				}
3288				/* FALLTHROUGH */
3289#endif
3290			case O_DENY:
3291				retval = IP_FW_DENY;
3292				goto done;
3293
3294			case O_FORWARD_IP: {
3295				struct sockaddr_in *sa;
3296				sa = &(((ipfw_insn_sa *)cmd)->sa);
3297				if (args->eh)	/* not valid on layer2 pkts */
3298					break;
3299				if (!q || dyn_dir == MATCH_FORWARD) {
3300					if (sa->sin_addr.s_addr == INADDR_ANY) {
3301						bcopy(sa, &args->hopstore,
3302							sizeof(*sa));
3303						args->hopstore.sin_addr.s_addr =
3304						    htonl(tablearg);
3305						args->next_hop =
3306						    &args->hopstore;
3307					} else {
3308						args->next_hop = sa;
3309					}
3310				}
3311				retval = IP_FW_PASS;
3312			    }
3313			    goto done;
3314
3315			case O_NETGRAPH:
3316			case O_NGTEE:
3317				args->rule = f;	/* report matching rule */
3318				if (cmd->arg1 == IP_FW_TABLEARG)
3319					args->cookie = tablearg;
3320				else
3321					args->cookie = cmd->arg1;
3322				retval = (cmd->opcode == O_NETGRAPH) ?
3323				    IP_FW_NETGRAPH : IP_FW_NGTEE;
3324				goto done;
3325
3326			case O_SETFIB:
3327				f->pcnt++;	/* update stats */
3328				f->bcnt += pktlen;
3329				f->timestamp = time_uptime;
3330				M_SETFIB(m, cmd->arg1);
3331				args->f_id.fib = cmd->arg1;
3332				goto next_rule;
3333
3334			case O_NAT: {
3335                        	struct cfg_nat *t;
3336                        	int nat_id;
3337
3338 				if (IPFW_NAT_LOADED) {
3339					args->rule = f; /* Report matching rule. */
3340					t = ((ipfw_insn_nat *)cmd)->nat;
3341					if (t == NULL) {
3342						nat_id = (cmd->arg1 == IP_FW_TABLEARG) ?
3343						    tablearg : cmd->arg1;
3344						LOOKUP_NAT(V_layer3_chain, nat_id, t);
3345						if (t == NULL) {
3346							retval = IP_FW_DENY;
3347							goto done;
3348						}
3349						if (cmd->arg1 != IP_FW_TABLEARG)
3350							((ipfw_insn_nat *)cmd)->nat = t;
3351					}
3352					retval = ipfw_nat_ptr(args, t, m);
3353				} else
3354					retval = IP_FW_DENY;
3355				goto done;
3356			}
3357
3358			default:
3359				panic("-- unknown opcode %d\n", cmd->opcode);
3360			} /* end of switch() on opcodes */
3361
3362			if (cmd->len & F_NOT)
3363				match = !match;
3364
3365			if (match) {
3366				if (cmd->len & F_OR)
3367					skip_or = 1;
3368			} else {
3369				if (!(cmd->len & F_OR)) /* not an OR block, */
3370					break;		/* try next rule    */
3371			}
3372
3373		}	/* end of inner for, scan opcodes */
3374
3375next_rule:;		/* try next rule		*/
3376
3377	}		/* end of outer for, scan rules */
3378	printf("ipfw: ouch!, skip past end of rules, denying packet\n");
3379	IPFW_RUNLOCK(chain);
3380	return (IP_FW_DENY);
3381
3382done:
3383	/* Update statistics */
3384	f->pcnt++;
3385	f->bcnt += pktlen;
3386	f->timestamp = time_uptime;
3387	IPFW_RUNLOCK(chain);
3388	return (retval);
3389
3390pullup_failed:
3391	if (V_fw_verbose)
3392		printf("ipfw: pullup failed\n");
3393	return (IP_FW_DENY);
3394}
3395
3396/*
3397 * When a rule is added/deleted, clear the next_rule pointers in all rules.
3398 * These will be reconstructed on the fly as packets are matched.
3399 */
3400static void
3401flush_rule_ptrs(struct ip_fw_chain *chain)
3402{
3403	struct ip_fw *rule;
3404
3405	IPFW_WLOCK_ASSERT(chain);
3406
3407	for (rule = chain->rules; rule; rule = rule->next)
3408		rule->next_rule = NULL;
3409}
3410
3411/*
3412 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
3413 * possibly create a rule number and add the rule to the list.
3414 * Update the rule_number in the input struct so the caller knows it as well.
3415 */
3416static int
3417add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
3418{
3419	INIT_VNET_IPFW(curvnet);
3420	struct ip_fw *rule, *f, *prev;
3421	int l = RULESIZE(input_rule);
3422
3423	if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
3424		return (EINVAL);
3425
3426	rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
3427	if (rule == NULL)
3428		return (ENOSPC);
3429
3430	bcopy(input_rule, rule, l);
3431
3432	rule->next = NULL;
3433	rule->next_rule = NULL;
3434
3435	rule->pcnt = 0;
3436	rule->bcnt = 0;
3437	rule->timestamp = 0;
3438
3439	IPFW_WLOCK(chain);
3440
3441	if (chain->rules == NULL) {	/* default rule */
3442		chain->rules = rule;
3443		goto done;
3444        }
3445
3446	/*
3447	 * If rulenum is 0, find highest numbered rule before the
3448	 * default rule, and add autoinc_step
3449	 */
3450	if (V_autoinc_step < 1)
3451		V_autoinc_step = 1;
3452	else if (V_autoinc_step > 1000)
3453		V_autoinc_step = 1000;
3454	if (rule->rulenum == 0) {
3455		/*
3456		 * locate the highest numbered rule before default
3457		 */
3458		for (f = chain->rules; f; f = f->next) {
3459			if (f->rulenum == IPFW_DEFAULT_RULE)
3460				break;
3461			rule->rulenum = f->rulenum;
3462		}
3463		if (rule->rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
3464			rule->rulenum += V_autoinc_step;
3465		input_rule->rulenum = rule->rulenum;
3466	}
3467
3468	/*
3469	 * Now insert the new rule in the right place in the sorted list.
3470	 */
3471	for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) {
3472		if (f->rulenum > rule->rulenum) { /* found the location */
3473			if (prev) {
3474				rule->next = f;
3475				prev->next = rule;
3476			} else { /* head insert */
3477				rule->next = chain->rules;
3478				chain->rules = rule;
3479			}
3480			break;
3481		}
3482	}
3483	flush_rule_ptrs(chain);
3484done:
3485	V_static_count++;
3486	V_static_len += l;
3487	IPFW_WUNLOCK(chain);
3488	DEB(printf("ipfw: installed rule %d, static count now %d\n",
3489		rule->rulenum, V_static_count);)
3490	return (0);
3491}
3492
3493/**
3494 * Remove a static rule (including derived * dynamic rules)
3495 * and place it on the ``reap list'' for later reclamation.
3496 * The caller is in charge of clearing rule pointers to avoid
3497 * dangling pointers.
3498 * @return a pointer to the next entry.
3499 * Arguments are not checked, so they better be correct.
3500 */
3501static struct ip_fw *
3502remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
3503    struct ip_fw *prev)
3504{
3505	INIT_VNET_IPFW(curvnet);
3506	struct ip_fw *n;
3507	int l = RULESIZE(rule);
3508
3509	IPFW_WLOCK_ASSERT(chain);
3510
3511	n = rule->next;
3512	IPFW_DYN_LOCK();
3513	remove_dyn_rule(rule, NULL /* force removal */);
3514	IPFW_DYN_UNLOCK();
3515	if (prev == NULL)
3516		chain->rules = n;
3517	else
3518		prev->next = n;
3519	V_static_count--;
3520	V_static_len -= l;
3521
3522	rule->next = chain->reap;
3523	chain->reap = rule;
3524
3525	return n;
3526}
3527
3528/**
3529 * Reclaim storage associated with a list of rules.  This is
3530 * typically the list created using remove_rule.
3531 */
3532static void
3533reap_rules(struct ip_fw *head)
3534{
3535	struct ip_fw *rule;
3536
3537	while ((rule = head) != NULL) {
3538		head = head->next;
3539		if (DUMMYNET_LOADED)
3540			ip_dn_ruledel_ptr(rule);
3541		free(rule, M_IPFW);
3542	}
3543}
3544
3545/*
3546 * Remove all rules from a chain (except rules in set RESVD_SET
3547 * unless kill_default = 1).  The caller is responsible for
3548 * reclaiming storage for the rules left in chain->reap.
3549 */
3550static void
3551free_chain(struct ip_fw_chain *chain, int kill_default)
3552{
3553	struct ip_fw *prev, *rule;
3554
3555	IPFW_WLOCK_ASSERT(chain);
3556
3557	flush_rule_ptrs(chain); /* more efficient to do outside the loop */
3558	for (prev = NULL, rule = chain->rules; rule ; )
3559		if (kill_default || rule->set != RESVD_SET)
3560			rule = remove_rule(chain, rule, prev);
3561		else {
3562			prev = rule;
3563			rule = rule->next;
3564		}
3565}
3566
3567/**
3568 * Remove all rules with given number, and also do set manipulation.
3569 * Assumes chain != NULL && *chain != NULL.
3570 *
3571 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
3572 * the next 8 bits are the new set, the top 8 bits are the command:
3573 *
3574 *	0	delete rules with given number
3575 *	1	delete rules with given set number
3576 *	2	move rules with given number to new set
3577 *	3	move rules with given set number to new set
3578 *	4	swap sets with given numbers
3579 *	5	delete rules with given number and with given set number
3580 */
3581static int
3582del_entry(struct ip_fw_chain *chain, u_int32_t arg)
3583{
3584	struct ip_fw *prev = NULL, *rule;
3585	u_int16_t rulenum;	/* rule or old_set */
3586	u_int8_t cmd, new_set;
3587
3588	rulenum = arg & 0xffff;
3589	cmd = (arg >> 24) & 0xff;
3590	new_set = (arg >> 16) & 0xff;
3591
3592	if (cmd > 5 || new_set > RESVD_SET)
3593		return EINVAL;
3594	if (cmd == 0 || cmd == 2 || cmd == 5) {
3595		if (rulenum >= IPFW_DEFAULT_RULE)
3596			return EINVAL;
3597	} else {
3598		if (rulenum > RESVD_SET)	/* old_set */
3599			return EINVAL;
3600	}
3601
3602	IPFW_WLOCK(chain);
3603	rule = chain->rules;
3604	chain->reap = NULL;
3605	switch (cmd) {
3606	case 0:	/* delete rules with given number */
3607		/*
3608		 * locate first rule to delete
3609		 */
3610		for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3611			;
3612		if (rule->rulenum != rulenum) {
3613			IPFW_WUNLOCK(chain);
3614			return EINVAL;
3615		}
3616
3617		/*
3618		 * flush pointers outside the loop, then delete all matching
3619		 * rules. prev remains the same throughout the cycle.
3620		 */
3621		flush_rule_ptrs(chain);
3622		while (rule->rulenum == rulenum)
3623			rule = remove_rule(chain, rule, prev);
3624		break;
3625
3626	case 1:	/* delete all rules with given set number */
3627		flush_rule_ptrs(chain);
3628		rule = chain->rules;
3629		while (rule->rulenum < IPFW_DEFAULT_RULE)
3630			if (rule->set == rulenum)
3631				rule = remove_rule(chain, rule, prev);
3632			else {
3633				prev = rule;
3634				rule = rule->next;
3635			}
3636		break;
3637
3638	case 2:	/* move rules with given number to new set */
3639		rule = chain->rules;
3640		for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3641			if (rule->rulenum == rulenum)
3642				rule->set = new_set;
3643		break;
3644
3645	case 3: /* move rules with given set number to new set */
3646		for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3647			if (rule->set == rulenum)
3648				rule->set = new_set;
3649		break;
3650
3651	case 4: /* swap two sets */
3652		for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3653			if (rule->set == rulenum)
3654				rule->set = new_set;
3655			else if (rule->set == new_set)
3656				rule->set = rulenum;
3657		break;
3658	case 5: /* delete rules with given number and with given set number.
3659		 * rulenum - given rule number;
3660		 * new_set - given set number.
3661		 */
3662		for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3663			;
3664		if (rule->rulenum != rulenum) {
3665			IPFW_WUNLOCK(chain);
3666			return (EINVAL);
3667		}
3668		flush_rule_ptrs(chain);
3669		while (rule->rulenum == rulenum) {
3670			if (rule->set == new_set)
3671				rule = remove_rule(chain, rule, prev);
3672			else {
3673				prev = rule;
3674				rule = rule->next;
3675			}
3676		}
3677	}
3678	/*
3679	 * Look for rules to reclaim.  We grab the list before
3680	 * releasing the lock then reclaim them w/o the lock to
3681	 * avoid a LOR with dummynet.
3682	 */
3683	rule = chain->reap;
3684	chain->reap = NULL;
3685	IPFW_WUNLOCK(chain);
3686	if (rule)
3687		reap_rules(rule);
3688	return 0;
3689}
3690
3691/*
3692 * Clear counters for a specific rule.
3693 * The enclosing "table" is assumed locked.
3694 */
3695static void
3696clear_counters(struct ip_fw *rule, int log_only)
3697{
3698	ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3699
3700	if (log_only == 0) {
3701		rule->bcnt = rule->pcnt = 0;
3702		rule->timestamp = 0;
3703	}
3704	if (l->o.opcode == O_LOG)
3705		l->log_left = l->max_log;
3706}
3707
3708/**
3709 * Reset some or all counters on firewall rules.
3710 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
3711 * the next 8 bits are the set number, the top 8 bits are the command:
3712 *	0	work with rules from all set's;
3713 *	1	work with rules only from specified set.
3714 * Specified rule number is zero if we want to clear all entries.
3715 * log_only is 1 if we only want to reset logs, zero otherwise.
3716 */
3717static int
3718zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
3719{
3720	INIT_VNET_IPFW(curvnet);
3721	struct ip_fw *rule;
3722	char *msg;
3723
3724	uint16_t rulenum = arg & 0xffff;
3725	uint8_t set = (arg >> 16) & 0xff;
3726	uint8_t cmd = (arg >> 24) & 0xff;
3727
3728	if (cmd > 1)
3729		return (EINVAL);
3730	if (cmd == 1 && set > RESVD_SET)
3731		return (EINVAL);
3732
3733	IPFW_WLOCK(chain);
3734	if (rulenum == 0) {
3735		V_norule_counter = 0;
3736		for (rule = chain->rules; rule; rule = rule->next) {
3737			/* Skip rules from another set. */
3738			if (cmd == 1 && rule->set != set)
3739				continue;
3740			clear_counters(rule, log_only);
3741		}
3742		msg = log_only ? "ipfw: All logging counts reset.\n" :
3743		    "ipfw: Accounting cleared.\n";
3744	} else {
3745		int cleared = 0;
3746		/*
3747		 * We can have multiple rules with the same number, so we
3748		 * need to clear them all.
3749		 */
3750		for (rule = chain->rules; rule; rule = rule->next)
3751			if (rule->rulenum == rulenum) {
3752				while (rule && rule->rulenum == rulenum) {
3753					if (cmd == 0 || rule->set == set)
3754						clear_counters(rule, log_only);
3755					rule = rule->next;
3756				}
3757				cleared = 1;
3758				break;
3759			}
3760		if (!cleared) {	/* we did not find any matching rules */
3761			IPFW_WUNLOCK(chain);
3762			return (EINVAL);
3763		}
3764		msg = log_only ? "ipfw: Entry %d logging count reset.\n" :
3765		    "ipfw: Entry %d cleared.\n";
3766	}
3767	IPFW_WUNLOCK(chain);
3768
3769	if (V_fw_verbose)
3770		log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
3771	return (0);
3772}
3773
3774/*
3775 * Check validity of the structure before insert.
3776 * Fortunately rules are simple, so this mostly need to check rule sizes.
3777 */
3778static int
3779check_ipfw_struct(struct ip_fw *rule, int size)
3780{
3781	int l, cmdlen = 0;
3782	int have_action=0;
3783	ipfw_insn *cmd;
3784
3785	if (size < sizeof(*rule)) {
3786		printf("ipfw: rule too short\n");
3787		return (EINVAL);
3788	}
3789	/* first, check for valid size */
3790	l = RULESIZE(rule);
3791	if (l != size) {
3792		printf("ipfw: size mismatch (have %d want %d)\n", size, l);
3793		return (EINVAL);
3794	}
3795	if (rule->act_ofs >= rule->cmd_len) {
3796		printf("ipfw: bogus action offset (%u > %u)\n",
3797		    rule->act_ofs, rule->cmd_len - 1);
3798		return (EINVAL);
3799	}
3800	/*
3801	 * Now go for the individual checks. Very simple ones, basically only
3802	 * instruction sizes.
3803	 */
3804	for (l = rule->cmd_len, cmd = rule->cmd ;
3805			l > 0 ; l -= cmdlen, cmd += cmdlen) {
3806		cmdlen = F_LEN(cmd);
3807		if (cmdlen > l) {
3808			printf("ipfw: opcode %d size truncated\n",
3809			    cmd->opcode);
3810			return EINVAL;
3811		}
3812		DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
3813		switch (cmd->opcode) {
3814		case O_PROBE_STATE:
3815		case O_KEEP_STATE:
3816		case O_PROTO:
3817		case O_IP_SRC_ME:
3818		case O_IP_DST_ME:
3819		case O_LAYER2:
3820		case O_IN:
3821		case O_FRAG:
3822		case O_DIVERTED:
3823		case O_IPOPT:
3824		case O_IPTOS:
3825		case O_IPPRECEDENCE:
3826		case O_IPVER:
3827		case O_TCPWIN:
3828		case O_TCPFLAGS:
3829		case O_TCPOPTS:
3830		case O_ESTAB:
3831		case O_VERREVPATH:
3832		case O_VERSRCREACH:
3833		case O_ANTISPOOF:
3834		case O_IPSEC:
3835#ifdef INET6
3836		case O_IP6_SRC_ME:
3837		case O_IP6_DST_ME:
3838		case O_EXT_HDR:
3839		case O_IP6:
3840#endif
3841		case O_IP4:
3842		case O_TAG:
3843			if (cmdlen != F_INSN_SIZE(ipfw_insn))
3844				goto bad_size;
3845			break;
3846
3847		case O_FIB:
3848			if (cmdlen != F_INSN_SIZE(ipfw_insn))
3849				goto bad_size;
3850			if (cmd->arg1 >= rt_numfibs) {
3851				printf("ipfw: invalid fib number %d\n",
3852					cmd->arg1);
3853				return EINVAL;
3854			}
3855			break;
3856
3857		case O_SETFIB:
3858			if (cmdlen != F_INSN_SIZE(ipfw_insn))
3859				goto bad_size;
3860			if (cmd->arg1 >= rt_numfibs) {
3861				printf("ipfw: invalid fib number %d\n",
3862					cmd->arg1);
3863				return EINVAL;
3864			}
3865			goto check_action;
3866
3867		case O_UID:
3868		case O_GID:
3869		case O_JAIL:
3870		case O_IP_SRC:
3871		case O_IP_DST:
3872		case O_TCPSEQ:
3873		case O_TCPACK:
3874		case O_PROB:
3875		case O_ICMPTYPE:
3876			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3877				goto bad_size;
3878			break;
3879
3880		case O_LIMIT:
3881			if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3882				goto bad_size;
3883			break;
3884
3885		case O_LOG:
3886			if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3887				goto bad_size;
3888
3889			((ipfw_insn_log *)cmd)->log_left =
3890			    ((ipfw_insn_log *)cmd)->max_log;
3891
3892			break;
3893
3894		case O_IP_SRC_MASK:
3895		case O_IP_DST_MASK:
3896			/* only odd command lengths */
3897			if ( !(cmdlen & 1) || cmdlen > 31)
3898				goto bad_size;
3899			break;
3900
3901		case O_IP_SRC_SET:
3902		case O_IP_DST_SET:
3903			if (cmd->arg1 == 0 || cmd->arg1 > 256) {
3904				printf("ipfw: invalid set size %d\n",
3905					cmd->arg1);
3906				return EINVAL;
3907			}
3908			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3909			    (cmd->arg1+31)/32 )
3910				goto bad_size;
3911			break;
3912
3913		case O_IP_SRC_LOOKUP:
3914		case O_IP_DST_LOOKUP:
3915			if (cmd->arg1 >= IPFW_TABLES_MAX) {
3916				printf("ipfw: invalid table number %d\n",
3917				    cmd->arg1);
3918				return (EINVAL);
3919			}
3920			if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
3921			    cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3922				goto bad_size;
3923			break;
3924
3925		case O_MACADDR2:
3926			if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
3927				goto bad_size;
3928			break;
3929
3930		case O_NOP:
3931		case O_IPID:
3932		case O_IPTTL:
3933		case O_IPLEN:
3934		case O_TCPDATALEN:
3935		case O_TAGGED:
3936			if (cmdlen < 1 || cmdlen > 31)
3937				goto bad_size;
3938			break;
3939
3940		case O_MAC_TYPE:
3941		case O_IP_SRCPORT:
3942		case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
3943			if (cmdlen < 2 || cmdlen > 31)
3944				goto bad_size;
3945			break;
3946
3947		case O_RECV:
3948		case O_XMIT:
3949		case O_VIA:
3950			if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
3951				goto bad_size;
3952			break;
3953
3954		case O_ALTQ:
3955			if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
3956				goto bad_size;
3957			break;
3958
3959		case O_PIPE:
3960		case O_QUEUE:
3961			if (cmdlen != F_INSN_SIZE(ipfw_insn))
3962				goto bad_size;
3963			goto check_action;
3964
3965		case O_FORWARD_IP:
3966#ifdef	IPFIREWALL_FORWARD
3967			if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
3968				goto bad_size;
3969			goto check_action;
3970#else
3971			return EINVAL;
3972#endif
3973
3974		case O_DIVERT:
3975		case O_TEE:
3976			if (ip_divert_ptr == NULL)
3977				return EINVAL;
3978			else
3979				goto check_size;
3980		case O_NETGRAPH:
3981		case O_NGTEE:
3982			if (!NG_IPFW_LOADED)
3983				return EINVAL;
3984			else
3985				goto check_size;
3986		case O_NAT:
3987			if (!IPFW_NAT_LOADED)
3988				return EINVAL;
3989			if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
3990 				goto bad_size;
3991 			goto check_action;
3992		case O_FORWARD_MAC: /* XXX not implemented yet */
3993		case O_CHECK_STATE:
3994		case O_COUNT:
3995		case O_ACCEPT:
3996		case O_DENY:
3997		case O_REJECT:
3998#ifdef INET6
3999		case O_UNREACH6:
4000#endif
4001		case O_SKIPTO:
4002check_size:
4003			if (cmdlen != F_INSN_SIZE(ipfw_insn))
4004				goto bad_size;
4005check_action:
4006			if (have_action) {
4007				printf("ipfw: opcode %d, multiple actions"
4008					" not allowed\n",
4009					cmd->opcode);
4010				return EINVAL;
4011			}
4012			have_action = 1;
4013			if (l != cmdlen) {
4014				printf("ipfw: opcode %d, action must be"
4015					" last opcode\n",
4016					cmd->opcode);
4017				return EINVAL;
4018			}
4019			break;
4020#ifdef INET6
4021		case O_IP6_SRC:
4022		case O_IP6_DST:
4023			if (cmdlen != F_INSN_SIZE(struct in6_addr) +
4024			    F_INSN_SIZE(ipfw_insn))
4025				goto bad_size;
4026			break;
4027
4028		case O_FLOW6ID:
4029			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
4030			    ((ipfw_insn_u32 *)cmd)->o.arg1)
4031				goto bad_size;
4032			break;
4033
4034		case O_IP6_SRC_MASK:
4035		case O_IP6_DST_MASK:
4036			if ( !(cmdlen & 1) || cmdlen > 127)
4037				goto bad_size;
4038			break;
4039		case O_ICMP6TYPE:
4040			if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
4041				goto bad_size;
4042			break;
4043#endif
4044
4045		default:
4046			switch (cmd->opcode) {
4047#ifndef INET6
4048			case O_IP6_SRC_ME:
4049			case O_IP6_DST_ME:
4050			case O_EXT_HDR:
4051			case O_IP6:
4052			case O_UNREACH6:
4053			case O_IP6_SRC:
4054			case O_IP6_DST:
4055			case O_FLOW6ID:
4056			case O_IP6_SRC_MASK:
4057			case O_IP6_DST_MASK:
4058			case O_ICMP6TYPE:
4059				printf("ipfw: no IPv6 support in kernel\n");
4060				return EPROTONOSUPPORT;
4061#endif
4062			default:
4063				printf("ipfw: opcode %d, unknown opcode\n",
4064					cmd->opcode);
4065				return EINVAL;
4066			}
4067		}
4068	}
4069	if (have_action == 0) {
4070		printf("ipfw: missing action\n");
4071		return EINVAL;
4072	}
4073	return 0;
4074
4075bad_size:
4076	printf("ipfw: opcode %d size %d wrong\n",
4077		cmd->opcode, cmdlen);
4078	return EINVAL;
4079}
4080
4081/*
4082 * Copy the static and dynamic rules to the supplied buffer
4083 * and return the amount of space actually used.
4084 */
4085static size_t
4086ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
4087{
4088	INIT_VNET_IPFW(curvnet);
4089	char *bp = buf;
4090	char *ep = bp + space;
4091	struct ip_fw *rule;
4092	int i;
4093	time_t	boot_seconds;
4094
4095        boot_seconds = boottime.tv_sec;
4096	/* XXX this can take a long time and locking will block packet flow */
4097	IPFW_RLOCK(chain);
4098	for (rule = chain->rules; rule ; rule = rule->next) {
4099		/*
4100		 * Verify the entry fits in the buffer in case the
4101		 * rules changed between calculating buffer space and
4102		 * now.  This would be better done using a generation
4103		 * number but should suffice for now.
4104		 */
4105		i = RULESIZE(rule);
4106		if (bp + i <= ep) {
4107			bcopy(rule, bp, i);
4108			/*
4109			 * XXX HACK. Store the disable mask in the "next"
4110			 * pointer in a wild attempt to keep the ABI the same.
4111			 * Why do we do this on EVERY rule?
4112			 */
4113			bcopy(&V_set_disable,
4114			    &(((struct ip_fw *)bp)->next_rule),
4115			    sizeof(V_set_disable));
4116			if (((struct ip_fw *)bp)->timestamp)
4117				((struct ip_fw *)bp)->timestamp += boot_seconds;
4118			bp += i;
4119		}
4120	}
4121	IPFW_RUNLOCK(chain);
4122	if (V_ipfw_dyn_v) {
4123		ipfw_dyn_rule *p, *last = NULL;
4124
4125		IPFW_DYN_LOCK();
4126		for (i = 0 ; i < V_curr_dyn_buckets; i++)
4127			for (p = V_ipfw_dyn_v[i] ; p != NULL; p = p->next) {
4128				if (bp + sizeof *p <= ep) {
4129					ipfw_dyn_rule *dst =
4130						(ipfw_dyn_rule *)bp;
4131					bcopy(p, dst, sizeof *p);
4132					bcopy(&(p->rule->rulenum), &(dst->rule),
4133					    sizeof(p->rule->rulenum));
4134					/*
4135					 * store set number into high word of
4136					 * dst->rule pointer.
4137					 */
4138					bcopy(&(p->rule->set),
4139					    (char *)&dst->rule +
4140					    sizeof(p->rule->rulenum),
4141					    sizeof(p->rule->set));
4142					/*
4143					 * store a non-null value in "next".
4144					 * The userland code will interpret a
4145					 * NULL here as a marker
4146					 * for the last dynamic rule.
4147					 */
4148					bcopy(&dst, &dst->next, sizeof(dst));
4149					last = dst;
4150					dst->expire =
4151					    TIME_LEQ(dst->expire, time_uptime) ?
4152						0 : dst->expire - time_uptime ;
4153					bp += sizeof(ipfw_dyn_rule);
4154				}
4155			}
4156		IPFW_DYN_UNLOCK();
4157		if (last != NULL) /* mark last dynamic rule */
4158			bzero(&last->next, sizeof(last));
4159	}
4160	return (bp - (char *)buf);
4161}
4162
4163
4164/**
4165 * {set|get}sockopt parser.
4166 */
4167static int
4168ipfw_ctl(struct sockopt *sopt)
4169{
4170#define	RULE_MAXSIZE	(256*sizeof(u_int32_t))
4171	INIT_VNET_IPFW(curvnet);
4172	int error;
4173	size_t size;
4174	struct ip_fw *buf, *rule;
4175	u_int32_t rulenum[2];
4176
4177	error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
4178	if (error)
4179		return (error);
4180
4181	/*
4182	 * Disallow modifications in really-really secure mode, but still allow
4183	 * the logging counters to be reset.
4184	 */
4185	if (sopt->sopt_name == IP_FW_ADD ||
4186	    (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
4187		error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
4188		if (error)
4189			return (error);
4190	}
4191
4192	error = 0;
4193
4194	switch (sopt->sopt_name) {
4195	case IP_FW_GET:
4196		/*
4197		 * pass up a copy of the current rules. Static rules
4198		 * come first (the last of which has number IPFW_DEFAULT_RULE),
4199		 * followed by a possibly empty list of dynamic rule.
4200		 * The last dynamic rule has NULL in the "next" field.
4201		 *
4202		 * Note that the calculated size is used to bound the
4203		 * amount of data returned to the user.  The rule set may
4204		 * change between calculating the size and returning the
4205		 * data in which case we'll just return what fits.
4206		 */
4207		size = V_static_len;	/* size of static rules */
4208		if (V_ipfw_dyn_v)		/* add size of dyn.rules */
4209			size += (V_dyn_count * sizeof(ipfw_dyn_rule));
4210
4211		/*
4212		 * XXX todo: if the user passes a short length just to know
4213		 * how much room is needed, do not bother filling up the
4214		 * buffer, just jump to the sooptcopyout.
4215		 */
4216		buf = malloc(size, M_TEMP, M_WAITOK);
4217		error = sooptcopyout(sopt, buf,
4218				ipfw_getrules(&V_layer3_chain, buf, size));
4219		free(buf, M_TEMP);
4220		break;
4221
4222	case IP_FW_FLUSH:
4223		/*
4224		 * Normally we cannot release the lock on each iteration.
4225		 * We could do it here only because we start from the head all
4226		 * the times so there is no risk of missing some entries.
4227		 * On the other hand, the risk is that we end up with
4228		 * a very inconsistent ruleset, so better keep the lock
4229		 * around the whole cycle.
4230		 *
4231		 * XXX this code can be improved by resetting the head of
4232		 * the list to point to the default rule, and then freeing
4233		 * the old list without the need for a lock.
4234		 */
4235
4236		IPFW_WLOCK(&V_layer3_chain);
4237		V_layer3_chain.reap = NULL;
4238		free_chain(&V_layer3_chain, 0 /* keep default rule */);
4239		rule = V_layer3_chain.reap;
4240		V_layer3_chain.reap = NULL;
4241		IPFW_WUNLOCK(&V_layer3_chain);
4242		if (rule != NULL)
4243			reap_rules(rule);
4244		break;
4245
4246	case IP_FW_ADD:
4247		rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
4248		error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
4249			sizeof(struct ip_fw) );
4250		if (error == 0)
4251			error = check_ipfw_struct(rule, sopt->sopt_valsize);
4252		if (error == 0) {
4253			error = add_rule(&V_layer3_chain, rule);
4254			size = RULESIZE(rule);
4255			if (!error && sopt->sopt_dir == SOPT_GET)
4256				error = sooptcopyout(sopt, rule, size);
4257		}
4258		free(rule, M_TEMP);
4259		break;
4260
4261	case IP_FW_DEL:
4262		/*
4263		 * IP_FW_DEL is used for deleting single rules or sets,
4264		 * and (ab)used to atomically manipulate sets. Argument size
4265		 * is used to distinguish between the two:
4266		 *    sizeof(u_int32_t)
4267		 *	delete single rule or set of rules,
4268		 *	or reassign rules (or sets) to a different set.
4269		 *    2*sizeof(u_int32_t)
4270		 *	atomic disable/enable sets.
4271		 *	first u_int32_t contains sets to be disabled,
4272		 *	second u_int32_t contains sets to be enabled.
4273		 */
4274		error = sooptcopyin(sopt, rulenum,
4275			2*sizeof(u_int32_t), sizeof(u_int32_t));
4276		if (error)
4277			break;
4278		size = sopt->sopt_valsize;
4279		if (size == sizeof(u_int32_t))	/* delete or reassign */
4280			error = del_entry(&V_layer3_chain, rulenum[0]);
4281		else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
4282			V_set_disable =
4283			    (V_set_disable | rulenum[0]) & ~rulenum[1] &
4284			    ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
4285		else
4286			error = EINVAL;
4287		break;
4288
4289	case IP_FW_ZERO:
4290	case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
4291		rulenum[0] = 0;
4292		if (sopt->sopt_val != 0) {
4293		    error = sooptcopyin(sopt, rulenum,
4294			    sizeof(u_int32_t), sizeof(u_int32_t));
4295		    if (error)
4296			break;
4297		}
4298		error = zero_entry(&V_layer3_chain, rulenum[0],
4299			sopt->sopt_name == IP_FW_RESETLOG);
4300		break;
4301
4302	case IP_FW_TABLE_ADD:
4303		{
4304			ipfw_table_entry ent;
4305
4306			error = sooptcopyin(sopt, &ent,
4307			    sizeof(ent), sizeof(ent));
4308			if (error)
4309				break;
4310			error = add_table_entry(&V_layer3_chain, ent.tbl,
4311			    ent.addr, ent.masklen, ent.value);
4312		}
4313		break;
4314
4315	case IP_FW_TABLE_DEL:
4316		{
4317			ipfw_table_entry ent;
4318
4319			error = sooptcopyin(sopt, &ent,
4320			    sizeof(ent), sizeof(ent));
4321			if (error)
4322				break;
4323			error = del_table_entry(&V_layer3_chain, ent.tbl,
4324			    ent.addr, ent.masklen);
4325		}
4326		break;
4327
4328	case IP_FW_TABLE_FLUSH:
4329		{
4330			u_int16_t tbl;
4331
4332			error = sooptcopyin(sopt, &tbl,
4333			    sizeof(tbl), sizeof(tbl));
4334			if (error)
4335				break;
4336			IPFW_WLOCK(&V_layer3_chain);
4337			error = flush_table(&V_layer3_chain, tbl);
4338			IPFW_WUNLOCK(&V_layer3_chain);
4339		}
4340		break;
4341
4342	case IP_FW_TABLE_GETSIZE:
4343		{
4344			u_int32_t tbl, cnt;
4345
4346			if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
4347			    sizeof(tbl))))
4348				break;
4349			IPFW_RLOCK(&V_layer3_chain);
4350			error = count_table(&V_layer3_chain, tbl, &cnt);
4351			IPFW_RUNLOCK(&V_layer3_chain);
4352			if (error)
4353				break;
4354			error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4355		}
4356		break;
4357
4358	case IP_FW_TABLE_LIST:
4359		{
4360			ipfw_table *tbl;
4361
4362			if (sopt->sopt_valsize < sizeof(*tbl)) {
4363				error = EINVAL;
4364				break;
4365			}
4366			size = sopt->sopt_valsize;
4367			tbl = malloc(size, M_TEMP, M_WAITOK);
4368			error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4369			if (error) {
4370				free(tbl, M_TEMP);
4371				break;
4372			}
4373			tbl->size = (size - sizeof(*tbl)) /
4374			    sizeof(ipfw_table_entry);
4375			IPFW_RLOCK(&V_layer3_chain);
4376			error = dump_table(&V_layer3_chain, tbl);
4377			IPFW_RUNLOCK(&V_layer3_chain);
4378			if (error) {
4379				free(tbl, M_TEMP);
4380				break;
4381			}
4382			error = sooptcopyout(sopt, tbl, size);
4383			free(tbl, M_TEMP);
4384		}
4385		break;
4386
4387	case IP_FW_NAT_CFG:
4388	{
4389		if (IPFW_NAT_LOADED)
4390			error = ipfw_nat_cfg_ptr(sopt);
4391		else {
4392			printf("IP_FW_NAT_CFG: ipfw_nat not present, please load it.\n");
4393			error = EINVAL;
4394		}
4395	}
4396	break;
4397
4398	case IP_FW_NAT_DEL:
4399	{
4400		if (IPFW_NAT_LOADED)
4401			error = ipfw_nat_del_ptr(sopt);
4402		else {
4403			printf("IP_FW_NAT_DEL: ipfw_nat not present, please load it.\n");
4404			printf("ipfw_nat not loaded: %d\n", sopt->sopt_name);
4405			error = EINVAL;
4406		}
4407	}
4408	break;
4409
4410	case IP_FW_NAT_GET_CONFIG:
4411	{
4412		if (IPFW_NAT_LOADED)
4413			error = ipfw_nat_get_cfg_ptr(sopt);
4414		else {
4415			printf("IP_FW_NAT_GET_CFG: ipfw_nat not present, please load it.\n");
4416			error = EINVAL;
4417		}
4418	}
4419	break;
4420
4421	case IP_FW_NAT_GET_LOG:
4422	{
4423		if (IPFW_NAT_LOADED)
4424			error = ipfw_nat_get_log_ptr(sopt);
4425		else {
4426			printf("IP_FW_NAT_GET_LOG: ipfw_nat not present, please load it.\n");
4427			error = EINVAL;
4428		}
4429	}
4430	break;
4431
4432	default:
4433		printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4434		error = EINVAL;
4435	}
4436
4437	return (error);
4438#undef RULE_MAXSIZE
4439}
4440
4441/**
4442 * dummynet needs a reference to the default rule, because rules can be
4443 * deleted while packets hold a reference to them. When this happens,
4444 * dummynet changes the reference to the default rule (it could well be a
4445 * NULL pointer, but this way we do not need to check for the special
4446 * case, plus here he have info on the default behaviour).
4447 */
4448struct ip_fw *ip_fw_default_rule;
4449
4450/*
4451 * This procedure is only used to handle keepalives. It is invoked
4452 * every dyn_keepalive_period
4453 */
4454static void
4455ipfw_tick(void * __unused unused)
4456{
4457	struct mbuf *m0, *m, *mnext, **mtailp;
4458	int i;
4459	ipfw_dyn_rule *q;
4460
4461	if (V_dyn_keepalive == 0 || V_ipfw_dyn_v == NULL || V_dyn_count == 0)
4462		goto done;
4463
4464	/*
4465	 * We make a chain of packets to go out here -- not deferring
4466	 * until after we drop the IPFW dynamic rule lock would result
4467	 * in a lock order reversal with the normal packet input -> ipfw
4468	 * call stack.
4469	 */
4470	m0 = NULL;
4471	mtailp = &m0;
4472	IPFW_DYN_LOCK();
4473	for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
4474		for (q = V_ipfw_dyn_v[i] ; q ; q = q->next ) {
4475			if (q->dyn_type == O_LIMIT_PARENT)
4476				continue;
4477			if (q->id.proto != IPPROTO_TCP)
4478				continue;
4479			if ( (q->state & BOTH_SYN) != BOTH_SYN)
4480				continue;
4481			if (TIME_LEQ(time_uptime + V_dyn_keepalive_interval,
4482			    q->expire))
4483				continue;	/* too early */
4484			if (TIME_LEQ(q->expire, time_uptime))
4485				continue;	/* too late, rule expired */
4486
4487			*mtailp = send_pkt(NULL, &(q->id), q->ack_rev - 1,
4488				q->ack_fwd, TH_SYN);
4489			if (*mtailp != NULL)
4490				mtailp = &(*mtailp)->m_nextpkt;
4491			*mtailp = send_pkt(NULL, &(q->id), q->ack_fwd - 1,
4492				q->ack_rev, 0);
4493			if (*mtailp != NULL)
4494				mtailp = &(*mtailp)->m_nextpkt;
4495		}
4496	}
4497	IPFW_DYN_UNLOCK();
4498	for (m = mnext = m0; m != NULL; m = mnext) {
4499		mnext = m->m_nextpkt;
4500		m->m_nextpkt = NULL;
4501		ip_output(m, NULL, NULL, 0, NULL, NULL);
4502	}
4503done:
4504	callout_reset(&V_ipfw_timeout, V_dyn_keepalive_period * hz,
4505		      ipfw_tick, NULL);
4506}
4507
4508int
4509ipfw_init(void)
4510{
4511	INIT_VNET_IPFW(curvnet);
4512	struct ip_fw default_rule;
4513	int error;
4514
4515#ifdef INET6
4516	/* Setup IPv6 fw sysctl tree. */
4517	sysctl_ctx_init(&ip6_fw_sysctl_ctx);
4518	ip6_fw_sysctl_tree = SYSCTL_ADD_NODE(&ip6_fw_sysctl_ctx,
4519	    SYSCTL_STATIC_CHILDREN(_net_inet6_ip6), OID_AUTO, "fw",
4520	    CTLFLAG_RW | CTLFLAG_SECURE, 0, "Firewall");
4521	SYSCTL_ADD_PROC(&ip6_fw_sysctl_ctx, SYSCTL_CHILDREN(ip6_fw_sysctl_tree),
4522	    OID_AUTO, "enable", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3,
4523	    &V_fw6_enable, 0, ipfw_chg_hook, "I", "Enable ipfw+6");
4524	SYSCTL_ADD_INT(&ip6_fw_sysctl_ctx, SYSCTL_CHILDREN(ip6_fw_sysctl_tree),
4525	    OID_AUTO, "deny_unknown_exthdrs", CTLFLAG_RW | CTLFLAG_SECURE,
4526	    &V_fw_deny_unknown_exthdrs, 0,
4527	    "Deny packets with unknown IPv6 Extension Headers");
4528#endif
4529
4530	V_layer3_chain.rules = NULL;
4531	IPFW_LOCK_INIT(&V_layer3_chain);
4532	ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
4533	    sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
4534	    UMA_ALIGN_PTR, 0);
4535	IPFW_DYN_LOCK_INIT();
4536	callout_init(&V_ipfw_timeout, CALLOUT_MPSAFE);
4537
4538	bzero(&default_rule, sizeof default_rule);
4539
4540	default_rule.act_ofs = 0;
4541	default_rule.rulenum = IPFW_DEFAULT_RULE;
4542	default_rule.cmd_len = 1;
4543	default_rule.set = RESVD_SET;
4544
4545	default_rule.cmd[0].len = 1;
4546	default_rule.cmd[0].opcode =
4547#ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
4548				1 ? O_ACCEPT :
4549#endif
4550				O_DENY;
4551
4552	error = add_rule(&V_layer3_chain, &default_rule);
4553	if (error != 0) {
4554		printf("ipfw2: error %u initializing default rule "
4555			"(support disabled)\n", error);
4556		IPFW_DYN_LOCK_DESTROY();
4557		IPFW_LOCK_DESTROY(&V_layer3_chain);
4558		uma_zdestroy(ipfw_dyn_rule_zone);
4559		return (error);
4560	}
4561
4562	ip_fw_default_rule = V_layer3_chain.rules;
4563	printf("ipfw2 "
4564#ifdef INET6
4565		"(+ipv6) "
4566#endif
4567		"initialized, divert %s, nat %s, "
4568		"rule-based forwarding "
4569#ifdef IPFIREWALL_FORWARD
4570		"enabled, "
4571#else
4572		"disabled, "
4573#endif
4574		"default to %s, logging ",
4575#ifdef IPDIVERT
4576		"enabled",
4577#else
4578		"loadable",
4579#endif
4580#ifdef IPFIREWALL_NAT
4581		"enabled",
4582#else
4583		"loadable",
4584#endif
4585
4586		default_rule.cmd[0].opcode == O_ACCEPT ? "accept" : "deny");
4587
4588#ifdef IPFIREWALL_VERBOSE
4589	V_fw_verbose = 1;
4590#endif
4591#ifdef IPFIREWALL_VERBOSE_LIMIT
4592	V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4593#endif
4594	if (V_fw_verbose == 0)
4595		printf("disabled\n");
4596	else if (V_verbose_limit == 0)
4597		printf("unlimited\n");
4598	else
4599		printf("limited to %d packets/entry by default\n",
4600		    V_verbose_limit);
4601
4602	error = init_tables(&V_layer3_chain);
4603	if (error) {
4604		IPFW_DYN_LOCK_DESTROY();
4605		IPFW_LOCK_DESTROY(&V_layer3_chain);
4606		uma_zdestroy(ipfw_dyn_rule_zone);
4607		return (error);
4608	}
4609	ip_fw_ctl_ptr = ipfw_ctl;
4610	ip_fw_chk_ptr = ipfw_chk;
4611	callout_reset(&V_ipfw_timeout, hz, ipfw_tick, NULL);
4612	LIST_INIT(&V_layer3_chain.nat);
4613	return (0);
4614}
4615
4616void
4617ipfw_destroy(void)
4618{
4619	struct ip_fw *reap;
4620
4621	ip_fw_chk_ptr = NULL;
4622	ip_fw_ctl_ptr = NULL;
4623	callout_drain(&V_ipfw_timeout);
4624	IPFW_WLOCK(&V_layer3_chain);
4625	flush_tables(&V_layer3_chain);
4626	V_layer3_chain.reap = NULL;
4627	free_chain(&V_layer3_chain, 1 /* kill default rule */);
4628	reap = V_layer3_chain.reap, V_layer3_chain.reap = NULL;
4629	IPFW_WUNLOCK(&V_layer3_chain);
4630	if (reap != NULL)
4631		reap_rules(reap);
4632	IPFW_DYN_LOCK_DESTROY();
4633	uma_zdestroy(ipfw_dyn_rule_zone);
4634	if (V_ipfw_dyn_v != NULL)
4635		free(V_ipfw_dyn_v, M_IPFW);
4636	IPFW_LOCK_DESTROY(&V_layer3_chain);
4637
4638#ifdef INET6
4639	/* Free IPv6 fw sysctl tree. */
4640	sysctl_ctx_free(&ip6_fw_sysctl_ctx);
4641#endif
4642
4643	printf("IP firewall unloaded\n");
4644}
4645