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