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