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