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