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