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