ip_fw2.c revision 196451
162587Sitojun/*-
262587Sitojun * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
362587Sitojun *
453541Sshin * Redistribution and use in source and binary forms, with or without
553541Sshin * modification, are permitted provided that the following conditions
653541Sshin * are met:
753541Sshin * 1. Redistributions of source code must retain the above copyright
853541Sshin *    notice, this list of conditions and the following disclaimer.
953541Sshin * 2. Redistributions in binary form must reproduce the above copyright
1053541Sshin *    notice, this list of conditions and the following disclaimer in the
1153541Sshin *    documentation and/or other materials provided with the distribution.
1253541Sshin *
1353541Sshin * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1453541Sshin * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1553541Sshin * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1653541Sshin * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
1753541Sshin * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1853541Sshin * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
1953541Sshin * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2053541Sshin * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2153541Sshin * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2253541Sshin * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2353541Sshin * SUCH DAMAGE.
2453541Sshin */
2553541Sshin
2653541Sshin#include <sys/cdefs.h>
2753541Sshin__FBSDID("$FreeBSD: head/sys/netinet/ipfw/ip_fw2.c 196451 2009-08-23 07:59:28Z julian $");
2853541Sshin
2953541Sshin#define        DEB(x)
3053541Sshin#define        DDB(x) x
3153541Sshin
3253541Sshin/*
3353541Sshin * Implement IP packet firewall (new version)
3453541Sshin */
3553541Sshin
3653541Sshin#if !defined(KLD_MODULE)
3753541Sshin#include "opt_ipfw.h"
3853541Sshin#include "opt_ipdivert.h"
3953541Sshin#include "opt_ipdn.h"
4053541Sshin#include "opt_inet.h"
4153541Sshin#ifndef INET
4253541Sshin#error IPFIREWALL requires INET.
4353541Sshin#endif /* INET */
4453541Sshin#endif
4553541Sshin#include "opt_inet6.h"
4653541Sshin#include "opt_ipsec.h"
4753541Sshin
4853541Sshin#include <sys/param.h>
4953541Sshin#include <sys/systm.h>
5062587Sitojun#include <sys/condvar.h>
5153541Sshin#include <sys/eventhandler.h>
5262587Sitojun#include <sys/malloc.h>
5353541Sshin#include <sys/mbuf.h>
5453541Sshin#include <sys/kernel.h>
5553541Sshin#include <sys/lock.h>
5653541Sshin#include <sys/jail.h>
5753541Sshin#include <sys/module.h>
5853541Sshin#include <sys/priv.h>
5953541Sshin#include <sys/proc.h>
6053541Sshin#include <sys/rwlock.h>
6162587Sitojun#include <sys/socket.h>
6253541Sshin#include <sys/socketvar.h>
6362587Sitojun#include <sys/sysctl.h>
6462587Sitojun#include <sys/syslog.h>
6562587Sitojun#include <sys/ucred.h>
6662587Sitojun#include <net/ethernet.h> /* for ETHERTYPE_IP */
6762587Sitojun#include <net/if.h>
6853541Sshin#include <net/radix.h>
6962587Sitojun#include <net/route.h>
7062587Sitojun#include <net/pf_mtag.h>
7162587Sitojun#include <net/vnet.h>
7253541Sshin
7362587Sitojun#define	IPFW_INTERNAL	/* Access to protected data structures in ip_fw.h. */
7469774Sphk
7562587Sitojun#include <netinet/in.h>
7653541Sshin#include <netinet/in_var.h>
7753541Sshin#include <netinet/in_pcb.h>
7853541Sshin#include <netinet/ip.h>
7953541Sshin#include <netinet/ip_var.h>
8053541Sshin#include <netinet/ip_icmp.h>
8153541Sshin#include <netinet/ip_fw.h>
8253541Sshin#include <netinet/ip_divert.h>
8353541Sshin#include <netinet/ip_dummynet.h>
8453541Sshin#include <netinet/ip_carp.h>
8553541Sshin#include <netinet/pim.h>
8653541Sshin#include <netinet/tcp_var.h>
8753541Sshin#include <netinet/udp.h>
8853541Sshin#include <netinet/udp_var.h>
8962587Sitojun#include <netinet/sctp.h>
9053541Sshin
9153541Sshin#include <netgraph/ng_ipfw.h>
9253541Sshin
9353541Sshin#include <netinet/ip6.h>
9462587Sitojun#include <netinet/icmp6.h>
9562587Sitojun#ifdef INET6
9662587Sitojun#include <netinet6/scope6_var.h>
9762587Sitojun#endif
9862587Sitojun
9962587Sitojun#include <machine/in_cksum.h>	/* XXX for in_cksum */
10062587Sitojun
10162587Sitojun#ifdef MAC
10262587Sitojun#include <security/mac/mac_framework.h>
10362587Sitojun#endif
10462587Sitojun
10562587Sitojunstatic VNET_DEFINE(int, ipfw_vnet_ready) = 0;
10662587Sitojun#define	V_ipfw_vnet_ready	VNET(ipfw_vnet_ready)
10762587Sitojun/*
10862587Sitojun * set_disable contains one bit per set value (0..31).
10962587Sitojun * If the bit is set, all rules with the corresponding set
11062587Sitojun * are disabled. Set RESVD_SET(31) is reserved for the default rule
11162587Sitojun * and rules that are not deleted by the flush command,
11262587Sitojun * and CANNOT be disabled.
11362587Sitojun * Rules in set RESVD_SET can only be deleted explicitly.
11462587Sitojun */
11562587Sitojunstatic VNET_DEFINE(u_int32_t, set_disable);
11662587Sitojunstatic VNET_DEFINE(int, fw_verbose);
11762587Sitojunstatic VNET_DEFINE(struct callout, ipfw_timeout);
11862587Sitojunstatic VNET_DEFINE(int, verbose_limit);
11962587Sitojun
12062587Sitojun#define	V_set_disable			VNET(set_disable)
12162587Sitojun#define	V_fw_verbose			VNET(fw_verbose)
12262587Sitojun#define	V_ipfw_timeout			VNET(ipfw_timeout)
12353541Sshin#define	V_verbose_limit			VNET(verbose_limit)
12453541Sshin
12553541Sshin#ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
12653541Sshinstatic int default_to_accept = 1;
12753541Sshin#else
12853541Sshinstatic int default_to_accept;
12953541Sshin#endif
13053541Sshinstatic uma_zone_t ipfw_dyn_rule_zone;
13153541Sshin
13253541Sshinstruct ip_fw *ip_fw_default_rule;
13353541Sshin
13462587Sitojun/*
13553541Sshin * list of rules for layer 3
13653541Sshin */
13762587SitojunVNET_DEFINE(struct ip_fw_chain, layer3_chain);
13853541Sshin
13953541SshinMALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
14053541SshinMALLOC_DEFINE(M_IPFW_TBL, "ipfw_tbl", "IpFw tables");
14153541Sshin#define IPFW_NAT_LOADED (ipfw_nat_ptr != NULL)
14253541Sshinipfw_nat_t *ipfw_nat_ptr = NULL;
14353541Sshinipfw_nat_cfg_t *ipfw_nat_cfg_ptr;
14462587Sitojunipfw_nat_cfg_t *ipfw_nat_del_ptr;
14562587Sitojunipfw_nat_cfg_t *ipfw_nat_get_cfg_ptr;
14653541Sshinipfw_nat_cfg_t *ipfw_nat_get_log_ptr;
14753541Sshin
14862587Sitojunstruct table_entry {
14962587Sitojun	struct radix_node	rn[2];
15062587Sitojun	struct sockaddr_in	addr, mask;
15162587Sitojun	u_int32_t		value;
15262587Sitojun};
15353541Sshin
15453541Sshinstatic VNET_DEFINE(int, autoinc_step);
15553541Sshin#define	V_autoinc_step			VNET(autoinc_step)
15653541Sshinstatic VNET_DEFINE(int, fw_deny_unknown_exthdrs);
15753541Sshin#define	V_fw_deny_unknown_exthdrs	VNET(fw_deny_unknown_exthdrs)
15853541Sshin
15953541Sshinextern int ipfw_chg_hook(SYSCTL_HANDLER_ARGS);
16053541Sshin
16153541Sshin#ifdef SYSCTL_NODE
16253541SshinSYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
16353541SshinSYSCTL_VNET_PROC(_net_inet_ip_fw, OID_AUTO, enable,
16453541Sshin    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_enable), 0,
16553541Sshin    ipfw_chg_hook, "I", "Enable ipfw");
16653541SshinSYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step,
16753541Sshin    CTLFLAG_RW, &VNET_NAME(autoinc_step), 0,
16853541Sshin    "Rule number auto-increment step");
16953541SshinSYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
17054350Sshin    CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_one_pass), 0,
17153541Sshin    "Only do a single pass through ipfw when using dummynet(4)");
17253541SshinSYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose,
17353541Sshin    CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw_verbose), 0,
17453541Sshin    "Log matches to ipfw rules");
17553541SshinSYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit,
17653541Sshin    CTLFLAG_RW, &VNET_NAME(verbose_limit), 0,
17753541Sshin    "Set upper limit of matches of ipfw rules logged");
17853541SshinSYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, default_rule, CTLFLAG_RD,
17953541Sshin    NULL, IPFW_DEFAULT_RULE,
18053541Sshin    "The default/max possible rule number.");
18153541SshinSYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, tables_max, CTLFLAG_RD,
18253541Sshin    NULL, IPFW_TABLES_MAX,
18353541Sshin    "The maximum number of tables.");
18453541SshinSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, default_to_accept, CTLFLAG_RDTUN,
18553541Sshin    &default_to_accept, 0,
18653541Sshin    "Make the default rule accept all packets.");
18753541SshinTUNABLE_INT("net.inet.ip.fw.default_to_accept", &default_to_accept);
18853541Sshin#ifdef INET6
18953541SshinSYSCTL_DECL(_net_inet6_ip6);
19053541SshinSYSCTL_NODE(_net_inet6_ip6, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
19153541SshinSYSCTL_VNET_PROC(_net_inet6_ip6_fw, OID_AUTO, enable,
19253541Sshin    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_SECURE3, &VNET_NAME(fw6_enable), 0,
19353541Sshin    ipfw_chg_hook, "I", "Enable ipfw+6");
19453541SshinSYSCTL_VNET_INT(_net_inet6_ip6_fw, OID_AUTO, deny_unknown_exthdrs,
19553541Sshin    CTLFLAG_RW | CTLFLAG_SECURE, &VNET_NAME(fw_deny_unknown_exthdrs), 0,
19662587Sitojun    "Deny packets with unknown IPv6 Extension Headers");
19753541Sshin#endif
19853541Sshin#endif
19953541Sshin
20053541Sshin/*
20153541Sshin * Description of dynamic rules.
20253541Sshin *
20353541Sshin * Dynamic rules are stored in lists accessed through a hash table
20462587Sitojun * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
20553541Sshin * be modified through the sysctl variable dyn_buckets which is
20653541Sshin * updated when the table becomes empty.
20753541Sshin *
20853541Sshin * XXX currently there is only one list, ipfw_dyn.
20953541Sshin *
21053541Sshin * When a packet is received, its address fields are first masked
21153541Sshin * with the mask defined for the rule, then hashed, then matched
21253541Sshin * against the entries in the corresponding list.
21353541Sshin * Dynamic rules can be used for different purposes:
21453541Sshin *  + stateful rules;
21553541Sshin *  + enforcing limits on the number of sessions;
21653541Sshin *  + in-kernel NAT (not implemented yet)
21753541Sshin *
21853541Sshin * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
21953541Sshin * measured in seconds and depending on the flags.
22053541Sshin *
22153541Sshin * The total number of dynamic rules is stored in dyn_count.
22253541Sshin * The max number of dynamic rules is dyn_max. When we reach
22353541Sshin * the maximum number of rules we do not create anymore. This is
22453541Sshin * done to avoid consuming too much memory, but also too much
22553541Sshin * time when searching on each packet (ideally, we should try instead
22653541Sshin * to put a limit on the length of the list on each bucket...).
22753541Sshin *
22853541Sshin * Each dynamic rule holds a pointer to the parent ipfw rule so
22953541Sshin * we know what action to perform. Dynamic rules are removed when
23053541Sshin * the parent rule is deleted. XXX we should make them survive.
23153541Sshin *
23253541Sshin * There are some limitations with dynamic rules -- we do not
23353541Sshin * obey the 'randomized match', and we do not do multiple
23453541Sshin * passes through the firewall. XXX check the latter!!!
23562587Sitojun */
23653541Sshinstatic VNET_DEFINE(ipfw_dyn_rule **, ipfw_dyn_v);
23753541Sshinstatic VNET_DEFINE(u_int32_t, dyn_buckets);
23853541Sshinstatic VNET_DEFINE(u_int32_t, curr_dyn_buckets);
23962587Sitojun
24053541Sshin#define	V_ipfw_dyn_v			VNET(ipfw_dyn_v)
24162587Sitojun#define	V_dyn_buckets			VNET(dyn_buckets)
24262587Sitojun#define	V_curr_dyn_buckets		VNET(curr_dyn_buckets)
24362587Sitojun
24453541Sshinstatic struct mtx ipfw_dyn_mtx;		/* mutex guarding dynamic rules */
24553541Sshin#define	IPFW_DYN_LOCK_INIT() \
24653541Sshin	mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
24753541Sshin#define	IPFW_DYN_LOCK_DESTROY()	mtx_destroy(&ipfw_dyn_mtx)
24853541Sshin#define	IPFW_DYN_LOCK()		mtx_lock(&ipfw_dyn_mtx)
24953541Sshin#define	IPFW_DYN_UNLOCK()	mtx_unlock(&ipfw_dyn_mtx)
25053541Sshin#define	IPFW_DYN_LOCK_ASSERT()	mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
25153541Sshin
25253541Sshin/*
25353541Sshin * Timeouts for various events in handing dynamic rules.
25453541Sshin */
25553541Sshinstatic VNET_DEFINE(u_int32_t, dyn_ack_lifetime);
25653541Sshinstatic VNET_DEFINE(u_int32_t, dyn_syn_lifetime);
25753541Sshinstatic VNET_DEFINE(u_int32_t, dyn_fin_lifetime);
25853541Sshinstatic VNET_DEFINE(u_int32_t, dyn_rst_lifetime);
25953541Sshinstatic VNET_DEFINE(u_int32_t, dyn_udp_lifetime);
26053541Sshinstatic VNET_DEFINE(u_int32_t, dyn_short_lifetime);
26153541Sshin
26253541Sshin#define	V_dyn_ack_lifetime		VNET(dyn_ack_lifetime)
26353541Sshin#define	V_dyn_syn_lifetime		VNET(dyn_syn_lifetime)
26453541Sshin#define	V_dyn_fin_lifetime		VNET(dyn_fin_lifetime)
26553541Sshin#define	V_dyn_rst_lifetime		VNET(dyn_rst_lifetime)
26653541Sshin#define	V_dyn_udp_lifetime		VNET(dyn_udp_lifetime)
26753541Sshin#define	V_dyn_short_lifetime		VNET(dyn_short_lifetime)
26862587Sitojun
26953541Sshin/*
27053541Sshin * Keepalives are sent if dyn_keepalive is set. They are sent every
27153541Sshin * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
27253541Sshin * seconds of lifetime of a rule.
27362587Sitojun * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
27462587Sitojun * than dyn_keepalive_period.
27553541Sshin */
27653541Sshin
27753541Sshinstatic VNET_DEFINE(u_int32_t, dyn_keepalive_interval);
27853541Sshinstatic VNET_DEFINE(u_int32_t, dyn_keepalive_period);
27953541Sshinstatic VNET_DEFINE(u_int32_t, dyn_keepalive);
28062587Sitojun
28162587Sitojun#define	V_dyn_keepalive_interval	VNET(dyn_keepalive_interval)
28253541Sshin#define	V_dyn_keepalive_period		VNET(dyn_keepalive_period)
28353541Sshin#define	V_dyn_keepalive			VNET(dyn_keepalive)
28453541Sshin
28553541Sshinstatic VNET_DEFINE(u_int32_t, static_count);	/* # of static rules */
28653541Sshinstatic VNET_DEFINE(u_int32_t, static_len);	/* bytes of static rules */
28753541Sshinstatic VNET_DEFINE(u_int32_t, dyn_count);	/* # of dynamic rules */
28853541Sshinstatic VNET_DEFINE(u_int32_t, dyn_max);		/* max # of dynamic rules */
28953541Sshin
29053541Sshin#define	V_static_count			VNET(static_count)
29153541Sshin#define	V_static_len			VNET(static_len)
29253541Sshin#define	V_dyn_count			VNET(dyn_count)
29353541Sshin#define	V_dyn_max			VNET(dyn_max)
29453541Sshin
29553541Sshin#ifdef SYSCTL_NODE
29653541SshinSYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets,
29753541Sshin    CTLFLAG_RW, &VNET_NAME(dyn_buckets), 0,
29853541Sshin    "Number of dyn. buckets");
29953541SshinSYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets,
30053541Sshin    CTLFLAG_RD, &VNET_NAME(curr_dyn_buckets), 0,
30162587Sitojun    "Current Number of dyn. buckets");
30253541SshinSYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_count,
30353541Sshin    CTLFLAG_RD, &VNET_NAME(dyn_count), 0,
30453541Sshin    "Number of dyn. rules");
30553541SshinSYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_max,
30653541Sshin    CTLFLAG_RW, &VNET_NAME(dyn_max), 0,
30753541Sshin    "Max number of dyn. rules");
30853541SshinSYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, static_count,
30953541Sshin    CTLFLAG_RD, &VNET_NAME(static_count), 0,
31053541Sshin    "Number of static rules");
31153541SshinSYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime,
31253541Sshin    CTLFLAG_RW, &VNET_NAME(dyn_ack_lifetime), 0,
31353541Sshin    "Lifetime of dyn. rules for acks");
31453541SshinSYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime,
31562587Sitojun    CTLFLAG_RW, &VNET_NAME(dyn_syn_lifetime), 0,
31662587Sitojun    "Lifetime of dyn. rules for syn");
31753541SshinSYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
31853541Sshin    CTLFLAG_RW, &VNET_NAME(dyn_fin_lifetime), 0,
31953541Sshin    "Lifetime of dyn. rules for fin");
32053541SshinSYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
32162587Sitojun    CTLFLAG_RW, &VNET_NAME(dyn_rst_lifetime), 0,
32262587Sitojun    "Lifetime of dyn. rules for rst");
32362587SitojunSYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime,
32462587Sitojun    CTLFLAG_RW, &VNET_NAME(dyn_udp_lifetime), 0,
32562587Sitojun    "Lifetime of dyn. rules for UDP");
32662587SitojunSYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime,
32762587Sitojun    CTLFLAG_RW, &VNET_NAME(dyn_short_lifetime), 0,
32862587Sitojun    "Lifetime of dyn. rules for other situations");
32962587SitojunSYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive,
33053541Sshin    CTLFLAG_RW, &VNET_NAME(dyn_keepalive), 0,
33153541Sshin    "Enable keepalives for dyn. rules");
33253541Sshin#endif /* SYSCTL_NODE */
33353541Sshin
33453541Sshin/*
33553541Sshin * L3HDR maps an ipv4 pointer into a layer3 header pointer of type T
33653541Sshin * Other macros just cast void * into the appropriate type
33753541Sshin */
33853541Sshin#define	L3HDR(T, ip)	((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
33953541Sshin#define	TCP(p)		((struct tcphdr *)(p))
34053541Sshin#define	SCTP(p)		((struct sctphdr *)(p))
34153541Sshin#define	UDP(p)		((struct udphdr *)(p))
34253541Sshin#define	ICMP(p)		((struct icmphdr *)(p))
34353541Sshin#define	ICMP6(p)	((struct icmp6_hdr *)(p))
34453541Sshin
34553541Sshinstatic __inline int
34653541Sshinicmptype_match(struct icmphdr *icmp, ipfw_insn_u32 *cmd)
34753541Sshin{
34853541Sshin	int type = icmp->icmp_type;
34962587Sitojun
35053541Sshin	return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
35162587Sitojun}
35262587Sitojun
35362587Sitojun#define TT	( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
35462587Sitojun    (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
35562587Sitojun
35662587Sitojunstatic int
35762587Sitojunis_icmp_query(struct icmphdr *icmp)
35862587Sitojun{
35962587Sitojun	int type = icmp->icmp_type;
36062587Sitojun
36162587Sitojun	return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
36262587Sitojun}
36362587Sitojun#undef TT
36462587Sitojun
36562587Sitojun/*
36662587Sitojun * The following checks use two arrays of 8 or 16 bits to store the
36762587Sitojun * bits that we want set or clear, respectively. They are in the
36862587Sitojun * low and high half of cmd->arg1 or cmd->d[0].
36962587Sitojun *
37062587Sitojun * We scan options and store the bits we find set. We succeed if
37162587Sitojun *
37262587Sitojun *	(want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
37362587Sitojun *
37462587Sitojun * The code is sometimes optimized not to store additional variables.
37562587Sitojun */
37662587Sitojun
37762587Sitojunstatic int
37862587Sitojunflags_match(ipfw_insn *cmd, u_int8_t bits)
37962587Sitojun{
38062587Sitojun	u_char want_clear;
38162587Sitojun	bits = ~bits;
38262587Sitojun
38362587Sitojun	if ( ((cmd->arg1 & 0xff) & bits) != 0)
38462587Sitojun		return 0; /* some bits we want set were clear */
38562587Sitojun	want_clear = (cmd->arg1 >> 8) & 0xff;
38653541Sshin	if ( (want_clear & bits) != want_clear)
38753541Sshin		return 0; /* some bits we want clear were set */
38853541Sshin	return 1;
38953541Sshin}
39053541Sshin
39153541Sshinstatic int
39253541Sshinipopts_match(struct ip *ip, ipfw_insn *cmd)
39353541Sshin{
39476899Ssumikawa	int optlen, bits = 0;
39553541Sshin	u_char *cp = (u_char *)(ip + 1);
39653541Sshin	int x = (ip->ip_hl << 2) - sizeof (struct ip);
39753541Sshin
39876899Ssumikawa	for (; x > 0; x -= optlen, cp += optlen) {
39976899Ssumikawa		int opt = cp[IPOPT_OPTVAL];
40053541Sshin
40153541Sshin		if (opt == IPOPT_EOL)
40253541Sshin			break;
40353541Sshin		if (opt == IPOPT_NOP)
40453541Sshin			optlen = 1;
40553541Sshin		else {
40676899Ssumikawa			optlen = cp[IPOPT_OLEN];
40753541Sshin			if (optlen <= 0 || optlen > x)
40853541Sshin				return 0; /* invalid or truncated */
40953541Sshin		}
41076899Ssumikawa		switch (opt) {
41176899Ssumikawa
41253541Sshin		default:
41353541Sshin			break;
41453541Sshin
41562587Sitojun		case IPOPT_LSRR:
41653541Sshin			bits |= IP_FW_IPOPT_LSRR;
41753541Sshin			break;
41853541Sshin
41953541Sshin		case IPOPT_SSRR:
42053541Sshin			bits |= IP_FW_IPOPT_SSRR;
42153541Sshin			break;
42253541Sshin
42353541Sshin		case IPOPT_RR:
42453541Sshin			bits |= IP_FW_IPOPT_RR;
42553541Sshin			break;
42662587Sitojun
42762587Sitojun		case IPOPT_TS:
42862587Sitojun			bits |= IP_FW_IPOPT_TS;
42962587Sitojun			break;
43062587Sitojun		}
43162587Sitojun	}
43253541Sshin	return (flags_match(cmd, bits));
43353541Sshin}
43453541Sshin
43553541Sshinstatic int
43653541Sshintcpopts_match(struct tcphdr *tcp, ipfw_insn *cmd)
43753541Sshin{
43853541Sshin	int optlen, bits = 0;
43953541Sshin	u_char *cp = (u_char *)(tcp + 1);
44053541Sshin	int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
44153541Sshin
44253541Sshin	for (; x > 0; x -= optlen, cp += optlen) {
44353541Sshin		int opt = cp[0];
44453541Sshin		if (opt == TCPOPT_EOL)
44553541Sshin			break;
44653541Sshin		if (opt == TCPOPT_NOP)
44753541Sshin			optlen = 1;
44853541Sshin		else {
44953541Sshin			optlen = cp[1];
45053541Sshin			if (optlen <= 0)
45153541Sshin				break;
45262587Sitojun		}
45353541Sshin
45462587Sitojun		switch (opt) {
45562587Sitojun
45653541Sshin		default:
45753541Sshin			break;
45853541Sshin
45962587Sitojun		case TCPOPT_MAXSEG:
46062587Sitojun			bits |= IP_FW_TCPOPT_MSS;
46162587Sitojun			break;
46253541Sshin
46353541Sshin		case TCPOPT_WINDOW:
46453541Sshin			bits |= IP_FW_TCPOPT_WINDOW;
46553541Sshin			break;
46662587Sitojun
46762587Sitojun		case TCPOPT_SACK_PERMITTED:
46853541Sshin		case TCPOPT_SACK:
46953541Sshin			bits |= IP_FW_TCPOPT_SACK;
47053541Sshin			break;
47153541Sshin
47262587Sitojun		case TCPOPT_TIMESTAMP:
47362587Sitojun			bits |= IP_FW_TCPOPT_TS;
47462587Sitojun			break;
47553541Sshin
47653541Sshin		}
47753541Sshin	}
47853541Sshin	return (flags_match(cmd, bits));
47962587Sitojun}
48053541Sshin
48153541Sshinstatic int
48262587Sitojuniface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
48362587Sitojun{
48462587Sitojun	if (ifp == NULL)	/* no iface with this packet, match fails */
48562587Sitojun		return 0;
48662587Sitojun	/* Check by name or by IP address */
48762587Sitojun	if (cmd->name[0] != '\0') { /* match by name */
48862587Sitojun		/* Check name */
48962587Sitojun		if (cmd->p.glob) {
49062587Sitojun			if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
49162587Sitojun				return(1);
49262587Sitojun		} else {
49362587Sitojun			if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
49453541Sshin				return(1);
49553541Sshin		}
49653541Sshin	} else {
49753541Sshin		struct ifaddr *ia;
49853541Sshin
49953541Sshin		if_addr_rlock(ifp);
50053541Sshin		TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
50153541Sshin			if (ia->ifa_addr->sa_family != AF_INET)
50253541Sshin				continue;
50353541Sshin			if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
50453541Sshin			    (ia->ifa_addr))->sin_addr.s_addr) {
50553541Sshin				if_addr_runlock(ifp);
50653541Sshin				return(1);	/* match */
50753541Sshin			}
50853541Sshin		}
50953541Sshin		if_addr_runlock(ifp);
51053541Sshin	}
51153541Sshin	return(0);	/* no match, fail ... */
51253541Sshin}
51353541Sshin
51453541Sshin/*
51553541Sshin * The verify_path function checks if a route to the src exists and
51653541Sshin * if it is reachable via ifp (when provided).
51753541Sshin *
51853541Sshin * The 'verrevpath' option checks that the interface that an IP packet
51953541Sshin * arrives on is the same interface that traffic destined for the
52053541Sshin * packet's source address would be routed out of.  The 'versrcreach'
52153541Sshin * option just checks that the source address is reachable via any route
52253541Sshin * (except default) in the routing table.  These two are a measure to block
52353541Sshin * forged packets.  This is also commonly known as "anti-spoofing" or Unicast
52453541Sshin * Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
52553541Sshin * is purposely reminiscent of the Cisco IOS command,
52653541Sshin *
52753541Sshin *   ip verify unicast reverse-path
52853541Sshin *   ip verify unicast source reachable-via any
52953541Sshin *
53053541Sshin * which implements the same functionality. But note that syntax is
53153541Sshin * misleading. The check may be performed on all IP packets whether unicast,
53253541Sshin * multicast, or broadcast.
53353541Sshin */
53453541Sshinstatic int
53553541Sshinverify_path(struct in_addr src, struct ifnet *ifp, u_int fib)
53653541Sshin{
53753541Sshin	struct route ro;
53853541Sshin	struct sockaddr_in *dst;
53953541Sshin
54053541Sshin	bzero(&ro, sizeof(ro));
54153541Sshin
54253541Sshin	dst = (struct sockaddr_in *)&(ro.ro_dst);
54353541Sshin	dst->sin_family = AF_INET;
54453541Sshin	dst->sin_len = sizeof(*dst);
54553541Sshin	dst->sin_addr = src;
54653541Sshin	in_rtalloc_ign(&ro, 0, fib);
54753541Sshin
54853541Sshin	if (ro.ro_rt == NULL)
54953541Sshin		return 0;
55053541Sshin
55153541Sshin	/*
55253541Sshin	 * If ifp is provided, check for equality with rtentry.
55353541Sshin	 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
55453541Sshin	 * in order to pass packets injected back by if_simloop():
55553541Sshin	 * if useloopback == 1 routing entry (via lo0) for our own address
55653541Sshin	 * may exist, so we need to handle routing assymetry.
55753541Sshin	 */
55853541Sshin	if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
55953541Sshin		RTFREE(ro.ro_rt);
56053541Sshin		return 0;
56153541Sshin	}
56253541Sshin
56353541Sshin	/* if no ifp provided, check if rtentry is not default route */
56453541Sshin	if (ifp == NULL &&
56553541Sshin	     satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
56653541Sshin		RTFREE(ro.ro_rt);
56753541Sshin		return 0;
56862587Sitojun	}
56953541Sshin
57062587Sitojun	/* or if this is a blackhole/reject route */
57153541Sshin	if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
57253541Sshin		RTFREE(ro.ro_rt);
57353541Sshin		return 0;
57453541Sshin	}
57553541Sshin
57653541Sshin	/* found valid route */
57753541Sshin	RTFREE(ro.ro_rt);
57853541Sshin	return 1;
57953541Sshin}
58053541Sshin
58153541Sshin#ifdef INET6
58253541Sshin/*
58353541Sshin * ipv6 specific rules here...
58453541Sshin */
58553541Sshinstatic __inline int
58653541Sshinicmp6type_match (int type, ipfw_insn_u32 *cmd)
58753541Sshin{
58853541Sshin	return (type <= ICMP6_MAXTYPE && (cmd->d[type/32] & (1<<(type%32)) ) );
58953541Sshin}
59053541Sshin
59153541Sshinstatic int
59253541Sshinflow6id_match( int curr_flow, ipfw_insn_u32 *cmd )
59353541Sshin{
59453541Sshin	int i;
59553541Sshin	for (i=0; i <= cmd->o.arg1; ++i )
59653541Sshin		if (curr_flow == cmd->d[i] )
59753541Sshin			return 1;
59853541Sshin	return 0;
59953541Sshin}
60053541Sshin
60153541Sshin/* support for IP6_*_ME opcodes */
60253541Sshinstatic int
60353541Sshinsearch_ip6_addr_net (struct in6_addr * ip6_addr)
60453541Sshin{
60553541Sshin	struct ifnet *mdc;
60653541Sshin	struct ifaddr *mdc2;
60753541Sshin	struct in6_ifaddr *fdm;
60853541Sshin	struct in6_addr copia;
60953541Sshin
61053541Sshin	TAILQ_FOREACH(mdc, &V_ifnet, if_link) {
61153541Sshin		if_addr_rlock(mdc);
61253541Sshin		TAILQ_FOREACH(mdc2, &mdc->if_addrhead, ifa_link) {
61353541Sshin			if (mdc2->ifa_addr->sa_family == AF_INET6) {
61453541Sshin				fdm = (struct in6_ifaddr *)mdc2;
61553541Sshin				copia = fdm->ia_addr.sin6_addr;
61653541Sshin				/* need for leaving scope_id in the sock_addr */
61753541Sshin				in6_clearscope(&copia);
61853541Sshin				if (IN6_ARE_ADDR_EQUAL(ip6_addr, &copia)) {
61953541Sshin					if_addr_runlock(mdc);
62053541Sshin					return 1;
62153541Sshin				}
62253541Sshin			}
62353541Sshin		}
62453541Sshin		if_addr_runlock(mdc);
62553541Sshin	}
62653541Sshin	return 0;
62753541Sshin}
62853541Sshin
62953541Sshinstatic int
63062587Sitojunverify_path6(struct in6_addr *src, struct ifnet *ifp)
63162587Sitojun{
63262587Sitojun	struct route_in6 ro;
63353541Sshin	struct sockaddr_in6 *dst;
63453541Sshin
63553541Sshin	bzero(&ro, sizeof(ro));
63653541Sshin
63753541Sshin	dst = (struct sockaddr_in6 * )&(ro.ro_dst);
63853541Sshin	dst->sin6_family = AF_INET6;
63953541Sshin	dst->sin6_len = sizeof(*dst);
64053541Sshin	dst->sin6_addr = *src;
64153541Sshin	/* XXX MRT 0 for ipv6 at this time */
64253541Sshin	rtalloc_ign((struct route *)&ro, 0);
64353541Sshin
64453541Sshin	if (ro.ro_rt == NULL)
64553541Sshin		return 0;
64653541Sshin
64753541Sshin	/*
64853541Sshin	 * if ifp is provided, check for equality with rtentry
64953541Sshin	 * We should use rt->rt_ifa->ifa_ifp, instead of rt->rt_ifp,
65053541Sshin	 * to support the case of sending packets to an address of our own.
65153541Sshin	 * (where the former interface is the first argument of if_simloop()
65253541Sshin	 *  (=ifp), the latter is lo0)
65353541Sshin	 */
65453541Sshin	if (ifp != NULL && ro.ro_rt->rt_ifa->ifa_ifp != ifp) {
65553541Sshin		RTFREE(ro.ro_rt);
65653541Sshin		return 0;
65762587Sitojun	}
65862587Sitojun
65962587Sitojun	/* if no ifp provided, check if rtentry is not default route */
66062587Sitojun	if (ifp == NULL &&
66162587Sitojun	    IN6_IS_ADDR_UNSPECIFIED(&satosin6(rt_key(ro.ro_rt))->sin6_addr)) {
66262587Sitojun		RTFREE(ro.ro_rt);
66362587Sitojun		return 0;
66462587Sitojun	}
66562587Sitojun
66662587Sitojun	/* or if this is a blackhole/reject route */
66762587Sitojun	if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
66862587Sitojun		RTFREE(ro.ro_rt);
66962587Sitojun		return 0;
67062587Sitojun	}
67162587Sitojun
67262587Sitojun	/* found valid route */
67362587Sitojun	RTFREE(ro.ro_rt);
67453541Sshin	return 1;
67553541Sshin
67653541Sshin}
67753541Sshinstatic __inline int
67853541Sshinhash_packet6(struct ipfw_flow_id *id)
67953541Sshin{
68053541Sshin	u_int32_t i;
68153541Sshin	i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
68253541Sshin	    (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
68353541Sshin	    (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
68453541Sshin	    (id->src_ip6.__u6_addr.__u6_addr32[3]) ^
68553541Sshin	    (id->dst_port) ^ (id->src_port);
68653541Sshin	return i;
68753541Sshin}
68853541Sshin
68953541Sshinstatic int
69053541Sshinis_icmp6_query(int icmp6_type)
691{
692	if ((icmp6_type <= ICMP6_MAXTYPE) &&
693	    (icmp6_type == ICMP6_ECHO_REQUEST ||
694	    icmp6_type == ICMP6_MEMBERSHIP_QUERY ||
695	    icmp6_type == ICMP6_WRUREQUEST ||
696	    icmp6_type == ICMP6_FQDN_QUERY ||
697	    icmp6_type == ICMP6_NI_QUERY))
698		return (1);
699
700	return (0);
701}
702
703static void
704send_reject6(struct ip_fw_args *args, int code, u_int hlen, struct ip6_hdr *ip6)
705{
706	struct mbuf *m;
707
708	m = args->m;
709	if (code == ICMP6_UNREACH_RST && args->f_id.proto == IPPROTO_TCP) {
710		struct tcphdr *tcp;
711		tcp_seq ack, seq;
712		int flags;
713		struct {
714			struct ip6_hdr ip6;
715			struct tcphdr th;
716		} ti;
717		tcp = (struct tcphdr *)((char *)ip6 + hlen);
718
719		if ((tcp->th_flags & TH_RST) != 0) {
720			m_freem(m);
721			args->m = NULL;
722			return;
723		}
724
725		ti.ip6 = *ip6;
726		ti.th = *tcp;
727		ti.th.th_seq = ntohl(ti.th.th_seq);
728		ti.th.th_ack = ntohl(ti.th.th_ack);
729		ti.ip6.ip6_nxt = IPPROTO_TCP;
730
731		if (ti.th.th_flags & TH_ACK) {
732			ack = 0;
733			seq = ti.th.th_ack;
734			flags = TH_RST;
735		} else {
736			ack = ti.th.th_seq;
737			if ((m->m_flags & M_PKTHDR) != 0) {
738				/*
739				 * total new data to ACK is:
740				 * total packet length,
741				 * minus the header length,
742				 * minus the tcp header length.
743				 */
744				ack += m->m_pkthdr.len - hlen
745					- (ti.th.th_off << 2);
746			} else if (ip6->ip6_plen) {
747				ack += ntohs(ip6->ip6_plen) + sizeof(*ip6) -
748				    hlen - (ti.th.th_off << 2);
749			} else {
750				m_freem(m);
751				return;
752			}
753			if (tcp->th_flags & TH_SYN)
754				ack++;
755			seq = 0;
756			flags = TH_RST|TH_ACK;
757		}
758		bcopy(&ti, ip6, sizeof(ti));
759		/*
760		 * m is only used to recycle the mbuf
761		 * The data in it is never read so we don't need
762		 * to correct the offsets or anything
763		 */
764		tcp_respond(NULL, ip6, tcp, m, ack, seq, flags);
765	} else if (code != ICMP6_UNREACH_RST) { /* Send an ICMPv6 unreach. */
766#if 0
767		/*
768		 * Unlike above, the mbufs need to line up with the ip6 hdr,
769		 * as the contents are read. We need to m_adj() the
770		 * needed amount.
771		 * The mbuf will however be thrown away so we can adjust it.
772		 * Remember we did an m_pullup on it already so we
773		 * can make some assumptions about contiguousness.
774		 */
775		if (args->L3offset)
776			m_adj(m, args->L3offset);
777#endif
778		icmp6_error(m, ICMP6_DST_UNREACH, code, 0);
779	} else
780		m_freem(m);
781
782	args->m = NULL;
783}
784
785#endif /* INET6 */
786
787/* counter for ipfw_log(NULL...) */
788static VNET_DEFINE(u_int64_t, norule_counter);
789#define	V_norule_counter		VNET(norule_counter)
790
791#define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
792#define SNP(buf) buf, sizeof(buf)
793
794/*
795 * We enter here when we have a rule with O_LOG.
796 * XXX this function alone takes about 2Kbytes of code!
797 */
798static void
799ipfw_log(struct ip_fw *f, u_int hlen, struct ip_fw_args *args,
800    struct mbuf *m, struct ifnet *oif, u_short offset, uint32_t tablearg,
801    struct ip *ip)
802{
803	struct ether_header *eh = args->eh;
804	char *action;
805	int limit_reached = 0;
806	char action2[40], proto[128], fragment[32];
807
808	fragment[0] = '\0';
809	proto[0] = '\0';
810
811	if (f == NULL) {	/* bogus pkt */
812		if (V_verbose_limit != 0 && V_norule_counter >= V_verbose_limit)
813			return;
814		V_norule_counter++;
815		if (V_norule_counter == V_verbose_limit)
816			limit_reached = V_verbose_limit;
817		action = "Refuse";
818	} else {	/* O_LOG is the first action, find the real one */
819		ipfw_insn *cmd = ACTION_PTR(f);
820		ipfw_insn_log *l = (ipfw_insn_log *)cmd;
821
822		if (l->max_log != 0 && l->log_left == 0)
823			return;
824		l->log_left--;
825		if (l->log_left == 0)
826			limit_reached = l->max_log;
827		cmd += F_LEN(cmd);	/* point to first action */
828		if (cmd->opcode == O_ALTQ) {
829			ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
830
831			snprintf(SNPARGS(action2, 0), "Altq %d",
832				altq->qid);
833			cmd += F_LEN(cmd);
834		}
835		if (cmd->opcode == O_PROB)
836			cmd += F_LEN(cmd);
837
838		if (cmd->opcode == O_TAG)
839			cmd += F_LEN(cmd);
840
841		action = action2;
842		switch (cmd->opcode) {
843		case O_DENY:
844			action = "Deny";
845			break;
846
847		case O_REJECT:
848			if (cmd->arg1==ICMP_REJECT_RST)
849				action = "Reset";
850			else if (cmd->arg1==ICMP_UNREACH_HOST)
851				action = "Reject";
852			else
853				snprintf(SNPARGS(action2, 0), "Unreach %d",
854					cmd->arg1);
855			break;
856
857		case O_UNREACH6:
858			if (cmd->arg1==ICMP6_UNREACH_RST)
859				action = "Reset";
860			else
861				snprintf(SNPARGS(action2, 0), "Unreach %d",
862					cmd->arg1);
863			break;
864
865		case O_ACCEPT:
866			action = "Accept";
867			break;
868		case O_COUNT:
869			action = "Count";
870			break;
871		case O_DIVERT:
872			snprintf(SNPARGS(action2, 0), "Divert %d",
873				cmd->arg1);
874			break;
875		case O_TEE:
876			snprintf(SNPARGS(action2, 0), "Tee %d",
877				cmd->arg1);
878			break;
879		case O_SETFIB:
880			snprintf(SNPARGS(action2, 0), "SetFib %d",
881				cmd->arg1);
882			break;
883		case O_SKIPTO:
884			snprintf(SNPARGS(action2, 0), "SkipTo %d",
885				cmd->arg1);
886			break;
887		case O_PIPE:
888			snprintf(SNPARGS(action2, 0), "Pipe %d",
889				cmd->arg1);
890			break;
891		case O_QUEUE:
892			snprintf(SNPARGS(action2, 0), "Queue %d",
893				cmd->arg1);
894			break;
895		case O_FORWARD_IP: {
896			ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
897			int len;
898			struct in_addr dummyaddr;
899			if (sa->sa.sin_addr.s_addr == INADDR_ANY)
900				dummyaddr.s_addr = htonl(tablearg);
901			else
902				dummyaddr.s_addr = sa->sa.sin_addr.s_addr;
903
904			len = snprintf(SNPARGS(action2, 0), "Forward to %s",
905				inet_ntoa(dummyaddr));
906
907			if (sa->sa.sin_port)
908				snprintf(SNPARGS(action2, len), ":%d",
909				    sa->sa.sin_port);
910			}
911			break;
912		case O_NETGRAPH:
913			snprintf(SNPARGS(action2, 0), "Netgraph %d",
914				cmd->arg1);
915			break;
916		case O_NGTEE:
917			snprintf(SNPARGS(action2, 0), "Ngtee %d",
918				cmd->arg1);
919			break;
920		case O_NAT:
921			action = "Nat";
922 			break;
923		case O_REASS:
924			action = "Reass";
925			break;
926		default:
927			action = "UNKNOWN";
928			break;
929		}
930	}
931
932	if (hlen == 0) {	/* non-ip */
933		snprintf(SNPARGS(proto, 0), "MAC");
934
935	} else {
936		int len;
937		char src[48], dst[48];
938		struct icmphdr *icmp;
939		struct tcphdr *tcp;
940		struct udphdr *udp;
941#ifdef INET6
942		struct ip6_hdr *ip6 = NULL;
943		struct icmp6_hdr *icmp6;
944#endif
945		src[0] = '\0';
946		dst[0] = '\0';
947#ifdef INET6
948		if (IS_IP6_FLOW_ID(&(args->f_id))) {
949			char ip6buf[INET6_ADDRSTRLEN];
950			snprintf(src, sizeof(src), "[%s]",
951			    ip6_sprintf(ip6buf, &args->f_id.src_ip6));
952			snprintf(dst, sizeof(dst), "[%s]",
953			    ip6_sprintf(ip6buf, &args->f_id.dst_ip6));
954
955			ip6 = (struct ip6_hdr *)ip;
956			tcp = (struct tcphdr *)(((char *)ip) + hlen);
957			udp = (struct udphdr *)(((char *)ip) + hlen);
958		} else
959#endif
960		{
961			tcp = L3HDR(struct tcphdr, ip);
962			udp = L3HDR(struct udphdr, ip);
963
964			inet_ntoa_r(ip->ip_src, src);
965			inet_ntoa_r(ip->ip_dst, dst);
966		}
967
968		switch (args->f_id.proto) {
969		case IPPROTO_TCP:
970			len = snprintf(SNPARGS(proto, 0), "TCP %s", src);
971			if (offset == 0)
972				snprintf(SNPARGS(proto, len), ":%d %s:%d",
973				    ntohs(tcp->th_sport),
974				    dst,
975				    ntohs(tcp->th_dport));
976			else
977				snprintf(SNPARGS(proto, len), " %s", dst);
978			break;
979
980		case IPPROTO_UDP:
981			len = snprintf(SNPARGS(proto, 0), "UDP %s", src);
982			if (offset == 0)
983				snprintf(SNPARGS(proto, len), ":%d %s:%d",
984				    ntohs(udp->uh_sport),
985				    dst,
986				    ntohs(udp->uh_dport));
987			else
988				snprintf(SNPARGS(proto, len), " %s", dst);
989			break;
990
991		case IPPROTO_ICMP:
992			icmp = L3HDR(struct icmphdr, ip);
993			if (offset == 0)
994				len = snprintf(SNPARGS(proto, 0),
995				    "ICMP:%u.%u ",
996				    icmp->icmp_type, icmp->icmp_code);
997			else
998				len = snprintf(SNPARGS(proto, 0), "ICMP ");
999			len += snprintf(SNPARGS(proto, len), "%s", src);
1000			snprintf(SNPARGS(proto, len), " %s", dst);
1001			break;
1002#ifdef INET6
1003		case IPPROTO_ICMPV6:
1004			icmp6 = (struct icmp6_hdr *)(((char *)ip) + hlen);
1005			if (offset == 0)
1006				len = snprintf(SNPARGS(proto, 0),
1007				    "ICMPv6:%u.%u ",
1008				    icmp6->icmp6_type, icmp6->icmp6_code);
1009			else
1010				len = snprintf(SNPARGS(proto, 0), "ICMPv6 ");
1011			len += snprintf(SNPARGS(proto, len), "%s", src);
1012			snprintf(SNPARGS(proto, len), " %s", dst);
1013			break;
1014#endif
1015		default:
1016			len = snprintf(SNPARGS(proto, 0), "P:%d %s",
1017			    args->f_id.proto, src);
1018			snprintf(SNPARGS(proto, len), " %s", dst);
1019			break;
1020		}
1021
1022#ifdef INET6
1023		if (IS_IP6_FLOW_ID(&(args->f_id))) {
1024			if (offset & (IP6F_OFF_MASK | IP6F_MORE_FRAG))
1025				snprintf(SNPARGS(fragment, 0),
1026				    " (frag %08x:%d@%d%s)",
1027				    args->f_id.frag_id6,
1028				    ntohs(ip6->ip6_plen) - hlen,
1029				    ntohs(offset & IP6F_OFF_MASK) << 3,
1030				    (offset & IP6F_MORE_FRAG) ? "+" : "");
1031		} else
1032#endif
1033		{
1034			int ip_off, ip_len;
1035			if (eh != NULL) { /* layer 2 packets are as on the wire */
1036				ip_off = ntohs(ip->ip_off);
1037				ip_len = ntohs(ip->ip_len);
1038			} else {
1039				ip_off = ip->ip_off;
1040				ip_len = ip->ip_len;
1041			}
1042			if (ip_off & (IP_MF | IP_OFFMASK))
1043				snprintf(SNPARGS(fragment, 0),
1044				    " (frag %d:%d@%d%s)",
1045				    ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
1046				    offset << 3,
1047				    (ip_off & IP_MF) ? "+" : "");
1048		}
1049	}
1050	if (oif || m->m_pkthdr.rcvif)
1051		log(LOG_SECURITY | LOG_INFO,
1052		    "ipfw: %d %s %s %s via %s%s\n",
1053		    f ? f->rulenum : -1,
1054		    action, proto, oif ? "out" : "in",
1055		    oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
1056		    fragment);
1057	else
1058		log(LOG_SECURITY | LOG_INFO,
1059		    "ipfw: %d %s %s [no if info]%s\n",
1060		    f ? f->rulenum : -1,
1061		    action, proto, fragment);
1062	if (limit_reached)
1063		log(LOG_SECURITY | LOG_NOTICE,
1064		    "ipfw: limit %d reached on entry %d\n",
1065		    limit_reached, f ? f->rulenum : -1);
1066}
1067
1068/*
1069 * IMPORTANT: the hash function for dynamic rules must be commutative
1070 * in source and destination (ip,port), because rules are bidirectional
1071 * and we want to find both in the same bucket.
1072 */
1073static __inline int
1074hash_packet(struct ipfw_flow_id *id)
1075{
1076	u_int32_t i;
1077
1078#ifdef INET6
1079	if (IS_IP6_FLOW_ID(id))
1080		i = hash_packet6(id);
1081	else
1082#endif /* INET6 */
1083	i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
1084	i &= (V_curr_dyn_buckets - 1);
1085	return i;
1086}
1087
1088/**
1089 * unlink a dynamic rule from a chain. prev is a pointer to
1090 * the previous one, q is a pointer to the rule to delete,
1091 * head is a pointer to the head of the queue.
1092 * Modifies q and potentially also head.
1093 */
1094#define UNLINK_DYN_RULE(prev, head, q) {				\
1095	ipfw_dyn_rule *old_q = q;					\
1096									\
1097	/* remove a refcount to the parent */				\
1098	if (q->dyn_type == O_LIMIT)					\
1099		q->parent->count--;					\
1100	DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
1101		(q->id.src_ip), (q->id.src_port),			\
1102		(q->id.dst_ip), (q->id.dst_port), V_dyn_count-1 ); )	\
1103	if (prev != NULL)						\
1104		prev->next = q = q->next;				\
1105	else								\
1106		head = q = q->next;					\
1107	V_dyn_count--;							\
1108	uma_zfree(ipfw_dyn_rule_zone, old_q); }
1109
1110#define TIME_LEQ(a,b)       ((int)((a)-(b)) <= 0)
1111
1112/**
1113 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
1114 *
1115 * If keep_me == NULL, rules are deleted even if not expired,
1116 * otherwise only expired rules are removed.
1117 *
1118 * The value of the second parameter is also used to point to identify
1119 * a rule we absolutely do not want to remove (e.g. because we are
1120 * holding a reference to it -- this is the case with O_LIMIT_PARENT
1121 * rules). The pointer is only used for comparison, so any non-null
1122 * value will do.
1123 */
1124static void
1125remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
1126{
1127	static u_int32_t last_remove = 0;
1128
1129#define FORCE (keep_me == NULL)
1130
1131	ipfw_dyn_rule *prev, *q;
1132	int i, pass = 0, max_pass = 0;
1133
1134	IPFW_DYN_LOCK_ASSERT();
1135
1136	if (V_ipfw_dyn_v == NULL || V_dyn_count == 0)
1137		return;
1138	/* do not expire more than once per second, it is useless */
1139	if (!FORCE && last_remove == time_uptime)
1140		return;
1141	last_remove = time_uptime;
1142
1143	/*
1144	 * because O_LIMIT refer to parent rules, during the first pass only
1145	 * remove child and mark any pending LIMIT_PARENT, and remove
1146	 * them in a second pass.
1147	 */
1148next_pass:
1149	for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
1150		for (prev=NULL, q = V_ipfw_dyn_v[i] ; q ; ) {
1151			/*
1152			 * Logic can become complex here, so we split tests.
1153			 */
1154			if (q == keep_me)
1155				goto next;
1156			if (rule != NULL && rule != q->rule)
1157				goto next; /* not the one we are looking for */
1158			if (q->dyn_type == O_LIMIT_PARENT) {
1159				/*
1160				 * handle parent in the second pass,
1161				 * record we need one.
1162				 */
1163				max_pass = 1;
1164				if (pass == 0)
1165					goto next;
1166				if (FORCE && q->count != 0 ) {
1167					/* XXX should not happen! */
1168					printf("ipfw: OUCH! cannot remove rule,"
1169					     " count %d\n", q->count);
1170				}
1171			} else {
1172				if (!FORCE &&
1173				    !TIME_LEQ( q->expire, time_uptime ))
1174					goto next;
1175			}
1176             if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
1177                     UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
1178                     continue;
1179             }
1180next:
1181			prev=q;
1182			q=q->next;
1183		}
1184	}
1185	if (pass++ < max_pass)
1186		goto next_pass;
1187}
1188
1189
1190/**
1191 * lookup a dynamic rule.
1192 */
1193static ipfw_dyn_rule *
1194lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
1195    struct tcphdr *tcp)
1196{
1197	/*
1198	 * stateful ipfw extensions.
1199	 * Lookup into dynamic session queue
1200	 */
1201#define MATCH_REVERSE	0
1202#define MATCH_FORWARD	1
1203#define MATCH_NONE	2
1204#define MATCH_UNKNOWN	3
1205	int i, dir = MATCH_NONE;
1206	ipfw_dyn_rule *prev, *q=NULL;
1207
1208	IPFW_DYN_LOCK_ASSERT();
1209
1210	if (V_ipfw_dyn_v == NULL)
1211		goto done;	/* not found */
1212	i = hash_packet( pkt );
1213	for (prev=NULL, q = V_ipfw_dyn_v[i] ; q != NULL ; ) {
1214		if (q->dyn_type == O_LIMIT_PARENT && q->count)
1215			goto next;
1216		if (TIME_LEQ( q->expire, time_uptime)) { /* expire entry */
1217			UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
1218			continue;
1219		}
1220		if (pkt->proto == q->id.proto &&
1221		    q->dyn_type != O_LIMIT_PARENT) {
1222			if (IS_IP6_FLOW_ID(pkt)) {
1223			    if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1224				&(q->id.src_ip6)) &&
1225			    IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1226				&(q->id.dst_ip6)) &&
1227			    pkt->src_port == q->id.src_port &&
1228			    pkt->dst_port == q->id.dst_port ) {
1229				dir = MATCH_FORWARD;
1230				break;
1231			    }
1232			    if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1233				    &(q->id.dst_ip6)) &&
1234				IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1235				    &(q->id.src_ip6)) &&
1236				pkt->src_port == q->id.dst_port &&
1237				pkt->dst_port == q->id.src_port ) {
1238				    dir = MATCH_REVERSE;
1239				    break;
1240			    }
1241			} else {
1242			    if (pkt->src_ip == q->id.src_ip &&
1243				pkt->dst_ip == q->id.dst_ip &&
1244				pkt->src_port == q->id.src_port &&
1245				pkt->dst_port == q->id.dst_port ) {
1246				    dir = MATCH_FORWARD;
1247				    break;
1248			    }
1249			    if (pkt->src_ip == q->id.dst_ip &&
1250				pkt->dst_ip == q->id.src_ip &&
1251				pkt->src_port == q->id.dst_port &&
1252				pkt->dst_port == q->id.src_port ) {
1253				    dir = MATCH_REVERSE;
1254				    break;
1255			    }
1256			}
1257		}
1258next:
1259		prev = q;
1260		q = q->next;
1261	}
1262	if (q == NULL)
1263		goto done; /* q = NULL, not found */
1264
1265	if ( prev != NULL) { /* found and not in front */
1266		prev->next = q->next;
1267		q->next = V_ipfw_dyn_v[i];
1268		V_ipfw_dyn_v[i] = q;
1269	}
1270	if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
1271		u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
1272
1273#define BOTH_SYN	(TH_SYN | (TH_SYN << 8))
1274#define BOTH_FIN	(TH_FIN | (TH_FIN << 8))
1275		q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
1276		switch (q->state) {
1277		case TH_SYN:				/* opening */
1278			q->expire = time_uptime + V_dyn_syn_lifetime;
1279			break;
1280
1281		case BOTH_SYN:			/* move to established */
1282		case BOTH_SYN | TH_FIN :	/* one side tries to close */
1283		case BOTH_SYN | (TH_FIN << 8) :
1284 			if (tcp) {
1285#define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
1286			    u_int32_t ack = ntohl(tcp->th_ack);
1287			    if (dir == MATCH_FORWARD) {
1288				if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
1289				    q->ack_fwd = ack;
1290				else { /* ignore out-of-sequence */
1291				    break;
1292				}
1293			    } else {
1294				if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
1295				    q->ack_rev = ack;
1296				else { /* ignore out-of-sequence */
1297				    break;
1298				}
1299			    }
1300			}
1301			q->expire = time_uptime + V_dyn_ack_lifetime;
1302			break;
1303
1304		case BOTH_SYN | BOTH_FIN:	/* both sides closed */
1305			if (V_dyn_fin_lifetime >= V_dyn_keepalive_period)
1306				V_dyn_fin_lifetime = V_dyn_keepalive_period - 1;
1307			q->expire = time_uptime + V_dyn_fin_lifetime;
1308			break;
1309
1310		default:
1311#if 0
1312			/*
1313			 * reset or some invalid combination, but can also
1314			 * occur if we use keep-state the wrong way.
1315			 */
1316			if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
1317				printf("invalid state: 0x%x\n", q->state);
1318#endif
1319			if (V_dyn_rst_lifetime >= V_dyn_keepalive_period)
1320				V_dyn_rst_lifetime = V_dyn_keepalive_period - 1;
1321			q->expire = time_uptime + V_dyn_rst_lifetime;
1322			break;
1323		}
1324	} else if (pkt->proto == IPPROTO_UDP) {
1325		q->expire = time_uptime + V_dyn_udp_lifetime;
1326	} else {
1327		/* other protocols */
1328		q->expire = time_uptime + V_dyn_short_lifetime;
1329	}
1330done:
1331	if (match_direction)
1332		*match_direction = dir;
1333	return q;
1334}
1335
1336static ipfw_dyn_rule *
1337lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
1338    struct tcphdr *tcp)
1339{
1340	ipfw_dyn_rule *q;
1341
1342	IPFW_DYN_LOCK();
1343	q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
1344	if (q == NULL)
1345		IPFW_DYN_UNLOCK();
1346	/* NB: return table locked when q is not NULL */
1347	return q;
1348}
1349
1350static void
1351realloc_dynamic_table(void)
1352{
1353	IPFW_DYN_LOCK_ASSERT();
1354
1355	/*
1356	 * Try reallocation, make sure we have a power of 2 and do
1357	 * not allow more than 64k entries. In case of overflow,
1358	 * default to 1024.
1359	 */
1360
1361	if (V_dyn_buckets > 65536)
1362		V_dyn_buckets = 1024;
1363	if ((V_dyn_buckets & (V_dyn_buckets-1)) != 0) { /* not a power of 2 */
1364		V_dyn_buckets = V_curr_dyn_buckets; /* reset */
1365		return;
1366	}
1367	V_curr_dyn_buckets = V_dyn_buckets;
1368	if (V_ipfw_dyn_v != NULL)
1369		free(V_ipfw_dyn_v, M_IPFW);
1370	for (;;) {
1371		V_ipfw_dyn_v = malloc(V_curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
1372		       M_IPFW, M_NOWAIT | M_ZERO);
1373		if (V_ipfw_dyn_v != NULL || V_curr_dyn_buckets <= 2)
1374			break;
1375		V_curr_dyn_buckets /= 2;
1376	}
1377}
1378
1379/**
1380 * Install state of type 'type' for a dynamic session.
1381 * The hash table contains two type of rules:
1382 * - regular rules (O_KEEP_STATE)
1383 * - rules for sessions with limited number of sess per user
1384 *   (O_LIMIT). When they are created, the parent is
1385 *   increased by 1, and decreased on delete. In this case,
1386 *   the third parameter is the parent rule and not the chain.
1387 * - "parent" rules for the above (O_LIMIT_PARENT).
1388 */
1389static ipfw_dyn_rule *
1390add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
1391{
1392	ipfw_dyn_rule *r;
1393	int i;
1394
1395	IPFW_DYN_LOCK_ASSERT();
1396
1397	if (V_ipfw_dyn_v == NULL ||
1398	    (V_dyn_count == 0 && V_dyn_buckets != V_curr_dyn_buckets)) {
1399		realloc_dynamic_table();
1400		if (V_ipfw_dyn_v == NULL)
1401			return NULL; /* failed ! */
1402	}
1403	i = hash_packet(id);
1404
1405	r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
1406	if (r == NULL) {
1407		printf ("ipfw: sorry cannot allocate state\n");
1408		return NULL;
1409	}
1410
1411	/* increase refcount on parent, and set pointer */
1412	if (dyn_type == O_LIMIT) {
1413		ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1414		if ( parent->dyn_type != O_LIMIT_PARENT)
1415			panic("invalid parent");
1416		parent->count++;
1417		r->parent = parent;
1418		rule = parent->rule;
1419	}
1420
1421	r->id = *id;
1422	r->expire = time_uptime + V_dyn_syn_lifetime;
1423	r->rule = rule;
1424	r->dyn_type = dyn_type;
1425	r->pcnt = r->bcnt = 0;
1426	r->count = 0;
1427
1428	r->bucket = i;
1429	r->next = V_ipfw_dyn_v[i];
1430	V_ipfw_dyn_v[i] = r;
1431	V_dyn_count++;
1432	DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1433	   dyn_type,
1434	   (r->id.src_ip), (r->id.src_port),
1435	   (r->id.dst_ip), (r->id.dst_port),
1436	   V_dyn_count ); )
1437	return r;
1438}
1439
1440/**
1441 * lookup dynamic parent rule using pkt and rule as search keys.
1442 * If the lookup fails, then install one.
1443 */
1444static ipfw_dyn_rule *
1445lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1446{
1447	ipfw_dyn_rule *q;
1448	int i;
1449
1450	IPFW_DYN_LOCK_ASSERT();
1451
1452	if (V_ipfw_dyn_v) {
1453		int is_v6 = IS_IP6_FLOW_ID(pkt);
1454		i = hash_packet( pkt );
1455		for (q = V_ipfw_dyn_v[i] ; q != NULL ; q=q->next)
1456			if (q->dyn_type == O_LIMIT_PARENT &&
1457			    rule== q->rule &&
1458			    pkt->proto == q->id.proto &&
1459			    pkt->src_port == q->id.src_port &&
1460			    pkt->dst_port == q->id.dst_port &&
1461			    (
1462				(is_v6 &&
1463				 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
1464					&(q->id.src_ip6)) &&
1465				 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
1466					&(q->id.dst_ip6))) ||
1467				(!is_v6 &&
1468				 pkt->src_ip == q->id.src_ip &&
1469				 pkt->dst_ip == q->id.dst_ip)
1470			    )
1471			) {
1472				q->expire = time_uptime + V_dyn_short_lifetime;
1473				DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
1474				return q;
1475			}
1476	}
1477	return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1478}
1479
1480/**
1481 * Install dynamic state for rule type cmd->o.opcode
1482 *
1483 * Returns 1 (failure) if state is not installed because of errors or because
1484 * session limitations are enforced.
1485 */
1486static int
1487install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1488    struct ip_fw_args *args, uint32_t tablearg)
1489{
1490	static int last_log;
1491	ipfw_dyn_rule *q;
1492	struct in_addr da;
1493	char src[48], dst[48];
1494
1495	src[0] = '\0';
1496	dst[0] = '\0';
1497
1498	DEB(
1499	printf("ipfw: %s: type %d 0x%08x %u -> 0x%08x %u\n",
1500	    __func__, cmd->o.opcode,
1501	    (args->f_id.src_ip), (args->f_id.src_port),
1502	    (args->f_id.dst_ip), (args->f_id.dst_port));
1503	)
1504
1505	IPFW_DYN_LOCK();
1506
1507	q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1508
1509	if (q != NULL) {	/* should never occur */
1510		if (last_log != time_uptime) {
1511			last_log = time_uptime;
1512			printf("ipfw: %s: entry already present, done\n",
1513			    __func__);
1514		}
1515		IPFW_DYN_UNLOCK();
1516		return (0);
1517	}
1518
1519	if (V_dyn_count >= V_dyn_max)
1520		/* Run out of slots, try to remove any expired rule. */
1521		remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1522
1523	if (V_dyn_count >= V_dyn_max) {
1524		if (last_log != time_uptime) {
1525			last_log = time_uptime;
1526			printf("ipfw: %s: Too many dynamic rules\n", __func__);
1527		}
1528		IPFW_DYN_UNLOCK();
1529		return (1);	/* cannot install, notify caller */
1530	}
1531
1532	switch (cmd->o.opcode) {
1533	case O_KEEP_STATE:	/* bidir rule */
1534		add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1535		break;
1536
1537	case O_LIMIT: {		/* limit number of sessions */
1538		struct ipfw_flow_id id;
1539		ipfw_dyn_rule *parent;
1540		uint32_t conn_limit;
1541		uint16_t limit_mask = cmd->limit_mask;
1542
1543		conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ?
1544		    tablearg : cmd->conn_limit;
1545
1546		DEB(
1547		if (cmd->conn_limit == IP_FW_TABLEARG)
1548			printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
1549			    "(tablearg)\n", __func__, conn_limit);
1550		else
1551			printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
1552			    __func__, conn_limit);
1553		)
1554
1555		id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
1556		id.proto = args->f_id.proto;
1557		id.addr_type = args->f_id.addr_type;
1558		id.fib = M_GETFIB(args->m);
1559
1560		if (IS_IP6_FLOW_ID (&(args->f_id))) {
1561			if (limit_mask & DYN_SRC_ADDR)
1562				id.src_ip6 = args->f_id.src_ip6;
1563			if (limit_mask & DYN_DST_ADDR)
1564				id.dst_ip6 = args->f_id.dst_ip6;
1565		} else {
1566			if (limit_mask & DYN_SRC_ADDR)
1567				id.src_ip = args->f_id.src_ip;
1568			if (limit_mask & DYN_DST_ADDR)
1569				id.dst_ip = args->f_id.dst_ip;
1570		}
1571		if (limit_mask & DYN_SRC_PORT)
1572			id.src_port = args->f_id.src_port;
1573		if (limit_mask & DYN_DST_PORT)
1574			id.dst_port = args->f_id.dst_port;
1575		if ((parent = lookup_dyn_parent(&id, rule)) == NULL) {
1576			printf("ipfw: %s: add parent failed\n", __func__);
1577			IPFW_DYN_UNLOCK();
1578			return (1);
1579		}
1580
1581		if (parent->count >= conn_limit) {
1582			/* See if we can remove some expired rule. */
1583			remove_dyn_rule(rule, parent);
1584			if (parent->count >= conn_limit) {
1585				if (V_fw_verbose && last_log != time_uptime) {
1586					last_log = time_uptime;
1587#ifdef INET6
1588					/*
1589					 * XXX IPv6 flows are not
1590					 * supported yet.
1591					 */
1592					if (IS_IP6_FLOW_ID(&(args->f_id))) {
1593						char ip6buf[INET6_ADDRSTRLEN];
1594						snprintf(src, sizeof(src),
1595						    "[%s]", ip6_sprintf(ip6buf,
1596							&args->f_id.src_ip6));
1597						snprintf(dst, sizeof(dst),
1598						    "[%s]", ip6_sprintf(ip6buf,
1599							&args->f_id.dst_ip6));
1600					} else
1601#endif
1602					{
1603						da.s_addr =
1604						    htonl(args->f_id.src_ip);
1605						inet_ntoa_r(da, src);
1606						da.s_addr =
1607						    htonl(args->f_id.dst_ip);
1608						inet_ntoa_r(da, dst);
1609					}
1610					log(LOG_SECURITY | LOG_DEBUG,
1611					    "ipfw: %d %s %s:%u -> %s:%u, %s\n",
1612					    parent->rule->rulenum,
1613					    "drop session",
1614					    src, (args->f_id.src_port),
1615					    dst, (args->f_id.dst_port),
1616					    "too many entries");
1617				}
1618				IPFW_DYN_UNLOCK();
1619				return (1);
1620			}
1621		}
1622		add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1623		break;
1624	}
1625	default:
1626		printf("ipfw: %s: unknown dynamic rule type %u\n",
1627		    __func__, cmd->o.opcode);
1628		IPFW_DYN_UNLOCK();
1629		return (1);
1630	}
1631
1632	/* XXX just set lifetime */
1633	lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1634
1635	IPFW_DYN_UNLOCK();
1636	return (0);
1637}
1638
1639/*
1640 * Generate a TCP packet, containing either a RST or a keepalive.
1641 * When flags & TH_RST, we are sending a RST packet, because of a
1642 * "reset" action matched the packet.
1643 * Otherwise we are sending a keepalive, and flags & TH_
1644 * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
1645 * so that MAC can label the reply appropriately.
1646 */
1647static struct mbuf *
1648send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
1649    u_int32_t ack, int flags)
1650{
1651	struct mbuf *m;
1652	struct ip *ip;
1653	struct tcphdr *tcp;
1654
1655	MGETHDR(m, M_DONTWAIT, MT_DATA);
1656	if (m == 0)
1657		return (NULL);
1658	m->m_pkthdr.rcvif = (struct ifnet *)0;
1659
1660	M_SETFIB(m, id->fib);
1661#ifdef MAC
1662	if (replyto != NULL)
1663		mac_netinet_firewall_reply(replyto, m);
1664	else
1665		mac_netinet_firewall_send(m);
1666#else
1667	(void)replyto;		/* don't warn about unused arg */
1668#endif
1669
1670	m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1671	m->m_data += max_linkhdr;
1672
1673	ip = mtod(m, struct ip *);
1674	bzero(ip, m->m_len);
1675	tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1676	ip->ip_p = IPPROTO_TCP;
1677	tcp->th_off = 5;
1678	/*
1679	 * Assume we are sending a RST (or a keepalive in the reverse
1680	 * direction), swap src and destination addresses and ports.
1681	 */
1682	ip->ip_src.s_addr = htonl(id->dst_ip);
1683	ip->ip_dst.s_addr = htonl(id->src_ip);
1684	tcp->th_sport = htons(id->dst_port);
1685	tcp->th_dport = htons(id->src_port);
1686	if (flags & TH_RST) {	/* we are sending a RST */
1687		if (flags & TH_ACK) {
1688			tcp->th_seq = htonl(ack);
1689			tcp->th_ack = htonl(0);
1690			tcp->th_flags = TH_RST;
1691		} else {
1692			if (flags & TH_SYN)
1693				seq++;
1694			tcp->th_seq = htonl(0);
1695			tcp->th_ack = htonl(seq);
1696			tcp->th_flags = TH_RST | TH_ACK;
1697		}
1698	} else {
1699		/*
1700		 * We are sending a keepalive. flags & TH_SYN determines
1701		 * the direction, forward if set, reverse if clear.
1702		 * NOTE: seq and ack are always assumed to be correct
1703		 * as set by the caller. This may be confusing...
1704		 */
1705		if (flags & TH_SYN) {
1706			/*
1707			 * we have to rewrite the correct addresses!
1708			 */
1709			ip->ip_dst.s_addr = htonl(id->dst_ip);
1710			ip->ip_src.s_addr = htonl(id->src_ip);
1711			tcp->th_dport = htons(id->dst_port);
1712			tcp->th_sport = htons(id->src_port);
1713		}
1714		tcp->th_seq = htonl(seq);
1715		tcp->th_ack = htonl(ack);
1716		tcp->th_flags = TH_ACK;
1717	}
1718	/*
1719	 * set ip_len to the payload size so we can compute
1720	 * the tcp checksum on the pseudoheader
1721	 * XXX check this, could save a couple of words ?
1722	 */
1723	ip->ip_len = htons(sizeof(struct tcphdr));
1724	tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1725	/*
1726	 * now fill fields left out earlier
1727	 */
1728	ip->ip_ttl = V_ip_defttl;
1729	ip->ip_len = m->m_pkthdr.len;
1730	m->m_flags |= M_SKIP_FIREWALL;
1731	return (m);
1732}
1733
1734/*
1735 * sends a reject message, consuming the mbuf passed as an argument.
1736 */
1737static void
1738send_reject(struct ip_fw_args *args, int code, int ip_len, struct ip *ip)
1739{
1740
1741#if 0
1742	/* XXX When ip is not guaranteed to be at mtod() we will
1743	 * need to account for this */
1744	 * The mbuf will however be thrown away so we can adjust it.
1745	 * Remember we did an m_pullup on it already so we
1746	 * can make some assumptions about contiguousness.
1747	 */
1748	if (args->L3offset)
1749		m_adj(m, args->L3offset);
1750#endif
1751	if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1752		/* We need the IP header in host order for icmp_error(). */
1753		if (args->eh != NULL) {
1754			ip->ip_len = ntohs(ip->ip_len);
1755			ip->ip_off = ntohs(ip->ip_off);
1756		}
1757		icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1758	} else if (args->f_id.proto == IPPROTO_TCP) {
1759		struct tcphdr *const tcp =
1760		    L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1761		if ( (tcp->th_flags & TH_RST) == 0) {
1762			struct mbuf *m;
1763			m = send_pkt(args->m, &(args->f_id),
1764				ntohl(tcp->th_seq), ntohl(tcp->th_ack),
1765				tcp->th_flags | TH_RST);
1766			if (m != NULL)
1767				ip_output(m, NULL, NULL, 0, NULL, NULL);
1768		}
1769		m_freem(args->m);
1770	} else
1771		m_freem(args->m);
1772	args->m = NULL;
1773}
1774
1775/**
1776 *
1777 * Given an ip_fw *, lookup_next_rule will return a pointer
1778 * to the next rule, which can be either the jump
1779 * target (for skipto instructions) or the next one in the list (in
1780 * all other cases including a missing jump target).
1781 * The result is also written in the "next_rule" field of the rule.
1782 * Backward jumps are not allowed, so start looking from the next
1783 * rule...
1784 *
1785 * This never returns NULL -- in case we do not have an exact match,
1786 * the next rule is returned. When the ruleset is changed,
1787 * pointers are flushed so we are always correct.
1788 */
1789
1790static struct ip_fw *
1791lookup_next_rule(struct ip_fw *me, u_int32_t tablearg)
1792{
1793	struct ip_fw *rule = NULL;
1794	ipfw_insn *cmd;
1795	u_int16_t	rulenum;
1796
1797	/* look for action, in case it is a skipto */
1798	cmd = ACTION_PTR(me);
1799	if (cmd->opcode == O_LOG)
1800		cmd += F_LEN(cmd);
1801	if (cmd->opcode == O_ALTQ)
1802		cmd += F_LEN(cmd);
1803	if (cmd->opcode == O_TAG)
1804		cmd += F_LEN(cmd);
1805	if (cmd->opcode == O_SKIPTO ) {
1806		if (tablearg != 0) {
1807			rulenum = (u_int16_t)tablearg;
1808		} else {
1809			rulenum = cmd->arg1;
1810		}
1811		for (rule = me->next; rule ; rule = rule->next) {
1812			if (rule->rulenum >= rulenum) {
1813				break;
1814			}
1815		}
1816	}
1817	if (rule == NULL)			/* failure or not a skipto */
1818		rule = me->next;
1819	me->next_rule = rule;
1820	return rule;
1821}
1822
1823static int
1824add_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1825    uint8_t mlen, uint32_t value)
1826{
1827	struct radix_node_head *rnh;
1828	struct table_entry *ent;
1829	struct radix_node *rn;
1830
1831	if (tbl >= IPFW_TABLES_MAX)
1832		return (EINVAL);
1833	rnh = ch->tables[tbl];
1834	ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO);
1835	if (ent == NULL)
1836		return (ENOMEM);
1837	ent->value = value;
1838	ent->addr.sin_len = ent->mask.sin_len = 8;
1839	ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1840	ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr;
1841	IPFW_WLOCK(ch);
1842	rn = rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent);
1843	if (rn == NULL) {
1844		IPFW_WUNLOCK(ch);
1845		free(ent, M_IPFW_TBL);
1846		return (EEXIST);
1847	}
1848	IPFW_WUNLOCK(ch);
1849	return (0);
1850}
1851
1852static int
1853del_table_entry(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1854    uint8_t mlen)
1855{
1856	struct radix_node_head *rnh;
1857	struct table_entry *ent;
1858	struct sockaddr_in sa, mask;
1859
1860	if (tbl >= IPFW_TABLES_MAX)
1861		return (EINVAL);
1862	rnh = ch->tables[tbl];
1863	sa.sin_len = mask.sin_len = 8;
1864	mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1865	sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr;
1866	IPFW_WLOCK(ch);
1867	ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh);
1868	if (ent == NULL) {
1869		IPFW_WUNLOCK(ch);
1870		return (ESRCH);
1871	}
1872	IPFW_WUNLOCK(ch);
1873	free(ent, M_IPFW_TBL);
1874	return (0);
1875}
1876
1877static int
1878flush_table_entry(struct radix_node *rn, void *arg)
1879{
1880	struct radix_node_head * const rnh = arg;
1881	struct table_entry *ent;
1882
1883	ent = (struct table_entry *)
1884	    rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh);
1885	if (ent != NULL)
1886		free(ent, M_IPFW_TBL);
1887	return (0);
1888}
1889
1890static int
1891flush_table(struct ip_fw_chain *ch, uint16_t tbl)
1892{
1893	struct radix_node_head *rnh;
1894
1895	IPFW_WLOCK_ASSERT(ch);
1896
1897	if (tbl >= IPFW_TABLES_MAX)
1898		return (EINVAL);
1899	rnh = ch->tables[tbl];
1900	KASSERT(rnh != NULL, ("NULL IPFW table"));
1901	rnh->rnh_walktree(rnh, flush_table_entry, rnh);
1902	return (0);
1903}
1904
1905static void
1906flush_tables(struct ip_fw_chain *ch)
1907{
1908	uint16_t tbl;
1909
1910	IPFW_WLOCK_ASSERT(ch);
1911
1912	for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++)
1913		flush_table(ch, tbl);
1914}
1915
1916static int
1917init_tables(struct ip_fw_chain *ch)
1918{
1919	int i;
1920	uint16_t j;
1921
1922	for (i = 0; i < IPFW_TABLES_MAX; i++) {
1923		if (!rn_inithead((void **)&ch->tables[i], 32)) {
1924			for (j = 0; j < i; j++) {
1925				(void) flush_table(ch, j);
1926			}
1927			return (ENOMEM);
1928		}
1929	}
1930	return (0);
1931}
1932
1933static int
1934lookup_table(struct ip_fw_chain *ch, uint16_t tbl, in_addr_t addr,
1935    uint32_t *val)
1936{
1937	struct radix_node_head *rnh;
1938	struct table_entry *ent;
1939	struct sockaddr_in sa;
1940
1941	if (tbl >= IPFW_TABLES_MAX)
1942		return (0);
1943	rnh = ch->tables[tbl];
1944	sa.sin_len = 8;
1945	sa.sin_addr.s_addr = addr;
1946	ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh));
1947	if (ent != NULL) {
1948		*val = ent->value;
1949		return (1);
1950	}
1951	return (0);
1952}
1953
1954static int
1955count_table_entry(struct radix_node *rn, void *arg)
1956{
1957	u_int32_t * const cnt = arg;
1958
1959	(*cnt)++;
1960	return (0);
1961}
1962
1963static int
1964count_table(struct ip_fw_chain *ch, uint32_t tbl, uint32_t *cnt)
1965{
1966	struct radix_node_head *rnh;
1967
1968	if (tbl >= IPFW_TABLES_MAX)
1969		return (EINVAL);
1970	rnh = ch->tables[tbl];
1971	*cnt = 0;
1972	rnh->rnh_walktree(rnh, count_table_entry, cnt);
1973	return (0);
1974}
1975
1976static int
1977dump_table_entry(struct radix_node *rn, void *arg)
1978{
1979	struct table_entry * const n = (struct table_entry *)rn;
1980	ipfw_table * const tbl = arg;
1981	ipfw_table_entry *ent;
1982
1983	if (tbl->cnt == tbl->size)
1984		return (1);
1985	ent = &tbl->ent[tbl->cnt];
1986	ent->tbl = tbl->tbl;
1987	if (in_nullhost(n->mask.sin_addr))
1988		ent->masklen = 0;
1989	else
1990		ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr));
1991	ent->addr = n->addr.sin_addr.s_addr;
1992	ent->value = n->value;
1993	tbl->cnt++;
1994	return (0);
1995}
1996
1997static int
1998dump_table(struct ip_fw_chain *ch, ipfw_table *tbl)
1999{
2000	struct radix_node_head *rnh;
2001
2002	if (tbl->tbl >= IPFW_TABLES_MAX)
2003		return (EINVAL);
2004	rnh = ch->tables[tbl->tbl];
2005	tbl->cnt = 0;
2006	rnh->rnh_walktree(rnh, dump_table_entry, tbl);
2007	return (0);
2008}
2009
2010static int
2011check_uidgid(ipfw_insn_u32 *insn, int proto, struct ifnet *oif,
2012    struct in_addr dst_ip, u_int16_t dst_port, struct in_addr src_ip,
2013    u_int16_t src_port, struct ucred **uc, int *ugid_lookupp,
2014    struct inpcb *inp)
2015{
2016	struct inpcbinfo *pi;
2017	int wildcard;
2018	struct inpcb *pcb;
2019	int match;
2020
2021	/*
2022	 * Check to see if the UDP or TCP stack supplied us with
2023	 * the PCB. If so, rather then holding a lock and looking
2024	 * up the PCB, we can use the one that was supplied.
2025	 */
2026	if (inp && *ugid_lookupp == 0) {
2027		INP_LOCK_ASSERT(inp);
2028		if (inp->inp_socket != NULL) {
2029			*uc = crhold(inp->inp_cred);
2030			*ugid_lookupp = 1;
2031		} else
2032			*ugid_lookupp = -1;
2033	}
2034	/*
2035	 * If we have already been here and the packet has no
2036	 * PCB entry associated with it, then we can safely
2037	 * assume that this is a no match.
2038	 */
2039	if (*ugid_lookupp == -1)
2040		return (0);
2041	if (proto == IPPROTO_TCP) {
2042		wildcard = 0;
2043		pi = &V_tcbinfo;
2044	} else if (proto == IPPROTO_UDP) {
2045		wildcard = INPLOOKUP_WILDCARD;
2046		pi = &V_udbinfo;
2047	} else
2048		return 0;
2049	match = 0;
2050	if (*ugid_lookupp == 0) {
2051		INP_INFO_RLOCK(pi);
2052		pcb =  (oif) ?
2053			in_pcblookup_hash(pi,
2054				dst_ip, htons(dst_port),
2055				src_ip, htons(src_port),
2056				wildcard, oif) :
2057			in_pcblookup_hash(pi,
2058				src_ip, htons(src_port),
2059				dst_ip, htons(dst_port),
2060				wildcard, NULL);
2061		if (pcb != NULL) {
2062			*uc = crhold(pcb->inp_cred);
2063			*ugid_lookupp = 1;
2064		}
2065		INP_INFO_RUNLOCK(pi);
2066		if (*ugid_lookupp == 0) {
2067			/*
2068			 * If the lookup did not yield any results, there
2069			 * is no sense in coming back and trying again. So
2070			 * we can set lookup to -1 and ensure that we wont
2071			 * bother the pcb system again.
2072			 */
2073			*ugid_lookupp = -1;
2074			return (0);
2075		}
2076	}
2077	if (insn->o.opcode == O_UID)
2078		match = ((*uc)->cr_uid == (uid_t)insn->d[0]);
2079	else if (insn->o.opcode == O_GID)
2080		match = groupmember((gid_t)insn->d[0], *uc);
2081	else if (insn->o.opcode == O_JAIL)
2082		match = ((*uc)->cr_prison->pr_id == (int)insn->d[0]);
2083	return match;
2084}
2085
2086/*
2087 * The main check routine for the firewall.
2088 *
2089 * All arguments are in args so we can modify them and return them
2090 * back to the caller.
2091 *
2092 * Parameters:
2093 *
2094 *	args->m	(in/out) The packet; we set to NULL when/if we nuke it.
2095 *		Starts with the IP header.
2096 *	args->eh (in)	Mac header if present, or NULL for layer3 packet.
2097 *	args->L3offset	Number of bytes bypassed if we came from L2.
2098 *			e.g. often sizeof(eh)  ** NOTYET **
2099 *	args->oif	Outgoing interface, or NULL if packet is incoming.
2100 *		The incoming interface is in the mbuf. (in)
2101 *	args->divert_rule (in/out)
2102 *		Skip up to the first rule past this rule number;
2103 *		upon return, non-zero port number for divert or tee.
2104 *
2105 *	args->rule	Pointer to the last matching rule (in/out)
2106 *	args->next_hop	Socket we are forwarding to (out).
2107 *	args->f_id	Addresses grabbed from the packet (out)
2108 * 	args->cookie	a cookie depending on rule action
2109 *
2110 * Return value:
2111 *
2112 *	IP_FW_PASS	the packet must be accepted
2113 *	IP_FW_DENY	the packet must be dropped
2114 *	IP_FW_DIVERT	divert packet, port in m_tag
2115 *	IP_FW_TEE	tee packet, port in m_tag
2116 *	IP_FW_DUMMYNET	to dummynet, pipe in args->cookie
2117 *	IP_FW_NETGRAPH	into netgraph, cookie args->cookie
2118 *
2119 */
2120int
2121ipfw_chk(struct ip_fw_args *args)
2122{
2123
2124	/*
2125	 * Local variables holding state during the processing of a packet:
2126	 *
2127	 * IMPORTANT NOTE: to speed up the processing of rules, there
2128	 * are some assumption on the values of the variables, which
2129	 * are documented here. Should you change them, please check
2130	 * the implementation of the various instructions to make sure
2131	 * that they still work.
2132	 *
2133	 * args->eh	The MAC header. It is non-null for a layer2
2134	 *	packet, it is NULL for a layer-3 packet.
2135	 * **notyet**
2136	 * args->L3offset Offset in the packet to the L3 (IP or equiv.) header.
2137	 *
2138	 * m | args->m	Pointer to the mbuf, as received from the caller.
2139	 *	It may change if ipfw_chk() does an m_pullup, or if it
2140	 *	consumes the packet because it calls send_reject().
2141	 *	XXX This has to change, so that ipfw_chk() never modifies
2142	 *	or consumes the buffer.
2143	 * ip	is the beginning of the ip(4 or 6) header.
2144	 *	Calculated by adding the L3offset to the start of data.
2145	 *	(Until we start using L3offset, the packet is
2146	 *	supposed to start with the ip header).
2147	 */
2148	struct mbuf *m = args->m;
2149	struct ip *ip = mtod(m, struct ip *);
2150
2151	/*
2152	 * For rules which contain uid/gid or jail constraints, cache
2153	 * a copy of the users credentials after the pcb lookup has been
2154	 * executed. This will speed up the processing of rules with
2155	 * these types of constraints, as well as decrease contention
2156	 * on pcb related locks.
2157	 */
2158	struct ucred *ucred_cache = NULL;
2159	int ucred_lookup = 0;
2160
2161	/*
2162	 * divinput_flags	If non-zero, set to the IP_FW_DIVERT_*_FLAG
2163	 *	associated with a packet input on a divert socket.  This
2164	 *	will allow to distinguish traffic and its direction when
2165	 *	it originates from a divert socket.
2166	 */
2167	u_int divinput_flags = 0;
2168
2169	/*
2170	 * oif | args->oif	If NULL, ipfw_chk has been called on the
2171	 *	inbound path (ether_input, ip_input).
2172	 *	If non-NULL, ipfw_chk has been called on the outbound path
2173	 *	(ether_output, ip_output).
2174	 */
2175	struct ifnet *oif = args->oif;
2176
2177	struct ip_fw *f = NULL;		/* matching rule */
2178	int retval = 0;
2179
2180	/*
2181	 * hlen	The length of the IP header.
2182	 */
2183	u_int hlen = 0;		/* hlen >0 means we have an IP pkt */
2184
2185	/*
2186	 * offset	The offset of a fragment. offset != 0 means that
2187	 *	we have a fragment at this offset of an IPv4 packet.
2188	 *	offset == 0 means that (if this is an IPv4 packet)
2189	 *	this is the first or only fragment.
2190	 *	For IPv6 offset == 0 means there is no Fragment Header.
2191	 *	If offset != 0 for IPv6 always use correct mask to
2192	 *	get the correct offset because we add IP6F_MORE_FRAG
2193	 *	to be able to dectect the first fragment which would
2194	 *	otherwise have offset = 0.
2195	 */
2196	u_short offset = 0;
2197
2198	/*
2199	 * Local copies of addresses. They are only valid if we have
2200	 * an IP packet.
2201	 *
2202	 * proto	The protocol. Set to 0 for non-ip packets,
2203	 *	or to the protocol read from the packet otherwise.
2204	 *	proto != 0 means that we have an IPv4 packet.
2205	 *
2206	 * src_port, dst_port	port numbers, in HOST format. Only
2207	 *	valid for TCP and UDP packets.
2208	 *
2209	 * src_ip, dst_ip	ip addresses, in NETWORK format.
2210	 *	Only valid for IPv4 packets.
2211	 */
2212	u_int8_t proto;
2213	u_int16_t src_port = 0, dst_port = 0;	/* NOTE: host format	*/
2214	struct in_addr src_ip, dst_ip;		/* NOTE: network format	*/
2215	u_int16_t ip_len=0;
2216	int pktlen;
2217	u_int16_t	etype = 0;	/* Host order stored ether type */
2218
2219	/*
2220	 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
2221	 * 	MATCH_NONE when checked and not matched (q = NULL),
2222	 *	MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
2223	 */
2224	int dyn_dir = MATCH_UNKNOWN;
2225	ipfw_dyn_rule *q = NULL;
2226	struct ip_fw_chain *chain = &V_layer3_chain;
2227	struct m_tag *mtag;
2228
2229	/*
2230	 * We store in ulp a pointer to the upper layer protocol header.
2231	 * In the ipv4 case this is easy to determine from the header,
2232	 * but for ipv6 we might have some additional headers in the middle.
2233	 * ulp is NULL if not found.
2234	 */
2235	void *ulp = NULL;		/* upper layer protocol pointer. */
2236	/* XXX ipv6 variables */
2237	int is_ipv6 = 0;
2238	u_int16_t ext_hd = 0;	/* bits vector for extension header filtering */
2239	/* end of ipv6 variables */
2240	int is_ipv4 = 0;
2241
2242	if (m->m_flags & M_SKIP_FIREWALL || (! V_ipfw_vnet_ready))
2243		return (IP_FW_PASS);	/* accept */
2244
2245	dst_ip.s_addr = 0;		/* make sure it is initialized */
2246	pktlen = m->m_pkthdr.len;
2247	args->f_id.fib = M_GETFIB(m); /* note mbuf not altered) */
2248	proto = args->f_id.proto = 0;	/* mark f_id invalid */
2249		/* XXX 0 is a valid proto: IP/IPv6 Hop-by-Hop Option */
2250
2251/*
2252 * PULLUP_TO(len, p, T) makes sure that len + sizeof(T) is contiguous,
2253 * then it sets p to point at the offset "len" in the mbuf. WARNING: the
2254 * pointer might become stale after other pullups (but we never use it
2255 * this way).
2256 */
2257#define PULLUP_TO(len, p, T)						\
2258do {									\
2259	int x = (len) + sizeof(T);					\
2260	if ((m)->m_len < x) {						\
2261		args->m = m = m_pullup(m, x);				\
2262		if (m == NULL)						\
2263			goto pullup_failed;				\
2264	}								\
2265	p = (mtod(m, char *) + (len));					\
2266} while (0)
2267
2268	/*
2269	 * if we have an ether header,
2270	 */
2271	if (args->eh)
2272		etype = ntohs(args->eh->ether_type);
2273
2274	/* Identify IP packets and fill up variables. */
2275	if (pktlen >= sizeof(struct ip6_hdr) &&
2276	    (args->eh == NULL || etype == ETHERTYPE_IPV6) && ip->ip_v == 6) {
2277		struct ip6_hdr *ip6 = (struct ip6_hdr *)ip;
2278		is_ipv6 = 1;
2279		args->f_id.addr_type = 6;
2280		hlen = sizeof(struct ip6_hdr);
2281		proto = ip6->ip6_nxt;
2282
2283		/* Search extension headers to find upper layer protocols */
2284		while (ulp == NULL) {
2285			switch (proto) {
2286			case IPPROTO_ICMPV6:
2287				PULLUP_TO(hlen, ulp, struct icmp6_hdr);
2288				args->f_id.flags = ICMP6(ulp)->icmp6_type;
2289				break;
2290
2291			case IPPROTO_TCP:
2292				PULLUP_TO(hlen, ulp, struct tcphdr);
2293				dst_port = TCP(ulp)->th_dport;
2294				src_port = TCP(ulp)->th_sport;
2295				args->f_id.flags = TCP(ulp)->th_flags;
2296				break;
2297
2298			case IPPROTO_SCTP:
2299				PULLUP_TO(hlen, ulp, struct sctphdr);
2300				src_port = SCTP(ulp)->src_port;
2301				dst_port = SCTP(ulp)->dest_port;
2302				break;
2303
2304			case IPPROTO_UDP:
2305				PULLUP_TO(hlen, ulp, struct udphdr);
2306				dst_port = UDP(ulp)->uh_dport;
2307				src_port = UDP(ulp)->uh_sport;
2308				break;
2309
2310			case IPPROTO_HOPOPTS:	/* RFC 2460 */
2311				PULLUP_TO(hlen, ulp, struct ip6_hbh);
2312				ext_hd |= EXT_HOPOPTS;
2313				hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2314				proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2315				ulp = NULL;
2316				break;
2317
2318			case IPPROTO_ROUTING:	/* RFC 2460 */
2319				PULLUP_TO(hlen, ulp, struct ip6_rthdr);
2320				switch (((struct ip6_rthdr *)ulp)->ip6r_type) {
2321				case 0:
2322					ext_hd |= EXT_RTHDR0;
2323					break;
2324				case 2:
2325					ext_hd |= EXT_RTHDR2;
2326					break;
2327				default:
2328					printf("IPFW2: IPV6 - Unknown Routing "
2329					    "Header type(%d)\n",
2330					    ((struct ip6_rthdr *)ulp)->ip6r_type);
2331					if (V_fw_deny_unknown_exthdrs)
2332					    return (IP_FW_DENY);
2333					break;
2334				}
2335				ext_hd |= EXT_ROUTING;
2336				hlen += (((struct ip6_rthdr *)ulp)->ip6r_len + 1) << 3;
2337				proto = ((struct ip6_rthdr *)ulp)->ip6r_nxt;
2338				ulp = NULL;
2339				break;
2340
2341			case IPPROTO_FRAGMENT:	/* RFC 2460 */
2342				PULLUP_TO(hlen, ulp, struct ip6_frag);
2343				ext_hd |= EXT_FRAGMENT;
2344				hlen += sizeof (struct ip6_frag);
2345				proto = ((struct ip6_frag *)ulp)->ip6f_nxt;
2346				offset = ((struct ip6_frag *)ulp)->ip6f_offlg &
2347					IP6F_OFF_MASK;
2348				/* Add IP6F_MORE_FRAG for offset of first
2349				 * fragment to be != 0. */
2350				offset |= ((struct ip6_frag *)ulp)->ip6f_offlg &
2351					IP6F_MORE_FRAG;
2352				if (offset == 0) {
2353					printf("IPFW2: IPV6 - Invalid Fragment "
2354					    "Header\n");
2355					if (V_fw_deny_unknown_exthdrs)
2356					    return (IP_FW_DENY);
2357					break;
2358				}
2359				args->f_id.frag_id6 =
2360				    ntohl(((struct ip6_frag *)ulp)->ip6f_ident);
2361				ulp = NULL;
2362				break;
2363
2364			case IPPROTO_DSTOPTS:	/* RFC 2460 */
2365				PULLUP_TO(hlen, ulp, struct ip6_hbh);
2366				ext_hd |= EXT_DSTOPTS;
2367				hlen += (((struct ip6_hbh *)ulp)->ip6h_len + 1) << 3;
2368				proto = ((struct ip6_hbh *)ulp)->ip6h_nxt;
2369				ulp = NULL;
2370				break;
2371
2372			case IPPROTO_AH:	/* RFC 2402 */
2373				PULLUP_TO(hlen, ulp, struct ip6_ext);
2374				ext_hd |= EXT_AH;
2375				hlen += (((struct ip6_ext *)ulp)->ip6e_len + 2) << 2;
2376				proto = ((struct ip6_ext *)ulp)->ip6e_nxt;
2377				ulp = NULL;
2378				break;
2379
2380			case IPPROTO_ESP:	/* RFC 2406 */
2381				PULLUP_TO(hlen, ulp, uint32_t);	/* SPI, Seq# */
2382				/* Anything past Seq# is variable length and
2383				 * data past this ext. header is encrypted. */
2384				ext_hd |= EXT_ESP;
2385				break;
2386
2387			case IPPROTO_NONE:	/* RFC 2460 */
2388				/*
2389				 * Packet ends here, and IPv6 header has
2390				 * already been pulled up. If ip6e_len!=0
2391				 * then octets must be ignored.
2392				 */
2393				ulp = ip; /* non-NULL to get out of loop. */
2394				break;
2395
2396			case IPPROTO_OSPFIGP:
2397				/* XXX OSPF header check? */
2398				PULLUP_TO(hlen, ulp, struct ip6_ext);
2399				break;
2400
2401			case IPPROTO_PIM:
2402				/* XXX PIM header check? */
2403				PULLUP_TO(hlen, ulp, struct pim);
2404				break;
2405
2406			case IPPROTO_CARP:
2407				PULLUP_TO(hlen, ulp, struct carp_header);
2408				if (((struct carp_header *)ulp)->carp_version !=
2409				    CARP_VERSION)
2410					return (IP_FW_DENY);
2411				if (((struct carp_header *)ulp)->carp_type !=
2412				    CARP_ADVERTISEMENT)
2413					return (IP_FW_DENY);
2414				break;
2415
2416			case IPPROTO_IPV6:	/* RFC 2893 */
2417				PULLUP_TO(hlen, ulp, struct ip6_hdr);
2418				break;
2419
2420			case IPPROTO_IPV4:	/* RFC 2893 */
2421				PULLUP_TO(hlen, ulp, struct ip);
2422				break;
2423
2424			default:
2425				printf("IPFW2: IPV6 - Unknown Extension "
2426				    "Header(%d), ext_hd=%x\n", proto, ext_hd);
2427				if (V_fw_deny_unknown_exthdrs)
2428				    return (IP_FW_DENY);
2429				PULLUP_TO(hlen, ulp, struct ip6_ext);
2430				break;
2431			} /*switch */
2432		}
2433		ip = mtod(m, struct ip *);
2434		ip6 = (struct ip6_hdr *)ip;
2435		args->f_id.src_ip6 = ip6->ip6_src;
2436		args->f_id.dst_ip6 = ip6->ip6_dst;
2437		args->f_id.src_ip = 0;
2438		args->f_id.dst_ip = 0;
2439		args->f_id.flow_id6 = ntohl(ip6->ip6_flow);
2440	} else if (pktlen >= sizeof(struct ip) &&
2441	    (args->eh == NULL || etype == ETHERTYPE_IP) && ip->ip_v == 4) {
2442	    	is_ipv4 = 1;
2443		hlen = ip->ip_hl << 2;
2444		args->f_id.addr_type = 4;
2445
2446		/*
2447		 * Collect parameters into local variables for faster matching.
2448		 */
2449		proto = ip->ip_p;
2450		src_ip = ip->ip_src;
2451		dst_ip = ip->ip_dst;
2452		if (args->eh != NULL) { /* layer 2 packets are as on the wire */
2453			offset = ntohs(ip->ip_off) & IP_OFFMASK;
2454			ip_len = ntohs(ip->ip_len);
2455		} else {
2456			offset = ip->ip_off & IP_OFFMASK;
2457			ip_len = ip->ip_len;
2458		}
2459		pktlen = ip_len < pktlen ? ip_len : pktlen;
2460
2461		if (offset == 0) {
2462			switch (proto) {
2463			case IPPROTO_TCP:
2464				PULLUP_TO(hlen, ulp, struct tcphdr);
2465				dst_port = TCP(ulp)->th_dport;
2466				src_port = TCP(ulp)->th_sport;
2467				args->f_id.flags = TCP(ulp)->th_flags;
2468				break;
2469
2470			case IPPROTO_UDP:
2471				PULLUP_TO(hlen, ulp, struct udphdr);
2472				dst_port = UDP(ulp)->uh_dport;
2473				src_port = UDP(ulp)->uh_sport;
2474				break;
2475
2476			case IPPROTO_ICMP:
2477				PULLUP_TO(hlen, ulp, struct icmphdr);
2478				args->f_id.flags = ICMP(ulp)->icmp_type;
2479				break;
2480
2481			default:
2482				break;
2483			}
2484		}
2485
2486		ip = mtod(m, struct ip *);
2487		args->f_id.src_ip = ntohl(src_ip.s_addr);
2488		args->f_id.dst_ip = ntohl(dst_ip.s_addr);
2489	}
2490#undef PULLUP_TO
2491	if (proto) { /* we may have port numbers, store them */
2492		args->f_id.proto = proto;
2493		args->f_id.src_port = src_port = ntohs(src_port);
2494		args->f_id.dst_port = dst_port = ntohs(dst_port);
2495	}
2496
2497	IPFW_RLOCK(chain);
2498	mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
2499	if (args->rule) {
2500		/*
2501		 * Packet has already been tagged. Look for the next rule
2502		 * to restart processing. Make sure that args->rule still
2503		 * exists and not changed.
2504		 */
2505		if (chain->id != args->chain_id) {
2506			for (f = chain->rules; f != NULL; f = f->next)
2507				if (f == args->rule && f->id == args->rule_id)
2508					break;
2509
2510			if (f != NULL)
2511				f = f->next_rule;
2512			else
2513				f = ip_fw_default_rule;
2514		} else
2515			f = args->rule->next_rule;
2516
2517		if (f == NULL)
2518			f = lookup_next_rule(args->rule, 0);
2519	} else {
2520		/*
2521		 * Find the starting rule. It can be either the first
2522		 * one, or the one after divert_rule if asked so.
2523		 */
2524		int skipto = mtag ? divert_cookie(mtag) : 0;
2525
2526		f = chain->rules;
2527		if (args->eh == NULL && skipto != 0) {
2528			if (skipto >= IPFW_DEFAULT_RULE) {
2529				IPFW_RUNLOCK(chain);
2530				return (IP_FW_DENY); /* invalid */
2531			}
2532			while (f && f->rulenum <= skipto)
2533				f = f->next;
2534			if (f == NULL) {	/* drop packet */
2535				IPFW_RUNLOCK(chain);
2536				return (IP_FW_DENY);
2537			}
2538		}
2539	}
2540	/* reset divert rule to avoid confusion later */
2541	if (mtag) {
2542		divinput_flags = divert_info(mtag) &
2543		    (IP_FW_DIVERT_OUTPUT_FLAG | IP_FW_DIVERT_LOOPBACK_FLAG);
2544		m_tag_delete(m, mtag);
2545	}
2546
2547	/*
2548	 * Now scan the rules, and parse microinstructions for each rule.
2549	 */
2550	for (; f; f = f->next) {
2551		ipfw_insn *cmd;
2552		uint32_t tablearg = 0;
2553		int l, cmdlen, skip_or; /* skip rest of OR block */
2554
2555again:
2556		if (V_set_disable & (1 << f->set) )
2557			continue;
2558
2559		skip_or = 0;
2560		for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
2561		    l -= cmdlen, cmd += cmdlen) {
2562			int match;
2563
2564			/*
2565			 * check_body is a jump target used when we find a
2566			 * CHECK_STATE, and need to jump to the body of
2567			 * the target rule.
2568			 */
2569
2570check_body:
2571			cmdlen = F_LEN(cmd);
2572			/*
2573			 * An OR block (insn_1 || .. || insn_n) has the
2574			 * F_OR bit set in all but the last instruction.
2575			 * The first match will set "skip_or", and cause
2576			 * the following instructions to be skipped until
2577			 * past the one with the F_OR bit clear.
2578			 */
2579			if (skip_or) {		/* skip this instruction */
2580				if ((cmd->len & F_OR) == 0)
2581					skip_or = 0;	/* next one is good */
2582				continue;
2583			}
2584			match = 0; /* set to 1 if we succeed */
2585
2586			switch (cmd->opcode) {
2587			/*
2588			 * The first set of opcodes compares the packet's
2589			 * fields with some pattern, setting 'match' if a
2590			 * match is found. At the end of the loop there is
2591			 * logic to deal with F_NOT and F_OR flags associated
2592			 * with the opcode.
2593			 */
2594			case O_NOP:
2595				match = 1;
2596				break;
2597
2598			case O_FORWARD_MAC:
2599				printf("ipfw: opcode %d unimplemented\n",
2600				    cmd->opcode);
2601				break;
2602
2603			case O_GID:
2604			case O_UID:
2605			case O_JAIL:
2606				/*
2607				 * We only check offset == 0 && proto != 0,
2608				 * as this ensures that we have a
2609				 * packet with the ports info.
2610				 */
2611				if (offset!=0)
2612					break;
2613				if (is_ipv6) /* XXX to be fixed later */
2614					break;
2615				if (proto == IPPROTO_TCP ||
2616				    proto == IPPROTO_UDP)
2617					match = check_uidgid(
2618						    (ipfw_insn_u32 *)cmd,
2619						    proto, oif,
2620						    dst_ip, dst_port,
2621						    src_ip, src_port, &ucred_cache,
2622						    &ucred_lookup, args->inp);
2623				break;
2624
2625			case O_RECV:
2626				match = iface_match(m->m_pkthdr.rcvif,
2627				    (ipfw_insn_if *)cmd);
2628				break;
2629
2630			case O_XMIT:
2631				match = iface_match(oif, (ipfw_insn_if *)cmd);
2632				break;
2633
2634			case O_VIA:
2635				match = iface_match(oif ? oif :
2636				    m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
2637				break;
2638
2639			case O_MACADDR2:
2640				if (args->eh != NULL) {	/* have MAC header */
2641					u_int32_t *want = (u_int32_t *)
2642						((ipfw_insn_mac *)cmd)->addr;
2643					u_int32_t *mask = (u_int32_t *)
2644						((ipfw_insn_mac *)cmd)->mask;
2645					u_int32_t *hdr = (u_int32_t *)args->eh;
2646
2647					match =
2648					    ( want[0] == (hdr[0] & mask[0]) &&
2649					      want[1] == (hdr[1] & mask[1]) &&
2650					      want[2] == (hdr[2] & mask[2]) );
2651				}
2652				break;
2653
2654			case O_MAC_TYPE:
2655				if (args->eh != NULL) {
2656					u_int16_t *p =
2657					    ((ipfw_insn_u16 *)cmd)->ports;
2658					int i;
2659
2660					for (i = cmdlen - 1; !match && i>0;
2661					    i--, p += 2)
2662						match = (etype >= p[0] &&
2663						    etype <= p[1]);
2664				}
2665				break;
2666
2667			case O_FRAG:
2668				match = (offset != 0);
2669				break;
2670
2671			case O_IN:	/* "out" is "not in" */
2672				match = (oif == NULL);
2673				break;
2674
2675			case O_LAYER2:
2676				match = (args->eh != NULL);
2677				break;
2678
2679			case O_DIVERTED:
2680				match = (cmd->arg1 & 1 && divinput_flags &
2681				    IP_FW_DIVERT_LOOPBACK_FLAG) ||
2682					(cmd->arg1 & 2 && divinput_flags &
2683				    IP_FW_DIVERT_OUTPUT_FLAG);
2684				break;
2685
2686			case O_PROTO:
2687				/*
2688				 * We do not allow an arg of 0 so the
2689				 * check of "proto" only suffices.
2690				 */
2691				match = (proto == cmd->arg1);
2692				break;
2693
2694			case O_IP_SRC:
2695				match = is_ipv4 &&
2696				    (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2697				    src_ip.s_addr);
2698				break;
2699
2700			case O_IP_SRC_LOOKUP:
2701			case O_IP_DST_LOOKUP:
2702				if (is_ipv4) {
2703				    uint32_t a =
2704					(cmd->opcode == O_IP_DST_LOOKUP) ?
2705					    dst_ip.s_addr : src_ip.s_addr;
2706				    uint32_t v = 0;
2707
2708				    match = lookup_table(chain, cmd->arg1, a,
2709					&v);
2710				    if (!match)
2711					break;
2712				    if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
2713					match =
2714					    ((ipfw_insn_u32 *)cmd)->d[0] == v;
2715				    else
2716					tablearg = v;
2717				}
2718				break;
2719
2720			case O_IP_SRC_MASK:
2721			case O_IP_DST_MASK:
2722				if (is_ipv4) {
2723				    uint32_t a =
2724					(cmd->opcode == O_IP_DST_MASK) ?
2725					    dst_ip.s_addr : src_ip.s_addr;
2726				    uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
2727				    int i = cmdlen-1;
2728
2729				    for (; !match && i>0; i-= 2, p+= 2)
2730					match = (p[0] == (a & p[1]));
2731				}
2732				break;
2733
2734			case O_IP_SRC_ME:
2735				if (is_ipv4) {
2736					struct ifnet *tif;
2737
2738					INADDR_TO_IFP(src_ip, tif);
2739					match = (tif != NULL);
2740				}
2741				break;
2742
2743			case O_IP_DST_SET:
2744			case O_IP_SRC_SET:
2745				if (is_ipv4) {
2746					u_int32_t *d = (u_int32_t *)(cmd+1);
2747					u_int32_t addr =
2748					    cmd->opcode == O_IP_DST_SET ?
2749						args->f_id.dst_ip :
2750						args->f_id.src_ip;
2751
2752					    if (addr < d[0])
2753						    break;
2754					    addr -= d[0]; /* subtract base */
2755					    match = (addr < cmd->arg1) &&
2756						( d[ 1 + (addr>>5)] &
2757						  (1<<(addr & 0x1f)) );
2758				}
2759				break;
2760
2761			case O_IP_DST:
2762				match = is_ipv4 &&
2763				    (((ipfw_insn_ip *)cmd)->addr.s_addr ==
2764				    dst_ip.s_addr);
2765				break;
2766
2767			case O_IP_DST_ME:
2768				if (is_ipv4) {
2769					struct ifnet *tif;
2770
2771					INADDR_TO_IFP(dst_ip, tif);
2772					match = (tif != NULL);
2773				}
2774				break;
2775
2776			case O_IP_SRCPORT:
2777			case O_IP_DSTPORT:
2778				/*
2779				 * offset == 0 && proto != 0 is enough
2780				 * to guarantee that we have a
2781				 * packet with port info.
2782				 */
2783				if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2784				    && offset == 0) {
2785					u_int16_t x =
2786					    (cmd->opcode == O_IP_SRCPORT) ?
2787						src_port : dst_port ;
2788					u_int16_t *p =
2789					    ((ipfw_insn_u16 *)cmd)->ports;
2790					int i;
2791
2792					for (i = cmdlen - 1; !match && i>0;
2793					    i--, p += 2)
2794						match = (x>=p[0] && x<=p[1]);
2795				}
2796				break;
2797
2798			case O_ICMPTYPE:
2799				match = (offset == 0 && proto==IPPROTO_ICMP &&
2800				    icmptype_match(ICMP(ulp), (ipfw_insn_u32 *)cmd) );
2801				break;
2802
2803#ifdef INET6
2804			case O_ICMP6TYPE:
2805				match = is_ipv6 && offset == 0 &&
2806				    proto==IPPROTO_ICMPV6 &&
2807				    icmp6type_match(
2808					ICMP6(ulp)->icmp6_type,
2809					(ipfw_insn_u32 *)cmd);
2810				break;
2811#endif /* INET6 */
2812
2813			case O_IPOPT:
2814				match = (is_ipv4 &&
2815				    ipopts_match(ip, cmd) );
2816				break;
2817
2818			case O_IPVER:
2819				match = (is_ipv4 &&
2820				    cmd->arg1 == ip->ip_v);
2821				break;
2822
2823			case O_IPID:
2824			case O_IPLEN:
2825			case O_IPTTL:
2826				if (is_ipv4) {	/* only for IP packets */
2827				    uint16_t x;
2828				    uint16_t *p;
2829				    int i;
2830
2831				    if (cmd->opcode == O_IPLEN)
2832					x = ip_len;
2833				    else if (cmd->opcode == O_IPTTL)
2834					x = ip->ip_ttl;
2835				    else /* must be IPID */
2836					x = ntohs(ip->ip_id);
2837				    if (cmdlen == 1) {
2838					match = (cmd->arg1 == x);
2839					break;
2840				    }
2841				    /* otherwise we have ranges */
2842				    p = ((ipfw_insn_u16 *)cmd)->ports;
2843				    i = cmdlen - 1;
2844				    for (; !match && i>0; i--, p += 2)
2845					match = (x >= p[0] && x <= p[1]);
2846				}
2847				break;
2848
2849			case O_IPPRECEDENCE:
2850				match = (is_ipv4 &&
2851				    (cmd->arg1 == (ip->ip_tos & 0xe0)) );
2852				break;
2853
2854			case O_IPTOS:
2855				match = (is_ipv4 &&
2856				    flags_match(cmd, ip->ip_tos));
2857				break;
2858
2859			case O_TCPDATALEN:
2860				if (proto == IPPROTO_TCP && offset == 0) {
2861				    struct tcphdr *tcp;
2862				    uint16_t x;
2863				    uint16_t *p;
2864				    int i;
2865
2866				    tcp = TCP(ulp);
2867				    x = ip_len -
2868					((ip->ip_hl + tcp->th_off) << 2);
2869				    if (cmdlen == 1) {
2870					match = (cmd->arg1 == x);
2871					break;
2872				    }
2873				    /* otherwise we have ranges */
2874				    p = ((ipfw_insn_u16 *)cmd)->ports;
2875				    i = cmdlen - 1;
2876				    for (; !match && i>0; i--, p += 2)
2877					match = (x >= p[0] && x <= p[1]);
2878				}
2879				break;
2880
2881			case O_TCPFLAGS:
2882				match = (proto == IPPROTO_TCP && offset == 0 &&
2883				    flags_match(cmd, TCP(ulp)->th_flags));
2884				break;
2885
2886			case O_TCPOPTS:
2887				match = (proto == IPPROTO_TCP && offset == 0 &&
2888				    tcpopts_match(TCP(ulp), cmd));
2889				break;
2890
2891			case O_TCPSEQ:
2892				match = (proto == IPPROTO_TCP && offset == 0 &&
2893				    ((ipfw_insn_u32 *)cmd)->d[0] ==
2894					TCP(ulp)->th_seq);
2895				break;
2896
2897			case O_TCPACK:
2898				match = (proto == IPPROTO_TCP && offset == 0 &&
2899				    ((ipfw_insn_u32 *)cmd)->d[0] ==
2900					TCP(ulp)->th_ack);
2901				break;
2902
2903			case O_TCPWIN:
2904				match = (proto == IPPROTO_TCP && offset == 0 &&
2905				    cmd->arg1 == TCP(ulp)->th_win);
2906				break;
2907
2908			case O_ESTAB:
2909				/* reject packets which have SYN only */
2910				/* XXX should i also check for TH_ACK ? */
2911				match = (proto == IPPROTO_TCP && offset == 0 &&
2912				    (TCP(ulp)->th_flags &
2913				     (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2914				break;
2915
2916			case O_ALTQ: {
2917				struct pf_mtag *at;
2918				ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
2919
2920				match = 1;
2921				at = pf_find_mtag(m);
2922				if (at != NULL && at->qid != 0)
2923					break;
2924				at = pf_get_mtag(m);
2925				if (at == NULL) {
2926					/*
2927					 * Let the packet fall back to the
2928					 * default ALTQ.
2929					 */
2930					break;
2931				}
2932				at->qid = altq->qid;
2933				if (is_ipv4)
2934					at->af = AF_INET;
2935				else
2936					at->af = AF_LINK;
2937				at->hdr = ip;
2938				break;
2939			}
2940
2941			case O_LOG:
2942				if (V_fw_verbose)
2943					ipfw_log(f, hlen, args, m,
2944					    oif, offset, tablearg, ip);
2945				match = 1;
2946				break;
2947
2948			case O_PROB:
2949				match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
2950				break;
2951
2952			case O_VERREVPATH:
2953				/* Outgoing packets automatically pass/match */
2954				match = ((oif != NULL) ||
2955				    (m->m_pkthdr.rcvif == NULL) ||
2956				    (
2957#ifdef INET6
2958				    is_ipv6 ?
2959					verify_path6(&(args->f_id.src_ip6),
2960					    m->m_pkthdr.rcvif) :
2961#endif
2962				    verify_path(src_ip, m->m_pkthdr.rcvif,
2963				        args->f_id.fib)));
2964				break;
2965
2966			case O_VERSRCREACH:
2967				/* Outgoing packets automatically pass/match */
2968				match = (hlen > 0 && ((oif != NULL) ||
2969#ifdef INET6
2970				    is_ipv6 ?
2971				        verify_path6(&(args->f_id.src_ip6),
2972				            NULL) :
2973#endif
2974				    verify_path(src_ip, NULL, args->f_id.fib)));
2975				break;
2976
2977			case O_ANTISPOOF:
2978				/* Outgoing packets automatically pass/match */
2979				if (oif == NULL && hlen > 0 &&
2980				    (  (is_ipv4 && in_localaddr(src_ip))
2981#ifdef INET6
2982				    || (is_ipv6 &&
2983				        in6_localaddr(&(args->f_id.src_ip6)))
2984#endif
2985				    ))
2986					match =
2987#ifdef INET6
2988					    is_ipv6 ? verify_path6(
2989					        &(args->f_id.src_ip6),
2990					        m->m_pkthdr.rcvif) :
2991#endif
2992					    verify_path(src_ip,
2993					    	m->m_pkthdr.rcvif,
2994					        args->f_id.fib);
2995				else
2996					match = 1;
2997				break;
2998
2999			case O_IPSEC:
3000#ifdef IPSEC
3001				match = (m_tag_find(m,
3002				    PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
3003#endif
3004				/* otherwise no match */
3005				break;
3006
3007#ifdef INET6
3008			case O_IP6_SRC:
3009				match = is_ipv6 &&
3010				    IN6_ARE_ADDR_EQUAL(&args->f_id.src_ip6,
3011				    &((ipfw_insn_ip6 *)cmd)->addr6);
3012				break;
3013
3014			case O_IP6_DST:
3015				match = is_ipv6 &&
3016				IN6_ARE_ADDR_EQUAL(&args->f_id.dst_ip6,
3017				    &((ipfw_insn_ip6 *)cmd)->addr6);
3018				break;
3019			case O_IP6_SRC_MASK:
3020			case O_IP6_DST_MASK:
3021				if (is_ipv6) {
3022					int i = cmdlen - 1;
3023					struct in6_addr p;
3024					struct in6_addr *d =
3025					    &((ipfw_insn_ip6 *)cmd)->addr6;
3026
3027					for (; !match && i > 0; d += 2,
3028					    i -= F_INSN_SIZE(struct in6_addr)
3029					    * 2) {
3030						p = (cmd->opcode ==
3031						    O_IP6_SRC_MASK) ?
3032						    args->f_id.src_ip6:
3033						    args->f_id.dst_ip6;
3034						APPLY_MASK(&p, &d[1]);
3035						match =
3036						    IN6_ARE_ADDR_EQUAL(&d[0],
3037						    &p);
3038					}
3039				}
3040				break;
3041
3042			case O_IP6_SRC_ME:
3043				match= is_ipv6 && search_ip6_addr_net(&args->f_id.src_ip6);
3044				break;
3045
3046			case O_IP6_DST_ME:
3047				match= is_ipv6 && search_ip6_addr_net(&args->f_id.dst_ip6);
3048				break;
3049
3050			case O_FLOW6ID:
3051				match = is_ipv6 &&
3052				    flow6id_match(args->f_id.flow_id6,
3053				    (ipfw_insn_u32 *) cmd);
3054				break;
3055
3056			case O_EXT_HDR:
3057				match = is_ipv6 &&
3058				    (ext_hd & ((ipfw_insn *) cmd)->arg1);
3059				break;
3060
3061			case O_IP6:
3062				match = is_ipv6;
3063				break;
3064#endif
3065
3066			case O_IP4:
3067				match = is_ipv4;
3068				break;
3069
3070			case O_TAG: {
3071				uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3072				    tablearg : cmd->arg1;
3073
3074				/* Packet is already tagged with this tag? */
3075				mtag = m_tag_locate(m, MTAG_IPFW, tag, NULL);
3076
3077				/* We have `untag' action when F_NOT flag is
3078				 * present. And we must remove this mtag from
3079				 * mbuf and reset `match' to zero (`match' will
3080				 * be inversed later).
3081				 * Otherwise we should allocate new mtag and
3082				 * push it into mbuf.
3083				 */
3084				if (cmd->len & F_NOT) { /* `untag' action */
3085					if (mtag != NULL)
3086						m_tag_delete(m, mtag);
3087				} else if (mtag == NULL) {
3088					if ((mtag = m_tag_alloc(MTAG_IPFW,
3089					    tag, 0, M_NOWAIT)) != NULL)
3090						m_tag_prepend(m, mtag);
3091				}
3092				match = (cmd->len & F_NOT) ? 0: 1;
3093				break;
3094			}
3095
3096			case O_FIB: /* try match the specified fib */
3097				if (args->f_id.fib == cmd->arg1)
3098					match = 1;
3099				break;
3100
3101			case O_TAGGED: {
3102				uint32_t tag = (cmd->arg1 == IP_FW_TABLEARG) ?
3103				    tablearg : cmd->arg1;
3104
3105				if (cmdlen == 1) {
3106					match = m_tag_locate(m, MTAG_IPFW,
3107					    tag, NULL) != NULL;
3108					break;
3109				}
3110
3111				/* we have ranges */
3112				for (mtag = m_tag_first(m);
3113				    mtag != NULL && !match;
3114				    mtag = m_tag_next(m, mtag)) {
3115					uint16_t *p;
3116					int i;
3117
3118					if (mtag->m_tag_cookie != MTAG_IPFW)
3119						continue;
3120
3121					p = ((ipfw_insn_u16 *)cmd)->ports;
3122					i = cmdlen - 1;
3123					for(; !match && i > 0; i--, p += 2)
3124						match =
3125						    mtag->m_tag_id >= p[0] &&
3126						    mtag->m_tag_id <= p[1];
3127				}
3128				break;
3129			}
3130
3131			/*
3132			 * The second set of opcodes represents 'actions',
3133			 * i.e. the terminal part of a rule once the packet
3134			 * matches all previous patterns.
3135			 * Typically there is only one action for each rule,
3136			 * and the opcode is stored at the end of the rule
3137			 * (but there are exceptions -- see below).
3138			 *
3139			 * In general, here we set retval and terminate the
3140			 * outer loop (would be a 'break 3' in some language,
3141			 * but we need to do a 'goto done').
3142			 *
3143			 * Exceptions:
3144			 * O_COUNT and O_SKIPTO actions:
3145			 *   instead of terminating, we jump to the next rule
3146			 *   ('goto next_rule', equivalent to a 'break 2'),
3147			 *   or to the SKIPTO target ('goto again' after
3148			 *   having set f, cmd and l), respectively.
3149			 *
3150			 * O_TAG, O_LOG and O_ALTQ action parameters:
3151			 *   perform some action and set match = 1;
3152			 *
3153			 * O_LIMIT and O_KEEP_STATE: these opcodes are
3154			 *   not real 'actions', and are stored right
3155			 *   before the 'action' part of the rule.
3156			 *   These opcodes try to install an entry in the
3157			 *   state tables; if successful, we continue with
3158			 *   the next opcode (match=1; break;), otherwise
3159			 *   the packet *   must be dropped
3160			 *   ('goto done' after setting retval);
3161			 *
3162			 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
3163			 *   cause a lookup of the state table, and a jump
3164			 *   to the 'action' part of the parent rule
3165			 *   ('goto check_body') if an entry is found, or
3166			 *   (CHECK_STATE only) a jump to the next rule if
3167			 *   the entry is not found ('goto next_rule').
3168			 *   The result of the lookup is cached to make
3169			 *   further instances of these opcodes are
3170			 *   effectively NOPs.
3171			 */
3172			case O_LIMIT:
3173			case O_KEEP_STATE:
3174				if (install_state(f,
3175				    (ipfw_insn_limit *)cmd, args, tablearg)) {
3176					retval = IP_FW_DENY;
3177					goto done; /* error/limit violation */
3178				}
3179				match = 1;
3180				break;
3181
3182			case O_PROBE_STATE:
3183			case O_CHECK_STATE:
3184				/*
3185				 * dynamic rules are checked at the first
3186				 * keep-state or check-state occurrence,
3187				 * with the result being stored in dyn_dir.
3188				 * The compiler introduces a PROBE_STATE
3189				 * instruction for us when we have a
3190				 * KEEP_STATE (because PROBE_STATE needs
3191				 * to be run first).
3192				 */
3193				if (dyn_dir == MATCH_UNKNOWN &&
3194				    (q = lookup_dyn_rule(&args->f_id,
3195				     &dyn_dir, proto == IPPROTO_TCP ?
3196					TCP(ulp) : NULL))
3197					!= NULL) {
3198					/*
3199					 * Found dynamic entry, update stats
3200					 * and jump to the 'action' part of
3201					 * the parent rule.
3202					 */
3203					q->pcnt++;
3204					q->bcnt += pktlen;
3205					f = q->rule;
3206					cmd = ACTION_PTR(f);
3207					l = f->cmd_len - f->act_ofs;
3208					IPFW_DYN_UNLOCK();
3209					goto check_body;
3210				}
3211				/*
3212				 * Dynamic entry not found. If CHECK_STATE,
3213				 * skip to next rule, if PROBE_STATE just
3214				 * ignore and continue with next opcode.
3215				 */
3216				if (cmd->opcode == O_CHECK_STATE)
3217					goto next_rule;
3218				match = 1;
3219				break;
3220
3221			case O_ACCEPT:
3222				retval = 0;	/* accept */
3223				goto done;
3224
3225			case O_PIPE:
3226			case O_QUEUE:
3227				args->rule = f; /* report matching rule */
3228				args->rule_id = f->id;
3229				args->chain_id = chain->id;
3230				if (cmd->arg1 == IP_FW_TABLEARG)
3231					args->cookie = tablearg;
3232				else
3233					args->cookie = cmd->arg1;
3234				retval = IP_FW_DUMMYNET;
3235				goto done;
3236
3237			case O_DIVERT:
3238			case O_TEE: {
3239				struct divert_tag *dt;
3240
3241				if (args->eh) /* not on layer 2 */
3242					break;
3243				mtag = m_tag_get(PACKET_TAG_DIVERT,
3244						sizeof(struct divert_tag),
3245						M_NOWAIT);
3246				if (mtag == NULL) {
3247					/* XXX statistic */
3248					/* drop packet */
3249					IPFW_RUNLOCK(chain);
3250					if (ucred_cache != NULL)
3251						crfree(ucred_cache);
3252					return (IP_FW_DENY);
3253				}
3254				dt = (struct divert_tag *)(mtag+1);
3255				dt->cookie = f->rulenum;
3256				if (cmd->arg1 == IP_FW_TABLEARG)
3257					dt->info = tablearg;
3258				else
3259					dt->info = cmd->arg1;
3260				m_tag_prepend(m, mtag);
3261				retval = (cmd->opcode == O_DIVERT) ?
3262				    IP_FW_DIVERT : IP_FW_TEE;
3263				goto done;
3264			}
3265			case O_COUNT:
3266			case O_SKIPTO:
3267				f->pcnt++;	/* update stats */
3268				f->bcnt += pktlen;
3269				f->timestamp = time_uptime;
3270				if (cmd->opcode == O_COUNT)
3271					goto next_rule;
3272				/* handle skipto */
3273				if (cmd->arg1 == IP_FW_TABLEARG) {
3274					f = lookup_next_rule(f, tablearg);
3275				} else {
3276					if (f->next_rule == NULL)
3277						lookup_next_rule(f, 0);
3278					f = f->next_rule;
3279				}
3280				goto again;
3281
3282			case O_REJECT:
3283				/*
3284				 * Drop the packet and send a reject notice
3285				 * if the packet is not ICMP (or is an ICMP
3286				 * query), and it is not multicast/broadcast.
3287				 */
3288				if (hlen > 0 && is_ipv4 && offset == 0 &&
3289				    (proto != IPPROTO_ICMP ||
3290				     is_icmp_query(ICMP(ulp))) &&
3291				    !(m->m_flags & (M_BCAST|M_MCAST)) &&
3292				    !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
3293					send_reject(args, cmd->arg1, ip_len, ip);
3294					m = args->m;
3295				}
3296				/* FALLTHROUGH */
3297#ifdef INET6
3298			case O_UNREACH6:
3299				if (hlen > 0 && is_ipv6 &&
3300				    ((offset & IP6F_OFF_MASK) == 0) &&
3301				    (proto != IPPROTO_ICMPV6 ||
3302				     (is_icmp6_query(args->f_id.flags) == 1)) &&
3303				    !(m->m_flags & (M_BCAST|M_MCAST)) &&
3304				    !IN6_IS_ADDR_MULTICAST(&args->f_id.dst_ip6)) {
3305					send_reject6(
3306					    args, cmd->arg1, hlen,
3307					    (struct ip6_hdr *)ip);
3308					m = args->m;
3309				}
3310				/* FALLTHROUGH */
3311#endif
3312			case O_DENY:
3313				retval = IP_FW_DENY;
3314				goto done;
3315
3316			case O_FORWARD_IP: {
3317				struct sockaddr_in *sa;
3318				sa = &(((ipfw_insn_sa *)cmd)->sa);
3319				if (args->eh)	/* not valid on layer2 pkts */
3320					break;
3321				if (!q || dyn_dir == MATCH_FORWARD) {
3322					if (sa->sin_addr.s_addr == INADDR_ANY) {
3323						bcopy(sa, &args->hopstore,
3324							sizeof(*sa));
3325						args->hopstore.sin_addr.s_addr =
3326						    htonl(tablearg);
3327						args->next_hop =
3328						    &args->hopstore;
3329					} else {
3330						args->next_hop = sa;
3331					}
3332				}
3333				retval = IP_FW_PASS;
3334			    }
3335			    goto done;
3336
3337			case O_NETGRAPH:
3338			case O_NGTEE:
3339				args->rule = f;	/* report matching rule */
3340				args->rule_id = f->id;
3341				args->chain_id = chain->id;
3342				if (cmd->arg1 == IP_FW_TABLEARG)
3343					args->cookie = tablearg;
3344				else
3345					args->cookie = cmd->arg1;
3346				retval = (cmd->opcode == O_NETGRAPH) ?
3347				    IP_FW_NETGRAPH : IP_FW_NGTEE;
3348				goto done;
3349
3350			case O_SETFIB:
3351				f->pcnt++;	/* update stats */
3352				f->bcnt += pktlen;
3353				f->timestamp = time_uptime;
3354				M_SETFIB(m, cmd->arg1);
3355				args->f_id.fib = cmd->arg1;
3356				goto next_rule;
3357
3358			case O_NAT: {
3359                        	struct cfg_nat *t;
3360                        	int nat_id;
3361
3362 				if (IPFW_NAT_LOADED) {
3363					args->rule = f; /* Report matching rule. */
3364					args->rule_id = f->id;
3365					args->chain_id = chain->id;
3366					t = ((ipfw_insn_nat *)cmd)->nat;
3367					if (t == NULL) {
3368						nat_id = (cmd->arg1 == IP_FW_TABLEARG) ?
3369						    tablearg : cmd->arg1;
3370						LOOKUP_NAT(V_layer3_chain, nat_id, t);
3371						if (t == NULL) {
3372							retval = IP_FW_DENY;
3373							goto done;
3374						}
3375						if (cmd->arg1 != IP_FW_TABLEARG)
3376							((ipfw_insn_nat *)cmd)->nat = t;
3377					}
3378					retval = ipfw_nat_ptr(args, t, m);
3379				} else
3380					retval = IP_FW_DENY;
3381				goto done;
3382			}
3383
3384			case O_REASS: {
3385				int ip_off;
3386
3387				f->pcnt++;
3388				f->bcnt += pktlen;
3389				ip_off = (args->eh != NULL) ? ntohs(ip->ip_off) : ip->ip_off;
3390				if (ip_off & (IP_MF | IP_OFFMASK)) {
3391					/*
3392					 * ip_reass() expects len & off in host
3393					 * byte order: fix them in case we come
3394					 * from layer2.
3395					 */
3396					if (args->eh != NULL) {
3397						ip->ip_len = ntohs(ip->ip_len);
3398						ip->ip_off = ntohs(ip->ip_off);
3399					}
3400
3401					m = ip_reass(m);
3402					args->m = m;
3403
3404					/*
3405					 * IP header checksum fixup after
3406					 * reassembly and leave header
3407					 * in network byte order.
3408					 */
3409					if (m != NULL) {
3410						int hlen;
3411
3412						ip = mtod(m, struct ip *);
3413						hlen = ip->ip_hl << 2;
3414						/* revert len & off for layer2 pkts */
3415						if (args->eh != NULL)
3416							ip->ip_len = htons(ip->ip_len);
3417						ip->ip_sum = 0;
3418						if (hlen == sizeof(struct ip))
3419							ip->ip_sum = in_cksum_hdr(ip);
3420						else
3421							ip->ip_sum = in_cksum(m, hlen);
3422						retval = IP_FW_REASS;
3423						args->rule = f;
3424						args->rule_id = f->id;
3425						args->chain_id = chain->id;
3426						goto done;
3427					} else {
3428						retval = IP_FW_DENY;
3429						goto done;
3430					}
3431				}
3432				goto next_rule;
3433			}
3434
3435			default:
3436				panic("-- unknown opcode %d\n", cmd->opcode);
3437			} /* end of switch() on opcodes */
3438
3439			if (cmd->len & F_NOT)
3440				match = !match;
3441
3442			if (match) {
3443				if (cmd->len & F_OR)
3444					skip_or = 1;
3445			} else {
3446				if (!(cmd->len & F_OR)) /* not an OR block, */
3447					break;		/* try next rule    */
3448			}
3449
3450		}	/* end of inner for, scan opcodes */
3451
3452next_rule:;		/* try next rule		*/
3453
3454	}		/* end of outer for, scan rules */
3455	printf("ipfw: ouch!, skip past end of rules, denying packet\n");
3456	IPFW_RUNLOCK(chain);
3457	if (ucred_cache != NULL)
3458		crfree(ucred_cache);
3459	return (IP_FW_DENY);
3460
3461done:
3462	/* Update statistics */
3463	f->pcnt++;
3464	f->bcnt += pktlen;
3465	f->timestamp = time_uptime;
3466	IPFW_RUNLOCK(chain);
3467	if (ucred_cache != NULL)
3468		crfree(ucred_cache);
3469	return (retval);
3470
3471pullup_failed:
3472	if (V_fw_verbose)
3473		printf("ipfw: pullup failed\n");
3474	return (IP_FW_DENY);
3475}
3476
3477/*
3478 * When a rule is added/deleted, clear the next_rule pointers in all rules.
3479 * These will be reconstructed on the fly as packets are matched.
3480 */
3481static void
3482flush_rule_ptrs(struct ip_fw_chain *chain)
3483{
3484	struct ip_fw *rule;
3485
3486	IPFW_WLOCK_ASSERT(chain);
3487
3488	chain->id++;
3489
3490	for (rule = chain->rules; rule; rule = rule->next)
3491		rule->next_rule = NULL;
3492}
3493
3494/*
3495 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
3496 * possibly create a rule number and add the rule to the list.
3497 * Update the rule_number in the input struct so the caller knows it as well.
3498 */
3499static int
3500add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
3501{
3502	struct ip_fw *rule, *f, *prev;
3503	int l = RULESIZE(input_rule);
3504
3505	if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
3506		return (EINVAL);
3507
3508	rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
3509	if (rule == NULL)
3510		return (ENOSPC);
3511
3512	bcopy(input_rule, rule, l);
3513
3514	rule->next = NULL;
3515	rule->next_rule = NULL;
3516
3517	rule->pcnt = 0;
3518	rule->bcnt = 0;
3519	rule->timestamp = 0;
3520
3521	IPFW_WLOCK(chain);
3522
3523	if (chain->rules == NULL) {	/* default rule */
3524		chain->rules = rule;
3525		rule->id = ++chain->id;
3526		goto done;
3527        }
3528
3529	/*
3530	 * If rulenum is 0, find highest numbered rule before the
3531	 * default rule, and add autoinc_step
3532	 */
3533	if (V_autoinc_step < 1)
3534		V_autoinc_step = 1;
3535	else if (V_autoinc_step > 1000)
3536		V_autoinc_step = 1000;
3537	if (rule->rulenum == 0) {
3538		/*
3539		 * locate the highest numbered rule before default
3540		 */
3541		for (f = chain->rules; f; f = f->next) {
3542			if (f->rulenum == IPFW_DEFAULT_RULE)
3543				break;
3544			rule->rulenum = f->rulenum;
3545		}
3546		if (rule->rulenum < IPFW_DEFAULT_RULE - V_autoinc_step)
3547			rule->rulenum += V_autoinc_step;
3548		input_rule->rulenum = rule->rulenum;
3549	}
3550
3551	/*
3552	 * Now insert the new rule in the right place in the sorted list.
3553	 */
3554	for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) {
3555		if (f->rulenum > rule->rulenum) { /* found the location */
3556			if (prev) {
3557				rule->next = f;
3558				prev->next = rule;
3559			} else { /* head insert */
3560				rule->next = chain->rules;
3561				chain->rules = rule;
3562			}
3563			break;
3564		}
3565	}
3566	flush_rule_ptrs(chain);
3567	/* chain->id incremented inside flush_rule_ptrs() */
3568	rule->id = chain->id;
3569done:
3570	V_static_count++;
3571	V_static_len += l;
3572	IPFW_WUNLOCK(chain);
3573	DEB(printf("ipfw: installed rule %d, static count now %d\n",
3574		rule->rulenum, V_static_count);)
3575	return (0);
3576}
3577
3578/**
3579 * Remove a static rule (including derived * dynamic rules)
3580 * and place it on the ``reap list'' for later reclamation.
3581 * The caller is in charge of clearing rule pointers to avoid
3582 * dangling pointers.
3583 * @return a pointer to the next entry.
3584 * Arguments are not checked, so they better be correct.
3585 */
3586static struct ip_fw *
3587remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule,
3588    struct ip_fw *prev)
3589{
3590	struct ip_fw *n;
3591	int l = RULESIZE(rule);
3592
3593	IPFW_WLOCK_ASSERT(chain);
3594
3595	n = rule->next;
3596	IPFW_DYN_LOCK();
3597	remove_dyn_rule(rule, NULL /* force removal */);
3598	IPFW_DYN_UNLOCK();
3599	if (prev == NULL)
3600		chain->rules = n;
3601	else
3602		prev->next = n;
3603	V_static_count--;
3604	V_static_len -= l;
3605
3606	rule->next = chain->reap;
3607	chain->reap = rule;
3608
3609	return n;
3610}
3611
3612/*
3613 * Reclaim storage associated with a list of rules.  This is
3614 * typically the list created using remove_rule.
3615 * A NULL pointer on input is handled correctly.
3616 */
3617static void
3618reap_rules(struct ip_fw *head)
3619{
3620	struct ip_fw *rule;
3621
3622	while ((rule = head) != NULL) {
3623		head = head->next;
3624		free(rule, M_IPFW);
3625	}
3626}
3627
3628/*
3629 * Remove all rules from a chain (except rules in set RESVD_SET
3630 * unless kill_default = 1).  The caller is responsible for
3631 * reclaiming storage for the rules left in chain->reap.
3632 */
3633static void
3634free_chain(struct ip_fw_chain *chain, int kill_default)
3635{
3636	struct ip_fw *prev, *rule;
3637
3638	IPFW_WLOCK_ASSERT(chain);
3639
3640	chain->reap = NULL;
3641	flush_rule_ptrs(chain); /* more efficient to do outside the loop */
3642	for (prev = NULL, rule = chain->rules; rule ; )
3643		if (kill_default || rule->set != RESVD_SET)
3644			rule = remove_rule(chain, rule, prev);
3645		else {
3646			prev = rule;
3647			rule = rule->next;
3648		}
3649}
3650
3651/**
3652 * Remove all rules with given number, and also do set manipulation.
3653 * Assumes chain != NULL && *chain != NULL.
3654 *
3655 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
3656 * the next 8 bits are the new set, the top 8 bits are the command:
3657 *
3658 *	0	delete rules with given number
3659 *	1	delete rules with given set number
3660 *	2	move rules with given number to new set
3661 *	3	move rules with given set number to new set
3662 *	4	swap sets with given numbers
3663 *	5	delete rules with given number and with given set number
3664 */
3665static int
3666del_entry(struct ip_fw_chain *chain, u_int32_t arg)
3667{
3668	struct ip_fw *prev = NULL, *rule;
3669	u_int16_t rulenum;	/* rule or old_set */
3670	u_int8_t cmd, new_set;
3671
3672	rulenum = arg & 0xffff;
3673	cmd = (arg >> 24) & 0xff;
3674	new_set = (arg >> 16) & 0xff;
3675
3676	if (cmd > 5 || new_set > RESVD_SET)
3677		return EINVAL;
3678	if (cmd == 0 || cmd == 2 || cmd == 5) {
3679		if (rulenum >= IPFW_DEFAULT_RULE)
3680			return EINVAL;
3681	} else {
3682		if (rulenum > RESVD_SET)	/* old_set */
3683			return EINVAL;
3684	}
3685
3686	IPFW_WLOCK(chain);
3687	rule = chain->rules;	/* common starting point */
3688	chain->reap = NULL;	/* prepare for deletions */
3689	switch (cmd) {
3690	case 0:	/* delete rules with given number */
3691		/*
3692		 * locate first rule to delete
3693		 */
3694		for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3695			;
3696		if (rule->rulenum != rulenum) {
3697			IPFW_WUNLOCK(chain);
3698			return EINVAL;
3699		}
3700
3701		/*
3702		 * flush pointers outside the loop, then delete all matching
3703		 * rules. prev remains the same throughout the cycle.
3704		 */
3705		flush_rule_ptrs(chain);
3706		while (rule->rulenum == rulenum)
3707			rule = remove_rule(chain, rule, prev);
3708		break;
3709
3710	case 1:	/* delete all rules with given set number */
3711		flush_rule_ptrs(chain);
3712		while (rule->rulenum < IPFW_DEFAULT_RULE) {
3713			if (rule->set == rulenum)
3714				rule = remove_rule(chain, rule, prev);
3715			else {
3716				prev = rule;
3717				rule = rule->next;
3718			}
3719		}
3720		break;
3721
3722	case 2:	/* move rules with given number to new set */
3723		for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3724			if (rule->rulenum == rulenum)
3725				rule->set = new_set;
3726		break;
3727
3728	case 3: /* move rules with given set number to new set */
3729		for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3730			if (rule->set == rulenum)
3731				rule->set = new_set;
3732		break;
3733
3734	case 4: /* swap two sets */
3735		for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
3736			if (rule->set == rulenum)
3737				rule->set = new_set;
3738			else if (rule->set == new_set)
3739				rule->set = rulenum;
3740		break;
3741
3742	case 5: /* delete rules with given number and with given set number.
3743		 * rulenum - given rule number;
3744		 * new_set - given set number.
3745		 */
3746		for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
3747			;
3748		if (rule->rulenum != rulenum) {
3749			IPFW_WUNLOCK(chain);
3750			return (EINVAL);
3751		}
3752		flush_rule_ptrs(chain);
3753		while (rule->rulenum == rulenum) {
3754			if (rule->set == new_set)
3755				rule = remove_rule(chain, rule, prev);
3756			else {
3757				prev = rule;
3758				rule = rule->next;
3759			}
3760		}
3761	}
3762	/*
3763	 * Look for rules to reclaim.  We grab the list before
3764	 * releasing the lock then reclaim them w/o the lock to
3765	 * avoid a LOR with dummynet.
3766	 */
3767	rule = chain->reap;
3768	IPFW_WUNLOCK(chain);
3769	reap_rules(rule);
3770	return 0;
3771}
3772
3773/*
3774 * Clear counters for a specific rule.
3775 * The enclosing "table" is assumed locked.
3776 */
3777static void
3778clear_counters(struct ip_fw *rule, int log_only)
3779{
3780	ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
3781
3782	if (log_only == 0) {
3783		rule->bcnt = rule->pcnt = 0;
3784		rule->timestamp = 0;
3785	}
3786	if (l->o.opcode == O_LOG)
3787		l->log_left = l->max_log;
3788}
3789
3790/**
3791 * Reset some or all counters on firewall rules.
3792 * The argument `arg' is an u_int32_t. The low 16 bit are the rule number,
3793 * the next 8 bits are the set number, the top 8 bits are the command:
3794 *	0	work with rules from all set's;
3795 *	1	work with rules only from specified set.
3796 * Specified rule number is zero if we want to clear all entries.
3797 * log_only is 1 if we only want to reset logs, zero otherwise.
3798 */
3799static int
3800zero_entry(struct ip_fw_chain *chain, u_int32_t arg, int log_only)
3801{
3802	struct ip_fw *rule;
3803	char *msg;
3804
3805	uint16_t rulenum = arg & 0xffff;
3806	uint8_t set = (arg >> 16) & 0xff;
3807	uint8_t cmd = (arg >> 24) & 0xff;
3808
3809	if (cmd > 1)
3810		return (EINVAL);
3811	if (cmd == 1 && set > RESVD_SET)
3812		return (EINVAL);
3813
3814	IPFW_WLOCK(chain);
3815	if (rulenum == 0) {
3816		V_norule_counter = 0;
3817		for (rule = chain->rules; rule; rule = rule->next) {
3818			/* Skip rules from another set. */
3819			if (cmd == 1 && rule->set != set)
3820				continue;
3821			clear_counters(rule, log_only);
3822		}
3823		msg = log_only ? "All logging counts reset" :
3824		    "Accounting cleared";
3825	} else {
3826		int cleared = 0;
3827		/*
3828		 * We can have multiple rules with the same number, so we
3829		 * need to clear them all.
3830		 */
3831		for (rule = chain->rules; rule; rule = rule->next)
3832			if (rule->rulenum == rulenum) {
3833				while (rule && rule->rulenum == rulenum) {
3834					if (cmd == 0 || rule->set == set)
3835						clear_counters(rule, log_only);
3836					rule = rule->next;
3837				}
3838				cleared = 1;
3839				break;
3840			}
3841		if (!cleared) {	/* we did not find any matching rules */
3842			IPFW_WUNLOCK(chain);
3843			return (EINVAL);
3844		}
3845		msg = log_only ? "logging count reset" : "cleared";
3846	}
3847	IPFW_WUNLOCK(chain);
3848
3849	if (V_fw_verbose) {
3850		int lev = LOG_SECURITY | LOG_NOTICE;
3851
3852		if (rulenum)
3853			log(lev, "ipfw: Entry %d %s.\n", rulenum, msg);
3854		else
3855			log(lev, "ipfw: %s.\n", msg);
3856	}
3857	return (0);
3858}
3859
3860/*
3861 * Check validity of the structure before insert.
3862 * Fortunately rules are simple, so this mostly need to check rule sizes.
3863 */
3864static int
3865check_ipfw_struct(struct ip_fw *rule, int size)
3866{
3867	int l, cmdlen = 0;
3868	int have_action=0;
3869	ipfw_insn *cmd;
3870
3871	if (size < sizeof(*rule)) {
3872		printf("ipfw: rule too short\n");
3873		return (EINVAL);
3874	}
3875	/* first, check for valid size */
3876	l = RULESIZE(rule);
3877	if (l != size) {
3878		printf("ipfw: size mismatch (have %d want %d)\n", size, l);
3879		return (EINVAL);
3880	}
3881	if (rule->act_ofs >= rule->cmd_len) {
3882		printf("ipfw: bogus action offset (%u > %u)\n",
3883		    rule->act_ofs, rule->cmd_len - 1);
3884		return (EINVAL);
3885	}
3886	/*
3887	 * Now go for the individual checks. Very simple ones, basically only
3888	 * instruction sizes.
3889	 */
3890	for (l = rule->cmd_len, cmd = rule->cmd ;
3891			l > 0 ; l -= cmdlen, cmd += cmdlen) {
3892		cmdlen = F_LEN(cmd);
3893		if (cmdlen > l) {
3894			printf("ipfw: opcode %d size truncated\n",
3895			    cmd->opcode);
3896			return EINVAL;
3897		}
3898		DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
3899		switch (cmd->opcode) {
3900		case O_PROBE_STATE:
3901		case O_KEEP_STATE:
3902		case O_PROTO:
3903		case O_IP_SRC_ME:
3904		case O_IP_DST_ME:
3905		case O_LAYER2:
3906		case O_IN:
3907		case O_FRAG:
3908		case O_DIVERTED:
3909		case O_IPOPT:
3910		case O_IPTOS:
3911		case O_IPPRECEDENCE:
3912		case O_IPVER:
3913		case O_TCPWIN:
3914		case O_TCPFLAGS:
3915		case O_TCPOPTS:
3916		case O_ESTAB:
3917		case O_VERREVPATH:
3918		case O_VERSRCREACH:
3919		case O_ANTISPOOF:
3920		case O_IPSEC:
3921#ifdef INET6
3922		case O_IP6_SRC_ME:
3923		case O_IP6_DST_ME:
3924		case O_EXT_HDR:
3925		case O_IP6:
3926#endif
3927		case O_IP4:
3928		case O_TAG:
3929			if (cmdlen != F_INSN_SIZE(ipfw_insn))
3930				goto bad_size;
3931			break;
3932
3933		case O_FIB:
3934			if (cmdlen != F_INSN_SIZE(ipfw_insn))
3935				goto bad_size;
3936			if (cmd->arg1 >= rt_numfibs) {
3937				printf("ipfw: invalid fib number %d\n",
3938					cmd->arg1);
3939				return EINVAL;
3940			}
3941			break;
3942
3943		case O_SETFIB:
3944			if (cmdlen != F_INSN_SIZE(ipfw_insn))
3945				goto bad_size;
3946			if (cmd->arg1 >= rt_numfibs) {
3947				printf("ipfw: invalid fib number %d\n",
3948					cmd->arg1);
3949				return EINVAL;
3950			}
3951			goto check_action;
3952
3953		case O_UID:
3954		case O_GID:
3955		case O_JAIL:
3956		case O_IP_SRC:
3957		case O_IP_DST:
3958		case O_TCPSEQ:
3959		case O_TCPACK:
3960		case O_PROB:
3961		case O_ICMPTYPE:
3962			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3963				goto bad_size;
3964			break;
3965
3966		case O_LIMIT:
3967			if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3968				goto bad_size;
3969			break;
3970
3971		case O_LOG:
3972			if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3973				goto bad_size;
3974
3975			((ipfw_insn_log *)cmd)->log_left =
3976			    ((ipfw_insn_log *)cmd)->max_log;
3977
3978			break;
3979
3980		case O_IP_SRC_MASK:
3981		case O_IP_DST_MASK:
3982			/* only odd command lengths */
3983			if ( !(cmdlen & 1) || cmdlen > 31)
3984				goto bad_size;
3985			break;
3986
3987		case O_IP_SRC_SET:
3988		case O_IP_DST_SET:
3989			if (cmd->arg1 == 0 || cmd->arg1 > 256) {
3990				printf("ipfw: invalid set size %d\n",
3991					cmd->arg1);
3992				return EINVAL;
3993			}
3994			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3995			    (cmd->arg1+31)/32 )
3996				goto bad_size;
3997			break;
3998
3999		case O_IP_SRC_LOOKUP:
4000		case O_IP_DST_LOOKUP:
4001			if (cmd->arg1 >= IPFW_TABLES_MAX) {
4002				printf("ipfw: invalid table number %d\n",
4003				    cmd->arg1);
4004				return (EINVAL);
4005			}
4006			if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
4007			    cmdlen != F_INSN_SIZE(ipfw_insn_u32))
4008				goto bad_size;
4009			break;
4010
4011		case O_MACADDR2:
4012			if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
4013				goto bad_size;
4014			break;
4015
4016		case O_NOP:
4017		case O_IPID:
4018		case O_IPTTL:
4019		case O_IPLEN:
4020		case O_TCPDATALEN:
4021		case O_TAGGED:
4022			if (cmdlen < 1 || cmdlen > 31)
4023				goto bad_size;
4024			break;
4025
4026		case O_MAC_TYPE:
4027		case O_IP_SRCPORT:
4028		case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
4029			if (cmdlen < 2 || cmdlen > 31)
4030				goto bad_size;
4031			break;
4032
4033		case O_RECV:
4034		case O_XMIT:
4035		case O_VIA:
4036			if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
4037				goto bad_size;
4038			break;
4039
4040		case O_ALTQ:
4041			if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
4042				goto bad_size;
4043			break;
4044
4045		case O_PIPE:
4046		case O_QUEUE:
4047			if (cmdlen != F_INSN_SIZE(ipfw_insn))
4048				goto bad_size;
4049			goto check_action;
4050
4051		case O_FORWARD_IP:
4052#ifdef	IPFIREWALL_FORWARD
4053			if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
4054				goto bad_size;
4055			goto check_action;
4056#else
4057			return EINVAL;
4058#endif
4059
4060		case O_DIVERT:
4061		case O_TEE:
4062			if (ip_divert_ptr == NULL)
4063				return EINVAL;
4064			else
4065				goto check_size;
4066		case O_NETGRAPH:
4067		case O_NGTEE:
4068			if (!NG_IPFW_LOADED)
4069				return EINVAL;
4070			else
4071				goto check_size;
4072		case O_NAT:
4073			if (!IPFW_NAT_LOADED)
4074				return EINVAL;
4075			if (cmdlen != F_INSN_SIZE(ipfw_insn_nat))
4076 				goto bad_size;
4077 			goto check_action;
4078		case O_FORWARD_MAC: /* XXX not implemented yet */
4079		case O_CHECK_STATE:
4080		case O_COUNT:
4081		case O_ACCEPT:
4082		case O_DENY:
4083		case O_REJECT:
4084#ifdef INET6
4085		case O_UNREACH6:
4086#endif
4087		case O_SKIPTO:
4088		case O_REASS:
4089check_size:
4090			if (cmdlen != F_INSN_SIZE(ipfw_insn))
4091				goto bad_size;
4092check_action:
4093			if (have_action) {
4094				printf("ipfw: opcode %d, multiple actions"
4095					" not allowed\n",
4096					cmd->opcode);
4097				return EINVAL;
4098			}
4099			have_action = 1;
4100			if (l != cmdlen) {
4101				printf("ipfw: opcode %d, action must be"
4102					" last opcode\n",
4103					cmd->opcode);
4104				return EINVAL;
4105			}
4106			break;
4107#ifdef INET6
4108		case O_IP6_SRC:
4109		case O_IP6_DST:
4110			if (cmdlen != F_INSN_SIZE(struct in6_addr) +
4111			    F_INSN_SIZE(ipfw_insn))
4112				goto bad_size;
4113			break;
4114
4115		case O_FLOW6ID:
4116			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
4117			    ((ipfw_insn_u32 *)cmd)->o.arg1)
4118				goto bad_size;
4119			break;
4120
4121		case O_IP6_SRC_MASK:
4122		case O_IP6_DST_MASK:
4123			if ( !(cmdlen & 1) || cmdlen > 127)
4124				goto bad_size;
4125			break;
4126		case O_ICMP6TYPE:
4127			if( cmdlen != F_INSN_SIZE( ipfw_insn_icmp6 ) )
4128				goto bad_size;
4129			break;
4130#endif
4131
4132		default:
4133			switch (cmd->opcode) {
4134#ifndef INET6
4135			case O_IP6_SRC_ME:
4136			case O_IP6_DST_ME:
4137			case O_EXT_HDR:
4138			case O_IP6:
4139			case O_UNREACH6:
4140			case O_IP6_SRC:
4141			case O_IP6_DST:
4142			case O_FLOW6ID:
4143			case O_IP6_SRC_MASK:
4144			case O_IP6_DST_MASK:
4145			case O_ICMP6TYPE:
4146				printf("ipfw: no IPv6 support in kernel\n");
4147				return EPROTONOSUPPORT;
4148#endif
4149			default:
4150				printf("ipfw: opcode %d, unknown opcode\n",
4151					cmd->opcode);
4152				return EINVAL;
4153			}
4154		}
4155	}
4156	if (have_action == 0) {
4157		printf("ipfw: missing action\n");
4158		return EINVAL;
4159	}
4160	return 0;
4161
4162bad_size:
4163	printf("ipfw: opcode %d size %d wrong\n",
4164		cmd->opcode, cmdlen);
4165	return EINVAL;
4166}
4167
4168/*
4169 * Copy the static and dynamic rules to the supplied buffer
4170 * and return the amount of space actually used.
4171 */
4172static size_t
4173ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
4174{
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	int error;
4258	size_t size;
4259	struct ip_fw *buf, *rule;
4260	u_int32_t rulenum[2];
4261
4262	error = priv_check(sopt->sopt_td, PRIV_NETINET_IPFW);
4263	if (error)
4264		return (error);
4265
4266	/*
4267	 * Disallow modifications in really-really secure mode, but still allow
4268	 * the logging counters to be reset.
4269	 */
4270	if (sopt->sopt_name == IP_FW_ADD ||
4271	    (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
4272		error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
4273		if (error)
4274			return (error);
4275	}
4276
4277	error = 0;
4278
4279	switch (sopt->sopt_name) {
4280	case IP_FW_GET:
4281		/*
4282		 * pass up a copy of the current rules. Static rules
4283		 * come first (the last of which has number IPFW_DEFAULT_RULE),
4284		 * followed by a possibly empty list of dynamic rule.
4285		 * The last dynamic rule has NULL in the "next" field.
4286		 *
4287		 * Note that the calculated size is used to bound the
4288		 * amount of data returned to the user.  The rule set may
4289		 * change between calculating the size and returning the
4290		 * data in which case we'll just return what fits.
4291		 */
4292		size = V_static_len;	/* size of static rules */
4293		if (V_ipfw_dyn_v)		/* add size of dyn.rules */
4294			size += (V_dyn_count * sizeof(ipfw_dyn_rule));
4295
4296		if (size >= sopt->sopt_valsize)
4297			break;
4298		/*
4299		 * XXX todo: if the user passes a short length just to know
4300		 * how much room is needed, do not bother filling up the
4301		 * buffer, just jump to the sooptcopyout.
4302		 */
4303		buf = malloc(size, M_TEMP, M_WAITOK);
4304		error = sooptcopyout(sopt, buf,
4305				ipfw_getrules(&V_layer3_chain, buf, size));
4306		free(buf, M_TEMP);
4307		break;
4308
4309	case IP_FW_FLUSH:
4310		/*
4311		 * Normally we cannot release the lock on each iteration.
4312		 * We could do it here only because we start from the head all
4313		 * the times so there is no risk of missing some entries.
4314		 * On the other hand, the risk is that we end up with
4315		 * a very inconsistent ruleset, so better keep the lock
4316		 * around the whole cycle.
4317		 *
4318		 * XXX this code can be improved by resetting the head of
4319		 * the list to point to the default rule, and then freeing
4320		 * the old list without the need for a lock.
4321		 */
4322
4323		IPFW_WLOCK(&V_layer3_chain);
4324		free_chain(&V_layer3_chain, 0 /* keep default rule */);
4325		rule = V_layer3_chain.reap;
4326		IPFW_WUNLOCK(&V_layer3_chain);
4327		reap_rules(rule);
4328		break;
4329
4330	case IP_FW_ADD:
4331		rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
4332		error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
4333			sizeof(struct ip_fw) );
4334		if (error == 0)
4335			error = check_ipfw_struct(rule, sopt->sopt_valsize);
4336		if (error == 0) {
4337			error = add_rule(&V_layer3_chain, rule);
4338			size = RULESIZE(rule);
4339			if (!error && sopt->sopt_dir == SOPT_GET)
4340				error = sooptcopyout(sopt, rule, size);
4341		}
4342		free(rule, M_TEMP);
4343		break;
4344
4345	case IP_FW_DEL:
4346		/*
4347		 * IP_FW_DEL is used for deleting single rules or sets,
4348		 * and (ab)used to atomically manipulate sets. Argument size
4349		 * is used to distinguish between the two:
4350		 *    sizeof(u_int32_t)
4351		 *	delete single rule or set of rules,
4352		 *	or reassign rules (or sets) to a different set.
4353		 *    2*sizeof(u_int32_t)
4354		 *	atomic disable/enable sets.
4355		 *	first u_int32_t contains sets to be disabled,
4356		 *	second u_int32_t contains sets to be enabled.
4357		 */
4358		error = sooptcopyin(sopt, rulenum,
4359			2*sizeof(u_int32_t), sizeof(u_int32_t));
4360		if (error)
4361			break;
4362		size = sopt->sopt_valsize;
4363		if (size == sizeof(u_int32_t))	/* delete or reassign */
4364			error = del_entry(&V_layer3_chain, rulenum[0]);
4365		else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
4366			V_set_disable =
4367			    (V_set_disable | rulenum[0]) & ~rulenum[1] &
4368			    ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
4369		else
4370			error = EINVAL;
4371		break;
4372
4373	case IP_FW_ZERO:
4374	case IP_FW_RESETLOG: /* argument is an u_int_32, the rule number */
4375		rulenum[0] = 0;
4376		if (sopt->sopt_val != 0) {
4377		    error = sooptcopyin(sopt, rulenum,
4378			    sizeof(u_int32_t), sizeof(u_int32_t));
4379		    if (error)
4380			break;
4381		}
4382		error = zero_entry(&V_layer3_chain, rulenum[0],
4383			sopt->sopt_name == IP_FW_RESETLOG);
4384		break;
4385
4386	case IP_FW_TABLE_ADD:
4387		{
4388			ipfw_table_entry ent;
4389
4390			error = sooptcopyin(sopt, &ent,
4391			    sizeof(ent), sizeof(ent));
4392			if (error)
4393				break;
4394			error = add_table_entry(&V_layer3_chain, ent.tbl,
4395			    ent.addr, ent.masklen, ent.value);
4396		}
4397		break;
4398
4399	case IP_FW_TABLE_DEL:
4400		{
4401			ipfw_table_entry ent;
4402
4403			error = sooptcopyin(sopt, &ent,
4404			    sizeof(ent), sizeof(ent));
4405			if (error)
4406				break;
4407			error = del_table_entry(&V_layer3_chain, ent.tbl,
4408			    ent.addr, ent.masklen);
4409		}
4410		break;
4411
4412	case IP_FW_TABLE_FLUSH:
4413		{
4414			u_int16_t tbl;
4415
4416			error = sooptcopyin(sopt, &tbl,
4417			    sizeof(tbl), sizeof(tbl));
4418			if (error)
4419				break;
4420			IPFW_WLOCK(&V_layer3_chain);
4421			error = flush_table(&V_layer3_chain, tbl);
4422			IPFW_WUNLOCK(&V_layer3_chain);
4423		}
4424		break;
4425
4426	case IP_FW_TABLE_GETSIZE:
4427		{
4428			u_int32_t tbl, cnt;
4429
4430			if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
4431			    sizeof(tbl))))
4432				break;
4433			IPFW_RLOCK(&V_layer3_chain);
4434			error = count_table(&V_layer3_chain, tbl, &cnt);
4435			IPFW_RUNLOCK(&V_layer3_chain);
4436			if (error)
4437				break;
4438			error = sooptcopyout(sopt, &cnt, sizeof(cnt));
4439		}
4440		break;
4441
4442	case IP_FW_TABLE_LIST:
4443		{
4444			ipfw_table *tbl;
4445
4446			if (sopt->sopt_valsize < sizeof(*tbl)) {
4447				error = EINVAL;
4448				break;
4449			}
4450			size = sopt->sopt_valsize;
4451			tbl = malloc(size, M_TEMP, M_WAITOK);
4452			error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
4453			if (error) {
4454				free(tbl, M_TEMP);
4455				break;
4456			}
4457			tbl->size = (size - sizeof(*tbl)) /
4458			    sizeof(ipfw_table_entry);
4459			IPFW_RLOCK(&V_layer3_chain);
4460			error = dump_table(&V_layer3_chain, tbl);
4461			IPFW_RUNLOCK(&V_layer3_chain);
4462			if (error) {
4463				free(tbl, M_TEMP);
4464				break;
4465			}
4466			error = sooptcopyout(sopt, tbl, size);
4467			free(tbl, M_TEMP);
4468		}
4469		break;
4470
4471	case IP_FW_NAT_CFG:
4472		if (IPFW_NAT_LOADED)
4473			error = ipfw_nat_cfg_ptr(sopt);
4474		else {
4475			printf("IP_FW_NAT_CFG: %s\n",
4476			    "ipfw_nat not present, please load it");
4477			error = EINVAL;
4478		}
4479		break;
4480
4481	case IP_FW_NAT_DEL:
4482		if (IPFW_NAT_LOADED)
4483			error = ipfw_nat_del_ptr(sopt);
4484		else {
4485			printf("IP_FW_NAT_DEL: %s\n",
4486			    "ipfw_nat not present, please load it");
4487			error = EINVAL;
4488		}
4489		break;
4490
4491	case IP_FW_NAT_GET_CONFIG:
4492		if (IPFW_NAT_LOADED)
4493			error = ipfw_nat_get_cfg_ptr(sopt);
4494		else {
4495			printf("IP_FW_NAT_GET_CFG: %s\n",
4496			    "ipfw_nat not present, please load it");
4497			error = EINVAL;
4498		}
4499		break;
4500
4501	case IP_FW_NAT_GET_LOG:
4502		if (IPFW_NAT_LOADED)
4503			error = ipfw_nat_get_log_ptr(sopt);
4504		else {
4505			printf("IP_FW_NAT_GET_LOG: %s\n",
4506			    "ipfw_nat not present, please load it");
4507			error = EINVAL;
4508		}
4509		break;
4510
4511	default:
4512		printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
4513		error = EINVAL;
4514	}
4515
4516	return (error);
4517#undef RULE_MAXSIZE
4518}
4519
4520
4521/*
4522 * This procedure is only used to handle keepalives. It is invoked
4523 * every dyn_keepalive_period
4524 */
4525static void
4526ipfw_tick(void * vnetx)
4527{
4528	struct mbuf *m0, *m, *mnext, **mtailp;
4529	int i;
4530	ipfw_dyn_rule *q;
4531#ifdef VIMAGE
4532	struct vnet *vp = vnetx;
4533#endif
4534
4535        CURVNET_SET(vp);
4536	if (V_dyn_keepalive == 0 || V_ipfw_dyn_v == NULL || V_dyn_count == 0)
4537		goto done;
4538
4539	/*
4540	 * We make a chain of packets to go out here -- not deferring
4541	 * until after we drop the IPFW dynamic rule lock would result
4542	 * in a lock order reversal with the normal packet input -> ipfw
4543	 * call stack.
4544	 */
4545	m0 = NULL;
4546	mtailp = &m0;
4547	IPFW_DYN_LOCK();
4548	for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
4549		for (q = V_ipfw_dyn_v[i] ; q ; q = q->next ) {
4550			if (q->dyn_type == O_LIMIT_PARENT)
4551				continue;
4552			if (q->id.proto != IPPROTO_TCP)
4553				continue;
4554			if ( (q->state & BOTH_SYN) != BOTH_SYN)
4555				continue;
4556			if (TIME_LEQ(time_uptime + V_dyn_keepalive_interval,
4557			    q->expire))
4558				continue;	/* too early */
4559			if (TIME_LEQ(q->expire, time_uptime))
4560				continue;	/* too late, rule expired */
4561
4562			*mtailp = send_pkt(NULL, &(q->id), q->ack_rev - 1,
4563				q->ack_fwd, TH_SYN);
4564			if (*mtailp != NULL)
4565				mtailp = &(*mtailp)->m_nextpkt;
4566			*mtailp = send_pkt(NULL, &(q->id), q->ack_fwd - 1,
4567				q->ack_rev, 0);
4568			if (*mtailp != NULL)
4569				mtailp = &(*mtailp)->m_nextpkt;
4570		}
4571	}
4572	IPFW_DYN_UNLOCK();
4573	for (m = mnext = m0; m != NULL; m = mnext) {
4574		mnext = m->m_nextpkt;
4575		m->m_nextpkt = NULL;
4576		ip_output(m, NULL, NULL, 0, NULL, NULL);
4577	}
4578done:
4579	callout_reset(&V_ipfw_timeout, V_dyn_keepalive_period * hz,
4580		      ipfw_tick, vnetx);
4581	CURVNET_RESTORE();
4582}
4583
4584/****************
4585 * Stuff that must be initialised only on boot or module load
4586 */
4587static int
4588ipfw_init(void)
4589{
4590	int error = 0;
4591
4592	ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
4593	    sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
4594	    UMA_ALIGN_PTR, 0);
4595
4596	IPFW_DYN_LOCK_INIT();
4597	/*
4598 	 * Only print out this stuff the first time around,
4599	 * when called from the sysinit code.
4600	 */
4601	printf("ipfw2 "
4602#ifdef INET6
4603		"(+ipv6) "
4604#endif
4605		"initialized, divert %s, nat %s, "
4606		"rule-based forwarding "
4607#ifdef IPFIREWALL_FORWARD
4608		"enabled, "
4609#else
4610		"disabled, "
4611#endif
4612		"default to %s, logging ",
4613#ifdef IPDIVERT
4614		"enabled",
4615#else
4616		"loadable",
4617#endif
4618#ifdef IPFIREWALL_NAT
4619		"enabled",
4620#else
4621		"loadable",
4622#endif
4623		default_to_accept ? "accept" : "deny");
4624
4625	/*
4626	 * Note: V_xxx variables can be accessed here but the vnet specific
4627	 * initializer may not have been called yet for the VIMAGE case.
4628	 * Tuneables will have been processed. We will print out values for
4629	 * the default vnet.
4630	 * XXX This should all be rationalized AFTER 8.0
4631	 */
4632	if (V_fw_verbose == 0)
4633		printf("disabled\n");
4634	else if (V_verbose_limit == 0)
4635		printf("unlimited\n");
4636	else
4637		printf("limited to %d packets/entry by default\n",
4638		    V_verbose_limit);
4639
4640	/*
4641	 * Hook us up to pfil.
4642	 * Eventually pfil will be per vnet.
4643	 */
4644	if ((error = ipfw_hook()) != 0) {
4645		printf("ipfw_hook() error\n");
4646		return (error);
4647	}
4648#ifdef INET6
4649	if ((error = ipfw6_hook()) != 0) {
4650		printf("ipfw6_hook() error\n");
4651		return (error);
4652	}
4653#endif
4654	/*
4655	 * Other things that are only done the first time.
4656	 * (now that we a re guaranteed of success).
4657	 */
4658	ip_fw_ctl_ptr = ipfw_ctl;
4659	ip_fw_chk_ptr = ipfw_chk;
4660	return (error);
4661}
4662
4663/****************
4664 * Stuff that must be initialized for every instance
4665 * (including the first of course).
4666 */
4667static int
4668vnet_ipfw_init(const void *unused)
4669{
4670	int error;
4671	struct ip_fw default_rule;
4672
4673	/* First set up some values that are compile time options */
4674#ifdef IPFIREWALL_VERBOSE
4675	V_fw_verbose = 1;
4676#endif
4677#ifdef IPFIREWALL_VERBOSE_LIMIT
4678	V_verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
4679#endif
4680
4681	error = init_tables(&V_layer3_chain);
4682	if (error) {
4683		panic("init_tables"); /* XXX Marko fix this ! */
4684	}
4685#ifdef IPFIREWALL_NAT
4686	LIST_INIT(&V_layer3_chain.nat);
4687#endif
4688
4689	V_autoinc_step = 100;	/* bounded to 1..1000 in add_rule() */
4690
4691	V_ipfw_dyn_v = NULL;
4692	V_dyn_buckets = 256;	/* must be power of 2 */
4693	V_curr_dyn_buckets = 256; /* must be power of 2 */
4694
4695	V_dyn_ack_lifetime = 300;
4696	V_dyn_syn_lifetime = 20;
4697	V_dyn_fin_lifetime = 1;
4698	V_dyn_rst_lifetime = 1;
4699	V_dyn_udp_lifetime = 10;
4700	V_dyn_short_lifetime = 5;
4701
4702	V_dyn_keepalive_interval = 20;
4703	V_dyn_keepalive_period = 5;
4704	V_dyn_keepalive = 1;	/* do send keepalives */
4705
4706	V_dyn_max = 4096;	/* max # of dynamic rules */
4707
4708	V_fw_deny_unknown_exthdrs = 1;
4709
4710	V_layer3_chain.rules = NULL;
4711	IPFW_LOCK_INIT(&V_layer3_chain);
4712	callout_init(&V_ipfw_timeout, CALLOUT_MPSAFE);
4713
4714	bzero(&default_rule, sizeof default_rule);
4715	default_rule.act_ofs = 0;
4716	default_rule.rulenum = IPFW_DEFAULT_RULE;
4717	default_rule.cmd_len = 1;
4718	default_rule.set = RESVD_SET;
4719	default_rule.cmd[0].len = 1;
4720	default_rule.cmd[0].opcode = default_to_accept ? O_ACCEPT : O_DENY;
4721	error = add_rule(&V_layer3_chain, &default_rule);
4722
4723	if (error != 0) {
4724		printf("ipfw2: error %u initializing default rule "
4725			"(support disabled)\n", error);
4726		IPFW_LOCK_DESTROY(&V_layer3_chain);
4727		printf("leaving ipfw_iattach (1) with error %d\n", error);
4728		return (error);
4729	}
4730
4731	ip_fw_default_rule = V_layer3_chain.rules;
4732
4733	if (error) {
4734		IPFW_LOCK_DESTROY(&V_layer3_chain);
4735		printf("leaving ipfw_iattach (2) with error %d\n", error);
4736		return (error);
4737	}
4738#ifdef VIMAGE  /* want a better way to do this */
4739	callout_reset(&V_ipfw_timeout, hz, ipfw_tick, curvnet);
4740#else
4741	callout_reset(&V_ipfw_timeout, hz, ipfw_tick, NULL);
4742#endif
4743
4744	/* First set up some values that are compile time options */
4745	V_ipfw_vnet_ready = 1;		/* Open for business */
4746	return (0);
4747}
4748
4749/**********************
4750 * Called for the removal of the last instance only on module unload.
4751 */
4752static void
4753ipfw_destroy(void)
4754{
4755
4756	uma_zdestroy(ipfw_dyn_rule_zone);
4757	IPFW_DYN_LOCK_DESTROY();
4758	printf("IP firewall unloaded\n");
4759}
4760
4761/***********************
4762 * Called for the removal of each instance.
4763 */
4764static int
4765vnet_ipfw_uninit(const void *unused)
4766{
4767	struct ip_fw *reap;
4768
4769	V_ipfw_vnet_ready = 0; /* tell new callers to go away */
4770	callout_drain(&V_ipfw_timeout);
4771	/* We wait on the wlock here until the last user leaves */
4772	IPFW_WLOCK(&V_layer3_chain);
4773	flush_tables(&V_layer3_chain);
4774	V_layer3_chain.reap = NULL;
4775	free_chain(&V_layer3_chain, 1 /* kill default rule */);
4776	reap = V_layer3_chain.reap;
4777	V_layer3_chain.reap = NULL;
4778	IPFW_WUNLOCK(&V_layer3_chain);
4779	if (reap != NULL)
4780		reap_rules(reap);
4781	IPFW_LOCK_DESTROY(&V_layer3_chain);
4782	if (V_ipfw_dyn_v != NULL)
4783		free(V_ipfw_dyn_v, M_IPFW);
4784	return 0;
4785}
4786
4787/*
4788 * Module event handler.
4789 * In general we have the choice of handling most of these events by the
4790 * event handler or by the (VNET_)SYS(UN)INIT handlers. I have chosen to
4791 * use the SYSINIT handlers as they are more capable of expressing the
4792 * flow of control during module and vnet operations, so this is just
4793 * a skeleton. Note there is no SYSINIT equivalent of the module
4794 * SHUTDOWN handler, but we don't have anything to do in that case anyhow.
4795 */
4796static int
4797ipfw_modevent(module_t mod, int type, void *unused)
4798{
4799	int err = 0;
4800
4801	switch (type) {
4802	case MOD_LOAD:
4803		/* Called once at module load or
4804	 	 * system boot if compiled in. */
4805		break;
4806	case MOD_UNLOAD:
4807		break;
4808	case MOD_QUIESCE:
4809		/* Yes, the unhooks can return errors, we can safely ignore
4810		 * them. Eventually these will be done per jail as they
4811		 * shut down. We will wait on each vnet's l3 lock as existing
4812		 * callers go away.
4813		 */
4814		ipfw_unhook();
4815#ifdef INET6
4816		ipfw6_unhook();
4817#endif
4818		/* layer2 and other entrypoints still come in this way. */
4819		ip_fw_chk_ptr = NULL;
4820		ip_fw_ctl_ptr = NULL;
4821		/* Called during unload. */
4822		break;
4823	case MOD_SHUTDOWN:
4824		/* Called during system shutdown. */
4825		break;
4826	default:
4827		err = EOPNOTSUPP;
4828		break;
4829	}
4830	return err;
4831}
4832
4833static moduledata_t ipfwmod = {
4834	"ipfw",
4835	ipfw_modevent,
4836	0
4837};
4838
4839/* Define startup order. */
4840#define	IPFW_SI_SUB_FIREWALL	SI_SUB_PROTO_IFATTACHDOMAIN
4841#define	IPFW_MODEVENT_ORDER	(SI_ORDER_ANY - 255) /* On boot slot in here. */
4842#define	IPFW_MODULE_ORDER	(IPFW_MODEVENT_ORDER + 1) /* A little later. */
4843#define	IPFW_VNET_ORDER		(IPFW_MODEVENT_ORDER + 2) /* Later still. */
4844
4845DECLARE_MODULE(ipfw, ipfwmod, IPFW_SI_SUB_FIREWALL, IPFW_MODEVENT_ORDER);
4846MODULE_VERSION(ipfw, 2);
4847/* should declare some dependencies here */
4848
4849/*
4850 * Starting up. Done in order after ipfwmod() has been called.
4851 * VNET_SYSINIT is also called for each existing vnet and each new vnet.
4852 */
4853SYSINIT(ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
4854	    ipfw_init, NULL);
4855VNET_SYSINIT(vnet_ipfw_init, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
4856	    vnet_ipfw_init, NULL);
4857
4858/*
4859 * Closing up shop. These are done in REVERSE ORDER, but still
4860 * after ipfwmod() has been called. Not called on reboot.
4861 * VNET_SYSUNINIT is also called for each exiting vnet as it exits.
4862 * or when the module is unloaded.
4863 */
4864SYSUNINIT(ipfw_destroy, IPFW_SI_SUB_FIREWALL, IPFW_MODULE_ORDER,
4865	    ipfw_destroy, NULL);
4866VNET_SYSUNINIT(vnet_ipfw_uninit, IPFW_SI_SUB_FIREWALL, IPFW_VNET_ORDER,
4867	    vnet_ipfw_uninit, NULL);
4868
4869
4870