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