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