ip_fw2.c revision 115793
153913Sarchie/*
253913Sarchie * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
353913Sarchie *
453913Sarchie * Redistribution and use in source and binary forms, with or without
553913Sarchie * modification, are permitted provided that the following conditions
653913Sarchie * are met:
753913Sarchie * 1. Redistributions of source code must retain the above copyright
853913Sarchie *    notice, this list of conditions and the following disclaimer.
953913Sarchie * 2. Redistributions in binary form must reproduce the above copyright
1053913Sarchie *    notice, this list of conditions and the following disclaimer in the
1153913Sarchie *    documentation and/or other materials provided with the distribution.
1253913Sarchie *
1353913Sarchie * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1453913Sarchie * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1553913Sarchie * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1653913Sarchie * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
1753913Sarchie * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1853913Sarchie * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
1953913Sarchie * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2053913Sarchie * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2153913Sarchie * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2253913Sarchie * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2353913Sarchie * SUCH DAMAGE.
2453913Sarchie *
2553913Sarchie * $FreeBSD: head/sys/netinet/ip_fw2.c 115793 2003-06-04 01:17:37Z ticso $
2653913Sarchie */
2753913Sarchie
2853913Sarchie#define        DEB(x)
2953913Sarchie#define        DDB(x) x
3053913Sarchie
3153913Sarchie/*
3253913Sarchie * Implement IP packet firewall (new version)
3353913Sarchie */
3453913Sarchie
3553913Sarchie#if !defined(KLD_MODULE)
3653913Sarchie#include "opt_ipfw.h"
3753913Sarchie#include "opt_ipdn.h"
3853913Sarchie#include "opt_ipdivert.h"
3953913Sarchie#include "opt_inet.h"
4053913Sarchie#ifndef INET
4153913Sarchie#error IPFIREWALL requires INET.
4253913Sarchie#endif /* INET */
4353913Sarchie#endif
4453913Sarchie
4553913Sarchie#define IPFW2	1
4653913Sarchie#if IPFW2
4753913Sarchie#include <sys/param.h>
4853913Sarchie#include <sys/systm.h>
4953913Sarchie#include <sys/malloc.h>
5053998Sarchie#include <sys/mbuf.h>
5153998Sarchie#include <sys/kernel.h>
5253998Sarchie#include <sys/proc.h>
5353913Sarchie#include <sys/socket.h>
5453998Sarchie#include <sys/socketvar.h>
5553998Sarchie#include <sys/sysctl.h>
5653998Sarchie#include <sys/syslog.h>
5753998Sarchie#include <sys/ucred.h>
5853998Sarchie#include <net/if.h>
5953998Sarchie#include <net/route.h>
6053998Sarchie#include <netinet/in.h>
6153998Sarchie#include <netinet/in_systm.h>
6253998Sarchie#include <netinet/in_var.h>
6353913Sarchie#include <netinet/in_pcb.h>
6453913Sarchie#include <netinet/ip.h>
6553913Sarchie#include <netinet/ip_var.h>
6653913Sarchie#include <netinet/ip_icmp.h>
6753913Sarchie#include <netinet/ip_fw.h>
6853913Sarchie#include <netinet/ip_dummynet.h>
6953913Sarchie#include <netinet/tcp.h>
7053913Sarchie#include <netinet/tcp_timer.h>
7153913Sarchie#include <netinet/tcp_var.h>
7253913Sarchie#include <netinet/tcpip.h>
7353913Sarchie#include <netinet/udp.h>
7453913Sarchie#include <netinet/udp_var.h>
7553913Sarchie
7653913Sarchie#include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
7753913Sarchie
7853913Sarchie#include <machine/in_cksum.h>	/* XXX for in_cksum */
7953913Sarchie
8053913Sarchie/*
8153913Sarchie * XXX This one should go in sys/mbuf.h. It is used to avoid that
8253913Sarchie * a firewall-generated packet loops forever through the firewall.
8353913Sarchie */
8453913Sarchie#ifndef	M_SKIP_FIREWALL
8553913Sarchie#define M_SKIP_FIREWALL         0x4000
8653913Sarchie#endif
8753913Sarchie
8853998Sarchie/*
8953913Sarchie * set_disable contains one bit per set value (0..31).
9053913Sarchie * If the bit is set, all rules with the corresponding set
9153913Sarchie * are disabled. Set 31 is reserved for the default rule
9253913Sarchie * and CANNOT be disabled.
9353998Sarchie */
9453998Sarchiestatic u_int32_t set_disable;
9553998Sarchie
9653998Sarchiestatic int fw_verbose;
9753913Sarchiestatic int verbose_limit;
9853998Sarchie
9953998Sarchiestatic struct callout_handle ipfw_timeout_h;
10053913Sarchie#define	IPFW_DEFAULT_RULE	65535
10153998Sarchie
10253998Sarchie/*
10353998Sarchie * list of rules for layer 3
10453998Sarchie */
10553998Sarchiestatic struct ip_fw *layer3_chain;
10653998Sarchie
10753998SarchieMALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
10853913Sarchie
10953998Sarchiestatic int fw_debug = 1;
11053998Sarchiestatic int autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
11153913Sarchie
11253998Sarchie#ifdef SYSCTL_NODE
11353998SarchieSYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
11453998SarchieSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, enable,
11553998Sarchie    CTLFLAG_RW | CTLFLAG_SECURE3,
11653998Sarchie    &fw_enable, 0, "Enable ipfw");
11753998SarchieSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLFLAG_RW,
11853998Sarchie    &autoinc_step, 0, "Rule number autincrement step");
11953998SarchieSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
12053998Sarchie    CTLFLAG_RW | CTLFLAG_SECURE3,
12153998Sarchie    &fw_one_pass, 0,
12253998Sarchie    "Only do a single pass through ipfw when using dummynet(4)");
12353998SarchieSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
12453998Sarchie    &fw_debug, 0, "Enable printing of debug ip_fw statements");
12553998SarchieSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
12653998Sarchie    CTLFLAG_RW | CTLFLAG_SECURE3,
12753998Sarchie    &fw_verbose, 0, "Log matches to ipfw rules");
12853998SarchieSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
12953998Sarchie    &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
13053998Sarchie
13153998Sarchie/*
13253998Sarchie * Description of dynamic rules.
13353998Sarchie *
13453998Sarchie * Dynamic rules are stored in lists accessed through a hash table
13553998Sarchie * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
13653998Sarchie * be modified through the sysctl variable dyn_buckets which is
13753998Sarchie * updated when the table becomes empty.
13853998Sarchie *
13953998Sarchie * XXX currently there is only one list, ipfw_dyn.
14053998Sarchie *
14153998Sarchie * When a packet is received, its address fields are first masked
14253998Sarchie * with the mask defined for the rule, then hashed, then matched
14353998Sarchie * against the entries in the corresponding list.
14453998Sarchie * Dynamic rules can be used for different purposes:
14553998Sarchie *  + stateful rules;
14653998Sarchie *  + enforcing limits on the number of sessions;
14753998Sarchie *  + in-kernel NAT (not implemented yet)
14853998Sarchie *
14953998Sarchie * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
15053998Sarchie * measured in seconds and depending on the flags.
15153998Sarchie *
15253998Sarchie * The total number of dynamic rules is stored in dyn_count.
15353998Sarchie * The max number of dynamic rules is dyn_max. When we reach
15453998Sarchie * the maximum number of rules we do not create anymore. This is
15553998Sarchie * done to avoid consuming too much memory, but also too much
15653998Sarchie * time when searching on each packet (ideally, we should try instead
15753998Sarchie * to put a limit on the length of the list on each bucket...).
15853998Sarchie *
15953998Sarchie * Each dynamic rule holds a pointer to the parent ipfw rule so
16053998Sarchie * we know what action to perform. Dynamic rules are removed when
16153998Sarchie * the parent rule is deleted. XXX we should make them survive.
16253998Sarchie *
16353998Sarchie * There are some limitations with dynamic rules -- we do not
16453998Sarchie * obey the 'randomized match', and we do not do multiple
16553998Sarchie * passes through the firewall. XXX check the latter!!!
16653998Sarchie */
16753998Sarchiestatic ipfw_dyn_rule **ipfw_dyn_v = NULL;
16853998Sarchiestatic u_int32_t dyn_buckets = 256; /* must be power of 2 */
16953998Sarchiestatic u_int32_t curr_dyn_buckets = 256; /* must be power of 2 */
17053998Sarchie
17153998Sarchie/*
17253998Sarchie * Timeouts for various events in handing dynamic rules.
17353998Sarchie */
17453998Sarchiestatic u_int32_t dyn_ack_lifetime = 300;
17553998Sarchiestatic u_int32_t dyn_syn_lifetime = 20;
17653998Sarchiestatic u_int32_t dyn_fin_lifetime = 1;
17753998Sarchiestatic u_int32_t dyn_rst_lifetime = 1;
17853998Sarchiestatic u_int32_t dyn_udp_lifetime = 10;
17953998Sarchiestatic u_int32_t dyn_short_lifetime = 5;
18053913Sarchie
18153998Sarchie/*
18253998Sarchie * Keepalives are sent if dyn_keepalive is set. They are sent every
18353998Sarchie * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
18453998Sarchie * seconds of lifetime of a rule.
18553913Sarchie * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
18653998Sarchie * than dyn_keepalive_period.
18753998Sarchie */
18853998Sarchie
18953913Sarchiestatic u_int32_t dyn_keepalive_interval = 20;
19053913Sarchiestatic u_int32_t dyn_keepalive_period = 5;
19153913Sarchiestatic u_int32_t dyn_keepalive = 1;	/* do send keepalives */
19253913Sarchie
19353913Sarchiestatic u_int32_t static_count;	/* # of static rules */
19453913Sarchiestatic u_int32_t static_len;	/* size in bytes of static rules */
19553913Sarchiestatic u_int32_t dyn_count;		/* # of dynamic rules */
19653913Sarchiestatic u_int32_t dyn_max = 4096;	/* max # of dynamic rules */
19753998Sarchie
19853998SarchieSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLFLAG_RW,
19953913Sarchie    &dyn_buckets, 0, "Number of dyn. buckets");
20053913SarchieSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
20153913Sarchie    &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
20253913SarchieSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
20353913Sarchie    &dyn_count, 0, "Number of dyn. rules");
20453913SarchieSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
20553913Sarchie    &dyn_max, 0, "Max number of dyn. rules");
20653913SarchieSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
20753913Sarchie    &static_count, 0, "Number of static rules");
20853913SarchieSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
20953913Sarchie    &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
21053913SarchieSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
21153913Sarchie    &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
21253913SarchieSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime, CTLFLAG_RW,
21353913Sarchie    &dyn_fin_lifetime, 0, "Lifetime of dyn. rules for fin");
21453913SarchieSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime, CTLFLAG_RW,
21553913Sarchie    &dyn_rst_lifetime, 0, "Lifetime of dyn. rules for rst");
21653913SarchieSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
21753913Sarchie    &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
21853913SarchieSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
21953913Sarchie    &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
22053913SarchieSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
22153913Sarchie    &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
22253913Sarchie
22353913Sarchie#endif /* SYSCTL_NODE */
22453913Sarchie
22553913Sarchie
22653913Sarchiestatic ip_fw_chk_t	ipfw_chk;
22753913Sarchie
22853913Sarchieip_dn_ruledel_t *ip_dn_ruledel_ptr = NULL;	/* hook into dummynet */
22953913Sarchie
23053913Sarchie/*
23153913Sarchie * This macro maps an ip pointer into a layer3 header pointer of type T
23253913Sarchie */
23353913Sarchie#define	L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
23453913Sarchie
23553913Sarchiestatic __inline int
23653913Sarchieicmptype_match(struct ip *ip, ipfw_insn_u32 *cmd)
23753913Sarchie{
23853913Sarchie	int type = L3HDR(struct icmp,ip)->icmp_type;
23953913Sarchie
24053913Sarchie	return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
24153913Sarchie}
24253913Sarchie
24353913Sarchie#define TT	( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
24453913Sarchie    (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
24553913Sarchie
24653913Sarchiestatic int
24753913Sarchieis_icmp_query(struct ip *ip)
24853913Sarchie{
24953913Sarchie	int type = L3HDR(struct icmp, ip)->icmp_type;
25053913Sarchie	return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
25153913Sarchie}
25253913Sarchie#undef TT
25353913Sarchie
25453913Sarchie/*
25553913Sarchie * The following checks use two arrays of 8 or 16 bits to store the
25653913Sarchie * bits that we want set or clear, respectively. They are in the
25753913Sarchie * low and high half of cmd->arg1 or cmd->d[0].
25853913Sarchie *
25953913Sarchie * We scan options and store the bits we find set. We succeed if
26053913Sarchie *
26153913Sarchie *	(want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
26253913Sarchie *
26353913Sarchie * The code is sometimes optimized not to store additional variables.
26453913Sarchie */
26553913Sarchie
26653913Sarchiestatic int
26753913Sarchieflags_match(ipfw_insn *cmd, u_int8_t bits)
26853998Sarchie{
26953998Sarchie	u_char want_clear;
27053998Sarchie	bits = ~bits;
27153998Sarchie
27253998Sarchie	if ( ((cmd->arg1 & 0xff) & bits) != 0)
27353998Sarchie		return 0; /* some bits we want set were clear */
27453998Sarchie	want_clear = (cmd->arg1 >> 8) & 0xff;
27553998Sarchie	if ( (want_clear & bits) != want_clear)
27653998Sarchie		return 0; /* some bits we want clear were set */
27753998Sarchie	return 1;
27853913Sarchie}
27953913Sarchie
28053913Sarchiestatic int
28153913Sarchieipopts_match(struct ip *ip, ipfw_insn *cmd)
28253913Sarchie{
28353913Sarchie	int optlen, bits = 0;
28453913Sarchie	u_char *cp = (u_char *)(ip + 1);
28553913Sarchie	int x = (ip->ip_hl << 2) - sizeof (struct ip);
28653913Sarchie
28753913Sarchie	for (; x > 0; x -= optlen, cp += optlen) {
28853913Sarchie		int opt = cp[IPOPT_OPTVAL];
28953913Sarchie
29053913Sarchie		if (opt == IPOPT_EOL)
29153913Sarchie			break;
29253913Sarchie		if (opt == IPOPT_NOP)
29353913Sarchie			optlen = 1;
29453998Sarchie		else {
29553913Sarchie			optlen = cp[IPOPT_OLEN];
29653998Sarchie			if (optlen <= 0 || optlen > x)
29753998Sarchie				return 0; /* invalid or truncated */
29853998Sarchie		}
29953998Sarchie		switch (opt) {
30053913Sarchie
30153913Sarchie		default:
30253913Sarchie			break;
30353913Sarchie
30453913Sarchie		case IPOPT_LSRR:
30553913Sarchie			bits |= IP_FW_IPOPT_LSRR;
30653913Sarchie			break;
30753913Sarchie
30853913Sarchie		case IPOPT_SSRR:
30953913Sarchie			bits |= IP_FW_IPOPT_SSRR;
31053913Sarchie			break;
31153913Sarchie
31253913Sarchie		case IPOPT_RR:
31353913Sarchie			bits |= IP_FW_IPOPT_RR;
31453913Sarchie			break;
31553913Sarchie
31653913Sarchie		case IPOPT_TS:
31753913Sarchie			bits |= IP_FW_IPOPT_TS;
31853913Sarchie			break;
31953998Sarchie		}
32053913Sarchie	}
32153998Sarchie	return (flags_match(cmd, bits));
32253998Sarchie}
32353998Sarchie
32453913Sarchiestatic int
32553913Sarchietcpopts_match(struct ip *ip, ipfw_insn *cmd)
32653913Sarchie{
32753913Sarchie	int optlen, bits = 0;
32853998Sarchie	struct tcphdr *tcp = L3HDR(struct tcphdr,ip);
32953998Sarchie	u_char *cp = (u_char *)(tcp + 1);
33053998Sarchie	int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
33153998Sarchie
33253998Sarchie	for (; x > 0; x -= optlen, cp += optlen) {
33353998Sarchie		int opt = cp[0];
33453998Sarchie		if (opt == TCPOPT_EOL)
33553913Sarchie			break;
33653913Sarchie		if (opt == TCPOPT_NOP)
33753913Sarchie			optlen = 1;
33853913Sarchie		else {
33953913Sarchie			optlen = cp[1];
34053913Sarchie			if (optlen <= 0)
34153913Sarchie				break;
34253913Sarchie		}
34353913Sarchie
34453913Sarchie		switch (opt) {
34553913Sarchie
34653998Sarchie		default:
34753913Sarchie			break;
34853998Sarchie
34953998Sarchie		case TCPOPT_MAXSEG:
35053998Sarchie			bits |= IP_FW_TCPOPT_MSS;
35153913Sarchie			break;
35253913Sarchie
35353913Sarchie		case TCPOPT_WINDOW:
35453913Sarchie			bits |= IP_FW_TCPOPT_WINDOW;
35553913Sarchie			break;
35653998Sarchie
35753998Sarchie		case TCPOPT_SACK_PERMITTED:
35853998Sarchie		case TCPOPT_SACK:
35953998Sarchie			bits |= IP_FW_TCPOPT_SACK;
36053998Sarchie			break;
36153998Sarchie
36253998Sarchie		case TCPOPT_TIMESTAMP:
36353998Sarchie			bits |= IP_FW_TCPOPT_TS;
36453998Sarchie			break;
36553913Sarchie
36653913Sarchie		case TCPOPT_CC:
36753913Sarchie		case TCPOPT_CCNEW:
36853913Sarchie		case TCPOPT_CCECHO:
36953913Sarchie			bits |= IP_FW_TCPOPT_CC;
37053913Sarchie			break;
37153913Sarchie		}
37253998Sarchie	}
37353913Sarchie	return (flags_match(cmd, bits));
37453998Sarchie}
37553998Sarchie
37653913Sarchiestatic int
37753913Sarchieiface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
37853913Sarchie{
37953913Sarchie	if (ifp == NULL)	/* no iface with this packet, match fails */
38053913Sarchie		return 0;
38153913Sarchie	/* Check by name or by IP address */
38253998Sarchie	if (cmd->name[0] != '\0') { /* match by name */
38353913Sarchie		/* Check unit number (-1 is wildcard) */
38453998Sarchie		if (cmd->p.unit != -1 && cmd->p.unit != ifp->if_unit)
38553998Sarchie			return(0);
38653998Sarchie		/* Check name */
38753913Sarchie		if (!strncmp(ifp->if_name, cmd->name, IFNAMSIZ))
38853913Sarchie			return(1);
38953913Sarchie	} else {
39053913Sarchie		struct ifaddr *ia;
39153913Sarchie
39253913Sarchie		TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
39353913Sarchie			if (ia->ifa_addr == NULL)
39453913Sarchie				continue;
39553913Sarchie			if (ia->ifa_addr->sa_family != AF_INET)
39653913Sarchie				continue;
39753998Sarchie			if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
39853913Sarchie			    (ia->ifa_addr))->sin_addr.s_addr)
39953913Sarchie				return(1);	/* match */
40053913Sarchie		}
40153913Sarchie	}
40253913Sarchie	return(0);	/* no match, fail ... */
40353913Sarchie}
40453913Sarchie
40553913Sarchie/*
40653998Sarchie * The 'verrevpath' option checks that the interface that an IP packet
40753913Sarchie * arrives on is the same interface that traffic destined for the
40853913Sarchie * packet's source address would be routed out of. This is a measure
40953913Sarchie * to block forged packets. This is also commonly known as "anti-spoofing"
41053913Sarchie * or Unicast Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The
41153913Sarchie * name of the knob is purposely reminisent of the Cisco IOS command,
41253913Sarchie *
41353913Sarchie *   ip verify unicast reverse-path
41453913Sarchie *
41553913Sarchie * which implements the same functionality. But note that syntax is
41653913Sarchie * misleading. The check may be performed on all IP packets whether unicast,
41753998Sarchie * multicast, or broadcast.
41853913Sarchie */
41953913Sarchiestatic int
42053913Sarchieverify_rev_path(struct in_addr src, struct ifnet *ifp)
42153913Sarchie{
42253913Sarchie	static struct route ro;
42353913Sarchie	struct sockaddr_in *dst;
42453913Sarchie
42553998Sarchie	dst = (struct sockaddr_in *)&(ro.ro_dst);
42653913Sarchie
42753998Sarchie	/* Check if we've cached the route from the previous call. */
42853998Sarchie	if (src.s_addr != dst->sin_addr.s_addr) {
42953998Sarchie		ro.ro_rt = NULL;
43053998Sarchie
43153913Sarchie		bzero(dst, sizeof(*dst));
43253913Sarchie		dst->sin_family = AF_INET;
43353913Sarchie		dst->sin_len = sizeof(*dst);
43453913Sarchie		dst->sin_addr = src;
43553913Sarchie
43653913Sarchie		rtalloc_ign(&ro, RTF_CLONING|RTF_PRCLONING);
43753998Sarchie	}
43853913Sarchie
43953998Sarchie	if ((ro.ro_rt == NULL) || (ifp == NULL) ||
44053998Sarchie	    (ro.ro_rt->rt_ifp->if_index != ifp->if_index))
44153913Sarchie		return 0;
44253913Sarchie
44353913Sarchie    	return 1;
44453913Sarchie}
44553913Sarchie
44653913Sarchie
44753913Sarchiestatic u_int64_t norule_counter;	/* counter for ipfw_log(NULL...) */
44853913Sarchie
44953913Sarchie#define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
45053913Sarchie#define SNP(buf) buf, sizeof(buf)
45153913Sarchie
45253913Sarchie/*
45353913Sarchie * We enter here when we have a rule with O_LOG.
45453913Sarchie * XXX this function alone takes about 2Kbytes of code!
45553913Sarchie */
45653913Sarchiestatic void
45753913Sarchieipfw_log(struct ip_fw *f, u_int hlen, struct ether_header *eh,
45853913Sarchie	struct mbuf *m, struct ifnet *oif)
45953913Sarchie{
46053913Sarchie	char *action;
46153913Sarchie	int limit_reached = 0;
46253913Sarchie	char action2[40], proto[48], fragment[28];
46353913Sarchie
46453913Sarchie	fragment[0] = '\0';
46553913Sarchie	proto[0] = '\0';
46653913Sarchie
46753913Sarchie	if (f == NULL) {	/* bogus pkt */
46853913Sarchie		if (verbose_limit != 0 && norule_counter >= verbose_limit)
46953913Sarchie			return;
47053913Sarchie		norule_counter++;
47153913Sarchie		if (norule_counter == verbose_limit)
47253913Sarchie			limit_reached = verbose_limit;
47353913Sarchie		action = "Refuse";
47453913Sarchie	} else {	/* O_LOG is the first action, find the real one */
47553913Sarchie		ipfw_insn *cmd = ACTION_PTR(f);
47653913Sarchie		ipfw_insn_log *l = (ipfw_insn_log *)cmd;
47753913Sarchie
47853913Sarchie		if (l->max_log != 0 && l->log_left == 0)
47953913Sarchie			return;
48053913Sarchie		l->log_left--;
48153913Sarchie		if (l->log_left == 0)
48253913Sarchie			limit_reached = l->max_log;
48353913Sarchie		cmd += F_LEN(cmd);	/* point to first action */
48453913Sarchie		if (cmd->opcode == O_PROB)
48553913Sarchie			cmd += F_LEN(cmd);
48653913Sarchie
48753913Sarchie		action = action2;
48853913Sarchie		switch (cmd->opcode) {
48953913Sarchie		case O_DENY:
49053913Sarchie			action = "Deny";
49153913Sarchie			break;
49253913Sarchie
49353913Sarchie		case O_REJECT:
49453913Sarchie			if (cmd->arg1==ICMP_REJECT_RST)
49553913Sarchie				action = "Reset";
49653913Sarchie			else if (cmd->arg1==ICMP_UNREACH_HOST)
49753913Sarchie				action = "Reject";
49853913Sarchie			else
49953913Sarchie				snprintf(SNPARGS(action2, 0), "Unreach %d",
50053913Sarchie					cmd->arg1);
50153913Sarchie			break;
50253913Sarchie
50353913Sarchie		case O_ACCEPT:
50453913Sarchie			action = "Accept";
50553913Sarchie			break;
50653913Sarchie		case O_COUNT:
50753913Sarchie			action = "Count";
508			break;
509		case O_DIVERT:
510			snprintf(SNPARGS(action2, 0), "Divert %d",
511				cmd->arg1);
512			break;
513		case O_TEE:
514			snprintf(SNPARGS(action2, 0), "Tee %d",
515				cmd->arg1);
516			break;
517		case O_SKIPTO:
518			snprintf(SNPARGS(action2, 0), "SkipTo %d",
519				cmd->arg1);
520			break;
521		case O_PIPE:
522			snprintf(SNPARGS(action2, 0), "Pipe %d",
523				cmd->arg1);
524			break;
525		case O_QUEUE:
526			snprintf(SNPARGS(action2, 0), "Queue %d",
527				cmd->arg1);
528			break;
529		case O_FORWARD_IP: {
530			ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
531			int len;
532
533			len = snprintf(SNPARGS(action2, 0), "Forward to %s",
534				inet_ntoa(sa->sa.sin_addr));
535			if (sa->sa.sin_port)
536				snprintf(SNPARGS(action2, len), ":%d",
537				    sa->sa.sin_port);
538			}
539			break;
540		default:
541			action = "UNKNOWN";
542			break;
543		}
544	}
545
546	if (hlen == 0) {	/* non-ip */
547		snprintf(SNPARGS(proto, 0), "MAC");
548	} else {
549		struct ip *ip = mtod(m, struct ip *);
550		/* these three are all aliases to the same thing */
551		struct icmp *const icmp = L3HDR(struct icmp, ip);
552		struct tcphdr *const tcp = (struct tcphdr *)icmp;
553		struct udphdr *const udp = (struct udphdr *)icmp;
554
555		int ip_off, offset, ip_len;
556
557		int len;
558
559		if (eh != NULL) { /* layer 2 packets are as on the wire */
560			ip_off = ntohs(ip->ip_off);
561			ip_len = ntohs(ip->ip_len);
562		} else {
563			ip_off = ip->ip_off;
564			ip_len = ip->ip_len;
565		}
566		offset = ip_off & IP_OFFMASK;
567		switch (ip->ip_p) {
568		case IPPROTO_TCP:
569			len = snprintf(SNPARGS(proto, 0), "TCP %s",
570			    inet_ntoa(ip->ip_src));
571			if (offset == 0)
572				snprintf(SNPARGS(proto, len), ":%d %s:%d",
573				    ntohs(tcp->th_sport),
574				    inet_ntoa(ip->ip_dst),
575				    ntohs(tcp->th_dport));
576			else
577				snprintf(SNPARGS(proto, len), " %s",
578				    inet_ntoa(ip->ip_dst));
579			break;
580
581		case IPPROTO_UDP:
582			len = snprintf(SNPARGS(proto, 0), "UDP %s",
583				inet_ntoa(ip->ip_src));
584			if (offset == 0)
585				snprintf(SNPARGS(proto, len), ":%d %s:%d",
586				    ntohs(udp->uh_sport),
587				    inet_ntoa(ip->ip_dst),
588				    ntohs(udp->uh_dport));
589			else
590				snprintf(SNPARGS(proto, len), " %s",
591				    inet_ntoa(ip->ip_dst));
592			break;
593
594		case IPPROTO_ICMP:
595			if (offset == 0)
596				len = snprintf(SNPARGS(proto, 0),
597				    "ICMP:%u.%u ",
598				    icmp->icmp_type, icmp->icmp_code);
599			else
600				len = snprintf(SNPARGS(proto, 0), "ICMP ");
601			len += snprintf(SNPARGS(proto, len), "%s",
602			    inet_ntoa(ip->ip_src));
603			snprintf(SNPARGS(proto, len), " %s",
604			    inet_ntoa(ip->ip_dst));
605			break;
606
607		default:
608			len = snprintf(SNPARGS(proto, 0), "P:%d %s", ip->ip_p,
609			    inet_ntoa(ip->ip_src));
610			snprintf(SNPARGS(proto, len), " %s",
611			    inet_ntoa(ip->ip_dst));
612			break;
613		}
614
615		if (ip_off & (IP_MF | IP_OFFMASK))
616			snprintf(SNPARGS(fragment, 0), " (frag %d:%d@%d%s)",
617			     ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
618			     offset << 3,
619			     (ip_off & IP_MF) ? "+" : "");
620	}
621	if (oif || m->m_pkthdr.rcvif)
622		log(LOG_SECURITY | LOG_INFO,
623		    "ipfw: %d %s %s %s via %s%d%s\n",
624		    f ? f->rulenum : -1,
625		    action, proto, oif ? "out" : "in",
626		    oif ? oif->if_name : m->m_pkthdr.rcvif->if_name,
627		    oif ? oif->if_unit : m->m_pkthdr.rcvif->if_unit,
628		    fragment);
629	else
630		log(LOG_SECURITY | LOG_INFO,
631		    "ipfw: %d %s %s [no if info]%s\n",
632		    f ? f->rulenum : -1,
633		    action, proto, fragment);
634	if (limit_reached)
635		log(LOG_SECURITY | LOG_NOTICE,
636		    "ipfw: limit %d reached on entry %d\n",
637		    limit_reached, f ? f->rulenum : -1);
638}
639
640/*
641 * IMPORTANT: the hash function for dynamic rules must be commutative
642 * in source and destination (ip,port), because rules are bidirectional
643 * and we want to find both in the same bucket.
644 */
645static __inline int
646hash_packet(struct ipfw_flow_id *id)
647{
648	u_int32_t i;
649
650	i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
651	i &= (curr_dyn_buckets - 1);
652	return i;
653}
654
655/**
656 * unlink a dynamic rule from a chain. prev is a pointer to
657 * the previous one, q is a pointer to the rule to delete,
658 * head is a pointer to the head of the queue.
659 * Modifies q and potentially also head.
660 */
661#define UNLINK_DYN_RULE(prev, head, q) {				\
662	ipfw_dyn_rule *old_q = q;					\
663									\
664	/* remove a refcount to the parent */				\
665	if (q->dyn_type == O_LIMIT)					\
666		q->parent->count--;					\
667	DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
668		(q->id.src_ip), (q->id.src_port),			\
669		(q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); )	\
670	if (prev != NULL)						\
671		prev->next = q = q->next;				\
672	else								\
673		head = q = q->next;					\
674	dyn_count--;							\
675	free(old_q, M_IPFW); }
676
677#define TIME_LEQ(a,b)       ((int)((a)-(b)) <= 0)
678
679/**
680 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
681 *
682 * If keep_me == NULL, rules are deleted even if not expired,
683 * otherwise only expired rules are removed.
684 *
685 * The value of the second parameter is also used to point to identify
686 * a rule we absolutely do not want to remove (e.g. because we are
687 * holding a reference to it -- this is the case with O_LIMIT_PARENT
688 * rules). The pointer is only used for comparison, so any non-null
689 * value will do.
690 */
691static void
692remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
693{
694	static u_int32_t last_remove = 0;
695
696#define FORCE (keep_me == NULL)
697
698	ipfw_dyn_rule *prev, *q;
699	int i, pass = 0, max_pass = 0;
700
701	if (ipfw_dyn_v == NULL || dyn_count == 0)
702		return;
703	/* do not expire more than once per second, it is useless */
704	if (!FORCE && last_remove == time_second)
705		return;
706	last_remove = time_second;
707
708	/*
709	 * because O_LIMIT refer to parent rules, during the first pass only
710	 * remove child and mark any pending LIMIT_PARENT, and remove
711	 * them in a second pass.
712	 */
713next_pass:
714	for (i = 0 ; i < curr_dyn_buckets ; i++) {
715		for (prev=NULL, q = ipfw_dyn_v[i] ; q ; ) {
716			/*
717			 * Logic can become complex here, so we split tests.
718			 */
719			if (q == keep_me)
720				goto next;
721			if (rule != NULL && rule != q->rule)
722				goto next; /* not the one we are looking for */
723			if (q->dyn_type == O_LIMIT_PARENT) {
724				/*
725				 * handle parent in the second pass,
726				 * record we need one.
727				 */
728				max_pass = 1;
729				if (pass == 0)
730					goto next;
731				if (FORCE && q->count != 0 ) {
732					/* XXX should not happen! */
733					printf("ipfw: OUCH! cannot remove rule,"
734					     " count %d\n", q->count);
735				}
736			} else {
737				if (!FORCE &&
738				    !TIME_LEQ( q->expire, time_second ))
739					goto next;
740			}
741			UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
742			continue;
743next:
744			prev=q;
745			q=q->next;
746		}
747	}
748	if (pass++ < max_pass)
749		goto next_pass;
750}
751
752
753/**
754 * lookup a dynamic rule.
755 */
756static ipfw_dyn_rule *
757lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
758	struct tcphdr *tcp)
759{
760	/*
761	 * stateful ipfw extensions.
762	 * Lookup into dynamic session queue
763	 */
764#define MATCH_REVERSE	0
765#define MATCH_FORWARD	1
766#define MATCH_NONE	2
767#define MATCH_UNKNOWN	3
768	int i, dir = MATCH_NONE;
769	ipfw_dyn_rule *prev, *q=NULL;
770
771	if (ipfw_dyn_v == NULL)
772		goto done;	/* not found */
773	i = hash_packet( pkt );
774	for (prev=NULL, q = ipfw_dyn_v[i] ; q != NULL ; ) {
775		if (q->dyn_type == O_LIMIT_PARENT)
776			goto next;
777		if (TIME_LEQ( q->expire, time_second)) { /* expire entry */
778			UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
779			continue;
780		}
781		if ( pkt->proto == q->id.proto) {
782			if (pkt->src_ip == q->id.src_ip &&
783			    pkt->dst_ip == q->id.dst_ip &&
784			    pkt->src_port == q->id.src_port &&
785			    pkt->dst_port == q->id.dst_port ) {
786				dir = MATCH_FORWARD;
787				break;
788			}
789			if (pkt->src_ip == q->id.dst_ip &&
790			    pkt->dst_ip == q->id.src_ip &&
791			    pkt->src_port == q->id.dst_port &&
792			    pkt->dst_port == q->id.src_port ) {
793				dir = MATCH_REVERSE;
794				break;
795			}
796		}
797next:
798		prev = q;
799		q = q->next;
800	}
801	if (q == NULL)
802		goto done; /* q = NULL, not found */
803
804	if ( prev != NULL) { /* found and not in front */
805		prev->next = q->next;
806		q->next = ipfw_dyn_v[i];
807		ipfw_dyn_v[i] = q;
808	}
809	if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
810		u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
811
812#define BOTH_SYN	(TH_SYN | (TH_SYN << 8))
813#define BOTH_FIN	(TH_FIN | (TH_FIN << 8))
814		q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
815		switch (q->state) {
816		case TH_SYN:				/* opening */
817			q->expire = time_second + dyn_syn_lifetime;
818			break;
819
820		case BOTH_SYN:			/* move to established */
821		case BOTH_SYN | TH_FIN :	/* one side tries to close */
822		case BOTH_SYN | (TH_FIN << 8) :
823 			if (tcp) {
824#define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
825			    u_int32_t ack = ntohl(tcp->th_ack);
826			    if (dir == MATCH_FORWARD) {
827				if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
828				    q->ack_fwd = ack;
829				else { /* ignore out-of-sequence */
830				    break;
831				}
832			    } else {
833				if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
834				    q->ack_rev = ack;
835				else { /* ignore out-of-sequence */
836				    break;
837				}
838			    }
839			}
840			q->expire = time_second + dyn_ack_lifetime;
841			break;
842
843		case BOTH_SYN | BOTH_FIN:	/* both sides closed */
844			if (dyn_fin_lifetime >= dyn_keepalive_period)
845				dyn_fin_lifetime = dyn_keepalive_period - 1;
846			q->expire = time_second + dyn_fin_lifetime;
847			break;
848
849		default:
850#if 0
851			/*
852			 * reset or some invalid combination, but can also
853			 * occur if we use keep-state the wrong way.
854			 */
855			if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
856				printf("invalid state: 0x%x\n", q->state);
857#endif
858			if (dyn_rst_lifetime >= dyn_keepalive_period)
859				dyn_rst_lifetime = dyn_keepalive_period - 1;
860			q->expire = time_second + dyn_rst_lifetime;
861			break;
862		}
863	} else if (pkt->proto == IPPROTO_UDP) {
864		q->expire = time_second + dyn_udp_lifetime;
865	} else {
866		/* other protocols */
867		q->expire = time_second + dyn_short_lifetime;
868	}
869done:
870	if (match_direction)
871		*match_direction = dir;
872	return q;
873}
874
875static void
876realloc_dynamic_table(void)
877{
878	/*
879	 * Try reallocation, make sure we have a power of 2 and do
880	 * not allow more than 64k entries. In case of overflow,
881	 * default to 1024.
882	 */
883
884	if (dyn_buckets > 65536)
885		dyn_buckets = 1024;
886	if ((dyn_buckets & (dyn_buckets-1)) != 0) { /* not a power of 2 */
887		dyn_buckets = curr_dyn_buckets; /* reset */
888		return;
889	}
890	curr_dyn_buckets = dyn_buckets;
891	if (ipfw_dyn_v != NULL)
892		free(ipfw_dyn_v, M_IPFW);
893	for (;;) {
894		ipfw_dyn_v = malloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
895		       M_IPFW, M_NOWAIT | M_ZERO);
896		if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
897			break;
898		curr_dyn_buckets /= 2;
899	}
900}
901
902/**
903 * Install state of type 'type' for a dynamic session.
904 * The hash table contains two type of rules:
905 * - regular rules (O_KEEP_STATE)
906 * - rules for sessions with limited number of sess per user
907 *   (O_LIMIT). When they are created, the parent is
908 *   increased by 1, and decreased on delete. In this case,
909 *   the third parameter is the parent rule and not the chain.
910 * - "parent" rules for the above (O_LIMIT_PARENT).
911 */
912static ipfw_dyn_rule *
913add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
914{
915	ipfw_dyn_rule *r;
916	int i;
917
918	if (ipfw_dyn_v == NULL ||
919	    (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
920		realloc_dynamic_table();
921		if (ipfw_dyn_v == NULL)
922			return NULL; /* failed ! */
923	}
924	i = hash_packet(id);
925
926	r = malloc(sizeof *r, M_IPFW, M_NOWAIT | M_ZERO);
927	if (r == NULL) {
928		printf ("ipfw: sorry cannot allocate state\n");
929		return NULL;
930	}
931
932	/* increase refcount on parent, and set pointer */
933	if (dyn_type == O_LIMIT) {
934		ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
935		if ( parent->dyn_type != O_LIMIT_PARENT)
936			panic("invalid parent");
937		parent->count++;
938		r->parent = parent;
939		rule = parent->rule;
940	}
941
942	r->id = *id;
943	r->expire = time_second + dyn_syn_lifetime;
944	r->rule = rule;
945	r->dyn_type = dyn_type;
946	r->pcnt = r->bcnt = 0;
947	r->count = 0;
948
949	r->bucket = i;
950	r->next = ipfw_dyn_v[i];
951	ipfw_dyn_v[i] = r;
952	dyn_count++;
953	DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
954	   dyn_type,
955	   (r->id.src_ip), (r->id.src_port),
956	   (r->id.dst_ip), (r->id.dst_port),
957	   dyn_count ); )
958	return r;
959}
960
961/**
962 * lookup dynamic parent rule using pkt and rule as search keys.
963 * If the lookup fails, then install one.
964 */
965static ipfw_dyn_rule *
966lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
967{
968	ipfw_dyn_rule *q;
969	int i;
970
971	if (ipfw_dyn_v) {
972		i = hash_packet( pkt );
973		for (q = ipfw_dyn_v[i] ; q != NULL ; q=q->next)
974			if (q->dyn_type == O_LIMIT_PARENT &&
975			    rule== q->rule &&
976			    pkt->proto == q->id.proto &&
977			    pkt->src_ip == q->id.src_ip &&
978			    pkt->dst_ip == q->id.dst_ip &&
979			    pkt->src_port == q->id.src_port &&
980			    pkt->dst_port == q->id.dst_port) {
981				q->expire = time_second + dyn_short_lifetime;
982				DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
983				return q;
984			}
985	}
986	return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
987}
988
989/**
990 * Install dynamic state for rule type cmd->o.opcode
991 *
992 * Returns 1 (failure) if state is not installed because of errors or because
993 * session limitations are enforced.
994 */
995static int
996install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
997	struct ip_fw_args *args)
998{
999	static int last_log;
1000
1001	ipfw_dyn_rule *q;
1002
1003	DEB(printf("ipfw: install state type %d 0x%08x %u -> 0x%08x %u\n",
1004	    cmd->o.opcode,
1005	    (args->f_id.src_ip), (args->f_id.src_port),
1006	    (args->f_id.dst_ip), (args->f_id.dst_port) );)
1007
1008	q = lookup_dyn_rule(&args->f_id, NULL, NULL);
1009
1010	if (q != NULL) { /* should never occur */
1011		if (last_log != time_second) {
1012			last_log = time_second;
1013			printf("ipfw: install_state: entry already present, done\n");
1014		}
1015		return 0;
1016	}
1017
1018	if (dyn_count >= dyn_max)
1019		/*
1020		 * Run out of slots, try to remove any expired rule.
1021		 */
1022		remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
1023
1024	if (dyn_count >= dyn_max) {
1025		if (last_log != time_second) {
1026			last_log = time_second;
1027			printf("ipfw: install_state: Too many dynamic rules\n");
1028		}
1029		return 1; /* cannot install, notify caller */
1030	}
1031
1032	switch (cmd->o.opcode) {
1033	case O_KEEP_STATE: /* bidir rule */
1034		add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
1035		break;
1036
1037	case O_LIMIT: /* limit number of sessions */
1038	    {
1039		u_int16_t limit_mask = cmd->limit_mask;
1040		struct ipfw_flow_id id;
1041		ipfw_dyn_rule *parent;
1042
1043		DEB(printf("ipfw: installing dyn-limit rule %d\n",
1044		    cmd->conn_limit);)
1045
1046		id.dst_ip = id.src_ip = 0;
1047		id.dst_port = id.src_port = 0;
1048		id.proto = args->f_id.proto;
1049
1050		if (limit_mask & DYN_SRC_ADDR)
1051			id.src_ip = args->f_id.src_ip;
1052		if (limit_mask & DYN_DST_ADDR)
1053			id.dst_ip = args->f_id.dst_ip;
1054		if (limit_mask & DYN_SRC_PORT)
1055			id.src_port = args->f_id.src_port;
1056		if (limit_mask & DYN_DST_PORT)
1057			id.dst_port = args->f_id.dst_port;
1058		parent = lookup_dyn_parent(&id, rule);
1059		if (parent == NULL) {
1060			printf("ipfw: add parent failed\n");
1061			return 1;
1062		}
1063		if (parent->count >= cmd->conn_limit) {
1064			/*
1065			 * See if we can remove some expired rule.
1066			 */
1067			remove_dyn_rule(rule, parent);
1068			if (parent->count >= cmd->conn_limit) {
1069				if (fw_verbose && last_log != time_second) {
1070					last_log = time_second;
1071					log(LOG_SECURITY | LOG_DEBUG,
1072					    "drop session, too many entries\n");
1073				}
1074				return 1;
1075			}
1076		}
1077		add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
1078	    }
1079		break;
1080	default:
1081		printf("ipfw: unknown dynamic rule type %u\n", cmd->o.opcode);
1082		return 1;
1083	}
1084	lookup_dyn_rule(&args->f_id, NULL, NULL); /* XXX just set lifetime */
1085	return 0;
1086}
1087
1088/*
1089 * Transmit a TCP packet, containing either a RST or a keepalive.
1090 * When flags & TH_RST, we are sending a RST packet, because of a
1091 * "reset" action matched the packet.
1092 * Otherwise we are sending a keepalive, and flags & TH_
1093 */
1094static void
1095send_pkt(struct ipfw_flow_id *id, u_int32_t seq, u_int32_t ack, int flags)
1096{
1097	struct mbuf *m;
1098	struct ip *ip;
1099	struct tcphdr *tcp;
1100	struct route sro;	/* fake route */
1101
1102	MGETHDR(m, M_DONTWAIT, MT_HEADER);
1103	if (m == 0)
1104		return;
1105	m->m_pkthdr.rcvif = (struct ifnet *)0;
1106	m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1107	m->m_data += max_linkhdr;
1108
1109	ip = mtod(m, struct ip *);
1110	bzero(ip, m->m_len);
1111	tcp = (struct tcphdr *)(ip + 1); /* no IP options */
1112	ip->ip_p = IPPROTO_TCP;
1113	tcp->th_off = 5;
1114	/*
1115	 * Assume we are sending a RST (or a keepalive in the reverse
1116	 * direction), swap src and destination addresses and ports.
1117	 */
1118	ip->ip_src.s_addr = htonl(id->dst_ip);
1119	ip->ip_dst.s_addr = htonl(id->src_ip);
1120	tcp->th_sport = htons(id->dst_port);
1121	tcp->th_dport = htons(id->src_port);
1122	if (flags & TH_RST) {	/* we are sending a RST */
1123		if (flags & TH_ACK) {
1124			tcp->th_seq = htonl(ack);
1125			tcp->th_ack = htonl(0);
1126			tcp->th_flags = TH_RST;
1127		} else {
1128			if (flags & TH_SYN)
1129				seq++;
1130			tcp->th_seq = htonl(0);
1131			tcp->th_ack = htonl(seq);
1132			tcp->th_flags = TH_RST | TH_ACK;
1133		}
1134	} else {
1135		/*
1136		 * We are sending a keepalive. flags & TH_SYN determines
1137		 * the direction, forward if set, reverse if clear.
1138		 * NOTE: seq and ack are always assumed to be correct
1139		 * as set by the caller. This may be confusing...
1140		 */
1141		if (flags & TH_SYN) {
1142			/*
1143			 * we have to rewrite the correct addresses!
1144			 */
1145			ip->ip_dst.s_addr = htonl(id->dst_ip);
1146			ip->ip_src.s_addr = htonl(id->src_ip);
1147			tcp->th_dport = htons(id->dst_port);
1148			tcp->th_sport = htons(id->src_port);
1149		}
1150		tcp->th_seq = htonl(seq);
1151		tcp->th_ack = htonl(ack);
1152		tcp->th_flags = TH_ACK;
1153	}
1154	/*
1155	 * set ip_len to the payload size so we can compute
1156	 * the tcp checksum on the pseudoheader
1157	 * XXX check this, could save a couple of words ?
1158	 */
1159	ip->ip_len = htons(sizeof(struct tcphdr));
1160	tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1161	/*
1162	 * now fill fields left out earlier
1163	 */
1164	ip->ip_ttl = ip_defttl;
1165	ip->ip_len = m->m_pkthdr.len;
1166	bzero (&sro, sizeof (sro));
1167	ip_rtaddr(ip->ip_dst, &sro);
1168	m->m_flags |= M_SKIP_FIREWALL;
1169	ip_output(m, NULL, &sro, 0, NULL, NULL);
1170	if (sro.ro_rt)
1171		RTFREE(sro.ro_rt);
1172}
1173
1174/*
1175 * sends a reject message, consuming the mbuf passed as an argument.
1176 */
1177static void
1178send_reject(struct ip_fw_args *args, int code, int offset, int ip_len)
1179{
1180
1181	if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
1182		/* We need the IP header in host order for icmp_error(). */
1183		if (args->eh != NULL) {
1184			struct ip *ip = mtod(args->m, struct ip *);
1185			ip->ip_len = ntohs(ip->ip_len);
1186			ip->ip_off = ntohs(ip->ip_off);
1187		}
1188		icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
1189	} else if (offset == 0 && args->f_id.proto == IPPROTO_TCP) {
1190		struct tcphdr *const tcp =
1191		    L3HDR(struct tcphdr, mtod(args->m, struct ip *));
1192		if ( (tcp->th_flags & TH_RST) == 0)
1193			send_pkt(&(args->f_id), ntohl(tcp->th_seq),
1194				ntohl(tcp->th_ack),
1195				tcp->th_flags | TH_RST);
1196		m_freem(args->m);
1197	} else
1198		m_freem(args->m);
1199	args->m = NULL;
1200}
1201
1202/**
1203 *
1204 * Given an ip_fw *, lookup_next_rule will return a pointer
1205 * to the next rule, which can be either the jump
1206 * target (for skipto instructions) or the next one in the list (in
1207 * all other cases including a missing jump target).
1208 * The result is also written in the "next_rule" field of the rule.
1209 * Backward jumps are not allowed, so start looking from the next
1210 * rule...
1211 *
1212 * This never returns NULL -- in case we do not have an exact match,
1213 * the next rule is returned. When the ruleset is changed,
1214 * pointers are flushed so we are always correct.
1215 */
1216
1217static struct ip_fw *
1218lookup_next_rule(struct ip_fw *me)
1219{
1220	struct ip_fw *rule = NULL;
1221	ipfw_insn *cmd;
1222
1223	/* look for action, in case it is a skipto */
1224	cmd = ACTION_PTR(me);
1225	if (cmd->opcode == O_LOG)
1226		cmd += F_LEN(cmd);
1227	if ( cmd->opcode == O_SKIPTO )
1228		for (rule = me->next; rule ; rule = rule->next)
1229			if (rule->rulenum >= cmd->arg1)
1230				break;
1231	if (rule == NULL)			/* failure or not a skipto */
1232		rule = me->next;
1233	me->next_rule = rule;
1234	return rule;
1235}
1236
1237/*
1238 * The main check routine for the firewall.
1239 *
1240 * All arguments are in args so we can modify them and return them
1241 * back to the caller.
1242 *
1243 * Parameters:
1244 *
1245 *	args->m	(in/out) The packet; we set to NULL when/if we nuke it.
1246 *		Starts with the IP header.
1247 *	args->eh (in)	Mac header if present, or NULL for layer3 packet.
1248 *	args->oif	Outgoing interface, or NULL if packet is incoming.
1249 *		The incoming interface is in the mbuf. (in)
1250 *	args->divert_rule (in/out)
1251 *		Skip up to the first rule past this rule number;
1252 *		upon return, non-zero port number for divert or tee.
1253 *
1254 *	args->rule	Pointer to the last matching rule (in/out)
1255 *	args->next_hop	Socket we are forwarding to (out).
1256 *	args->f_id	Addresses grabbed from the packet (out)
1257 *
1258 * Return value:
1259 *
1260 *	IP_FW_PORT_DENY_FLAG	the packet must be dropped.
1261 *	0	The packet is to be accepted and routed normally OR
1262 *      	the packet was denied/rejected and has been dropped;
1263 *		in the latter case, *m is equal to NULL upon return.
1264 *	port	Divert the packet to port, with these caveats:
1265 *
1266 *		- If IP_FW_PORT_TEE_FLAG is set, tee the packet instead
1267 *		  of diverting it (ie, 'ipfw tee').
1268 *
1269 *		- If IP_FW_PORT_DYNT_FLAG is set, interpret the lower
1270 *		  16 bits as a dummynet pipe number instead of diverting
1271 */
1272
1273static int
1274ipfw_chk(struct ip_fw_args *args)
1275{
1276	/*
1277	 * Local variables hold state during the processing of a packet.
1278	 *
1279	 * IMPORTANT NOTE: to speed up the processing of rules, there
1280	 * are some assumption on the values of the variables, which
1281	 * are documented here. Should you change them, please check
1282	 * the implementation of the various instructions to make sure
1283	 * that they still work.
1284	 *
1285	 * args->eh	The MAC header. It is non-null for a layer2
1286	 *	packet, it is NULL for a layer-3 packet.
1287	 *
1288	 * m | args->m	Pointer to the mbuf, as received from the caller.
1289	 *	It may change if ipfw_chk() does an m_pullup, or if it
1290	 *	consumes the packet because it calls send_reject().
1291	 *	XXX This has to change, so that ipfw_chk() never modifies
1292	 *	or consumes the buffer.
1293	 * ip	is simply an alias of the value of m, and it is kept
1294	 *	in sync with it (the packet is	supposed to start with
1295	 *	the ip header).
1296	 */
1297	struct mbuf *m = args->m;
1298	struct ip *ip = mtod(m, struct ip *);
1299
1300	/*
1301	 * oif | args->oif	If NULL, ipfw_chk has been called on the
1302	 *	inbound path (ether_input, bdg_forward, ip_input).
1303	 *	If non-NULL, ipfw_chk has been called on the outbound path
1304	 *	(ether_output, ip_output).
1305	 */
1306	struct ifnet *oif = args->oif;
1307
1308	struct ip_fw *f = NULL;		/* matching rule */
1309	int retval = 0;
1310
1311	/*
1312	 * hlen	The length of the IPv4 header.
1313	 *	hlen >0 means we have an IPv4 packet.
1314	 */
1315	u_int hlen = 0;		/* hlen >0 means we have an IP pkt */
1316
1317	/*
1318	 * offset	The offset of a fragment. offset != 0 means that
1319	 *	we have a fragment at this offset of an IPv4 packet.
1320	 *	offset == 0 means that (if this is an IPv4 packet)
1321	 *	this is the first or only fragment.
1322	 */
1323	u_short offset = 0;
1324
1325	/*
1326	 * Local copies of addresses. They are only valid if we have
1327	 * an IP packet.
1328	 *
1329	 * proto	The protocol. Set to 0 for non-ip packets,
1330	 *	or to the protocol read from the packet otherwise.
1331	 *	proto != 0 means that we have an IPv4 packet.
1332	 *
1333	 * src_port, dst_port	port numbers, in HOST format. Only
1334	 *	valid for TCP and UDP packets.
1335	 *
1336	 * src_ip, dst_ip	ip addresses, in NETWORK format.
1337	 *	Only valid for IPv4 packets.
1338	 */
1339	u_int8_t proto;
1340	u_int16_t src_port = 0, dst_port = 0;	/* NOTE: host format	*/
1341	struct in_addr src_ip, dst_ip;		/* NOTE: network format	*/
1342	u_int16_t ip_len=0;
1343	int pktlen;
1344	int dyn_dir = MATCH_UNKNOWN;
1345	ipfw_dyn_rule *q = NULL;
1346
1347	if (m->m_flags & M_SKIP_FIREWALL)
1348		return 0;	/* accept */
1349	/*
1350	 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
1351	 * 	MATCH_NONE when checked and not matched (q = NULL),
1352	 *	MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
1353	 */
1354
1355	pktlen = m->m_pkthdr.len;
1356	if (args->eh == NULL ||		/* layer 3 packet */
1357		( m->m_pkthdr.len >= sizeof(struct ip) &&
1358		    ntohs(args->eh->ether_type) == ETHERTYPE_IP))
1359			hlen = ip->ip_hl << 2;
1360
1361	/*
1362	 * Collect parameters into local variables for faster matching.
1363	 */
1364	if (hlen == 0) {	/* do not grab addresses for non-ip pkts */
1365		proto = args->f_id.proto = 0;	/* mark f_id invalid */
1366		goto after_ip_checks;
1367	}
1368
1369	proto = args->f_id.proto = ip->ip_p;
1370	src_ip = ip->ip_src;
1371	dst_ip = ip->ip_dst;
1372	if (args->eh != NULL) { /* layer 2 packets are as on the wire */
1373		offset = ntohs(ip->ip_off) & IP_OFFMASK;
1374		ip_len = ntohs(ip->ip_len);
1375	} else {
1376		offset = ip->ip_off & IP_OFFMASK;
1377		ip_len = ip->ip_len;
1378	}
1379	pktlen = ip_len < pktlen ? ip_len : pktlen;
1380
1381#define PULLUP_TO(len)						\
1382		do {						\
1383			if ((m)->m_len < (len)) {		\
1384			    args->m = m = m_pullup(m, (len));	\
1385			    if (m == 0)				\
1386				goto pullup_failed;		\
1387			    ip = mtod(m, struct ip *);		\
1388			}					\
1389		} while (0)
1390
1391	if (offset == 0) {
1392		switch (proto) {
1393		case IPPROTO_TCP:
1394		    {
1395			struct tcphdr *tcp;
1396
1397			PULLUP_TO(hlen + sizeof(struct tcphdr));
1398			tcp = L3HDR(struct tcphdr, ip);
1399			dst_port = tcp->th_dport;
1400			src_port = tcp->th_sport;
1401			args->f_id.flags = tcp->th_flags;
1402			}
1403			break;
1404
1405		case IPPROTO_UDP:
1406		    {
1407			struct udphdr *udp;
1408
1409			PULLUP_TO(hlen + sizeof(struct udphdr));
1410			udp = L3HDR(struct udphdr, ip);
1411			dst_port = udp->uh_dport;
1412			src_port = udp->uh_sport;
1413			}
1414			break;
1415
1416		case IPPROTO_ICMP:
1417			PULLUP_TO(hlen + 4);	/* type, code and checksum. */
1418			args->f_id.flags = L3HDR(struct icmp, ip)->icmp_type;
1419			break;
1420
1421		default:
1422			break;
1423		}
1424#undef PULLUP_TO
1425	}
1426
1427	args->f_id.src_ip = ntohl(src_ip.s_addr);
1428	args->f_id.dst_ip = ntohl(dst_ip.s_addr);
1429	args->f_id.src_port = src_port = ntohs(src_port);
1430	args->f_id.dst_port = dst_port = ntohs(dst_port);
1431
1432after_ip_checks:
1433	if (args->rule) {
1434		/*
1435		 * Packet has already been tagged. Look for the next rule
1436		 * to restart processing.
1437		 *
1438		 * If fw_one_pass != 0 then just accept it.
1439		 * XXX should not happen here, but optimized out in
1440		 * the caller.
1441		 */
1442		if (fw_one_pass)
1443			return 0;
1444
1445		f = args->rule->next_rule;
1446		if (f == NULL)
1447			f = lookup_next_rule(args->rule);
1448	} else {
1449		/*
1450		 * Find the starting rule. It can be either the first
1451		 * one, or the one after divert_rule if asked so.
1452		 */
1453		int skipto = args->divert_rule;
1454
1455		f = layer3_chain;
1456		if (args->eh == NULL && skipto != 0) {
1457			if (skipto >= IPFW_DEFAULT_RULE)
1458				return(IP_FW_PORT_DENY_FLAG); /* invalid */
1459			while (f && f->rulenum <= skipto)
1460				f = f->next;
1461			if (f == NULL)	/* drop packet */
1462				return(IP_FW_PORT_DENY_FLAG);
1463		}
1464	}
1465	args->divert_rule = 0;	/* reset to avoid confusion later */
1466
1467	/*
1468	 * Now scan the rules, and parse microinstructions for each rule.
1469	 */
1470	for (; f; f = f->next) {
1471		int l, cmdlen;
1472		ipfw_insn *cmd;
1473		int skip_or; /* skip rest of OR block */
1474
1475again:
1476		if (set_disable & (1 << f->set) )
1477			continue;
1478
1479		skip_or = 0;
1480		for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
1481		    l -= cmdlen, cmd += cmdlen) {
1482			int match;
1483
1484			/*
1485			 * check_body is a jump target used when we find a
1486			 * CHECK_STATE, and need to jump to the body of
1487			 * the target rule.
1488			 */
1489
1490check_body:
1491			cmdlen = F_LEN(cmd);
1492			/*
1493			 * An OR block (insn_1 || .. || insn_n) has the
1494			 * F_OR bit set in all but the last instruction.
1495			 * The first match will set "skip_or", and cause
1496			 * the following instructions to be skipped until
1497			 * past the one with the F_OR bit clear.
1498			 */
1499			if (skip_or) {		/* skip this instruction */
1500				if ((cmd->len & F_OR) == 0)
1501					skip_or = 0;	/* next one is good */
1502				continue;
1503			}
1504			match = 0; /* set to 1 if we succeed */
1505
1506			switch (cmd->opcode) {
1507			/*
1508			 * The first set of opcodes compares the packet's
1509			 * fields with some pattern, setting 'match' if a
1510			 * match is found. At the end of the loop there is
1511			 * logic to deal with F_NOT and F_OR flags associated
1512			 * with the opcode.
1513			 */
1514			case O_NOP:
1515				match = 1;
1516				break;
1517
1518			case O_FORWARD_MAC:
1519				printf("ipfw: opcode %d unimplemented\n",
1520				    cmd->opcode);
1521				break;
1522
1523			case O_GID:
1524			case O_UID:
1525				/*
1526				 * We only check offset == 0 && proto != 0,
1527				 * as this ensures that we have an IPv4
1528				 * packet with the ports info.
1529				 */
1530				if (offset!=0)
1531					break;
1532			    {
1533				struct inpcbinfo *pi;
1534				int wildcard;
1535				struct inpcb *pcb;
1536
1537				if (proto == IPPROTO_TCP) {
1538					wildcard = 0;
1539					pi = &tcbinfo;
1540				} else if (proto == IPPROTO_UDP) {
1541					wildcard = 1;
1542					pi = &udbinfo;
1543				} else
1544					break;
1545
1546				pcb =  (oif) ?
1547					in_pcblookup_hash(pi,
1548					    dst_ip, htons(dst_port),
1549					    src_ip, htons(src_port),
1550					    wildcard, oif) :
1551					in_pcblookup_hash(pi,
1552					    src_ip, htons(src_port),
1553					    dst_ip, htons(dst_port),
1554					    wildcard, NULL);
1555
1556				if (pcb == NULL || pcb->inp_socket == NULL)
1557					break;
1558#if __FreeBSD_version < 500034
1559#define socheckuid(a,b)	((a)->so_cred->cr_uid != (b))
1560#endif
1561				if (cmd->opcode == O_UID) {
1562					match =
1563					  !socheckuid(pcb->inp_socket,
1564					   (uid_t)((ipfw_insn_u32 *)cmd)->d[0]);
1565				} else  {
1566					match = groupmember(
1567					    (uid_t)((ipfw_insn_u32 *)cmd)->d[0],
1568					    pcb->inp_socket->so_cred);
1569				}
1570			    }
1571				break;
1572
1573			case O_RECV:
1574				match = iface_match(m->m_pkthdr.rcvif,
1575				    (ipfw_insn_if *)cmd);
1576				break;
1577
1578			case O_XMIT:
1579				match = iface_match(oif, (ipfw_insn_if *)cmd);
1580				break;
1581
1582			case O_VIA:
1583				match = iface_match(oif ? oif :
1584				    m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
1585				break;
1586
1587			case O_MACADDR2:
1588				if (args->eh != NULL) {	/* have MAC header */
1589					u_int32_t *want = (u_int32_t *)
1590						((ipfw_insn_mac *)cmd)->addr;
1591					u_int32_t *mask = (u_int32_t *)
1592						((ipfw_insn_mac *)cmd)->mask;
1593					u_int32_t *hdr = (u_int32_t *)args->eh;
1594
1595					match =
1596					    ( want[0] == (hdr[0] & mask[0]) &&
1597					      want[1] == (hdr[1] & mask[1]) &&
1598					      want[2] == (hdr[2] & mask[2]) );
1599				}
1600				break;
1601
1602			case O_MAC_TYPE:
1603				if (args->eh != NULL) {
1604					u_int16_t t =
1605					    ntohs(args->eh->ether_type);
1606					u_int16_t *p =
1607					    ((ipfw_insn_u16 *)cmd)->ports;
1608					int i;
1609
1610					for (i = cmdlen - 1; !match && i>0;
1611					    i--, p += 2)
1612						match = (t>=p[0] && t<=p[1]);
1613				}
1614				break;
1615
1616			case O_FRAG:
1617				match = (hlen > 0 && offset != 0);
1618				break;
1619
1620			case O_IN:	/* "out" is "not in" */
1621				match = (oif == NULL);
1622				break;
1623
1624			case O_LAYER2:
1625				match = (args->eh != NULL);
1626				break;
1627
1628			case O_PROTO:
1629				/*
1630				 * We do not allow an arg of 0 so the
1631				 * check of "proto" only suffices.
1632				 */
1633				match = (proto == cmd->arg1);
1634				break;
1635
1636			case O_IP_SRC:
1637				match = (hlen > 0 &&
1638				    ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1639				    src_ip.s_addr);
1640				break;
1641
1642			case O_IP_SRC_MASK:
1643				match = (hlen > 0 &&
1644				    ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1645				     (src_ip.s_addr &
1646				     ((ipfw_insn_ip *)cmd)->mask.s_addr));
1647				break;
1648
1649			case O_IP_SRC_ME:
1650				if (hlen > 0) {
1651					struct ifnet *tif;
1652
1653					INADDR_TO_IFP(src_ip, tif);
1654					match = (tif != NULL);
1655				}
1656				break;
1657
1658			case O_IP_DST_SET:
1659			case O_IP_SRC_SET:
1660				if (hlen > 0) {
1661					u_int32_t *d = (u_int32_t *)(cmd+1);
1662					u_int32_t addr =
1663					    cmd->opcode == O_IP_DST_SET ?
1664						args->f_id.dst_ip :
1665						args->f_id.src_ip;
1666
1667					    if (addr < d[0])
1668						    break;
1669					    addr -= d[0]; /* subtract base */
1670					    match = (addr < cmd->arg1) &&
1671						( d[ 1 + (addr>>5)] &
1672						  (1<<(addr & 0x1f)) );
1673				}
1674				break;
1675
1676			case O_IP_DST:
1677				match = (hlen > 0 &&
1678				    ((ipfw_insn_ip *)cmd)->addr.s_addr ==
1679				    dst_ip.s_addr);
1680				break;
1681
1682			case O_IP_DST_MASK:
1683				match = (hlen > 0) &&
1684				    (((ipfw_insn_ip *)cmd)->addr.s_addr ==
1685				     (dst_ip.s_addr &
1686				     ((ipfw_insn_ip *)cmd)->mask.s_addr));
1687				break;
1688
1689			case O_IP_DST_ME:
1690				if (hlen > 0) {
1691					struct ifnet *tif;
1692
1693					INADDR_TO_IFP(dst_ip, tif);
1694					match = (tif != NULL);
1695				}
1696				break;
1697
1698			case O_IP_SRCPORT:
1699			case O_IP_DSTPORT:
1700				/*
1701				 * offset == 0 && proto != 0 is enough
1702				 * to guarantee that we have an IPv4
1703				 * packet with port info.
1704				 */
1705				if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
1706				    && offset == 0) {
1707					u_int16_t x =
1708					    (cmd->opcode == O_IP_SRCPORT) ?
1709						src_port : dst_port ;
1710					u_int16_t *p =
1711					    ((ipfw_insn_u16 *)cmd)->ports;
1712					int i;
1713
1714					for (i = cmdlen - 1; !match && i>0;
1715					    i--, p += 2)
1716						match = (x>=p[0] && x<=p[1]);
1717				}
1718				break;
1719
1720			case O_ICMPTYPE:
1721				match = (offset == 0 && proto==IPPROTO_ICMP &&
1722				    icmptype_match(ip, (ipfw_insn_u32 *)cmd) );
1723				break;
1724
1725			case O_IPOPT:
1726				match = (hlen > 0 && ipopts_match(ip, cmd) );
1727				break;
1728
1729			case O_IPVER:
1730				match = (hlen > 0 && cmd->arg1 == ip->ip_v);
1731				break;
1732
1733			case O_IPTTL:
1734				match = (hlen > 0 && cmd->arg1 == ip->ip_ttl);
1735				break;
1736
1737			case O_IPID:
1738				match = (hlen > 0 &&
1739				    cmd->arg1 == ntohs(ip->ip_id));
1740				break;
1741
1742			case O_IPLEN:
1743				match = (hlen > 0 && cmd->arg1 == ip_len);
1744				break;
1745
1746			case O_IPPRECEDENCE:
1747				match = (hlen > 0 &&
1748				    (cmd->arg1 == (ip->ip_tos & 0xe0)) );
1749				break;
1750
1751			case O_IPTOS:
1752				match = (hlen > 0 &&
1753				    flags_match(cmd, ip->ip_tos));
1754				break;
1755
1756			case O_TCPFLAGS:
1757				match = (proto == IPPROTO_TCP && offset == 0 &&
1758				    flags_match(cmd,
1759					L3HDR(struct tcphdr,ip)->th_flags));
1760				break;
1761
1762			case O_TCPOPTS:
1763				match = (proto == IPPROTO_TCP && offset == 0 &&
1764				    tcpopts_match(ip, cmd));
1765				break;
1766
1767			case O_TCPSEQ:
1768				match = (proto == IPPROTO_TCP && offset == 0 &&
1769				    ((ipfw_insn_u32 *)cmd)->d[0] ==
1770					L3HDR(struct tcphdr,ip)->th_seq);
1771				break;
1772
1773			case O_TCPACK:
1774				match = (proto == IPPROTO_TCP && offset == 0 &&
1775				    ((ipfw_insn_u32 *)cmd)->d[0] ==
1776					L3HDR(struct tcphdr,ip)->th_ack);
1777				break;
1778
1779			case O_TCPWIN:
1780				match = (proto == IPPROTO_TCP && offset == 0 &&
1781				    cmd->arg1 ==
1782					L3HDR(struct tcphdr,ip)->th_win);
1783				break;
1784
1785			case O_ESTAB:
1786				/* reject packets which have SYN only */
1787				/* XXX should i also check for TH_ACK ? */
1788				match = (proto == IPPROTO_TCP && offset == 0 &&
1789				    (L3HDR(struct tcphdr,ip)->th_flags &
1790				     (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
1791				break;
1792
1793			case O_LOG:
1794				if (fw_verbose)
1795					ipfw_log(f, hlen, args->eh, m, oif);
1796				match = 1;
1797				break;
1798
1799			case O_PROB:
1800				match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
1801				break;
1802
1803			case O_VERREVPATH:
1804				/* Outgoing packets automatically pass/match */
1805				match = ((oif != NULL) ||
1806				    (m->m_pkthdr.rcvif == NULL) ||
1807				    verify_rev_path(src_ip, m->m_pkthdr.rcvif));
1808				break;
1809
1810			/*
1811			 * The second set of opcodes represents 'actions',
1812			 * i.e. the terminal part of a rule once the packet
1813			 * matches all previous patterns.
1814			 * Typically there is only one action for each rule,
1815			 * and the opcode is stored at the end of the rule
1816			 * (but there are exceptions -- see below).
1817			 *
1818			 * In general, here we set retval and terminate the
1819			 * outer loop (would be a 'break 3' in some language,
1820			 * but we need to do a 'goto done').
1821			 *
1822			 * Exceptions:
1823			 * O_COUNT and O_SKIPTO actions:
1824			 *   instead of terminating, we jump to the next rule
1825			 *   ('goto next_rule', equivalent to a 'break 2'),
1826			 *   or to the SKIPTO target ('goto again' after
1827			 *   having set f, cmd and l), respectively.
1828			 *
1829			 * O_LIMIT and O_KEEP_STATE: these opcodes are
1830			 *   not real 'actions', and are stored right
1831			 *   before the 'action' part of the rule.
1832			 *   These opcodes try to install an entry in the
1833			 *   state tables; if successful, we continue with
1834			 *   the next opcode (match=1; break;), otherwise
1835			 *   the packet *   must be dropped
1836			 *   ('goto done' after setting retval);
1837			 *
1838			 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
1839			 *   cause a lookup of the state table, and a jump
1840			 *   to the 'action' part of the parent rule
1841			 *   ('goto check_body') if an entry is found, or
1842			 *   (CHECK_STATE only) a jump to the next rule if
1843			 *   the entry is not found ('goto next_rule').
1844			 *   The result of the lookup is cached to make
1845			 *   further instances of these opcodes are
1846			 *   effectively NOPs.
1847			 */
1848			case O_LIMIT:
1849			case O_KEEP_STATE:
1850				if (install_state(f,
1851				    (ipfw_insn_limit *)cmd, args)) {
1852					retval = IP_FW_PORT_DENY_FLAG;
1853					goto done; /* error/limit violation */
1854				}
1855				match = 1;
1856				break;
1857
1858			case O_PROBE_STATE:
1859			case O_CHECK_STATE:
1860				/*
1861				 * dynamic rules are checked at the first
1862				 * keep-state or check-state occurrence,
1863				 * with the result being stored in dyn_dir.
1864				 * The compiler introduces a PROBE_STATE
1865				 * instruction for us when we have a
1866				 * KEEP_STATE (because PROBE_STATE needs
1867				 * to be run first).
1868				 */
1869				if (dyn_dir == MATCH_UNKNOWN &&
1870				    (q = lookup_dyn_rule(&args->f_id,
1871				     &dyn_dir, proto == IPPROTO_TCP ?
1872					L3HDR(struct tcphdr, ip) : NULL))
1873					!= NULL) {
1874					/*
1875					 * Found dynamic entry, update stats
1876					 * and jump to the 'action' part of
1877					 * the parent rule.
1878					 */
1879					q->pcnt++;
1880					q->bcnt += pktlen;
1881					f = q->rule;
1882					cmd = ACTION_PTR(f);
1883					l = f->cmd_len - f->act_ofs;
1884					goto check_body;
1885				}
1886				/*
1887				 * Dynamic entry not found. If CHECK_STATE,
1888				 * skip to next rule, if PROBE_STATE just
1889				 * ignore and continue with next opcode.
1890				 */
1891				if (cmd->opcode == O_CHECK_STATE)
1892					goto next_rule;
1893				match = 1;
1894				break;
1895
1896			case O_ACCEPT:
1897				retval = 0;	/* accept */
1898				goto done;
1899
1900			case O_PIPE:
1901			case O_QUEUE:
1902				args->rule = f; /* report matching rule */
1903				retval = cmd->arg1 | IP_FW_PORT_DYNT_FLAG;
1904				goto done;
1905
1906			case O_DIVERT:
1907			case O_TEE:
1908				if (args->eh) /* not on layer 2 */
1909					break;
1910				args->divert_rule = f->rulenum;
1911				retval = (cmd->opcode == O_DIVERT) ?
1912				    cmd->arg1 :
1913				    cmd->arg1 | IP_FW_PORT_TEE_FLAG;
1914				goto done;
1915
1916			case O_COUNT:
1917			case O_SKIPTO:
1918				f->pcnt++;	/* update stats */
1919				f->bcnt += pktlen;
1920				f->timestamp = time_second;
1921				if (cmd->opcode == O_COUNT)
1922					goto next_rule;
1923				/* handle skipto */
1924				if (f->next_rule == NULL)
1925					lookup_next_rule(f);
1926				f = f->next_rule;
1927				goto again;
1928
1929			case O_REJECT:
1930				/*
1931				 * Drop the packet and send a reject notice
1932				 * if the packet is not ICMP (or is an ICMP
1933				 * query), and it is not multicast/broadcast.
1934				 */
1935				if (hlen > 0 &&
1936				    (proto != IPPROTO_ICMP ||
1937				     is_icmp_query(ip)) &&
1938				    !(m->m_flags & (M_BCAST|M_MCAST)) &&
1939				    !IN_MULTICAST(dst_ip.s_addr)) {
1940					send_reject(args, cmd->arg1,
1941					    offset,ip_len);
1942					m = args->m;
1943				}
1944				/* FALLTHROUGH */
1945			case O_DENY:
1946				retval = IP_FW_PORT_DENY_FLAG;
1947				goto done;
1948
1949			case O_FORWARD_IP:
1950				if (args->eh)	/* not valid on layer2 pkts */
1951					break;
1952				if (!q || dyn_dir == MATCH_FORWARD)
1953					args->next_hop =
1954					    &((ipfw_insn_sa *)cmd)->sa;
1955				retval = 0;
1956				goto done;
1957
1958			default:
1959				panic("-- unknown opcode %d\n", cmd->opcode);
1960			} /* end of switch() on opcodes */
1961
1962			if (cmd->len & F_NOT)
1963				match = !match;
1964
1965			if (match) {
1966				if (cmd->len & F_OR)
1967					skip_or = 1;
1968			} else {
1969				if (!(cmd->len & F_OR)) /* not an OR block, */
1970					break;		/* try next rule    */
1971			}
1972
1973		}	/* end of inner for, scan opcodes */
1974
1975next_rule:;		/* try next rule		*/
1976
1977	}		/* end of outer for, scan rules */
1978	printf("ipfw: ouch!, skip past end of rules, denying packet\n");
1979	return(IP_FW_PORT_DENY_FLAG);
1980
1981done:
1982	/* Update statistics */
1983	f->pcnt++;
1984	f->bcnt += pktlen;
1985	f->timestamp = time_second;
1986	return retval;
1987
1988pullup_failed:
1989	if (fw_verbose)
1990		printf("ipfw: pullup failed\n");
1991	return(IP_FW_PORT_DENY_FLAG);
1992}
1993
1994/*
1995 * When a rule is added/deleted, clear the next_rule pointers in all rules.
1996 * These will be reconstructed on the fly as packets are matched.
1997 * Must be called at splimp().
1998 */
1999static void
2000flush_rule_ptrs(void)
2001{
2002	struct ip_fw *rule;
2003
2004	for (rule = layer3_chain; rule; rule = rule->next)
2005		rule->next_rule = NULL;
2006}
2007
2008/*
2009 * When pipes/queues are deleted, clear the "pipe_ptr" pointer to a given
2010 * pipe/queue, or to all of them (match == NULL).
2011 * Must be called at splimp().
2012 */
2013void
2014flush_pipe_ptrs(struct dn_flow_set *match)
2015{
2016	struct ip_fw *rule;
2017
2018	for (rule = layer3_chain; rule; rule = rule->next) {
2019		ipfw_insn_pipe *cmd = (ipfw_insn_pipe *)ACTION_PTR(rule);
2020
2021		if (cmd->o.opcode != O_PIPE && cmd->o.opcode != O_QUEUE)
2022			continue;
2023		/*
2024		 * XXX Use bcmp/bzero to handle pipe_ptr to overcome
2025		 * possible alignment problems on 64-bit architectures.
2026		 * This code is seldom used so we do not worry too
2027		 * much about efficiency.
2028		 */
2029		if (match == NULL ||
2030		    !bcmp(&cmd->pipe_ptr, &match, sizeof(match)) )
2031			bzero(&cmd->pipe_ptr, sizeof(cmd->pipe_ptr));
2032	}
2033}
2034
2035/*
2036 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
2037 * possibly create a rule number and add the rule to the list.
2038 * Update the rule_number in the input struct so the caller knows it as well.
2039 */
2040static int
2041add_rule(struct ip_fw **head, struct ip_fw *input_rule)
2042{
2043	struct ip_fw *rule, *f, *prev;
2044	int s;
2045	int l = RULESIZE(input_rule);
2046
2047	if (*head == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
2048		return (EINVAL);
2049
2050	rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
2051	if (rule == NULL)
2052		return (ENOSPC);
2053
2054	bcopy(input_rule, rule, l);
2055
2056	rule->next = NULL;
2057	rule->next_rule = NULL;
2058
2059	rule->pcnt = 0;
2060	rule->bcnt = 0;
2061	rule->timestamp = 0;
2062
2063	s = splimp();
2064
2065	if (*head == NULL) {	/* default rule */
2066		*head = rule;
2067		goto done;
2068        }
2069
2070	/*
2071	 * If rulenum is 0, find highest numbered rule before the
2072	 * default rule, and add autoinc_step
2073	 */
2074	if (autoinc_step < 1)
2075		autoinc_step = 1;
2076	else if (autoinc_step > 1000)
2077		autoinc_step = 1000;
2078	if (rule->rulenum == 0) {
2079		/*
2080		 * locate the highest numbered rule before default
2081		 */
2082		for (f = *head; f; f = f->next) {
2083			if (f->rulenum == IPFW_DEFAULT_RULE)
2084				break;
2085			rule->rulenum = f->rulenum;
2086		}
2087		if (rule->rulenum < IPFW_DEFAULT_RULE - autoinc_step)
2088			rule->rulenum += autoinc_step;
2089		input_rule->rulenum = rule->rulenum;
2090	}
2091
2092	/*
2093	 * Now insert the new rule in the right place in the sorted list.
2094	 */
2095	for (prev = NULL, f = *head; f; prev = f, f = f->next) {
2096		if (f->rulenum > rule->rulenum) { /* found the location */
2097			if (prev) {
2098				rule->next = f;
2099				prev->next = rule;
2100			} else { /* head insert */
2101				rule->next = *head;
2102				*head = rule;
2103			}
2104			break;
2105		}
2106	}
2107	flush_rule_ptrs();
2108done:
2109	static_count++;
2110	static_len += l;
2111	splx(s);
2112	DEB(printf("ipfw: installed rule %d, static count now %d\n",
2113		rule->rulenum, static_count);)
2114	return (0);
2115}
2116
2117/**
2118 * Free storage associated with a static rule (including derived
2119 * dynamic rules).
2120 * The caller is in charge of clearing rule pointers to avoid
2121 * dangling pointers.
2122 * @return a pointer to the next entry.
2123 * Arguments are not checked, so they better be correct.
2124 * Must be called at splimp().
2125 */
2126static struct ip_fw *
2127delete_rule(struct ip_fw **head, struct ip_fw *prev, struct ip_fw *rule)
2128{
2129	struct ip_fw *n;
2130	int l = RULESIZE(rule);
2131
2132	n = rule->next;
2133	remove_dyn_rule(rule, NULL /* force removal */);
2134	if (prev == NULL)
2135		*head = n;
2136	else
2137		prev->next = n;
2138	static_count--;
2139	static_len -= l;
2140
2141	if (DUMMYNET_LOADED)
2142		ip_dn_ruledel_ptr(rule);
2143	free(rule, M_IPFW);
2144	return n;
2145}
2146
2147/*
2148 * Deletes all rules from a chain (including the default rule
2149 * if the second argument is set).
2150 * Must be called at splimp().
2151 */
2152static void
2153free_chain(struct ip_fw **chain, int kill_default)
2154{
2155	struct ip_fw *rule;
2156
2157	flush_rule_ptrs(); /* more efficient to do outside the loop */
2158
2159	while ( (rule = *chain) != NULL &&
2160	    (kill_default || rule->rulenum != IPFW_DEFAULT_RULE) )
2161		delete_rule(chain, NULL, rule);
2162}
2163
2164/**
2165 * Remove all rules with given number, and also do set manipulation.
2166 *
2167 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
2168 * the next 8 bits are the new set, the top 8 bits are the command:
2169 *
2170 *	0	delete rules with given number
2171 *	1	delete rules with given set number
2172 *	2	move rules with given number to new set
2173 *	3	move rules with given set number to new set
2174 *	4	swap sets with given numbers
2175 */
2176static int
2177del_entry(struct ip_fw **chain, u_int32_t arg)
2178{
2179	struct ip_fw *prev, *rule;
2180	int s;
2181	u_int16_t rulenum;
2182	u_int8_t cmd, new_set;
2183
2184	rulenum = arg & 0xffff;
2185	cmd = (arg >> 24) & 0xff;
2186	new_set = (arg >> 16) & 0xff;
2187
2188	if (cmd > 4)
2189		return EINVAL;
2190	if (new_set > 30)
2191		return EINVAL;
2192	if (cmd == 0 || cmd == 2) {
2193		if (rulenum == IPFW_DEFAULT_RULE)
2194			return EINVAL;
2195	} else {
2196		if (rulenum > 30)
2197			return EINVAL;
2198	}
2199
2200	switch (cmd) {
2201	case 0:	/* delete rules with given number */
2202		/*
2203		 * locate first rule to delete
2204		 */
2205		for (prev = NULL, rule = *chain;
2206		    rule && rule->rulenum < rulenum;
2207		     prev = rule, rule = rule->next)
2208			;
2209		if (rule->rulenum != rulenum)
2210			return EINVAL;
2211
2212		s = splimp(); /* no access to rules while removing */
2213		/*
2214		 * flush pointers outside the loop, then delete all matching
2215		 * rules. prev remains the same throughout the cycle.
2216		 */
2217		flush_rule_ptrs();
2218		while (rule && rule->rulenum == rulenum)
2219			rule = delete_rule(chain, prev, rule);
2220		splx(s);
2221		break;
2222
2223	case 1:	/* delete all rules with given set number */
2224		s = splimp();
2225		flush_rule_ptrs();
2226		for (prev = NULL, rule = *chain; rule ; )
2227			if (rule->set == rulenum)
2228				rule = delete_rule(chain, prev, rule);
2229			else {
2230				prev = rule;
2231				rule = rule->next;
2232			}
2233		splx(s);
2234		break;
2235
2236	case 2:	/* move rules with given number to new set */
2237		s = splimp();
2238		for (rule = *chain; rule ; rule = rule->next)
2239			if (rule->rulenum == rulenum)
2240				rule->set = new_set;
2241		splx(s);
2242		break;
2243
2244	case 3: /* move rules with given set number to new set */
2245		s = splimp();
2246		for (rule = *chain; rule ; rule = rule->next)
2247			if (rule->set == rulenum)
2248				rule->set = new_set;
2249		splx(s);
2250		break;
2251
2252	case 4: /* swap two sets */
2253		s = splimp();
2254		for (rule = *chain; rule ; rule = rule->next)
2255			if (rule->set == rulenum)
2256				rule->set = new_set;
2257			else if (rule->set == new_set)
2258				rule->set = rulenum;
2259		splx(s);
2260		break;
2261	}
2262	return 0;
2263}
2264
2265/*
2266 * Clear counters for a specific rule.
2267 */
2268static void
2269clear_counters(struct ip_fw *rule, int log_only)
2270{
2271	ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
2272
2273	if (log_only == 0) {
2274		rule->bcnt = rule->pcnt = 0;
2275		rule->timestamp = 0;
2276	}
2277	if (l->o.opcode == O_LOG)
2278		l->log_left = l->max_log;
2279}
2280
2281/**
2282 * Reset some or all counters on firewall rules.
2283 * @arg frwl is null to clear all entries, or contains a specific
2284 * rule number.
2285 * @arg log_only is 1 if we only want to reset logs, zero otherwise.
2286 */
2287static int
2288zero_entry(int rulenum, int log_only)
2289{
2290	struct ip_fw *rule;
2291	int s;
2292	char *msg;
2293
2294	if (rulenum == 0) {
2295		s = splimp();
2296		norule_counter = 0;
2297		for (rule = layer3_chain; rule; rule = rule->next)
2298			clear_counters(rule, log_only);
2299		splx(s);
2300		msg = log_only ? "ipfw: All logging counts reset.\n" :
2301				"ipfw: Accounting cleared.\n";
2302	} else {
2303		int cleared = 0;
2304		/*
2305		 * We can have multiple rules with the same number, so we
2306		 * need to clear them all.
2307		 */
2308		for (rule = layer3_chain; rule; rule = rule->next)
2309			if (rule->rulenum == rulenum) {
2310				s = splimp();
2311				while (rule && rule->rulenum == rulenum) {
2312					clear_counters(rule, log_only);
2313					rule = rule->next;
2314				}
2315				splx(s);
2316				cleared = 1;
2317				break;
2318			}
2319		if (!cleared)	/* we did not find any matching rules */
2320			return (EINVAL);
2321		msg = log_only ? "ipfw: Entry %d logging count reset.\n" :
2322				"ipfw: Entry %d cleared.\n";
2323	}
2324	if (fw_verbose)
2325		log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
2326	return (0);
2327}
2328
2329/*
2330 * Check validity of the structure before insert.
2331 * Fortunately rules are simple, so this mostly need to check rule sizes.
2332 */
2333static int
2334check_ipfw_struct(struct ip_fw *rule, int size)
2335{
2336	int l, cmdlen = 0;
2337	int have_action=0;
2338	ipfw_insn *cmd;
2339
2340	if (size < sizeof(*rule)) {
2341		printf("ipfw: rule too short\n");
2342		return (EINVAL);
2343	}
2344	/* first, check for valid size */
2345	l = RULESIZE(rule);
2346	if (l != size) {
2347		printf("ipfw: size mismatch (have %d want %d)\n", size, l);
2348		return (EINVAL);
2349	}
2350	/*
2351	 * Now go for the individual checks. Very simple ones, basically only
2352	 * instruction sizes.
2353	 */
2354	for (l = rule->cmd_len, cmd = rule->cmd ;
2355			l > 0 ; l -= cmdlen, cmd += cmdlen) {
2356		cmdlen = F_LEN(cmd);
2357		if (cmdlen > l) {
2358			printf("ipfw: opcode %d size truncated\n",
2359			    cmd->opcode);
2360			return EINVAL;
2361		}
2362		DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
2363		switch (cmd->opcode) {
2364		case O_NOP:
2365		case O_PROBE_STATE:
2366		case O_KEEP_STATE:
2367		case O_PROTO:
2368		case O_IP_SRC_ME:
2369		case O_IP_DST_ME:
2370		case O_LAYER2:
2371		case O_IN:
2372		case O_FRAG:
2373		case O_IPOPT:
2374		case O_IPLEN:
2375		case O_IPID:
2376		case O_IPTOS:
2377		case O_IPPRECEDENCE:
2378		case O_IPTTL:
2379		case O_IPVER:
2380		case O_TCPWIN:
2381		case O_TCPFLAGS:
2382		case O_TCPOPTS:
2383		case O_ESTAB:
2384		case O_VERREVPATH:
2385			if (cmdlen != F_INSN_SIZE(ipfw_insn))
2386				goto bad_size;
2387			break;
2388
2389		case O_UID:
2390		case O_GID:
2391		case O_IP_SRC:
2392		case O_IP_DST:
2393		case O_TCPSEQ:
2394		case O_TCPACK:
2395		case O_PROB:
2396		case O_ICMPTYPE:
2397			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
2398				goto bad_size;
2399			break;
2400
2401		case O_LIMIT:
2402			if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
2403				goto bad_size;
2404			break;
2405
2406		case O_LOG:
2407			if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
2408				goto bad_size;
2409
2410			((ipfw_insn_log *)cmd)->log_left =
2411			    ((ipfw_insn_log *)cmd)->max_log;
2412
2413			break;
2414
2415		case O_IP_SRC_MASK:
2416		case O_IP_DST_MASK:
2417			if (cmdlen != F_INSN_SIZE(ipfw_insn_ip))
2418				goto bad_size;
2419			if (((ipfw_insn_ip *)cmd)->mask.s_addr == 0) {
2420				printf("ipfw: opcode %d, useless rule\n",
2421					cmd->opcode);
2422				return EINVAL;
2423			}
2424			break;
2425
2426		case O_IP_SRC_SET:
2427		case O_IP_DST_SET:
2428			if (cmd->arg1 == 0 || cmd->arg1 > 256) {
2429				printf("ipfw: invalid set size %d\n",
2430					cmd->arg1);
2431				return EINVAL;
2432			}
2433			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
2434			    (cmd->arg1+31)/32 )
2435				goto bad_size;
2436			break;
2437
2438		case O_MACADDR2:
2439			if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
2440				goto bad_size;
2441			break;
2442
2443		case O_MAC_TYPE:
2444		case O_IP_SRCPORT:
2445		case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
2446			if (cmdlen < 2 || cmdlen > 31)
2447				goto bad_size;
2448			break;
2449
2450		case O_RECV:
2451		case O_XMIT:
2452		case O_VIA:
2453			if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
2454				goto bad_size;
2455			break;
2456
2457		case O_PIPE:
2458		case O_QUEUE:
2459			if (cmdlen != F_INSN_SIZE(ipfw_insn_pipe))
2460				goto bad_size;
2461			goto check_action;
2462
2463		case O_FORWARD_IP:
2464			if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
2465				goto bad_size;
2466			goto check_action;
2467
2468		case O_FORWARD_MAC: /* XXX not implemented yet */
2469		case O_CHECK_STATE:
2470		case O_COUNT:
2471		case O_ACCEPT:
2472		case O_DENY:
2473		case O_REJECT:
2474		case O_SKIPTO:
2475		case O_DIVERT:
2476		case O_TEE:
2477			if (cmdlen != F_INSN_SIZE(ipfw_insn))
2478				goto bad_size;
2479check_action:
2480			if (have_action) {
2481				printf("ipfw: opcode %d, multiple actions"
2482					" not allowed\n",
2483					cmd->opcode);
2484				return EINVAL;
2485			}
2486			have_action = 1;
2487			if (l != cmdlen) {
2488				printf("ipfw: opcode %d, action must be"
2489					" last opcode\n",
2490					cmd->opcode);
2491				return EINVAL;
2492			}
2493			break;
2494		default:
2495			printf("ipfw: opcode %d, unknown opcode\n",
2496				cmd->opcode);
2497			return EINVAL;
2498		}
2499	}
2500	if (have_action == 0) {
2501		printf("ipfw: missing action\n");
2502		return EINVAL;
2503	}
2504	return 0;
2505
2506bad_size:
2507	printf("ipfw: opcode %d size %d wrong\n",
2508		cmd->opcode, cmdlen);
2509	return EINVAL;
2510}
2511
2512
2513/**
2514 * {set|get}sockopt parser.
2515 */
2516static int
2517ipfw_ctl(struct sockopt *sopt)
2518{
2519	int error, s, rulenum;
2520	size_t size;
2521	struct ip_fw *bp , *buf, *rule;
2522
2523	static u_int32_t rule_buf[255];	/* we copy the data here */
2524
2525	/*
2526	 * Disallow modifications in really-really secure mode, but still allow
2527	 * the logging counters to be reset.
2528	 */
2529	if (sopt->sopt_name == IP_FW_ADD ||
2530	    (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
2531#if __FreeBSD_version >= 500034
2532		error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
2533		if (error)
2534			return (error);
2535#else /* FreeBSD 4.x */
2536		if (securelevel >= 3)
2537			return (EPERM);
2538#endif
2539	}
2540
2541	error = 0;
2542
2543	switch (sopt->sopt_name) {
2544	case IP_FW_GET:
2545		/*
2546		 * pass up a copy of the current rules. Static rules
2547		 * come first (the last of which has number IPFW_DEFAULT_RULE),
2548		 * followed by a possibly empty list of dynamic rule.
2549		 * The last dynamic rule has NULL in the "next" field.
2550		 */
2551		s = splimp();
2552		size = static_len;	/* size of static rules */
2553		if (ipfw_dyn_v)		/* add size of dyn.rules */
2554			size += (dyn_count * sizeof(ipfw_dyn_rule));
2555
2556		/*
2557		 * XXX todo: if the user passes a short length just to know
2558		 * how much room is needed, do not bother filling up the
2559		 * buffer, just jump to the sooptcopyout.
2560		 */
2561		buf = malloc(size, M_TEMP, M_WAITOK);
2562		if (buf == 0) {
2563			splx(s);
2564			error = ENOBUFS;
2565			break;
2566		}
2567
2568		bp = buf;
2569		for (rule = layer3_chain; rule ; rule = rule->next) {
2570			int i = RULESIZE(rule);
2571			bcopy(rule, bp, i);
2572			bcopy(&set_disable, &(bp->next_rule),
2573			    sizeof(set_disable));
2574			bp = (struct ip_fw *)((char *)bp + i);
2575		}
2576		if (ipfw_dyn_v) {
2577			int i;
2578			ipfw_dyn_rule *p, *dst, *last = NULL;
2579
2580			dst = (ipfw_dyn_rule *)bp;
2581			for (i = 0 ; i < curr_dyn_buckets ; i++ )
2582				for ( p = ipfw_dyn_v[i] ; p != NULL ;
2583				    p = p->next, dst++ ) {
2584					bcopy(p, dst, sizeof *p);
2585					bcopy(&(p->rule->rulenum), &(dst->rule),
2586					    sizeof(p->rule->rulenum));
2587					/*
2588					 * store a non-null value in "next".
2589					 * The userland code will interpret a
2590					 * NULL here as a marker
2591					 * for the last dynamic rule.
2592					 */
2593					bcopy(&dst, &dst->next, sizeof(dst));
2594					last = dst ;
2595					dst->expire =
2596					    TIME_LEQ(dst->expire, time_second) ?
2597						0 : dst->expire - time_second ;
2598				}
2599			if (last != NULL) /* mark last dynamic rule */
2600				bzero(&last->next, sizeof(last));
2601		}
2602		splx(s);
2603
2604		error = sooptcopyout(sopt, buf, size);
2605		free(buf, M_TEMP);
2606		break;
2607
2608	case IP_FW_FLUSH:
2609		/*
2610		 * Normally we cannot release the lock on each iteration.
2611		 * We could do it here only because we start from the head all
2612		 * the times so there is no risk of missing some entries.
2613		 * On the other hand, the risk is that we end up with
2614		 * a very inconsistent ruleset, so better keep the lock
2615		 * around the whole cycle.
2616		 *
2617		 * XXX this code can be improved by resetting the head of
2618		 * the list to point to the default rule, and then freeing
2619		 * the old list without the need for a lock.
2620		 */
2621
2622		s = splimp();
2623		free_chain(&layer3_chain, 0 /* keep default rule */);
2624		splx(s);
2625		break;
2626
2627	case IP_FW_ADD:
2628		rule = (struct ip_fw *)rule_buf; /* XXX do a malloc */
2629		error = sooptcopyin(sopt, rule, sizeof(rule_buf),
2630			sizeof(struct ip_fw) );
2631		size = sopt->sopt_valsize;
2632		if (error || (error = check_ipfw_struct(rule, size)))
2633			break;
2634
2635		error = add_rule(&layer3_chain, rule);
2636		size = RULESIZE(rule);
2637		if (!error && sopt->sopt_dir == SOPT_GET)
2638			error = sooptcopyout(sopt, rule, size);
2639		break;
2640
2641	case IP_FW_DEL:
2642		/*
2643		 * IP_FW_DEL is used for deleting single rules or sets,
2644		 * and (ab)used to atomically manipulate sets. Argument size
2645		 * is used to distinguish between the two:
2646		 *    sizeof(u_int32_t)
2647		 *	delete single rule or set of rules,
2648		 *	or reassign rules (or sets) to a different set.
2649		 *    2*sizeof(u_int32_t)
2650		 *	atomic disable/enable sets.
2651		 *	first u_int32_t contains sets to be disabled,
2652		 *	second u_int32_t contains sets to be enabled.
2653		 */
2654		error = sooptcopyin(sopt, rule_buf,
2655			2*sizeof(u_int32_t), sizeof(u_int32_t));
2656		if (error)
2657			break;
2658		size = sopt->sopt_valsize;
2659		if (size == sizeof(u_int32_t))	/* delete or reassign */
2660			error = del_entry(&layer3_chain, rule_buf[0]);
2661		else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
2662			set_disable =
2663			    (set_disable | rule_buf[0]) & ~rule_buf[1] &
2664			    ~(1<<31); /* set 31 always enabled */
2665		else
2666			error = EINVAL;
2667		break;
2668
2669	case IP_FW_ZERO:
2670	case IP_FW_RESETLOG: /* argument is an int, the rule number */
2671		rulenum=0;
2672
2673		if (sopt->sopt_val != 0) {
2674		    error = sooptcopyin(sopt, &rulenum,
2675			    sizeof(int), sizeof(int));
2676		    if (error)
2677			break;
2678		}
2679		error = zero_entry(rulenum, sopt->sopt_name == IP_FW_RESETLOG);
2680		break;
2681
2682	default:
2683		printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
2684		error = EINVAL;
2685	}
2686
2687	return (error);
2688}
2689
2690/**
2691 * dummynet needs a reference to the default rule, because rules can be
2692 * deleted while packets hold a reference to them. When this happens,
2693 * dummynet changes the reference to the default rule (it could well be a
2694 * NULL pointer, but this way we do not need to check for the special
2695 * case, plus here he have info on the default behaviour).
2696 */
2697struct ip_fw *ip_fw_default_rule;
2698
2699/*
2700 * This procedure is only used to handle keepalives. It is invoked
2701 * every dyn_keepalive_period
2702 */
2703static void
2704ipfw_tick(void * __unused unused)
2705{
2706	int i;
2707	int s;
2708	ipfw_dyn_rule *q;
2709
2710	if (dyn_keepalive == 0 || ipfw_dyn_v == NULL || dyn_count == 0)
2711		goto done;
2712
2713	s = splimp();
2714	for (i = 0 ; i < curr_dyn_buckets ; i++) {
2715		for (q = ipfw_dyn_v[i] ; q ; q = q->next ) {
2716			if (q->dyn_type == O_LIMIT_PARENT)
2717				continue;
2718			if (q->id.proto != IPPROTO_TCP)
2719				continue;
2720			if ( (q->state & BOTH_SYN) != BOTH_SYN)
2721				continue;
2722			if (TIME_LEQ( time_second+dyn_keepalive_interval,
2723			    q->expire))
2724				continue;	/* too early */
2725			if (TIME_LEQ(q->expire, time_second))
2726				continue;	/* too late, rule expired */
2727
2728			send_pkt(&(q->id), q->ack_rev - 1, q->ack_fwd, TH_SYN);
2729			send_pkt(&(q->id), q->ack_fwd - 1, q->ack_rev, 0);
2730		}
2731	}
2732	splx(s);
2733done:
2734	ipfw_timeout_h = timeout(ipfw_tick, NULL, dyn_keepalive_period*hz);
2735}
2736
2737static void
2738ipfw_init(void)
2739{
2740	struct ip_fw default_rule;
2741
2742	ip_fw_chk_ptr = ipfw_chk;
2743	ip_fw_ctl_ptr = ipfw_ctl;
2744	layer3_chain = NULL;
2745
2746	bzero(&default_rule, sizeof default_rule);
2747
2748	default_rule.act_ofs = 0;
2749	default_rule.rulenum = IPFW_DEFAULT_RULE;
2750	default_rule.cmd_len = 1;
2751	default_rule.set = 31;
2752
2753	default_rule.cmd[0].len = 1;
2754	default_rule.cmd[0].opcode =
2755#ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
2756				1 ? O_ACCEPT :
2757#endif
2758				O_DENY;
2759
2760	add_rule(&layer3_chain, &default_rule);
2761
2762	ip_fw_default_rule = layer3_chain;
2763	printf("ipfw2 initialized, divert %s, "
2764		"rule-based forwarding enabled, default to %s, logging ",
2765#ifdef IPDIVERT
2766		"enabled",
2767#else
2768		"disabled",
2769#endif
2770		default_rule.cmd[0].opcode == O_ACCEPT ? "accept" : "deny");
2771
2772#ifdef IPFIREWALL_VERBOSE
2773	fw_verbose = 1;
2774#endif
2775#ifdef IPFIREWALL_VERBOSE_LIMIT
2776	verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
2777#endif
2778	if (fw_verbose == 0)
2779		printf("disabled\n");
2780	else if (verbose_limit == 0)
2781		printf("unlimited\n");
2782	else
2783		printf("limited to %d packets/entry by default\n",
2784		    verbose_limit);
2785	bzero(&ipfw_timeout_h, sizeof(struct callout_handle));
2786	ipfw_timeout_h = timeout(ipfw_tick, NULL, hz);
2787}
2788
2789static int
2790ipfw_modevent(module_t mod, int type, void *unused)
2791{
2792	int s;
2793	int err = 0;
2794
2795	switch (type) {
2796	case MOD_LOAD:
2797		s = splimp();
2798		if (IPFW_LOADED) {
2799			splx(s);
2800			printf("IP firewall already loaded\n");
2801			err = EEXIST;
2802		} else {
2803			ipfw_init();
2804			splx(s);
2805		}
2806		break;
2807
2808	case MOD_UNLOAD:
2809#if !defined(KLD_MODULE)
2810		printf("ipfw statically compiled, cannot unload\n");
2811		err = EBUSY;
2812#else
2813                s = splimp();
2814		untimeout(ipfw_tick, NULL, ipfw_timeout_h);
2815		ip_fw_chk_ptr = NULL;
2816		ip_fw_ctl_ptr = NULL;
2817		free_chain(&layer3_chain, 1 /* kill default rule */);
2818		splx(s);
2819		printf("IP firewall unloaded\n");
2820#endif
2821		break;
2822	default:
2823		break;
2824	}
2825	return err;
2826}
2827
2828static moduledata_t ipfwmod = {
2829	"ipfw",
2830	ipfw_modevent,
2831	0
2832};
2833DECLARE_MODULE(ipfw, ipfwmod, SI_SUB_PSEUDO, SI_ORDER_ANY);
2834MODULE_VERSION(ipfw, 1);
2835#endif /* IPFW2 */
2836