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