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