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