ip_fw2.c revision 130311
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 * $FreeBSD: head/sys/netinet/ip_fw2.c 130311 2004-06-10 20:20:37Z ru $
2653541Sshin */
2753541Sshin
2853541Sshin#define        DEB(x)
2953541Sshin#define        DDB(x) x
3053541Sshin
3153541Sshin/*
3253541Sshin * Implement IP packet firewall (new version)
3353541Sshin */
3453541Sshin
3553541Sshin#if !defined(KLD_MODULE)
3653541Sshin#include "opt_ipfw.h"
3753541Sshin#include "opt_ipdn.h"
3853541Sshin#include "opt_ipdivert.h"
3953541Sshin#include "opt_inet.h"
4053541Sshin#include "opt_ipsec.h"
4153541Sshin#ifndef INET
4253541Sshin#error IPFIREWALL requires INET.
4353541Sshin#endif /* INET */
4453541Sshin#endif
4553541Sshin
4653541Sshin#define IPFW2	1
4753541Sshin#if IPFW2
4853541Sshin#include <sys/param.h>
4953541Sshin#include <sys/systm.h>
5062587Sitojun#include <sys/malloc.h>
5153541Sshin#include <sys/mbuf.h>
5262587Sitojun#include <sys/kernel.h>
5353541Sshin#include <sys/module.h>
5453541Sshin#include <sys/proc.h>
5553541Sshin#include <sys/socket.h>
5653541Sshin#include <sys/socketvar.h>
5753541Sshin#include <sys/sysctl.h>
5853541Sshin#include <sys/syslog.h>
5953541Sshin#include <sys/ucred.h>
6053541Sshin#include <net/if.h>
6162587Sitojun#include <net/radix.h>
6253541Sshin#include <net/route.h>
6362587Sitojun#include <netinet/in.h>
6462587Sitojun#include <netinet/in_systm.h>
6562587Sitojun#include <netinet/in_var.h>
6662587Sitojun#include <netinet/in_pcb.h>
6762587Sitojun#include <netinet/ip.h>
6853541Sshin#include <netinet/ip_var.h>
6962587Sitojun#include <netinet/ip_icmp.h>
7062587Sitojun#include <netinet/ip_fw.h>
7162587Sitojun#include <netinet/ip_divert.h>
7253541Sshin#include <netinet/ip_dummynet.h>
7362587Sitojun#include <netinet/tcp.h>
7469774Sphk#include <netinet/tcp_timer.h>
7562587Sitojun#include <netinet/tcp_var.h>
7653541Sshin#include <netinet/tcpip.h>
7753541Sshin#include <netinet/udp.h>
7853541Sshin#include <netinet/udp_var.h>
7953541Sshin
8053541Sshin#ifdef IPSEC
8153541Sshin#include <netinet6/ipsec.h>
8253541Sshin#endif
8353541Sshin
8453541Sshin#include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
8553541Sshin
8653541Sshin#include <machine/in_cksum.h>	/* XXX for in_cksum */
8753541Sshin
8853541Sshin/*
8962587Sitojun * This is used to avoid that a firewall-generated packet
9053541Sshin * loops forever through the firewall.  Note that it must
9153541Sshin * be a flag that is unused by other protocols that might
9253541Sshin * be called from ip_output (e.g. IPsec) and it must be
9353541Sshin * listed in M_COPYFLAGS in mbuf.h so that if the mbuf chain
9462587Sitojun * is altered on the way through ip_output it is not lost.
9562587Sitojun * It might be better to add an m_tag since the this happens
9662587Sitojun * infrequently.
9762587Sitojun */
9862587Sitojun#define M_SKIP_FIREWALL         M_PROTO6
9962587Sitojun
10062587Sitojun/*
10162587Sitojun * set_disable contains one bit per set value (0..31).
10262587Sitojun * If the bit is set, all rules with the corresponding set
10362587Sitojun * are disabled. Set RESVD_SET(31) is reserved for the default rule
10462587Sitojun * and rules that are not deleted by the flush command,
10562587Sitojun * and CANNOT be disabled.
10662587Sitojun * Rules in set RESVD_SET can only be deleted explicitly.
10762587Sitojun */
10862587Sitojunstatic u_int32_t set_disable;
10962587Sitojun
11062587Sitojunstatic int fw_verbose;
11162587Sitojunstatic int verbose_limit;
11262587Sitojun
11362587Sitojunstatic struct callout ipfw_timeout;
11462587Sitojun#define	IPFW_DEFAULT_RULE	65535
11562587Sitojun
11662587Sitojunstruct ip_fw_chain {
11762587Sitojun	struct ip_fw	*rules;		/* list of rules */
11862587Sitojun	struct ip_fw	*reap;		/* list of rules to reap */
11962587Sitojun	struct mtx	mtx;		/* lock guarding rule list */
12062587Sitojun};
12162587Sitojun#define	IPFW_LOCK_INIT(_chain) \
12262587Sitojun	mtx_init(&(_chain)->mtx, "IPFW static rules", NULL, \
12353541Sshin		MTX_DEF | MTX_RECURSE)
12453541Sshin#define	IPFW_LOCK_DESTROY(_chain)	mtx_destroy(&(_chain)->mtx)
12553541Sshin#define	IPFW_LOCK(_chain)	mtx_lock(&(_chain)->mtx)
12653541Sshin#define	IPFW_UNLOCK(_chain)	mtx_unlock(&(_chain)->mtx)
12753541Sshin#define	IPFW_LOCK_ASSERT(_chain)	mtx_assert(&(_chain)->mtx, MA_OWNED)
12853541Sshin
12953541Sshin/*
13053541Sshin * list of rules for layer 3
13153541Sshin */
13253541Sshinstatic struct ip_fw_chain layer3_chain;
13353541Sshin
13462587SitojunMALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
13553541SshinMALLOC_DEFINE(M_IPFW_TBL, "ipfw_tbl", "IpFw tables");
13653541Sshin
13762587Sitojunstruct table_entry {
13853541Sshin	struct radix_node	rn[2];
13953541Sshin	struct sockaddr_in	addr, mask;
14053541Sshin	u_int32_t		value;
14153541Sshin};
14253541Sshin
14353541Sshin#define	IPFW_TABLES_MAX		128
14462587Sitojunstatic struct {
14562587Sitojun	struct radix_node_head	*rnh;
14653541Sshin	int			modified;
14753541Sshin} ipfw_tables[IPFW_TABLES_MAX];
14862587Sitojun
14962587Sitojunstatic int fw_debug = 1;
15062587Sitojunstatic int autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
15162587Sitojun
15262587Sitojun#ifdef SYSCTL_NODE
15353541SshinSYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
15453541SshinSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, enable,
15553541Sshin    CTLFLAG_RW | CTLFLAG_SECURE3,
15653541Sshin    &fw_enable, 0, "Enable ipfw");
15753541SshinSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLFLAG_RW,
15853541Sshin    &autoinc_step, 0, "Rule number autincrement step");
15953541SshinSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
16053541Sshin    CTLFLAG_RW | CTLFLAG_SECURE3,
16153541Sshin    &fw_one_pass, 0,
16253541Sshin    "Only do a single pass through ipfw when using dummynet(4)");
16353541SshinSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
16453541Sshin    &fw_debug, 0, "Enable printing of debug ip_fw statements");
16553541SshinSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
16653541Sshin    CTLFLAG_RW | CTLFLAG_SECURE3,
16753541Sshin    &fw_verbose, 0, "Log matches to ipfw rules");
16853541SshinSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
16953541Sshin    &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
17054350Sshin
17153541Sshin/*
17253541Sshin * Description of dynamic rules.
17353541Sshin *
17453541Sshin * Dynamic rules are stored in lists accessed through a hash table
17553541Sshin * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
17653541Sshin * be modified through the sysctl variable dyn_buckets which is
17753541Sshin * updated when the table becomes empty.
17853541Sshin *
17953541Sshin * XXX currently there is only one list, ipfw_dyn.
18053541Sshin *
18153541Sshin * When a packet is received, its address fields are first masked
18253541Sshin * with the mask defined for the rule, then hashed, then matched
18353541Sshin * against the entries in the corresponding list.
18453541Sshin * Dynamic rules can be used for different purposes:
18553541Sshin *  + stateful rules;
18653541Sshin *  + enforcing limits on the number of sessions;
18753541Sshin *  + in-kernel NAT (not implemented yet)
18853541Sshin *
18953541Sshin * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
19053541Sshin * measured in seconds and depending on the flags.
19153541Sshin *
19253541Sshin * The total number of dynamic rules is stored in dyn_count.
19353541Sshin * The max number of dynamic rules is dyn_max. When we reach
19453541Sshin * the maximum number of rules we do not create anymore. This is
19553541Sshin * done to avoid consuming too much memory, but also too much
19662587Sitojun * time when searching on each packet (ideally, we should try instead
19753541Sshin * to put a limit on the length of the list on each bucket...).
19853541Sshin *
19953541Sshin * Each dynamic rule holds a pointer to the parent ipfw rule so
20053541Sshin * we know what action to perform. Dynamic rules are removed when
20153541Sshin * the parent rule is deleted. XXX we should make them survive.
20253541Sshin *
20353541Sshin * There are some limitations with dynamic rules -- we do not
20462587Sitojun * obey the 'randomized match', and we do not do multiple
20553541Sshin * passes through the firewall. XXX check the latter!!!
20653541Sshin */
20753541Sshinstatic ipfw_dyn_rule **ipfw_dyn_v = NULL;
20853541Sshinstatic u_int32_t dyn_buckets = 256; /* must be power of 2 */
20953541Sshinstatic u_int32_t curr_dyn_buckets = 256; /* must be power of 2 */
21053541Sshin
21153541Sshinstatic struct mtx ipfw_dyn_mtx;		/* mutex guarding dynamic rules */
21253541Sshin#define	IPFW_DYN_LOCK_INIT() \
21353541Sshin	mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
21453541Sshin#define	IPFW_DYN_LOCK_DESTROY()	mtx_destroy(&ipfw_dyn_mtx)
21553541Sshin#define	IPFW_DYN_LOCK()		mtx_lock(&ipfw_dyn_mtx)
21653541Sshin#define	IPFW_DYN_UNLOCK()	mtx_unlock(&ipfw_dyn_mtx)
21753541Sshin#define	IPFW_DYN_LOCK_ASSERT()	mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
21853541Sshin
21953541Sshin/*
22053541Sshin * Timeouts for various events in handing dynamic rules.
22153541Sshin */
22253541Sshinstatic u_int32_t dyn_ack_lifetime = 300;
22353541Sshinstatic u_int32_t dyn_syn_lifetime = 20;
22453541Sshinstatic u_int32_t dyn_fin_lifetime = 1;
22553541Sshinstatic u_int32_t dyn_rst_lifetime = 1;
22653541Sshinstatic u_int32_t dyn_udp_lifetime = 10;
22753541Sshinstatic u_int32_t dyn_short_lifetime = 5;
22853541Sshin
22953541Sshin/*
23053541Sshin * Keepalives are sent if dyn_keepalive is set. They are sent every
23153541Sshin * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
23253541Sshin * seconds of lifetime of a rule.
23353541Sshin * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
23453541Sshin * than dyn_keepalive_period.
23562587Sitojun */
23653541Sshin
23753541Sshinstatic u_int32_t dyn_keepalive_interval = 20;
23853541Sshinstatic u_int32_t dyn_keepalive_period = 5;
23962587Sitojunstatic u_int32_t dyn_keepalive = 1;	/* do send keepalives */
24053541Sshin
24162587Sitojunstatic u_int32_t static_count;	/* # of static rules */
24262587Sitojunstatic u_int32_t static_len;	/* size in bytes of static rules */
24362587Sitojunstatic u_int32_t dyn_count;		/* # of dynamic rules */
24453541Sshinstatic u_int32_t dyn_max = 4096;	/* max # of dynamic rules */
24553541Sshin
24653541SshinSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLFLAG_RW,
24753541Sshin    &dyn_buckets, 0, "Number of dyn. buckets");
24853541SshinSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
24953541Sshin    &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
25053541SshinSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
25153541Sshin    &dyn_count, 0, "Number of dyn. rules");
25253541SshinSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
25353541Sshin    &dyn_max, 0, "Max number of dyn. rules");
25453541SshinSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
25553541Sshin    &static_count, 0, "Number of static rules");
25653541SshinSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
25753541Sshin    &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
25853541SshinSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
25953541Sshin    &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
26053541SshinSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime, CTLFLAG_RW,
26153541Sshin    &dyn_fin_lifetime, 0, "Lifetime of dyn. rules for fin");
26253541SshinSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime, CTLFLAG_RW,
26353541Sshin    &dyn_rst_lifetime, 0, "Lifetime of dyn. rules for rst");
26453541SshinSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
26553541Sshin    &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
26653541SshinSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
26753541Sshin    &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
26862587SitojunSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
26953541Sshin    &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
27053541Sshin
27153541Sshin#endif /* SYSCTL_NODE */
27253541Sshin
27362587Sitojun
27462587Sitojunstatic ip_fw_chk_t	ipfw_chk;
27553541Sshin
27653541Sshinip_dn_ruledel_t *ip_dn_ruledel_ptr = NULL;	/* hook into dummynet */
27753541Sshin
27853541Sshin/*
27953541Sshin * This macro maps an ip pointer into a layer3 header pointer of type T
28062587Sitojun */
28162587Sitojun#define	L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
28253541Sshin
28353541Sshinstatic __inline int
28453541Sshinicmptype_match(struct ip *ip, ipfw_insn_u32 *cmd)
28553541Sshin{
28653541Sshin	int type = L3HDR(struct icmp,ip)->icmp_type;
28753541Sshin
28853541Sshin	return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
28953541Sshin}
29053541Sshin
29153541Sshin#define TT	( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
29253541Sshin    (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
29353541Sshin
29453541Sshinstatic int
29553541Sshinis_icmp_query(struct ip *ip)
29653541Sshin{
29753541Sshin	int type = L3HDR(struct icmp, ip)->icmp_type;
29853541Sshin	return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
29953541Sshin}
30053541Sshin#undef TT
30162587Sitojun
30253541Sshin/*
30353541Sshin * The following checks use two arrays of 8 or 16 bits to store the
30453541Sshin * bits that we want set or clear, respectively. They are in the
30553541Sshin * low and high half of cmd->arg1 or cmd->d[0].
30653541Sshin *
30753541Sshin * We scan options and store the bits we find set. We succeed if
30853541Sshin *
30953541Sshin *	(want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
31053541Sshin *
31153541Sshin * The code is sometimes optimized not to store additional variables.
31253541Sshin */
31353541Sshin
31453541Sshinstatic int
31562587Sitojunflags_match(ipfw_insn *cmd, u_int8_t bits)
31662587Sitojun{
31753541Sshin	u_char want_clear;
31853541Sshin	bits = ~bits;
31953541Sshin
32053541Sshin	if ( ((cmd->arg1 & 0xff) & bits) != 0)
32162587Sitojun		return 0; /* some bits we want set were clear */
32262587Sitojun	want_clear = (cmd->arg1 >> 8) & 0xff;
32362587Sitojun	if ( (want_clear & bits) != want_clear)
32462587Sitojun		return 0; /* some bits we want clear were set */
32562587Sitojun	return 1;
32662587Sitojun}
32762587Sitojun
32862587Sitojunstatic int
32962587Sitojunipopts_match(struct ip *ip, ipfw_insn *cmd)
33053541Sshin{
33153541Sshin	int optlen, bits = 0;
33253541Sshin	u_char *cp = (u_char *)(ip + 1);
33353541Sshin	int x = (ip->ip_hl << 2) - sizeof (struct ip);
33453541Sshin
33553541Sshin	for (; x > 0; x -= optlen, cp += optlen) {
33653541Sshin		int opt = cp[IPOPT_OPTVAL];
33753541Sshin
33853541Sshin		if (opt == IPOPT_EOL)
33953541Sshin			break;
34053541Sshin		if (opt == IPOPT_NOP)
34153541Sshin			optlen = 1;
34253541Sshin		else {
34353541Sshin			optlen = cp[IPOPT_OLEN];
34453541Sshin			if (optlen <= 0 || optlen > x)
34553541Sshin				return 0; /* invalid or truncated */
34653541Sshin		}
34753541Sshin		switch (opt) {
34853541Sshin
34962587Sitojun		default:
35053541Sshin			break;
35162587Sitojun
35262587Sitojun		case IPOPT_LSRR:
35362587Sitojun			bits |= IP_FW_IPOPT_LSRR;
35462587Sitojun			break;
35562587Sitojun
35662587Sitojun		case IPOPT_SSRR:
35762587Sitojun			bits |= IP_FW_IPOPT_SSRR;
35862587Sitojun			break;
35962587Sitojun
36062587Sitojun		case IPOPT_RR:
36162587Sitojun			bits |= IP_FW_IPOPT_RR;
36262587Sitojun			break;
36362587Sitojun
36462587Sitojun		case IPOPT_TS:
36562587Sitojun			bits |= IP_FW_IPOPT_TS;
36662587Sitojun			break;
36762587Sitojun		}
36862587Sitojun	}
36962587Sitojun	return (flags_match(cmd, bits));
37062587Sitojun}
37162587Sitojun
37262587Sitojunstatic int
37362587Sitojuntcpopts_match(struct ip *ip, ipfw_insn *cmd)
37462587Sitojun{
37562587Sitojun	int optlen, bits = 0;
37662587Sitojun	struct tcphdr *tcp = L3HDR(struct tcphdr,ip);
37762587Sitojun	u_char *cp = (u_char *)(tcp + 1);
37862587Sitojun	int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
37962587Sitojun
38062587Sitojun	for (; x > 0; x -= optlen, cp += optlen) {
38162587Sitojun		int opt = cp[0];
38262587Sitojun		if (opt == TCPOPT_EOL)
38362587Sitojun			break;
38462587Sitojun		if (opt == TCPOPT_NOP)
38562587Sitojun			optlen = 1;
38653541Sshin		else {
38753541Sshin			optlen = cp[1];
38853541Sshin			if (optlen <= 0)
38953541Sshin				break;
39053541Sshin		}
39153541Sshin
39253541Sshin		switch (opt) {
39353541Sshin
39476899Ssumikawa		default:
39553541Sshin			break;
39653541Sshin
39753541Sshin		case TCPOPT_MAXSEG:
39876899Ssumikawa			bits |= IP_FW_TCPOPT_MSS;
39976899Ssumikawa			break;
40053541Sshin
40153541Sshin		case TCPOPT_WINDOW:
40253541Sshin			bits |= IP_FW_TCPOPT_WINDOW;
40353541Sshin			break;
40453541Sshin
40553541Sshin		case TCPOPT_SACK_PERMITTED:
40676899Ssumikawa		case TCPOPT_SACK:
40753541Sshin			bits |= IP_FW_TCPOPT_SACK;
40853541Sshin			break;
40953541Sshin
41076899Ssumikawa		case TCPOPT_TIMESTAMP:
41176899Ssumikawa			bits |= IP_FW_TCPOPT_TS;
41253541Sshin			break;
41353541Sshin
41453541Sshin		case TCPOPT_CC:
41562587Sitojun		case TCPOPT_CCNEW:
41653541Sshin		case TCPOPT_CCECHO:
41753541Sshin			bits |= IP_FW_TCPOPT_CC;
41853541Sshin			break;
41953541Sshin		}
42053541Sshin	}
42153541Sshin	return (flags_match(cmd, bits));
42253541Sshin}
42353541Sshin
42453541Sshinstatic int
42553541Sshiniface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
42662587Sitojun{
42762587Sitojun	if (ifp == NULL)	/* no iface with this packet, match fails */
42862587Sitojun		return 0;
42962587Sitojun	/* Check by name or by IP address */
43062587Sitojun	if (cmd->name[0] != '\0') { /* match by name */
43162587Sitojun		/* Check name */
43253541Sshin		if (cmd->p.glob) {
43353541Sshin			if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
43453541Sshin				return(1);
43553541Sshin		} else {
43653541Sshin			if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
43753541Sshin				return(1);
43853541Sshin		}
43953541Sshin	} else {
44053541Sshin		struct ifaddr *ia;
44153541Sshin
44253541Sshin		/* XXX lock? */
44353541Sshin		TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
44453541Sshin			if (ia->ifa_addr == NULL)
44553541Sshin				continue;
44653541Sshin			if (ia->ifa_addr->sa_family != AF_INET)
44753541Sshin				continue;
44853541Sshin			if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
44953541Sshin			    (ia->ifa_addr))->sin_addr.s_addr)
45053541Sshin				return(1);	/* match */
45153541Sshin		}
45262587Sitojun	}
45353541Sshin	return(0);	/* no match, fail ... */
45462587Sitojun}
45562587Sitojun
45653541Sshin/*
45753541Sshin * The verify_path function checks if a route to the src exists and
45853541Sshin * if it is reachable via ifp (when provided).
45962587Sitojun *
46062587Sitojun * The 'verrevpath' option checks that the interface that an IP packet
46162587Sitojun * arrives on is the same interface that traffic destined for the
46253541Sshin * packet's source address would be routed out of.  The 'versrcreach'
46353541Sshin * option just checks that the source address is reachable via any route
46453541Sshin * (except default) in the routing table.  These two are a measure to block
46553541Sshin * forged packets.  This is also commonly known as "anti-spoofing" or Unicast
46662587Sitojun * Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
46762587Sitojun * is purposely reminiscent of the Cisco IOS command,
46853541Sshin *
46953541Sshin *   ip verify unicast reverse-path
47053541Sshin *   ip verify unicast source reachable-via any
47153541Sshin *
47262587Sitojun * which implements the same functionality. But note that syntax is
47362587Sitojun * misleading. The check may be performed on all IP packets whether unicast,
47462587Sitojun * multicast, or broadcast.
47553541Sshin */
47653541Sshinstatic int
47753541Sshinverify_path(struct in_addr src, struct ifnet *ifp)
47853541Sshin{
47962587Sitojun	struct route ro;
48053541Sshin	struct sockaddr_in *dst;
48153541Sshin
48262587Sitojun	bzero(&ro, sizeof(ro));
48362587Sitojun
48462587Sitojun	dst = (struct sockaddr_in *)&(ro.ro_dst);
48562587Sitojun	dst->sin_family = AF_INET;
48662587Sitojun	dst->sin_len = sizeof(*dst);
48762587Sitojun	dst->sin_addr = src;
48862587Sitojun	rtalloc_ign(&ro, RTF_CLONING);
48962587Sitojun
49062587Sitojun	if (ro.ro_rt == NULL)
49162587Sitojun		return 0;
49262587Sitojun
49362587Sitojun	/* if ifp is provided, check for equality with rtentry */
49453541Sshin	if (ifp != NULL && ro.ro_rt->rt_ifp != ifp) {
49553541Sshin		RTFREE(ro.ro_rt);
49653541Sshin		return 0;
49753541Sshin	}
49853541Sshin
49953541Sshin	/* if no ifp provided, check if rtentry is not default route */
50053541Sshin	if (ifp == NULL &&
50153541Sshin	     satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
50253541Sshin		RTFREE(ro.ro_rt);
50353541Sshin		return 0;
50453541Sshin	}
50553541Sshin
50653541Sshin	/* found valid route */
50753541Sshin	RTFREE(ro.ro_rt);
50853541Sshin	return 1;
50953541Sshin}
51053541Sshin
51153541Sshin
51253541Sshinstatic u_int64_t norule_counter;	/* counter for ipfw_log(NULL...) */
51353541Sshin
51453541Sshin#define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
51553541Sshin#define SNP(buf) buf, sizeof(buf)
51653541Sshin
51753541Sshin/*
51853541Sshin * We enter here when we have a rule with O_LOG.
51953541Sshin * XXX this function alone takes about 2Kbytes of code!
52053541Sshin */
52153541Sshinstatic void
52253541Sshinipfw_log(struct ip_fw *f, u_int hlen, struct ether_header *eh,
52353541Sshin	struct mbuf *m, struct ifnet *oif)
52453541Sshin{
52553541Sshin	char *action;
52653541Sshin	int limit_reached = 0;
52753541Sshin	char action2[40], proto[48], fragment[28];
52853541Sshin
52953541Sshin	fragment[0] = '\0';
53053541Sshin	proto[0] = '\0';
53153541Sshin
53253541Sshin	if (f == NULL) {	/* bogus pkt */
53353541Sshin		if (verbose_limit != 0 && norule_counter >= verbose_limit)
53453541Sshin			return;
53553541Sshin		norule_counter++;
53653541Sshin		if (norule_counter == verbose_limit)
53753541Sshin			limit_reached = verbose_limit;
53853541Sshin		action = "Refuse";
53953541Sshin	} else {	/* O_LOG is the first action, find the real one */
54053541Sshin		ipfw_insn *cmd = ACTION_PTR(f);
54153541Sshin		ipfw_insn_log *l = (ipfw_insn_log *)cmd;
54253541Sshin
54353541Sshin		if (l->max_log != 0 && l->log_left == 0)
54453541Sshin			return;
54553541Sshin		l->log_left--;
54653541Sshin		if (l->log_left == 0)
54753541Sshin			limit_reached = l->max_log;
54853541Sshin		cmd += F_LEN(cmd);	/* point to first action */
54953541Sshin		if (cmd->opcode == O_PROB)
55053541Sshin			cmd += F_LEN(cmd);
55153541Sshin
55253541Sshin		action = action2;
55353541Sshin		switch (cmd->opcode) {
55453541Sshin		case O_DENY:
55553541Sshin			action = "Deny";
55653541Sshin			break;
55753541Sshin
55853541Sshin		case O_REJECT:
55953541Sshin			if (cmd->arg1==ICMP_REJECT_RST)
56053541Sshin				action = "Reset";
56153541Sshin			else if (cmd->arg1==ICMP_UNREACH_HOST)
56253541Sshin				action = "Reject";
56353541Sshin			else
56453541Sshin				snprintf(SNPARGS(action2, 0), "Unreach %d",
56553541Sshin					cmd->arg1);
56653541Sshin			break;
56753541Sshin
56862587Sitojun		case O_ACCEPT:
56953541Sshin			action = "Accept";
57062587Sitojun			break;
57153541Sshin		case O_COUNT:
57253541Sshin			action = "Count";
57353541Sshin			break;
57453541Sshin		case O_DIVERT:
57553541Sshin			snprintf(SNPARGS(action2, 0), "Divert %d",
57653541Sshin				cmd->arg1);
57753541Sshin			break;
57853541Sshin		case O_TEE:
57953541Sshin			snprintf(SNPARGS(action2, 0), "Tee %d",
58053541Sshin				cmd->arg1);
58153541Sshin			break;
58253541Sshin		case O_SKIPTO:
58353541Sshin			snprintf(SNPARGS(action2, 0), "SkipTo %d",
58453541Sshin				cmd->arg1);
58553541Sshin			break;
58653541Sshin		case O_PIPE:
58753541Sshin			snprintf(SNPARGS(action2, 0), "Pipe %d",
58853541Sshin				cmd->arg1);
58953541Sshin			break;
59053541Sshin		case O_QUEUE:
59153541Sshin			snprintf(SNPARGS(action2, 0), "Queue %d",
59253541Sshin				cmd->arg1);
59353541Sshin			break;
59453541Sshin		case O_FORWARD_IP: {
59553541Sshin			ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
59653541Sshin			int len;
59753541Sshin
59853541Sshin			len = snprintf(SNPARGS(action2, 0), "Forward to %s",
59953541Sshin				inet_ntoa(sa->sa.sin_addr));
60053541Sshin			if (sa->sa.sin_port)
60153541Sshin				snprintf(SNPARGS(action2, len), ":%d",
60253541Sshin				    sa->sa.sin_port);
60353541Sshin			}
60453541Sshin			break;
60553541Sshin		default:
60653541Sshin			action = "UNKNOWN";
60753541Sshin			break;
60853541Sshin		}
60953541Sshin	}
61053541Sshin
61153541Sshin	if (hlen == 0) {	/* non-ip */
61253541Sshin		snprintf(SNPARGS(proto, 0), "MAC");
61353541Sshin	} else {
61453541Sshin		struct ip *ip = mtod(m, struct ip *);
61553541Sshin		/* these three are all aliases to the same thing */
61653541Sshin		struct icmp *const icmp = L3HDR(struct icmp, ip);
61753541Sshin		struct tcphdr *const tcp = (struct tcphdr *)icmp;
61853541Sshin		struct udphdr *const udp = (struct udphdr *)icmp;
61953541Sshin
62053541Sshin		int ip_off, offset, ip_len;
62153541Sshin
62253541Sshin		int len;
62353541Sshin
62453541Sshin		if (eh != NULL) { /* layer 2 packets are as on the wire */
62553541Sshin			ip_off = ntohs(ip->ip_off);
62653541Sshin			ip_len = ntohs(ip->ip_len);
62753541Sshin		} else {
62853541Sshin			ip_off = ip->ip_off;
62953541Sshin			ip_len = ip->ip_len;
63062587Sitojun		}
63162587Sitojun		offset = ip_off & IP_OFFMASK;
63262587Sitojun		switch (ip->ip_p) {
63353541Sshin		case IPPROTO_TCP:
63453541Sshin			len = snprintf(SNPARGS(proto, 0), "TCP %s",
63553541Sshin			    inet_ntoa(ip->ip_src));
63653541Sshin			if (offset == 0)
63753541Sshin				snprintf(SNPARGS(proto, len), ":%d %s:%d",
63853541Sshin				    ntohs(tcp->th_sport),
63953541Sshin				    inet_ntoa(ip->ip_dst),
64053541Sshin				    ntohs(tcp->th_dport));
64153541Sshin			else
64253541Sshin				snprintf(SNPARGS(proto, len), " %s",
64353541Sshin				    inet_ntoa(ip->ip_dst));
64453541Sshin			break;
64553541Sshin
64653541Sshin		case IPPROTO_UDP:
64753541Sshin			len = snprintf(SNPARGS(proto, 0), "UDP %s",
64853541Sshin				inet_ntoa(ip->ip_src));
64953541Sshin			if (offset == 0)
65053541Sshin				snprintf(SNPARGS(proto, len), ":%d %s:%d",
65153541Sshin				    ntohs(udp->uh_sport),
65253541Sshin				    inet_ntoa(ip->ip_dst),
65353541Sshin				    ntohs(udp->uh_dport));
65453541Sshin			else
65553541Sshin				snprintf(SNPARGS(proto, len), " %s",
65653541Sshin				    inet_ntoa(ip->ip_dst));
65762587Sitojun			break;
65862587Sitojun
65962587Sitojun		case IPPROTO_ICMP:
66062587Sitojun			if (offset == 0)
66162587Sitojun				len = snprintf(SNPARGS(proto, 0),
66262587Sitojun				    "ICMP:%u.%u ",
66362587Sitojun				    icmp->icmp_type, icmp->icmp_code);
66462587Sitojun			else
66562587Sitojun				len = snprintf(SNPARGS(proto, 0), "ICMP ");
66662587Sitojun			len += snprintf(SNPARGS(proto, len), "%s",
66762587Sitojun			    inet_ntoa(ip->ip_src));
66862587Sitojun			snprintf(SNPARGS(proto, len), " %s",
66962587Sitojun			    inet_ntoa(ip->ip_dst));
67062587Sitojun			break;
67162587Sitojun
67262587Sitojun		default:
67362587Sitojun			len = snprintf(SNPARGS(proto, 0), "P:%d %s", ip->ip_p,
67453541Sshin			    inet_ntoa(ip->ip_src));
67553541Sshin			snprintf(SNPARGS(proto, len), " %s",
67653541Sshin			    inet_ntoa(ip->ip_dst));
67753541Sshin			break;
67853541Sshin		}
67953541Sshin
68053541Sshin		if (ip_off & (IP_MF | IP_OFFMASK))
68153541Sshin			snprintf(SNPARGS(fragment, 0), " (frag %d:%d@%d%s)",
68253541Sshin			     ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
68353541Sshin			     offset << 3,
68453541Sshin			     (ip_off & IP_MF) ? "+" : "");
68553541Sshin	}
68653541Sshin	if (oif || m->m_pkthdr.rcvif)
68753541Sshin		log(LOG_SECURITY | LOG_INFO,
68853541Sshin		    "ipfw: %d %s %s %s via %s%s\n",
68953541Sshin		    f ? f->rulenum : -1,
69053541Sshin		    action, proto, oif ? "out" : "in",
691		    oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
692		    fragment);
693	else
694		log(LOG_SECURITY | LOG_INFO,
695		    "ipfw: %d %s %s [no if info]%s\n",
696		    f ? f->rulenum : -1,
697		    action, proto, fragment);
698	if (limit_reached)
699		log(LOG_SECURITY | LOG_NOTICE,
700		    "ipfw: limit %d reached on entry %d\n",
701		    limit_reached, f ? f->rulenum : -1);
702}
703
704/*
705 * IMPORTANT: the hash function for dynamic rules must be commutative
706 * in source and destination (ip,port), because rules are bidirectional
707 * and we want to find both in the same bucket.
708 */
709static __inline int
710hash_packet(struct ipfw_flow_id *id)
711{
712	u_int32_t i;
713
714	i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
715	i &= (curr_dyn_buckets - 1);
716	return i;
717}
718
719/**
720 * unlink a dynamic rule from a chain. prev is a pointer to
721 * the previous one, q is a pointer to the rule to delete,
722 * head is a pointer to the head of the queue.
723 * Modifies q and potentially also head.
724 */
725#define UNLINK_DYN_RULE(prev, head, q) {				\
726	ipfw_dyn_rule *old_q = q;					\
727									\
728	/* remove a refcount to the parent */				\
729	if (q->dyn_type == O_LIMIT)					\
730		q->parent->count--;					\
731	DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
732		(q->id.src_ip), (q->id.src_port),			\
733		(q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); )	\
734	if (prev != NULL)						\
735		prev->next = q = q->next;				\
736	else								\
737		head = q = q->next;					\
738	dyn_count--;							\
739	free(old_q, M_IPFW); }
740
741#define TIME_LEQ(a,b)       ((int)((a)-(b)) <= 0)
742
743/**
744 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
745 *
746 * If keep_me == NULL, rules are deleted even if not expired,
747 * otherwise only expired rules are removed.
748 *
749 * The value of the second parameter is also used to point to identify
750 * a rule we absolutely do not want to remove (e.g. because we are
751 * holding a reference to it -- this is the case with O_LIMIT_PARENT
752 * rules). The pointer is only used for comparison, so any non-null
753 * value will do.
754 */
755static void
756remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
757{
758	static u_int32_t last_remove = 0;
759
760#define FORCE (keep_me == NULL)
761
762	ipfw_dyn_rule *prev, *q;
763	int i, pass = 0, max_pass = 0;
764
765	IPFW_DYN_LOCK_ASSERT();
766
767	if (ipfw_dyn_v == NULL || dyn_count == 0)
768		return;
769	/* do not expire more than once per second, it is useless */
770	if (!FORCE && last_remove == time_second)
771		return;
772	last_remove = time_second;
773
774	/*
775	 * because O_LIMIT refer to parent rules, during the first pass only
776	 * remove child and mark any pending LIMIT_PARENT, and remove
777	 * them in a second pass.
778	 */
779next_pass:
780	for (i = 0 ; i < curr_dyn_buckets ; i++) {
781		for (prev=NULL, q = ipfw_dyn_v[i] ; q ; ) {
782			/*
783			 * Logic can become complex here, so we split tests.
784			 */
785			if (q == keep_me)
786				goto next;
787			if (rule != NULL && rule != q->rule)
788				goto next; /* not the one we are looking for */
789			if (q->dyn_type == O_LIMIT_PARENT) {
790				/*
791				 * handle parent in the second pass,
792				 * record we need one.
793				 */
794				max_pass = 1;
795				if (pass == 0)
796					goto next;
797				if (FORCE && q->count != 0 ) {
798					/* XXX should not happen! */
799					printf("ipfw: OUCH! cannot remove rule,"
800					     " count %d\n", q->count);
801				}
802			} else {
803				if (!FORCE &&
804				    !TIME_LEQ( q->expire, time_second ))
805					goto next;
806			}
807             if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
808                     UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
809                     continue;
810             }
811next:
812			prev=q;
813			q=q->next;
814		}
815	}
816	if (pass++ < max_pass)
817		goto next_pass;
818}
819
820
821/**
822 * lookup a dynamic rule.
823 */
824static ipfw_dyn_rule *
825lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
826	struct tcphdr *tcp)
827{
828	/*
829	 * stateful ipfw extensions.
830	 * Lookup into dynamic session queue
831	 */
832#define MATCH_REVERSE	0
833#define MATCH_FORWARD	1
834#define MATCH_NONE	2
835#define MATCH_UNKNOWN	3
836	int i, dir = MATCH_NONE;
837	ipfw_dyn_rule *prev, *q=NULL;
838
839	IPFW_DYN_LOCK_ASSERT();
840
841	if (ipfw_dyn_v == NULL)
842		goto done;	/* not found */
843	i = hash_packet( pkt );
844	for (prev=NULL, q = ipfw_dyn_v[i] ; q != NULL ; ) {
845		if (q->dyn_type == O_LIMIT_PARENT && q->count)
846			goto next;
847		if (TIME_LEQ( q->expire, time_second)) { /* expire entry */
848			UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
849			continue;
850		}
851		if (pkt->proto == q->id.proto &&
852		    q->dyn_type != O_LIMIT_PARENT) {
853			if (pkt->src_ip == q->id.src_ip &&
854			    pkt->dst_ip == q->id.dst_ip &&
855			    pkt->src_port == q->id.src_port &&
856			    pkt->dst_port == q->id.dst_port ) {
857				dir = MATCH_FORWARD;
858				break;
859			}
860			if (pkt->src_ip == q->id.dst_ip &&
861			    pkt->dst_ip == q->id.src_ip &&
862			    pkt->src_port == q->id.dst_port &&
863			    pkt->dst_port == q->id.src_port ) {
864				dir = MATCH_REVERSE;
865				break;
866			}
867		}
868next:
869		prev = q;
870		q = q->next;
871	}
872	if (q == NULL)
873		goto done; /* q = NULL, not found */
874
875	if ( prev != NULL) { /* found and not in front */
876		prev->next = q->next;
877		q->next = ipfw_dyn_v[i];
878		ipfw_dyn_v[i] = q;
879	}
880	if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
881		u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
882
883#define BOTH_SYN	(TH_SYN | (TH_SYN << 8))
884#define BOTH_FIN	(TH_FIN | (TH_FIN << 8))
885		q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
886		switch (q->state) {
887		case TH_SYN:				/* opening */
888			q->expire = time_second + dyn_syn_lifetime;
889			break;
890
891		case BOTH_SYN:			/* move to established */
892		case BOTH_SYN | TH_FIN :	/* one side tries to close */
893		case BOTH_SYN | (TH_FIN << 8) :
894 			if (tcp) {
895#define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
896			    u_int32_t ack = ntohl(tcp->th_ack);
897			    if (dir == MATCH_FORWARD) {
898				if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
899				    q->ack_fwd = ack;
900				else { /* ignore out-of-sequence */
901				    break;
902				}
903			    } else {
904				if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
905				    q->ack_rev = ack;
906				else { /* ignore out-of-sequence */
907				    break;
908				}
909			    }
910			}
911			q->expire = time_second + dyn_ack_lifetime;
912			break;
913
914		case BOTH_SYN | BOTH_FIN:	/* both sides closed */
915			if (dyn_fin_lifetime >= dyn_keepalive_period)
916				dyn_fin_lifetime = dyn_keepalive_period - 1;
917			q->expire = time_second + dyn_fin_lifetime;
918			break;
919
920		default:
921#if 0
922			/*
923			 * reset or some invalid combination, but can also
924			 * occur if we use keep-state the wrong way.
925			 */
926			if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
927				printf("invalid state: 0x%x\n", q->state);
928#endif
929			if (dyn_rst_lifetime >= dyn_keepalive_period)
930				dyn_rst_lifetime = dyn_keepalive_period - 1;
931			q->expire = time_second + dyn_rst_lifetime;
932			break;
933		}
934	} else if (pkt->proto == IPPROTO_UDP) {
935		q->expire = time_second + dyn_udp_lifetime;
936	} else {
937		/* other protocols */
938		q->expire = time_second + dyn_short_lifetime;
939	}
940done:
941	if (match_direction)
942		*match_direction = dir;
943	return q;
944}
945
946static ipfw_dyn_rule *
947lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
948	struct tcphdr *tcp)
949{
950	ipfw_dyn_rule *q;
951
952	IPFW_DYN_LOCK();
953	q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
954	if (q == NULL)
955		IPFW_DYN_UNLOCK();
956	/* NB: return table locked when q is not NULL */
957	return q;
958}
959
960static void
961realloc_dynamic_table(void)
962{
963	IPFW_DYN_LOCK_ASSERT();
964
965	/*
966	 * Try reallocation, make sure we have a power of 2 and do
967	 * not allow more than 64k entries. In case of overflow,
968	 * default to 1024.
969	 */
970
971	if (dyn_buckets > 65536)
972		dyn_buckets = 1024;
973	if ((dyn_buckets & (dyn_buckets-1)) != 0) { /* not a power of 2 */
974		dyn_buckets = curr_dyn_buckets; /* reset */
975		return;
976	}
977	curr_dyn_buckets = dyn_buckets;
978	if (ipfw_dyn_v != NULL)
979		free(ipfw_dyn_v, M_IPFW);
980	for (;;) {
981		ipfw_dyn_v = malloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
982		       M_IPFW, M_NOWAIT | M_ZERO);
983		if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
984			break;
985		curr_dyn_buckets /= 2;
986	}
987}
988
989/**
990 * Install state of type 'type' for a dynamic session.
991 * The hash table contains two type of rules:
992 * - regular rules (O_KEEP_STATE)
993 * - rules for sessions with limited number of sess per user
994 *   (O_LIMIT). When they are created, the parent is
995 *   increased by 1, and decreased on delete. In this case,
996 *   the third parameter is the parent rule and not the chain.
997 * - "parent" rules for the above (O_LIMIT_PARENT).
998 */
999static ipfw_dyn_rule *
1000add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
1001{
1002	ipfw_dyn_rule *r;
1003	int i;
1004
1005	IPFW_DYN_LOCK_ASSERT();
1006
1007	if (ipfw_dyn_v == NULL ||
1008	    (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
1009		realloc_dynamic_table();
1010		if (ipfw_dyn_v == NULL)
1011			return NULL; /* failed ! */
1012	}
1013	i = hash_packet(id);
1014
1015	r = malloc(sizeof *r, M_IPFW, M_NOWAIT | M_ZERO);
1016	if (r == NULL) {
1017		printf ("ipfw: sorry cannot allocate state\n");
1018		return NULL;
1019	}
1020
1021	/* increase refcount on parent, and set pointer */
1022	if (dyn_type == O_LIMIT) {
1023		ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
1024		if ( parent->dyn_type != O_LIMIT_PARENT)
1025			panic("invalid parent");
1026		parent->count++;
1027		r->parent = parent;
1028		rule = parent->rule;
1029	}
1030
1031	r->id = *id;
1032	r->expire = time_second + dyn_syn_lifetime;
1033	r->rule = rule;
1034	r->dyn_type = dyn_type;
1035	r->pcnt = r->bcnt = 0;
1036	r->count = 0;
1037
1038	r->bucket = i;
1039	r->next = ipfw_dyn_v[i];
1040	ipfw_dyn_v[i] = r;
1041	dyn_count++;
1042	DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1043	   dyn_type,
1044	   (r->id.src_ip), (r->id.src_port),
1045	   (r->id.dst_ip), (r->id.dst_port),
1046	   dyn_count ); )
1047	return r;
1048}
1049
1050/**
1051 * lookup dynamic parent rule using pkt and rule as search keys.
1052 * If the lookup fails, then install one.
1053 */
1054static ipfw_dyn_rule *
1055lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
1056{
1057	ipfw_dyn_rule *q;
1058	int i;
1059
1060	IPFW_DYN_LOCK_ASSERT();
1061
1062	if (ipfw_dyn_v) {
1063		i = hash_packet( pkt );
1064		for (q = ipfw_dyn_v[i] ; q != NULL ; q=q->next)
1065			if (q->dyn_type == O_LIMIT_PARENT &&
1066			    rule== q->rule &&
1067			    pkt->proto == q->id.proto &&
1068			    pkt->src_ip == q->id.src_ip &&
1069			    pkt->dst_ip == q->id.dst_ip &&
1070			    pkt->src_port == q->id.src_port &&
1071			    pkt->dst_port == q->id.dst_port) {
1072				q->expire = time_second + dyn_short_lifetime;
1073				DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
1074				return q;
1075			}
1076	}
1077	return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
1078}
1079
1080/**
1081 * Install dynamic state for rule type cmd->o.opcode
1082 *
1083 * Returns 1 (failure) if state is not installed because of errors or because
1084 * session limitations are enforced.
1085 */
1086static int
1087install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
1088	struct ip_fw_args *args)
1089{
1090	static int last_log;
1091
1092	ipfw_dyn_rule *q;
1093
1094	DEB(printf("ipfw: install state type %d 0x%08x %u -> 0x%08x %u\n",
1095	    cmd->o.opcode,
1096	    (args->f_id.src_ip), (args->f_id.src_port),
1097	    (args->f_id.dst_ip), (args->f_id.dst_port) );)
1098
1099	IPFW_DYN_LOCK();
1100
1101	q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
1102
1103	if (q != NULL) { /* should never occur */
1104		if (last_log != time_second) {
1105			last_log = time_second;
1106			printf("ipfw: install_state: entry already present, done\n");
1107		}
1108		IPFW_DYN_UNLOCK();
1109		return 0;
1110	}
1111
1112	if (dyn_count >= dyn_max)
1113		/*
1114		 * Run out of slots, try to remove any expired rule.
1115		 */
1116		remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1117
1118	if (dyn_count >= dyn_max) {
1119		if (last_log != time_second) {
1120			last_log = time_second;
1121			printf("ipfw: install_state: Too many dynamic rules\n");
1122		}
1123		IPFW_DYN_UNLOCK();
1124		return 1; /* cannot install, notify caller */
1125	}
1126
1127	switch (cmd->o.opcode) {
1128	case O_KEEP_STATE: /* bidir rule */
1129		add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1130		break;
1131
1132	case O_LIMIT: /* limit number of sessions */
1133	    {
1134		u_int16_t limit_mask = cmd->limit_mask;
1135		struct ipfw_flow_id id;
1136		ipfw_dyn_rule *parent;
1137
1138		DEB(printf("ipfw: installing dyn-limit rule %d\n",
1139		    cmd->conn_limit);)
1140
1141		id.dst_ip = id.src_ip = 0;
1142		id.dst_port = id.src_port = 0;
1143		id.proto = args->f_id.proto;
1144
1145		if (limit_mask & DYN_SRC_ADDR)
1146			id.src_ip = args->f_id.src_ip;
1147		if (limit_mask & DYN_DST_ADDR)
1148			id.dst_ip = args->f_id.dst_ip;
1149		if (limit_mask & DYN_SRC_PORT)
1150			id.src_port = args->f_id.src_port;
1151		if (limit_mask & DYN_DST_PORT)
1152			id.dst_port = args->f_id.dst_port;
1153		parent = lookup_dyn_parent(&id, rule);
1154		if (parent == NULL) {
1155			printf("ipfw: add parent failed\n");
1156			return 1;
1157		}
1158		if (parent->count >= cmd->conn_limit) {
1159			/*
1160			 * See if we can remove some expired rule.
1161			 */
1162			remove_dyn_rule(rule, parent);
1163			if (parent->count >= cmd->conn_limit) {
1164				if (fw_verbose && last_log != time_second) {
1165					last_log = time_second;
1166					log(LOG_SECURITY | LOG_DEBUG,
1167					    "drop session, too many entries\n");
1168				}
1169				IPFW_DYN_UNLOCK();
1170				return 1;
1171			}
1172		}
1173		add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1174	    }
1175		break;
1176	default:
1177		printf("ipfw: unknown dynamic rule type %u\n", cmd->o.opcode);
1178		IPFW_DYN_UNLOCK();
1179		return 1;
1180	}
1181	lookup_dyn_rule_locked(&args->f_id, NULL, NULL); /* XXX just set lifetime */
1182	IPFW_DYN_UNLOCK();
1183	return 0;
1184}
1185
1186/*
1187 * Transmit a TCP packet, containing either a RST or a keepalive.
1188 * When flags & TH_RST, we are sending a RST packet, because of a
1189 * "reset" action matched the packet.
1190 * Otherwise we are sending a keepalive, and flags & TH_
1191 */
1192static void
1193send_pkt(struct ipfw_flow_id *id, u_int32_t seq, u_int32_t ack, int flags)
1194{
1195	struct mbuf *m;
1196	struct ip *ip;
1197	struct tcphdr *tcp;
1198
1199	MGETHDR(m, M_DONTWAIT, MT_HEADER);
1200	if (m == 0)
1201		return;
1202	m->m_pkthdr.rcvif = (struct ifnet *)0;
1203	m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1204	m->m_data += max_linkhdr;
1205
1206	ip = mtod(m, struct ip *);
1207	bzero(ip, m->m_len);
1208	tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1209	ip->ip_p = IPPROTO_TCP;
1210	tcp->th_off = 5;
1211	/*
1212	 * Assume we are sending a RST (or a keepalive in the reverse
1213	 * direction), swap src and destination addresses and ports.
1214	 */
1215	ip->ip_src.s_addr = htonl(id->dst_ip);
1216	ip->ip_dst.s_addr = htonl(id->src_ip);
1217	tcp->th_sport = htons(id->dst_port);
1218	tcp->th_dport = htons(id->src_port);
1219	if (flags & TH_RST) {	/* we are sending a RST */
1220		if (flags & TH_ACK) {
1221			tcp->th_seq = htonl(ack);
1222			tcp->th_ack = htonl(0);
1223			tcp->th_flags = TH_RST;
1224		} else {
1225			if (flags & TH_SYN)
1226				seq++;
1227			tcp->th_seq = htonl(0);
1228			tcp->th_ack = htonl(seq);
1229			tcp->th_flags = TH_RST | TH_ACK;
1230		}
1231	} else {
1232		/*
1233		 * We are sending a keepalive. flags & TH_SYN determines
1234		 * the direction, forward if set, reverse if clear.
1235		 * NOTE: seq and ack are always assumed to be correct
1236		 * as set by the caller. This may be confusing...
1237		 */
1238		if (flags & TH_SYN) {
1239			/*
1240			 * we have to rewrite the correct addresses!
1241			 */
1242			ip->ip_dst.s_addr = htonl(id->dst_ip);
1243			ip->ip_src.s_addr = htonl(id->src_ip);
1244			tcp->th_dport = htons(id->dst_port);
1245			tcp->th_sport = htons(id->src_port);
1246		}
1247		tcp->th_seq = htonl(seq);
1248		tcp->th_ack = htonl(ack);
1249		tcp->th_flags = TH_ACK;
1250	}
1251	/*
1252	 * set ip_len to the payload size so we can compute
1253	 * the tcp checksum on the pseudoheader
1254	 * XXX check this, could save a couple of words ?
1255	 */
1256	ip->ip_len = htons(sizeof(struct tcphdr));
1257	tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1258	/*
1259	 * now fill fields left out earlier
1260	 */
1261	ip->ip_ttl = ip_defttl;
1262	ip->ip_len = m->m_pkthdr.len;
1263	m->m_flags |= M_SKIP_FIREWALL;
1264	ip_output(m, NULL, NULL, 0, NULL, NULL);
1265}
1266
1267/*
1268 * sends a reject message, consuming the mbuf passed as an argument.
1269 */
1270static void
1271send_reject(struct ip_fw_args *args, int code, int offset, int ip_len)
1272{
1273
1274	if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1275		/* We need the IP header in host order for icmp_error(). */
1276		if (args->eh != NULL) {
1277			struct ip *ip = mtod(args->m, struct ip *);
1278			ip->ip_len = ntohs(ip->ip_len);
1279			ip->ip_off = ntohs(ip->ip_off);
1280		}
1281		icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1282	} else if (offset == 0 && args->f_id.proto == IPPROTO_TCP) {
1283		struct tcphdr *const tcp =
1284		    L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1285		if ( (tcp->th_flags & TH_RST) == 0)
1286			send_pkt(&(args->f_id), ntohl(tcp->th_seq),
1287				ntohl(tcp->th_ack),
1288				tcp->th_flags | TH_RST);
1289		m_freem(args->m);
1290	} else
1291		m_freem(args->m);
1292	args->m = NULL;
1293}
1294
1295/**
1296 *
1297 * Given an ip_fw *, lookup_next_rule will return a pointer
1298 * to the next rule, which can be either the jump
1299 * target (for skipto instructions) or the next one in the list (in
1300 * all other cases including a missing jump target).
1301 * The result is also written in the "next_rule" field of the rule.
1302 * Backward jumps are not allowed, so start looking from the next
1303 * rule...
1304 *
1305 * This never returns NULL -- in case we do not have an exact match,
1306 * the next rule is returned. When the ruleset is changed,
1307 * pointers are flushed so we are always correct.
1308 */
1309
1310static struct ip_fw *
1311lookup_next_rule(struct ip_fw *me)
1312{
1313	struct ip_fw *rule = NULL;
1314	ipfw_insn *cmd;
1315
1316	/* look for action, in case it is a skipto */
1317	cmd = ACTION_PTR(me);
1318	if (cmd->opcode == O_LOG)
1319		cmd += F_LEN(cmd);
1320	if ( cmd->opcode == O_SKIPTO )
1321		for (rule = me->next; rule ; rule = rule->next)
1322			if (rule->rulenum >= cmd->arg1)
1323				break;
1324	if (rule == NULL)			/* failure or not a skipto */
1325		rule = me->next;
1326	me->next_rule = rule;
1327	return rule;
1328}
1329
1330static void
1331init_tables(void)
1332{
1333	int i;
1334
1335	for (i = 0; i < IPFW_TABLES_MAX; i++) {
1336		rn_inithead((void **)&ipfw_tables[i].rnh, 32);
1337		ipfw_tables[i].modified = 1;
1338	}
1339}
1340
1341static int
1342add_table_entry(u_int16_t tbl, in_addr_t addr, u_int8_t mlen, u_int32_t value)
1343{
1344	struct radix_node_head *rnh;
1345	struct table_entry *ent;
1346
1347	if (tbl >= IPFW_TABLES_MAX)
1348		return (EINVAL);
1349	rnh = ipfw_tables[tbl].rnh;
1350	ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO);
1351	if (ent == NULL)
1352		return (ENOMEM);
1353	ent->value = value;
1354	ent->addr.sin_len = ent->mask.sin_len = 8;
1355	ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1356	ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr;
1357	RADIX_NODE_HEAD_LOCK(rnh);
1358	if (rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent) ==
1359	    NULL) {
1360		RADIX_NODE_HEAD_UNLOCK(rnh);
1361		free(ent, M_IPFW_TBL);
1362		return (EEXIST);
1363	}
1364	ipfw_tables[tbl].modified = 1;
1365	RADIX_NODE_HEAD_UNLOCK(rnh);
1366	return (0);
1367}
1368
1369static int
1370del_table_entry(u_int16_t tbl, in_addr_t addr, u_int8_t mlen)
1371{
1372	struct radix_node_head *rnh;
1373	struct table_entry *ent;
1374	struct sockaddr_in sa, mask;
1375
1376	if (tbl >= IPFW_TABLES_MAX)
1377		return (EINVAL);
1378	rnh = ipfw_tables[tbl].rnh;
1379	sa.sin_len = mask.sin_len = 8;
1380	mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
1381	sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr;
1382	RADIX_NODE_HEAD_LOCK(rnh);
1383	ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh);
1384	if (ent == NULL) {
1385		RADIX_NODE_HEAD_UNLOCK(rnh);
1386		return (ESRCH);
1387	}
1388	ipfw_tables[tbl].modified = 1;
1389	RADIX_NODE_HEAD_UNLOCK(rnh);
1390	free(ent, M_IPFW_TBL);
1391	return (0);
1392}
1393
1394static int
1395flush_table_entry(struct radix_node *rn, void *arg)
1396{
1397	struct radix_node_head * const rnh = arg;
1398	struct table_entry *ent;
1399
1400	ent = (struct table_entry *)
1401	    rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh);
1402	if (ent != NULL)
1403		free(ent, M_IPFW_TBL);
1404	return (0);
1405}
1406
1407static int
1408flush_table(u_int16_t tbl)
1409{
1410	struct radix_node_head *rnh;
1411
1412	if (tbl >= IPFW_TABLES_MAX)
1413		return (EINVAL);
1414	rnh = ipfw_tables[tbl].rnh;
1415	RADIX_NODE_HEAD_LOCK(rnh);
1416	rnh->rnh_walktree(rnh, flush_table_entry, rnh);
1417	ipfw_tables[tbl].modified = 1;
1418	RADIX_NODE_HEAD_UNLOCK(rnh);
1419	return (0);
1420}
1421
1422static void
1423flush_tables(void)
1424{
1425	u_int16_t tbl;
1426
1427	for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++)
1428		flush_table(tbl);
1429}
1430
1431static int
1432lookup_table(u_int16_t tbl, in_addr_t addr, u_int32_t *val)
1433{
1434	struct radix_node_head *rnh;
1435	struct table_entry *ent;
1436	struct sockaddr_in sa;
1437	static in_addr_t last_addr;
1438	static int last_tbl;
1439	static int last_match;
1440	static u_int32_t last_value;
1441
1442	if (tbl >= IPFW_TABLES_MAX)
1443		return (0);
1444	if (tbl == last_tbl && addr == last_addr &&
1445	    !ipfw_tables[tbl].modified) {
1446		if (last_match)
1447			*val = last_value;
1448		return (last_match);
1449	}
1450	rnh = ipfw_tables[tbl].rnh;
1451	sa.sin_len = 8;
1452	sa.sin_addr.s_addr = addr;
1453	RADIX_NODE_HEAD_LOCK(rnh);
1454	ipfw_tables[tbl].modified = 0;
1455	ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh));
1456	RADIX_NODE_HEAD_UNLOCK(rnh);
1457	last_addr = addr;
1458	last_tbl = tbl;
1459	if (ent != NULL) {
1460		last_value = *val = ent->value;
1461		last_match = 1;
1462		return (1);
1463	}
1464	last_match = 0;
1465	return (0);
1466}
1467
1468static int
1469count_table_entry(struct radix_node *rn, void *arg)
1470{
1471	u_int32_t * const cnt = arg;
1472
1473	(*cnt)++;
1474	return (0);
1475}
1476
1477static int
1478count_table(u_int32_t tbl, u_int32_t *cnt)
1479{
1480	struct radix_node_head *rnh;
1481
1482	if (tbl >= IPFW_TABLES_MAX)
1483		return (EINVAL);
1484	rnh = ipfw_tables[tbl].rnh;
1485	*cnt = 0;
1486	RADIX_NODE_HEAD_LOCK(rnh);
1487	rnh->rnh_walktree(rnh, count_table_entry, cnt);
1488	RADIX_NODE_HEAD_UNLOCK(rnh);
1489	return (0);
1490}
1491
1492static int
1493dump_table_entry(struct radix_node *rn, void *arg)
1494{
1495	struct table_entry * const n = (struct table_entry *)rn;
1496	ipfw_table * const tbl = arg;
1497	ipfw_table_entry *ent;
1498
1499	if (tbl->cnt == tbl->size)
1500		return (1);
1501	ent = &tbl->ent[tbl->cnt];
1502	ent->tbl = tbl->tbl;
1503	if (in_nullhost(n->mask.sin_addr))
1504		ent->masklen = 0;
1505	else
1506		ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr));
1507	ent->addr = n->addr.sin_addr.s_addr;
1508	ent->value = n->value;
1509	tbl->cnt++;
1510	return (0);
1511}
1512
1513static int
1514dump_table(ipfw_table *tbl)
1515{
1516	struct radix_node_head *rnh;
1517
1518	if (tbl->tbl >= IPFW_TABLES_MAX)
1519		return (EINVAL);
1520	rnh = ipfw_tables[tbl->tbl].rnh;
1521	tbl->cnt = 0;
1522	RADIX_NODE_HEAD_LOCK(rnh);
1523	rnh->rnh_walktree(rnh, dump_table_entry, tbl);
1524	RADIX_NODE_HEAD_UNLOCK(rnh);
1525	return (0);
1526}
1527
1528static int
1529check_uidgid(ipfw_insn_u32 *insn,
1530	int proto, struct ifnet *oif,
1531	struct in_addr dst_ip, u_int16_t dst_port,
1532	struct in_addr src_ip, u_int16_t src_port)
1533{
1534	struct inpcbinfo *pi;
1535	int wildcard;
1536	struct inpcb *pcb;
1537	int match;
1538
1539	if (proto == IPPROTO_TCP) {
1540		wildcard = 0;
1541		pi = &tcbinfo;
1542	} else if (proto == IPPROTO_UDP) {
1543		wildcard = 1;
1544		pi = &udbinfo;
1545	} else
1546		return 0;
1547
1548	match = 0;
1549
1550	INP_INFO_RLOCK(pi);	/* XXX LOR with IPFW */
1551	pcb =  (oif) ?
1552		in_pcblookup_hash(pi,
1553		    dst_ip, htons(dst_port),
1554		    src_ip, htons(src_port),
1555		    wildcard, oif) :
1556		in_pcblookup_hash(pi,
1557		    src_ip, htons(src_port),
1558		    dst_ip, htons(dst_port),
1559		    wildcard, NULL);
1560	if (pcb != NULL) {
1561		INP_LOCK(pcb);
1562		if (pcb->inp_socket != NULL) {
1563#if __FreeBSD_version < 500034
1564#define socheckuid(a,b)	((a)->so_cred->cr_uid != (b))
1565#endif
1566			if (insn->o.opcode == O_UID) {
1567				match = !socheckuid(pcb->inp_socket,
1568				   (uid_t)insn->d[0]);
1569			} else  {
1570				match = groupmember((uid_t)insn->d[0],
1571				    pcb->inp_socket->so_cred);
1572			}
1573		}
1574		INP_UNLOCK(pcb);
1575	}
1576	INP_INFO_RUNLOCK(pi);
1577
1578	return match;
1579}
1580
1581/*
1582 * The main check routine for the firewall.
1583 *
1584 * All arguments are in args so we can modify them and return them
1585 * back to the caller.
1586 *
1587 * Parameters:
1588 *
1589 *	args->m	(in/out) The packet; we set to NULL when/if we nuke it.
1590 *		Starts with the IP header.
1591 *	args->eh (in)	Mac header if present, or NULL for layer3 packet.
1592 *	args->oif	Outgoing interface, or NULL if packet is incoming.
1593 *		The incoming interface is in the mbuf. (in)
1594 *	args->divert_rule (in/out)
1595 *		Skip up to the first rule past this rule number;
1596 *		upon return, non-zero port number for divert or tee.
1597 *
1598 *	args->rule	Pointer to the last matching rule (in/out)
1599 *	args->next_hop	Socket we are forwarding to (out).
1600 *	args->f_id	Addresses grabbed from the packet (out)
1601 *
1602 * Return value:
1603 *
1604 *	IP_FW_PORT_DENY_FLAG	the packet must be dropped.
1605 *	0	The packet is to be accepted and routed normally OR
1606 *      	the packet was denied/rejected and has been dropped;
1607 *		in the latter case, *m is equal to NULL upon return.
1608 *	port	Divert the packet to port, with these caveats:
1609 *
1610 *		- If IP_FW_PORT_TEE_FLAG is set, tee the packet instead
1611 *		  of diverting it (ie, 'ipfw tee').
1612 *
1613 *		- If IP_FW_PORT_DYNT_FLAG is set, interpret the lower
1614 *		  16 bits as a dummynet pipe number instead of diverting
1615 */
1616
1617static int
1618ipfw_chk(struct ip_fw_args *args)
1619{
1620	/*
1621	 * Local variables hold state during the processing of a packet.
1622	 *
1623	 * IMPORTANT NOTE: to speed up the processing of rules, there
1624	 * are some assumption on the values of the variables, which
1625	 * are documented here. Should you change them, please check
1626	 * the implementation of the various instructions to make sure
1627	 * that they still work.
1628	 *
1629	 * args->eh	The MAC header. It is non-null for a layer2
1630	 *	packet, it is NULL for a layer-3 packet.
1631	 *
1632	 * m | args->m	Pointer to the mbuf, as received from the caller.
1633	 *	It may change if ipfw_chk() does an m_pullup, or if it
1634	 *	consumes the packet because it calls send_reject().
1635	 *	XXX This has to change, so that ipfw_chk() never modifies
1636	 *	or consumes the buffer.
1637	 * ip	is simply an alias of the value of m, and it is kept
1638	 *	in sync with it (the packet is	supposed to start with
1639	 *	the ip header).
1640	 */
1641	struct mbuf *m = args->m;
1642	struct ip *ip = mtod(m, struct ip *);
1643
1644	/*
1645	 * oif | args->oif	If NULL, ipfw_chk has been called on the
1646	 *	inbound path (ether_input, bdg_forward, ip_input).
1647	 *	If non-NULL, ipfw_chk has been called on the outbound path
1648	 *	(ether_output, ip_output).
1649	 */
1650	struct ifnet *oif = args->oif;
1651
1652	struct ip_fw *f = NULL;		/* matching rule */
1653	int retval = 0;
1654
1655	/*
1656	 * hlen	The length of the IPv4 header.
1657	 *	hlen >0 means we have an IPv4 packet.
1658	 */
1659	u_int hlen = 0;		/* hlen >0 means we have an IP pkt */
1660
1661	/*
1662	 * offset	The offset of a fragment. offset != 0 means that
1663	 *	we have a fragment at this offset of an IPv4 packet.
1664	 *	offset == 0 means that (if this is an IPv4 packet)
1665	 *	this is the first or only fragment.
1666	 */
1667	u_short offset = 0;
1668
1669	/*
1670	 * Local copies of addresses. They are only valid if we have
1671	 * an IP packet.
1672	 *
1673	 * proto	The protocol. Set to 0 for non-ip packets,
1674	 *	or to the protocol read from the packet otherwise.
1675	 *	proto != 0 means that we have an IPv4 packet.
1676	 *
1677	 * src_port, dst_port	port numbers, in HOST format. Only
1678	 *	valid for TCP and UDP packets.
1679	 *
1680	 * src_ip, dst_ip	ip addresses, in NETWORK format.
1681	 *	Only valid for IPv4 packets.
1682	 */
1683	u_int8_t proto;
1684	u_int16_t src_port = 0, dst_port = 0;	/* NOTE: host format	*/
1685	struct in_addr src_ip, dst_ip;		/* NOTE: network format	*/
1686	u_int16_t ip_len=0;
1687	int pktlen;
1688	int dyn_dir = MATCH_UNKNOWN;
1689	ipfw_dyn_rule *q = NULL;
1690	struct ip_fw_chain *chain = &layer3_chain;
1691	struct m_tag *mtag;
1692
1693	if (m->m_flags & M_SKIP_FIREWALL)
1694		return 0;	/* accept */
1695	/*
1696	 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
1697	 * 	MATCH_NONE when checked and not matched (q = NULL),
1698	 *	MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
1699	 */
1700
1701	pktlen = m->m_pkthdr.len;
1702	if (args->eh == NULL ||		/* layer 3 packet */
1703		( m->m_pkthdr.len >= sizeof(struct ip) &&
1704		    ntohs(args->eh->ether_type) == ETHERTYPE_IP))
1705			hlen = ip->ip_hl << 2;
1706
1707	/*
1708	 * Collect parameters into local variables for faster matching.
1709	 */
1710	if (hlen == 0) {	/* do not grab addresses for non-ip pkts */
1711		proto = args->f_id.proto = 0;	/* mark f_id invalid */
1712		goto after_ip_checks;
1713	}
1714
1715	proto = args->f_id.proto = ip->ip_p;
1716	src_ip = ip->ip_src;
1717	dst_ip = ip->ip_dst;
1718	if (args->eh != NULL) { /* layer 2 packets are as on the wire */
1719		offset = ntohs(ip->ip_off) & IP_OFFMASK;
1720		ip_len = ntohs(ip->ip_len);
1721	} else {
1722		offset = ip->ip_off & IP_OFFMASK;
1723		ip_len = ip->ip_len;
1724	}
1725	pktlen = ip_len < pktlen ? ip_len : pktlen;
1726
1727#define PULLUP_TO(len)						\
1728		do {						\
1729			if ((m)->m_len < (len)) {		\
1730			    args->m = m = m_pullup(m, (len));	\
1731			    if (m == 0)				\
1732				goto pullup_failed;		\
1733			    ip = mtod(m, struct ip *);		\
1734			}					\
1735		} while (0)
1736
1737	if (offset == 0) {
1738		switch (proto) {
1739		case IPPROTO_TCP:
1740		    {
1741			struct tcphdr *tcp;
1742
1743			PULLUP_TO(hlen + sizeof(struct tcphdr));
1744			tcp = L3HDR(struct tcphdr, ip);
1745			dst_port = tcp->th_dport;
1746			src_port = tcp->th_sport;
1747			args->f_id.flags = tcp->th_flags;
1748			}
1749			break;
1750
1751		case IPPROTO_UDP:
1752		    {
1753			struct udphdr *udp;
1754
1755			PULLUP_TO(hlen + sizeof(struct udphdr));
1756			udp = L3HDR(struct udphdr, ip);
1757			dst_port = udp->uh_dport;
1758			src_port = udp->uh_sport;
1759			}
1760			break;
1761
1762		case IPPROTO_ICMP:
1763			PULLUP_TO(hlen + 4);	/* type, code and checksum. */
1764			args->f_id.flags = L3HDR(struct icmp, ip)->icmp_type;
1765			break;
1766
1767		default:
1768			break;
1769		}
1770#undef PULLUP_TO
1771	}
1772
1773	args->f_id.src_ip = ntohl(src_ip.s_addr);
1774	args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1775	args->f_id.src_port = src_port = ntohs(src_port);
1776	args->f_id.dst_port = dst_port = ntohs(dst_port);
1777
1778after_ip_checks:
1779	IPFW_LOCK(chain);		/* XXX expensive? can we run lock free? */
1780	mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
1781	if (args->rule) {
1782		/*
1783		 * Packet has already been tagged. Look for the next rule
1784		 * to restart processing.
1785		 *
1786		 * If fw_one_pass != 0 then just accept it.
1787		 * XXX should not happen here, but optimized out in
1788		 * the caller.
1789		 */
1790		if (fw_one_pass) {
1791			IPFW_UNLOCK(chain);	/* XXX optimize */
1792			return 0;
1793		}
1794
1795		f = args->rule->next_rule;
1796		if (f == NULL)
1797			f = lookup_next_rule(args->rule);
1798	} else {
1799		/*
1800		 * Find the starting rule. It can be either the first
1801		 * one, or the one after divert_rule if asked so.
1802		 */
1803		int skipto = mtag ? divert_cookie(mtag) : 0;
1804
1805		f = chain->rules;
1806		if (args->eh == NULL && skipto != 0) {
1807			if (skipto >= IPFW_DEFAULT_RULE) {
1808				IPFW_UNLOCK(chain);
1809				return(IP_FW_PORT_DENY_FLAG); /* invalid */
1810			}
1811			while (f && f->rulenum <= skipto)
1812				f = f->next;
1813			if (f == NULL) {	/* drop packet */
1814				IPFW_UNLOCK(chain);
1815				return(IP_FW_PORT_DENY_FLAG);
1816			}
1817		}
1818	}
1819	/* reset divert rule to avoid confusion later */
1820	if (mtag)
1821		m_tag_delete(m, mtag);
1822
1823	/*
1824	 * Now scan the rules, and parse microinstructions for each rule.
1825	 */
1826	for (; f; f = f->next) {
1827		int l, cmdlen;
1828		ipfw_insn *cmd;
1829		int skip_or; /* skip rest of OR block */
1830
1831again:
1832		if (set_disable & (1 << f->set) )
1833			continue;
1834
1835		skip_or = 0;
1836		for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
1837		    l -= cmdlen, cmd += cmdlen) {
1838			int match;
1839
1840			/*
1841			 * check_body is a jump target used when we find a
1842			 * CHECK_STATE, and need to jump to the body of
1843			 * the target rule.
1844			 */
1845
1846check_body:
1847			cmdlen = F_LEN(cmd);
1848			/*
1849			 * An OR block (insn_1 || .. || insn_n) has the
1850			 * F_OR bit set in all but the last instruction.
1851			 * The first match will set "skip_or", and cause
1852			 * the following instructions to be skipped until
1853			 * past the one with the F_OR bit clear.
1854			 */
1855			if (skip_or) {		/* skip this instruction */
1856				if ((cmd->len & F_OR) == 0)
1857					skip_or = 0;	/* next one is good */
1858				continue;
1859			}
1860			match = 0; /* set to 1 if we succeed */
1861
1862			switch (cmd->opcode) {
1863			/*
1864			 * The first set of opcodes compares the packet's
1865			 * fields with some pattern, setting 'match' if a
1866			 * match is found. At the end of the loop there is
1867			 * logic to deal with F_NOT and F_OR flags associated
1868			 * with the opcode.
1869			 */
1870			case O_NOP:
1871				match = 1;
1872				break;
1873
1874			case O_FORWARD_MAC:
1875				printf("ipfw: opcode %d unimplemented\n",
1876				    cmd->opcode);
1877				break;
1878
1879			case O_GID:
1880			case O_UID:
1881				/*
1882				 * We only check offset == 0 && proto != 0,
1883				 * as this ensures that we have an IPv4
1884				 * packet with the ports info.
1885				 */
1886				if (offset!=0)
1887					break;
1888				if (proto == IPPROTO_TCP ||
1889				    proto == IPPROTO_UDP)
1890					match = check_uidgid(
1891						    (ipfw_insn_u32 *)cmd,
1892						    proto, oif,
1893						    dst_ip, dst_port,
1894						    src_ip, src_port);
1895				break;
1896
1897			case O_RECV:
1898				match = iface_match(m->m_pkthdr.rcvif,
1899				    (ipfw_insn_if *)cmd);
1900				break;
1901
1902			case O_XMIT:
1903				match = iface_match(oif, (ipfw_insn_if *)cmd);
1904				break;
1905
1906			case O_VIA:
1907				match = iface_match(oif ? oif :
1908				    m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
1909				break;
1910
1911			case O_MACADDR2:
1912				if (args->eh != NULL) {	/* have MAC header */
1913					u_int32_t *want = (u_int32_t *)
1914						((ipfw_insn_mac *)cmd)->addr;
1915					u_int32_t *mask = (u_int32_t *)
1916						((ipfw_insn_mac *)cmd)->mask;
1917					u_int32_t *hdr = (u_int32_t *)args->eh;
1918
1919					match =
1920					    ( want[0] == (hdr[0] & mask[0]) &&
1921					      want[1] == (hdr[1] & mask[1]) &&
1922					      want[2] == (hdr[2] & mask[2]) );
1923				}
1924				break;
1925
1926			case O_MAC_TYPE:
1927				if (args->eh != NULL) {
1928					u_int16_t t =
1929					    ntohs(args->eh->ether_type);
1930					u_int16_t *p =
1931					    ((ipfw_insn_u16 *)cmd)->ports;
1932					int i;
1933
1934					for (i = cmdlen - 1; !match && i>0;
1935					    i--, p += 2)
1936						match = (t>=p[0] && t<=p[1]);
1937				}
1938				break;
1939
1940			case O_FRAG:
1941				match = (hlen > 0 && offset != 0);
1942				break;
1943
1944			case O_IN:	/* "out" is "not in" */
1945				match = (oif == NULL);
1946				break;
1947
1948			case O_LAYER2:
1949				match = (args->eh != NULL);
1950				break;
1951
1952			case O_PROTO:
1953				/*
1954				 * We do not allow an arg of 0 so the
1955				 * check of "proto" only suffices.
1956				 */
1957				match = (proto == cmd->arg1);
1958				break;
1959
1960			case O_IP_SRC:
1961				match = (hlen > 0 &&
1962				    ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1963				    src_ip.s_addr);
1964				break;
1965
1966			case O_IP_SRC_LOOKUP:
1967			case O_IP_DST_LOOKUP:
1968				if (hlen > 0) {
1969				    uint32_t a =
1970					(cmd->opcode == O_IP_DST_LOOKUP) ?
1971					    dst_ip.s_addr : src_ip.s_addr;
1972				    uint32_t v;
1973
1974				    match = lookup_table(cmd->arg1, a, &v);
1975				    if (!match)
1976					break;
1977				    if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
1978					match =
1979					    ((ipfw_insn_u32 *)cmd)->d[0] == v;
1980				}
1981				break;
1982
1983			case O_IP_SRC_MASK:
1984			case O_IP_DST_MASK:
1985				if (hlen > 0) {
1986				    uint32_t a =
1987					(cmd->opcode == O_IP_DST_MASK) ?
1988					    dst_ip.s_addr : src_ip.s_addr;
1989				    uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
1990				    int i = cmdlen-1;
1991
1992				    for (; !match && i>0; i-= 2, p+= 2)
1993					match = (p[0] == (a & p[1]));
1994				}
1995				break;
1996
1997			case O_IP_SRC_ME:
1998				if (hlen > 0) {
1999					struct ifnet *tif;
2000
2001					INADDR_TO_IFP(src_ip, tif);
2002					match = (tif != NULL);
2003				}
2004				break;
2005
2006			case O_IP_DST_SET:
2007			case O_IP_SRC_SET:
2008				if (hlen > 0) {
2009					u_int32_t *d = (u_int32_t *)(cmd+1);
2010					u_int32_t addr =
2011					    cmd->opcode == O_IP_DST_SET ?
2012						args->f_id.dst_ip :
2013						args->f_id.src_ip;
2014
2015					    if (addr < d[0])
2016						    break;
2017					    addr -= d[0]; /* subtract base */
2018					    match = (addr < cmd->arg1) &&
2019						( d[ 1 + (addr>>5)] &
2020						  (1<<(addr & 0x1f)) );
2021				}
2022				break;
2023
2024			case O_IP_DST:
2025				match = (hlen > 0 &&
2026				    ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2027				    dst_ip.s_addr);
2028				break;
2029
2030			case O_IP_DST_ME:
2031				if (hlen > 0) {
2032					struct ifnet *tif;
2033
2034					INADDR_TO_IFP(dst_ip, tif);
2035					match = (tif != NULL);
2036				}
2037				break;
2038
2039			case O_IP_SRCPORT:
2040			case O_IP_DSTPORT:
2041				/*
2042				 * offset == 0 && proto != 0 is enough
2043				 * to guarantee that we have an IPv4
2044				 * packet with port info.
2045				 */
2046				if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2047				    && offset == 0) {
2048					u_int16_t x =
2049					    (cmd->opcode == O_IP_SRCPORT) ?
2050						src_port : dst_port ;
2051					u_int16_t *p =
2052					    ((ipfw_insn_u16 *)cmd)->ports;
2053					int i;
2054
2055					for (i = cmdlen - 1; !match && i>0;
2056					    i--, p += 2)
2057						match = (x>=p[0] && x<=p[1]);
2058				}
2059				break;
2060
2061			case O_ICMPTYPE:
2062				match = (offset == 0 && proto==IPPROTO_ICMP &&
2063				    icmptype_match(ip, (ipfw_insn_u32 *)cmd) );
2064				break;
2065
2066			case O_IPOPT:
2067				match = (hlen > 0 && ipopts_match(ip, cmd) );
2068				break;
2069
2070			case O_IPVER:
2071				match = (hlen > 0 && cmd->arg1 == ip->ip_v);
2072				break;
2073
2074			case O_IPID:
2075			case O_IPLEN:
2076			case O_IPTTL:
2077				if (hlen > 0) {	/* only for IP packets */
2078				    uint16_t x;
2079				    uint16_t *p;
2080				    int i;
2081
2082				    if (cmd->opcode == O_IPLEN)
2083					x = ip_len;
2084				    else if (cmd->opcode == O_IPTTL)
2085					x = ip->ip_ttl;
2086				    else /* must be IPID */
2087					x = ntohs(ip->ip_id);
2088				    if (cmdlen == 1) {
2089					match = (cmd->arg1 == x);
2090					break;
2091				    }
2092				    /* otherwise we have ranges */
2093				    p = ((ipfw_insn_u16 *)cmd)->ports;
2094				    i = cmdlen - 1;
2095				    for (; !match && i>0; i--, p += 2)
2096					match = (x >= p[0] && x <= p[1]);
2097				}
2098				break;
2099
2100			case O_IPPRECEDENCE:
2101				match = (hlen > 0 &&
2102				    (cmd->arg1 == (ip->ip_tos & 0xe0)) );
2103				break;
2104
2105			case O_IPTOS:
2106				match = (hlen > 0 &&
2107				    flags_match(cmd, ip->ip_tos));
2108				break;
2109
2110			case O_TCPFLAGS:
2111				match = (proto == IPPROTO_TCP && offset == 0 &&
2112				    flags_match(cmd,
2113					L3HDR(struct tcphdr,ip)->th_flags));
2114				break;
2115
2116			case O_TCPOPTS:
2117				match = (proto == IPPROTO_TCP && offset == 0 &&
2118				    tcpopts_match(ip, cmd));
2119				break;
2120
2121			case O_TCPSEQ:
2122				match = (proto == IPPROTO_TCP && offset == 0 &&
2123				    ((ipfw_insn_u32 *)cmd)->d[0] ==
2124					L3HDR(struct tcphdr,ip)->th_seq);
2125				break;
2126
2127			case O_TCPACK:
2128				match = (proto == IPPROTO_TCP && offset == 0 &&
2129				    ((ipfw_insn_u32 *)cmd)->d[0] ==
2130					L3HDR(struct tcphdr,ip)->th_ack);
2131				break;
2132
2133			case O_TCPWIN:
2134				match = (proto == IPPROTO_TCP && offset == 0 &&
2135				    cmd->arg1 ==
2136					L3HDR(struct tcphdr,ip)->th_win);
2137				break;
2138
2139			case O_ESTAB:
2140				/* reject packets which have SYN only */
2141				/* XXX should i also check for TH_ACK ? */
2142				match = (proto == IPPROTO_TCP && offset == 0 &&
2143				    (L3HDR(struct tcphdr,ip)->th_flags &
2144				     (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2145				break;
2146
2147			case O_LOG:
2148				if (fw_verbose)
2149					ipfw_log(f, hlen, args->eh, m, oif);
2150				match = 1;
2151				break;
2152
2153			case O_PROB:
2154				match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
2155				break;
2156
2157			case O_VERREVPATH:
2158				/* Outgoing packets automatically pass/match */
2159				match = ((oif != NULL) ||
2160				    (m->m_pkthdr.rcvif == NULL) ||
2161				    verify_path(src_ip, m->m_pkthdr.rcvif));
2162				break;
2163
2164			case O_VERSRCREACH:
2165				/* Outgoing packets automatically pass/match */
2166				match = ((oif != NULL) ||
2167				     verify_path(src_ip, NULL));
2168				break;
2169
2170			case O_IPSEC:
2171#ifdef FAST_IPSEC
2172				match = (m_tag_find(m,
2173				    PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
2174#endif
2175#ifdef IPSEC
2176				match = (ipsec_getnhist(m) != 0);
2177#endif
2178				/* otherwise no match */
2179				break;
2180
2181			/*
2182			 * The second set of opcodes represents 'actions',
2183			 * i.e. the terminal part of a rule once the packet
2184			 * matches all previous patterns.
2185			 * Typically there is only one action for each rule,
2186			 * and the opcode is stored at the end of the rule
2187			 * (but there are exceptions -- see below).
2188			 *
2189			 * In general, here we set retval and terminate the
2190			 * outer loop (would be a 'break 3' in some language,
2191			 * but we need to do a 'goto done').
2192			 *
2193			 * Exceptions:
2194			 * O_COUNT and O_SKIPTO actions:
2195			 *   instead of terminating, we jump to the next rule
2196			 *   ('goto next_rule', equivalent to a 'break 2'),
2197			 *   or to the SKIPTO target ('goto again' after
2198			 *   having set f, cmd and l), respectively.
2199			 *
2200			 * O_LIMIT and O_KEEP_STATE: these opcodes are
2201			 *   not real 'actions', and are stored right
2202			 *   before the 'action' part of the rule.
2203			 *   These opcodes try to install an entry in the
2204			 *   state tables; if successful, we continue with
2205			 *   the next opcode (match=1; break;), otherwise
2206			 *   the packet *   must be dropped
2207			 *   ('goto done' after setting retval);
2208			 *
2209			 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2210			 *   cause a lookup of the state table, and a jump
2211			 *   to the 'action' part of the parent rule
2212			 *   ('goto check_body') if an entry is found, or
2213			 *   (CHECK_STATE only) a jump to the next rule if
2214			 *   the entry is not found ('goto next_rule').
2215			 *   The result of the lookup is cached to make
2216			 *   further instances of these opcodes are
2217			 *   effectively NOPs.
2218			 */
2219			case O_LIMIT:
2220			case O_KEEP_STATE:
2221				if (install_state(f,
2222				    (ipfw_insn_limit *)cmd, args)) {
2223					retval = IP_FW_PORT_DENY_FLAG;
2224					goto done; /* error/limit violation */
2225				}
2226				match = 1;
2227				break;
2228
2229			case O_PROBE_STATE:
2230			case O_CHECK_STATE:
2231				/*
2232				 * dynamic rules are checked at the first
2233				 * keep-state or check-state occurrence,
2234				 * with the result being stored in dyn_dir.
2235				 * The compiler introduces a PROBE_STATE
2236				 * instruction for us when we have a
2237				 * KEEP_STATE (because PROBE_STATE needs
2238				 * to be run first).
2239				 */
2240				if (dyn_dir == MATCH_UNKNOWN &&
2241				    (q = lookup_dyn_rule(&args->f_id,
2242				     &dyn_dir, proto == IPPROTO_TCP ?
2243					L3HDR(struct tcphdr, ip) : NULL))
2244					!= NULL) {
2245					/*
2246					 * Found dynamic entry, update stats
2247					 * and jump to the 'action' part of
2248					 * the parent rule.
2249					 */
2250					q->pcnt++;
2251					q->bcnt += pktlen;
2252					f = q->rule;
2253					cmd = ACTION_PTR(f);
2254					l = f->cmd_len - f->act_ofs;
2255					IPFW_DYN_UNLOCK();
2256					goto check_body;
2257				}
2258				/*
2259				 * Dynamic entry not found. If CHECK_STATE,
2260				 * skip to next rule, if PROBE_STATE just
2261				 * ignore and continue with next opcode.
2262				 */
2263				if (cmd->opcode == O_CHECK_STATE)
2264					goto next_rule;
2265				match = 1;
2266				break;
2267
2268			case O_ACCEPT:
2269				retval = 0;	/* accept */
2270				goto done;
2271
2272			case O_PIPE:
2273			case O_QUEUE:
2274				args->rule = f; /* report matching rule */
2275				retval = cmd->arg1 | IP_FW_PORT_DYNT_FLAG;
2276				goto done;
2277
2278			case O_DIVERT:
2279			case O_TEE: {
2280				struct divert_tag *dt;
2281
2282				if (args->eh) /* not on layer 2 */
2283					break;
2284				mtag = m_tag_get(PACKET_TAG_DIVERT,
2285						sizeof(struct divert_tag),
2286						M_NOWAIT);
2287				if (mtag == NULL) {
2288					/* XXX statistic */
2289					/* drop packet */
2290					IPFW_UNLOCK(chain);
2291					return IP_FW_PORT_DENY_FLAG;
2292				}
2293				dt = (struct divert_tag *)(mtag+1);
2294				dt->cookie = f->rulenum;
2295				dt->info = (cmd->opcode == O_DIVERT) ?
2296				    cmd->arg1 :
2297				    cmd->arg1 | IP_FW_PORT_TEE_FLAG;
2298				m_tag_prepend(m, mtag);
2299				retval = dt->info;
2300				goto done;
2301			}
2302
2303			case O_COUNT:
2304			case O_SKIPTO:
2305				f->pcnt++;	/* update stats */
2306				f->bcnt += pktlen;
2307				f->timestamp = time_second;
2308				if (cmd->opcode == O_COUNT)
2309					goto next_rule;
2310				/* handle skipto */
2311				if (f->next_rule == NULL)
2312					lookup_next_rule(f);
2313				f = f->next_rule;
2314				goto again;
2315
2316			case O_REJECT:
2317				/*
2318				 * Drop the packet and send a reject notice
2319				 * if the packet is not ICMP (or is an ICMP
2320				 * query), and it is not multicast/broadcast.
2321				 */
2322				if (hlen > 0 &&
2323				    (proto != IPPROTO_ICMP ||
2324				     is_icmp_query(ip)) &&
2325				    !(m->m_flags & (M_BCAST|M_MCAST)) &&
2326				    !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2327					send_reject(args, cmd->arg1,
2328					    offset,ip_len);
2329					m = args->m;
2330				}
2331				/* FALLTHROUGH */
2332			case O_DENY:
2333				retval = IP_FW_PORT_DENY_FLAG;
2334				goto done;
2335
2336			case O_FORWARD_IP:
2337				if (args->eh)	/* not valid on layer2 pkts */
2338					break;
2339				if (!q || dyn_dir == MATCH_FORWARD)
2340					args->next_hop =
2341					    &((ipfw_insn_sa *)cmd)->sa;
2342				retval = 0;
2343				goto done;
2344
2345			default:
2346				panic("-- unknown opcode %d\n", cmd->opcode);
2347			} /* end of switch() on opcodes */
2348
2349			if (cmd->len & F_NOT)
2350				match = !match;
2351
2352			if (match) {
2353				if (cmd->len & F_OR)
2354					skip_or = 1;
2355			} else {
2356				if (!(cmd->len & F_OR)) /* not an OR block, */
2357					break;		/* try next rule    */
2358			}
2359
2360		}	/* end of inner for, scan opcodes */
2361
2362next_rule:;		/* try next rule		*/
2363
2364	}		/* end of outer for, scan rules */
2365	printf("ipfw: ouch!, skip past end of rules, denying packet\n");
2366	IPFW_UNLOCK(chain);
2367	return(IP_FW_PORT_DENY_FLAG);
2368
2369done:
2370	/* Update statistics */
2371	f->pcnt++;
2372	f->bcnt += pktlen;
2373	f->timestamp = time_second;
2374	IPFW_UNLOCK(chain);
2375	return retval;
2376
2377pullup_failed:
2378	if (fw_verbose)
2379		printf("ipfw: pullup failed\n");
2380	return(IP_FW_PORT_DENY_FLAG);
2381}
2382
2383/*
2384 * When a rule is added/deleted, clear the next_rule pointers in all rules.
2385 * These will be reconstructed on the fly as packets are matched.
2386 */
2387static void
2388flush_rule_ptrs(struct ip_fw_chain *chain)
2389{
2390	struct ip_fw *rule;
2391
2392	IPFW_LOCK_ASSERT(chain);
2393
2394	for (rule = chain->rules; rule; rule = rule->next)
2395		rule->next_rule = NULL;
2396}
2397
2398/*
2399 * When pipes/queues are deleted, clear the "pipe_ptr" pointer to a given
2400 * pipe/queue, or to all of them (match == NULL).
2401 */
2402void
2403flush_pipe_ptrs(struct dn_flow_set *match)
2404{
2405	struct ip_fw *rule;
2406
2407	IPFW_LOCK(&layer3_chain);
2408	for (rule = layer3_chain.rules; rule; rule = rule->next) {
2409		ipfw_insn_pipe *cmd = (ipfw_insn_pipe *)ACTION_PTR(rule);
2410
2411		if (cmd->o.opcode != O_PIPE && cmd->o.opcode != O_QUEUE)
2412			continue;
2413		/*
2414		 * XXX Use bcmp/bzero to handle pipe_ptr to overcome
2415		 * possible alignment problems on 64-bit architectures.
2416		 * This code is seldom used so we do not worry too
2417		 * much about efficiency.
2418		 */
2419		if (match == NULL ||
2420		    !bcmp(&cmd->pipe_ptr, &match, sizeof(match)) )
2421			bzero(&cmd->pipe_ptr, sizeof(cmd->pipe_ptr));
2422	}
2423	IPFW_UNLOCK(&layer3_chain);
2424}
2425
2426/*
2427 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
2428 * possibly create a rule number and add the rule to the list.
2429 * Update the rule_number in the input struct so the caller knows it as well.
2430 */
2431static int
2432add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
2433{
2434	struct ip_fw *rule, *f, *prev;
2435	int l = RULESIZE(input_rule);
2436
2437	if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
2438		return (EINVAL);
2439
2440	rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
2441	if (rule == NULL)
2442		return (ENOSPC);
2443
2444	bcopy(input_rule, rule, l);
2445
2446	rule->next = NULL;
2447	rule->next_rule = NULL;
2448
2449	rule->pcnt = 0;
2450	rule->bcnt = 0;
2451	rule->timestamp = 0;
2452
2453	IPFW_LOCK(chain);
2454
2455	if (chain->rules == NULL) {	/* default rule */
2456		chain->rules = rule;
2457		goto done;
2458        }
2459
2460	/*
2461	 * If rulenum is 0, find highest numbered rule before the
2462	 * default rule, and add autoinc_step
2463	 */
2464	if (autoinc_step < 1)
2465		autoinc_step = 1;
2466	else if (autoinc_step > 1000)
2467		autoinc_step = 1000;
2468	if (rule->rulenum == 0) {
2469		/*
2470		 * locate the highest numbered rule before default
2471		 */
2472		for (f = chain->rules; f; f = f->next) {
2473			if (f->rulenum == IPFW_DEFAULT_RULE)
2474				break;
2475			rule->rulenum = f->rulenum;
2476		}
2477		if (rule->rulenum < IPFW_DEFAULT_RULE - autoinc_step)
2478			rule->rulenum += autoinc_step;
2479		input_rule->rulenum = rule->rulenum;
2480	}
2481
2482	/*
2483	 * Now insert the new rule in the right place in the sorted list.
2484	 */
2485	for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) {
2486		if (f->rulenum > rule->rulenum) { /* found the location */
2487			if (prev) {
2488				rule->next = f;
2489				prev->next = rule;
2490			} else { /* head insert */
2491				rule->next = chain->rules;
2492				chain->rules = rule;
2493			}
2494			break;
2495		}
2496	}
2497	flush_rule_ptrs(chain);
2498done:
2499	static_count++;
2500	static_len += l;
2501	IPFW_UNLOCK(chain);
2502	DEB(printf("ipfw: installed rule %d, static count now %d\n",
2503		rule->rulenum, static_count);)
2504	return (0);
2505}
2506
2507/**
2508 * Remove a static rule (including derived * dynamic rules)
2509 * and place it on the ``reap list'' for later reclamation.
2510 * The caller is in charge of clearing rule pointers to avoid
2511 * dangling pointers.
2512 * @return a pointer to the next entry.
2513 * Arguments are not checked, so they better be correct.
2514 */
2515static struct ip_fw *
2516remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule, struct ip_fw *prev)
2517{
2518	struct ip_fw *n;
2519	int l = RULESIZE(rule);
2520
2521	IPFW_LOCK_ASSERT(chain);
2522
2523	n = rule->next;
2524	IPFW_DYN_LOCK();
2525	remove_dyn_rule(rule, NULL /* force removal */);
2526	IPFW_DYN_UNLOCK();
2527	if (prev == NULL)
2528		chain->rules = n;
2529	else
2530		prev->next = n;
2531	static_count--;
2532	static_len -= l;
2533
2534	rule->next = chain->reap;
2535	chain->reap = rule;
2536
2537	return n;
2538}
2539
2540/**
2541 * Reclaim storage associated with a list of rules.  This is
2542 * typically the list created using remove_rule.
2543 */
2544static void
2545reap_rules(struct ip_fw *head)
2546{
2547	struct ip_fw *rule;
2548
2549	while ((rule = head) != NULL) {
2550		head = head->next;
2551		if (DUMMYNET_LOADED)
2552			ip_dn_ruledel_ptr(rule);
2553		free(rule, M_IPFW);
2554	}
2555}
2556
2557/*
2558 * Remove all rules from a chain (except rules in set RESVD_SET
2559 * unless kill_default = 1).  The caller is responsible for
2560 * reclaiming storage for the rules left in chain->reap.
2561 */
2562static void
2563free_chain(struct ip_fw_chain *chain, int kill_default)
2564{
2565	struct ip_fw *prev, *rule;
2566
2567	IPFW_LOCK_ASSERT(chain);
2568
2569	flush_rule_ptrs(chain); /* more efficient to do outside the loop */
2570	for (prev = NULL, rule = chain->rules; rule ; )
2571		if (kill_default || rule->set != RESVD_SET)
2572			rule = remove_rule(chain, rule, prev);
2573		else {
2574			prev = rule;
2575			rule = rule->next;
2576		}
2577}
2578
2579/**
2580 * Remove all rules with given number, and also do set manipulation.
2581 * Assumes chain != NULL && *chain != NULL.
2582 *
2583 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
2584 * the next 8 bits are the new set, the top 8 bits are the command:
2585 *
2586 *	0	delete rules with given number
2587 *	1	delete rules with given set number
2588 *	2	move rules with given number to new set
2589 *	3	move rules with given set number to new set
2590 *	4	swap sets with given numbers
2591 */
2592static int
2593del_entry(struct ip_fw_chain *chain, u_int32_t arg)
2594{
2595	struct ip_fw *prev = NULL, *rule;
2596	u_int16_t rulenum;	/* rule or old_set */
2597	u_int8_t cmd, new_set;
2598
2599	rulenum = arg & 0xffff;
2600	cmd = (arg >> 24) & 0xff;
2601	new_set = (arg >> 16) & 0xff;
2602
2603	if (cmd > 4)
2604		return EINVAL;
2605	if (new_set > RESVD_SET)
2606		return EINVAL;
2607	if (cmd == 0 || cmd == 2) {
2608		if (rulenum >= IPFW_DEFAULT_RULE)
2609			return EINVAL;
2610	} else {
2611		if (rulenum > RESVD_SET)	/* old_set */
2612			return EINVAL;
2613	}
2614
2615	IPFW_LOCK(chain);
2616	rule = chain->rules;
2617	chain->reap = NULL;
2618	switch (cmd) {
2619	case 0:	/* delete rules with given number */
2620		/*
2621		 * locate first rule to delete
2622		 */
2623		for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
2624			;
2625		if (rule->rulenum != rulenum) {
2626			IPFW_UNLOCK(chain);
2627			return EINVAL;
2628		}
2629
2630		/*
2631		 * flush pointers outside the loop, then delete all matching
2632		 * rules. prev remains the same throughout the cycle.
2633		 */
2634		flush_rule_ptrs(chain);
2635		while (rule->rulenum == rulenum)
2636			rule = remove_rule(chain, rule, prev);
2637		break;
2638
2639	case 1:	/* delete all rules with given set number */
2640		flush_rule_ptrs(chain);
2641		rule = chain->rules;
2642		while (rule->rulenum < IPFW_DEFAULT_RULE)
2643			if (rule->set == rulenum)
2644				rule = remove_rule(chain, rule, prev);
2645			else {
2646				prev = rule;
2647				rule = rule->next;
2648			}
2649		break;
2650
2651	case 2:	/* move rules with given number to new set */
2652		rule = chain->rules;
2653		for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
2654			if (rule->rulenum == rulenum)
2655				rule->set = new_set;
2656		break;
2657
2658	case 3: /* move rules with given set number to new set */
2659		for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
2660			if (rule->set == rulenum)
2661				rule->set = new_set;
2662		break;
2663
2664	case 4: /* swap two sets */
2665		for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
2666			if (rule->set == rulenum)
2667				rule->set = new_set;
2668			else if (rule->set == new_set)
2669				rule->set = rulenum;
2670		break;
2671	}
2672	/*
2673	 * Look for rules to reclaim.  We grab the list before
2674	 * releasing the lock then reclaim them w/o the lock to
2675	 * avoid a LOR with dummynet.
2676	 */
2677	rule = chain->reap;
2678	chain->reap = NULL;
2679	IPFW_UNLOCK(chain);
2680	if (rule)
2681		reap_rules(rule);
2682	return 0;
2683}
2684
2685/*
2686 * Clear counters for a specific rule.
2687 * The enclosing "table" is assumed locked.
2688 */
2689static void
2690clear_counters(struct ip_fw *rule, int log_only)
2691{
2692	ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
2693
2694	if (log_only == 0) {
2695		rule->bcnt = rule->pcnt = 0;
2696		rule->timestamp = 0;
2697	}
2698	if (l->o.opcode == O_LOG)
2699		l->log_left = l->max_log;
2700}
2701
2702/**
2703 * Reset some or all counters on firewall rules.
2704 * @arg frwl is null to clear all entries, or contains a specific
2705 * rule number.
2706 * @arg log_only is 1 if we only want to reset logs, zero otherwise.
2707 */
2708static int
2709zero_entry(struct ip_fw_chain *chain, int rulenum, int log_only)
2710{
2711	struct ip_fw *rule;
2712	char *msg;
2713
2714	IPFW_LOCK(chain);
2715	if (rulenum == 0) {
2716		norule_counter = 0;
2717		for (rule = chain->rules; rule; rule = rule->next)
2718			clear_counters(rule, log_only);
2719		msg = log_only ? "ipfw: All logging counts reset.\n" :
2720				"ipfw: Accounting cleared.\n";
2721	} else {
2722		int cleared = 0;
2723		/*
2724		 * We can have multiple rules with the same number, so we
2725		 * need to clear them all.
2726		 */
2727		for (rule = chain->rules; rule; rule = rule->next)
2728			if (rule->rulenum == rulenum) {
2729				while (rule && rule->rulenum == rulenum) {
2730					clear_counters(rule, log_only);
2731					rule = rule->next;
2732				}
2733				cleared = 1;
2734				break;
2735			}
2736		if (!cleared) {	/* we did not find any matching rules */
2737			IPFW_UNLOCK(chain);
2738			return (EINVAL);
2739		}
2740		msg = log_only ? "ipfw: Entry %d logging count reset.\n" :
2741				"ipfw: Entry %d cleared.\n";
2742	}
2743	IPFW_UNLOCK(chain);
2744
2745	if (fw_verbose)
2746		log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
2747	return (0);
2748}
2749
2750/*
2751 * Check validity of the structure before insert.
2752 * Fortunately rules are simple, so this mostly need to check rule sizes.
2753 */
2754static int
2755check_ipfw_struct(struct ip_fw *rule, int size)
2756{
2757	int l, cmdlen = 0;
2758	int have_action=0;
2759	ipfw_insn *cmd;
2760
2761	if (size < sizeof(*rule)) {
2762		printf("ipfw: rule too short\n");
2763		return (EINVAL);
2764	}
2765	/* first, check for valid size */
2766	l = RULESIZE(rule);
2767	if (l != size) {
2768		printf("ipfw: size mismatch (have %d want %d)\n", size, l);
2769		return (EINVAL);
2770	}
2771	/*
2772	 * Now go for the individual checks. Very simple ones, basically only
2773	 * instruction sizes.
2774	 */
2775	for (l = rule->cmd_len, cmd = rule->cmd ;
2776			l > 0 ; l -= cmdlen, cmd += cmdlen) {
2777		cmdlen = F_LEN(cmd);
2778		if (cmdlen > l) {
2779			printf("ipfw: opcode %d size truncated\n",
2780			    cmd->opcode);
2781			return EINVAL;
2782		}
2783		DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
2784		switch (cmd->opcode) {
2785		case O_PROBE_STATE:
2786		case O_KEEP_STATE:
2787		case O_PROTO:
2788		case O_IP_SRC_ME:
2789		case O_IP_DST_ME:
2790		case O_LAYER2:
2791		case O_IN:
2792		case O_FRAG:
2793		case O_IPOPT:
2794		case O_IPTOS:
2795		case O_IPPRECEDENCE:
2796		case O_IPVER:
2797		case O_TCPWIN:
2798		case O_TCPFLAGS:
2799		case O_TCPOPTS:
2800		case O_ESTAB:
2801		case O_VERREVPATH:
2802		case O_VERSRCREACH:
2803		case O_IPSEC:
2804			if (cmdlen != F_INSN_SIZE(ipfw_insn))
2805				goto bad_size;
2806			break;
2807
2808		case O_UID:
2809		case O_GID:
2810		case O_IP_SRC:
2811		case O_IP_DST:
2812		case O_TCPSEQ:
2813		case O_TCPACK:
2814		case O_PROB:
2815		case O_ICMPTYPE:
2816			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
2817				goto bad_size;
2818			break;
2819
2820		case O_LIMIT:
2821			if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
2822				goto bad_size;
2823			break;
2824
2825		case O_LOG:
2826			if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
2827				goto bad_size;
2828
2829			((ipfw_insn_log *)cmd)->log_left =
2830			    ((ipfw_insn_log *)cmd)->max_log;
2831
2832			break;
2833
2834		case O_IP_SRC_MASK:
2835		case O_IP_DST_MASK:
2836			/* only odd command lengths */
2837			if ( !(cmdlen & 1) || cmdlen > 31)
2838				goto bad_size;
2839			break;
2840
2841		case O_IP_SRC_SET:
2842		case O_IP_DST_SET:
2843			if (cmd->arg1 == 0 || cmd->arg1 > 256) {
2844				printf("ipfw: invalid set size %d\n",
2845					cmd->arg1);
2846				return EINVAL;
2847			}
2848			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
2849			    (cmd->arg1+31)/32 )
2850				goto bad_size;
2851			break;
2852
2853		case O_IP_SRC_LOOKUP:
2854		case O_IP_DST_LOOKUP:
2855			if (cmd->arg1 >= IPFW_TABLES_MAX) {
2856				printf("ipfw: invalid table number %d\n",
2857				    cmd->arg1);
2858				return (EINVAL);
2859			}
2860			if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
2861			    cmdlen != F_INSN_SIZE(ipfw_insn_u32))
2862				goto bad_size;
2863			break;
2864
2865		case O_MACADDR2:
2866			if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
2867				goto bad_size;
2868			break;
2869
2870		case O_NOP:
2871		case O_IPID:
2872		case O_IPTTL:
2873		case O_IPLEN:
2874			if (cmdlen < 1 || cmdlen > 31)
2875				goto bad_size;
2876			break;
2877
2878		case O_MAC_TYPE:
2879		case O_IP_SRCPORT:
2880		case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
2881			if (cmdlen < 2 || cmdlen > 31)
2882				goto bad_size;
2883			break;
2884
2885		case O_RECV:
2886		case O_XMIT:
2887		case O_VIA:
2888			if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
2889				goto bad_size;
2890			break;
2891
2892		case O_PIPE:
2893		case O_QUEUE:
2894			if (cmdlen != F_INSN_SIZE(ipfw_insn_pipe))
2895				goto bad_size;
2896			goto check_action;
2897
2898		case O_FORWARD_IP:
2899			if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
2900				goto bad_size;
2901			goto check_action;
2902
2903		case O_FORWARD_MAC: /* XXX not implemented yet */
2904		case O_CHECK_STATE:
2905		case O_COUNT:
2906		case O_ACCEPT:
2907		case O_DENY:
2908		case O_REJECT:
2909		case O_SKIPTO:
2910		case O_DIVERT:
2911		case O_TEE:
2912			if (cmdlen != F_INSN_SIZE(ipfw_insn))
2913				goto bad_size;
2914check_action:
2915			if (have_action) {
2916				printf("ipfw: opcode %d, multiple actions"
2917					" not allowed\n",
2918					cmd->opcode);
2919				return EINVAL;
2920			}
2921			have_action = 1;
2922			if (l != cmdlen) {
2923				printf("ipfw: opcode %d, action must be"
2924					" last opcode\n",
2925					cmd->opcode);
2926				return EINVAL;
2927			}
2928			break;
2929		default:
2930			printf("ipfw: opcode %d, unknown opcode\n",
2931				cmd->opcode);
2932			return EINVAL;
2933		}
2934	}
2935	if (have_action == 0) {
2936		printf("ipfw: missing action\n");
2937		return EINVAL;
2938	}
2939	return 0;
2940
2941bad_size:
2942	printf("ipfw: opcode %d size %d wrong\n",
2943		cmd->opcode, cmdlen);
2944	return EINVAL;
2945}
2946
2947/*
2948 * Copy the static and dynamic rules to the supplied buffer
2949 * and return the amount of space actually used.
2950 */
2951static size_t
2952ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
2953{
2954	char *bp = buf;
2955	char *ep = bp + space;
2956	struct ip_fw *rule;
2957	int i;
2958
2959	/* XXX this can take a long time and locking will block packet flow */
2960	IPFW_LOCK(chain);
2961	for (rule = chain->rules; rule ; rule = rule->next) {
2962		/*
2963		 * Verify the entry fits in the buffer in case the
2964		 * rules changed between calculating buffer space and
2965		 * now.  This would be better done using a generation
2966		 * number but should suffice for now.
2967		 */
2968		i = RULESIZE(rule);
2969		if (bp + i <= ep) {
2970			bcopy(rule, bp, i);
2971			bcopy(&set_disable, &(((struct ip_fw *)bp)->next_rule),
2972			    sizeof(set_disable));
2973			bp += i;
2974		}
2975	}
2976	IPFW_UNLOCK(chain);
2977	if (ipfw_dyn_v) {
2978		ipfw_dyn_rule *p, *last = NULL;
2979
2980		IPFW_DYN_LOCK();
2981		for (i = 0 ; i < curr_dyn_buckets; i++)
2982			for (p = ipfw_dyn_v[i] ; p != NULL; p = p->next) {
2983				if (bp + sizeof *p <= ep) {
2984					ipfw_dyn_rule *dst =
2985						(ipfw_dyn_rule *)bp;
2986					bcopy(p, dst, sizeof *p);
2987					bcopy(&(p->rule->rulenum), &(dst->rule),
2988					    sizeof(p->rule->rulenum));
2989					/*
2990					 * store a non-null value in "next".
2991					 * The userland code will interpret a
2992					 * NULL here as a marker
2993					 * for the last dynamic rule.
2994					 */
2995					bcopy(&dst, &dst->next, sizeof(dst));
2996					last = dst;
2997					dst->expire =
2998					    TIME_LEQ(dst->expire, time_second) ?
2999						0 : dst->expire - time_second ;
3000					bp += sizeof(ipfw_dyn_rule);
3001				}
3002			}
3003		IPFW_DYN_UNLOCK();
3004		if (last != NULL) /* mark last dynamic rule */
3005			bzero(&last->next, sizeof(last));
3006	}
3007	return (bp - (char *)buf);
3008}
3009
3010
3011/**
3012 * {set|get}sockopt parser.
3013 */
3014static int
3015ipfw_ctl(struct sockopt *sopt)
3016{
3017#define	RULE_MAXSIZE	(256*sizeof(u_int32_t))
3018	int error, rule_num;
3019	size_t size;
3020	struct ip_fw *buf, *rule;
3021	u_int32_t rulenum[2];
3022
3023	error = suser(sopt->sopt_td);
3024	if (error)
3025		return (error);
3026
3027	/*
3028	 * Disallow modifications in really-really secure mode, but still allow
3029	 * the logging counters to be reset.
3030	 */
3031	if (sopt->sopt_name == IP_FW_ADD ||
3032	    (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
3033#if __FreeBSD_version >= 500034
3034		error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3035		if (error)
3036			return (error);
3037#else /* FreeBSD 4.x */
3038		if (securelevel >= 3)
3039			return (EPERM);
3040#endif
3041	}
3042
3043	error = 0;
3044
3045	switch (sopt->sopt_name) {
3046	case IP_FW_GET:
3047		/*
3048		 * pass up a copy of the current rules. Static rules
3049		 * come first (the last of which has number IPFW_DEFAULT_RULE),
3050		 * followed by a possibly empty list of dynamic rule.
3051		 * The last dynamic rule has NULL in the "next" field.
3052		 *
3053		 * Note that the calculated size is used to bound the
3054		 * amount of data returned to the user.  The rule set may
3055		 * change between calculating the size and returning the
3056		 * data in which case we'll just return what fits.
3057		 */
3058		size = static_len;	/* size of static rules */
3059		if (ipfw_dyn_v)		/* add size of dyn.rules */
3060			size += (dyn_count * sizeof(ipfw_dyn_rule));
3061
3062		/*
3063		 * XXX todo: if the user passes a short length just to know
3064		 * how much room is needed, do not bother filling up the
3065		 * buffer, just jump to the sooptcopyout.
3066		 */
3067		buf = malloc(size, M_TEMP, M_WAITOK);
3068		error = sooptcopyout(sopt, buf,
3069				ipfw_getrules(&layer3_chain, buf, size));
3070		free(buf, M_TEMP);
3071		break;
3072
3073	case IP_FW_FLUSH:
3074		/*
3075		 * Normally we cannot release the lock on each iteration.
3076		 * We could do it here only because we start from the head all
3077		 * the times so there is no risk of missing some entries.
3078		 * On the other hand, the risk is that we end up with
3079		 * a very inconsistent ruleset, so better keep the lock
3080		 * around the whole cycle.
3081		 *
3082		 * XXX this code can be improved by resetting the head of
3083		 * the list to point to the default rule, and then freeing
3084		 * the old list without the need for a lock.
3085		 */
3086
3087		IPFW_LOCK(&layer3_chain);
3088		layer3_chain.reap = NULL;
3089		free_chain(&layer3_chain, 0 /* keep default rule */);
3090		rule = layer3_chain.reap, layer3_chain.reap = NULL;
3091		IPFW_UNLOCK(&layer3_chain);
3092		if (layer3_chain.reap != NULL)
3093			reap_rules(rule);
3094		break;
3095
3096	case IP_FW_ADD:
3097		rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
3098		error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
3099			sizeof(struct ip_fw) );
3100		if (error == 0)
3101			error = check_ipfw_struct(rule, sopt->sopt_valsize);
3102		if (error == 0) {
3103			error = add_rule(&layer3_chain, rule);
3104			size = RULESIZE(rule);
3105			if (!error && sopt->sopt_dir == SOPT_GET)
3106				error = sooptcopyout(sopt, rule, size);
3107		}
3108		free(rule, M_TEMP);
3109		break;
3110
3111	case IP_FW_DEL:
3112		/*
3113		 * IP_FW_DEL is used for deleting single rules or sets,
3114		 * and (ab)used to atomically manipulate sets. Argument size
3115		 * is used to distinguish between the two:
3116		 *    sizeof(u_int32_t)
3117		 *	delete single rule or set of rules,
3118		 *	or reassign rules (or sets) to a different set.
3119		 *    2*sizeof(u_int32_t)
3120		 *	atomic disable/enable sets.
3121		 *	first u_int32_t contains sets to be disabled,
3122		 *	second u_int32_t contains sets to be enabled.
3123		 */
3124		error = sooptcopyin(sopt, rulenum,
3125			2*sizeof(u_int32_t), sizeof(u_int32_t));
3126		if (error)
3127			break;
3128		size = sopt->sopt_valsize;
3129		if (size == sizeof(u_int32_t))	/* delete or reassign */
3130			error = del_entry(&layer3_chain, rulenum[0]);
3131		else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
3132			set_disable =
3133			    (set_disable | rulenum[0]) & ~rulenum[1] &
3134			    ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
3135		else
3136			error = EINVAL;
3137		break;
3138
3139	case IP_FW_ZERO:
3140	case IP_FW_RESETLOG: /* argument is an int, the rule number */
3141		rule_num = 0;
3142		if (sopt->sopt_val != 0) {
3143		    error = sooptcopyin(sopt, &rule_num,
3144			    sizeof(int), sizeof(int));
3145		    if (error)
3146			break;
3147		}
3148		error = zero_entry(&layer3_chain, rule_num,
3149			sopt->sopt_name == IP_FW_RESETLOG);
3150		break;
3151
3152	case IP_FW_TABLE_ADD:
3153		{
3154			ipfw_table_entry ent;
3155
3156			error = sooptcopyin(sopt, &ent,
3157			    sizeof(ent), sizeof(ent));
3158			if (error)
3159				break;
3160			error = add_table_entry(ent.tbl, ent.addr,
3161			    ent.masklen, ent.value);
3162		}
3163		break;
3164
3165	case IP_FW_TABLE_DEL:
3166		{
3167			ipfw_table_entry ent;
3168
3169			error = sooptcopyin(sopt, &ent,
3170			    sizeof(ent), sizeof(ent));
3171			if (error)
3172				break;
3173			error = del_table_entry(ent.tbl, ent.addr, ent.masklen);
3174		}
3175		break;
3176
3177	case IP_FW_TABLE_FLUSH:
3178		{
3179			u_int16_t tbl;
3180
3181			error = sooptcopyin(sopt, &tbl,
3182			    sizeof(tbl), sizeof(tbl));
3183			if (error)
3184				break;
3185			error = flush_table(tbl);
3186		}
3187		break;
3188
3189	case IP_FW_TABLE_GETSIZE:
3190		{
3191			u_int32_t tbl, cnt;
3192
3193			if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
3194			    sizeof(tbl))))
3195				break;
3196			if ((error = count_table(tbl, &cnt)))
3197				break;
3198			error = sooptcopyout(sopt, &cnt, sizeof(cnt));
3199		}
3200		break;
3201
3202	case IP_FW_TABLE_LIST:
3203		{
3204			ipfw_table *tbl;
3205
3206			if (sopt->sopt_valsize < sizeof(*tbl)) {
3207				error = EINVAL;
3208				break;
3209			}
3210			size = sopt->sopt_valsize;
3211			tbl = malloc(size, M_TEMP, M_WAITOK);
3212			if (tbl == NULL) {
3213				error = ENOMEM;
3214				break;
3215			}
3216			error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
3217			if (error) {
3218				free(tbl, M_TEMP);
3219				break;
3220			}
3221			tbl->size = (size - sizeof(*tbl)) /
3222			    sizeof(ipfw_table_entry);
3223			error = dump_table(tbl);
3224			if (error) {
3225				free(tbl, M_TEMP);
3226				break;
3227			}
3228			error = sooptcopyout(sopt, tbl, size);
3229			free(tbl, M_TEMP);
3230		}
3231		break;
3232
3233	default:
3234		printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
3235		error = EINVAL;
3236	}
3237
3238	return (error);
3239#undef RULE_MAXSIZE
3240}
3241
3242/**
3243 * dummynet needs a reference to the default rule, because rules can be
3244 * deleted while packets hold a reference to them. When this happens,
3245 * dummynet changes the reference to the default rule (it could well be a
3246 * NULL pointer, but this way we do not need to check for the special
3247 * case, plus here he have info on the default behaviour).
3248 */
3249struct ip_fw *ip_fw_default_rule;
3250
3251/*
3252 * This procedure is only used to handle keepalives. It is invoked
3253 * every dyn_keepalive_period
3254 */
3255static void
3256ipfw_tick(void * __unused unused)
3257{
3258	int i;
3259	ipfw_dyn_rule *q;
3260
3261	if (dyn_keepalive == 0 || ipfw_dyn_v == NULL || dyn_count == 0)
3262		goto done;
3263
3264	IPFW_DYN_LOCK();
3265	for (i = 0 ; i < curr_dyn_buckets ; i++) {
3266		for (q = ipfw_dyn_v[i] ; q ; q = q->next ) {
3267			if (q->dyn_type == O_LIMIT_PARENT)
3268				continue;
3269			if (q->id.proto != IPPROTO_TCP)
3270				continue;
3271			if ( (q->state & BOTH_SYN) != BOTH_SYN)
3272				continue;
3273			if (TIME_LEQ( time_second+dyn_keepalive_interval,
3274			    q->expire))
3275				continue;	/* too early */
3276			if (TIME_LEQ(q->expire, time_second))
3277				continue;	/* too late, rule expired */
3278
3279			send_pkt(&(q->id), q->ack_rev - 1, q->ack_fwd, TH_SYN);
3280			send_pkt(&(q->id), q->ack_fwd - 1, q->ack_rev, 0);
3281		}
3282	}
3283	IPFW_DYN_UNLOCK();
3284done:
3285	callout_reset(&ipfw_timeout, dyn_keepalive_period*hz, ipfw_tick, NULL);
3286}
3287
3288static int
3289ipfw_init(void)
3290{
3291	struct ip_fw default_rule;
3292	int error;
3293
3294	layer3_chain.rules = NULL;
3295	IPFW_LOCK_INIT(&layer3_chain);
3296	IPFW_DYN_LOCK_INIT();
3297	callout_init(&ipfw_timeout, debug_mpsafenet ? CALLOUT_MPSAFE : 0);
3298
3299	bzero(&default_rule, sizeof default_rule);
3300
3301	default_rule.act_ofs = 0;
3302	default_rule.rulenum = IPFW_DEFAULT_RULE;
3303	default_rule.cmd_len = 1;
3304	default_rule.set = RESVD_SET;
3305
3306	default_rule.cmd[0].len = 1;
3307	default_rule.cmd[0].opcode =
3308#ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
3309				1 ? O_ACCEPT :
3310#endif
3311				O_DENY;
3312
3313	error = add_rule(&layer3_chain, &default_rule);
3314	if (error != 0) {
3315		printf("ipfw2: error %u initializing default rule "
3316			"(support disabled)\n", error);
3317		IPFW_DYN_LOCK_DESTROY();
3318		IPFW_LOCK_DESTROY(&layer3_chain);
3319		return (error);
3320	}
3321
3322	ip_fw_default_rule = layer3_chain.rules;
3323	printf("ipfw2 initialized, divert %s, "
3324		"rule-based forwarding enabled, default to %s, logging ",
3325#ifdef IPDIVERT
3326		"enabled",
3327#else
3328		"disabled",
3329#endif
3330		default_rule.cmd[0].opcode == O_ACCEPT ? "accept" : "deny");
3331
3332#ifdef IPFIREWALL_VERBOSE
3333	fw_verbose = 1;
3334#endif
3335#ifdef IPFIREWALL_VERBOSE_LIMIT
3336	verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
3337#endif
3338	if (fw_verbose == 0)
3339		printf("disabled\n");
3340	else if (verbose_limit == 0)
3341		printf("unlimited\n");
3342	else
3343		printf("limited to %d packets/entry by default\n",
3344		    verbose_limit);
3345
3346	ip_fw_chk_ptr = ipfw_chk;
3347	ip_fw_ctl_ptr = ipfw_ctl;
3348	callout_reset(&ipfw_timeout, hz, ipfw_tick, NULL);
3349
3350	return (0);
3351}
3352
3353static void
3354ipfw_destroy(void)
3355{
3356	struct ip_fw *reap;
3357
3358	IPFW_LOCK(&layer3_chain);
3359	callout_stop(&ipfw_timeout);
3360	ip_fw_chk_ptr = NULL;
3361	ip_fw_ctl_ptr = NULL;
3362	layer3_chain.reap = NULL;
3363	free_chain(&layer3_chain, 1 /* kill default rule */);
3364	reap = layer3_chain.reap, layer3_chain.reap = NULL;
3365	IPFW_UNLOCK(&layer3_chain);
3366	if (reap != NULL)
3367		reap_rules(reap);
3368	flush_tables();
3369	IPFW_DYN_LOCK_DESTROY();
3370	IPFW_LOCK_DESTROY(&layer3_chain);
3371	printf("IP firewall unloaded\n");
3372}
3373
3374static int
3375ipfw_modevent(module_t mod, int type, void *unused)
3376{
3377	int err = 0;
3378
3379	switch (type) {
3380	case MOD_LOAD:
3381		if (IPFW_LOADED) {
3382			printf("IP firewall already loaded\n");
3383			err = EEXIST;
3384		} else {
3385			err = ipfw_init();
3386		}
3387		break;
3388
3389	case MOD_UNLOAD:
3390		ipfw_destroy();
3391		err = 0;
3392		break;
3393	default:
3394		break;
3395	}
3396	return err;
3397}
3398
3399static moduledata_t ipfwmod = {
3400	"ipfw",
3401	ipfw_modevent,
3402	0
3403};
3404DECLARE_MODULE(ipfw, ipfwmod, SI_SUB_PSEUDO, SI_ORDER_ANY);
3405MODULE_VERSION(ipfw, 1);
3406
3407/* Must be run after route_init(). */
3408SYSINIT(ipfw, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY, init_tables, 0)
3409
3410#endif /* IPFW2 */
3411