ip_fw2.c revision 141383
11541Srgrimes/*-
21541Srgrimes * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
31541Srgrimes *
41541Srgrimes * Redistribution and use in source and binary forms, with or without
51541Srgrimes * modification, are permitted provided that the following conditions
61541Srgrimes * are met:
71541Srgrimes * 1. Redistributions of source code must retain the above copyright
81541Srgrimes *    notice, this list of conditions and the following disclaimer.
91541Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
101541Srgrimes *    notice, this list of conditions and the following disclaimer in the
111541Srgrimes *    documentation and/or other materials provided with the distribution.
121541Srgrimes *
131541Srgrimes * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
141541Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
151541Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
161541Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
171541Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
181541Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
191541Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
201541Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
211541Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
221541Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
231541Srgrimes * SUCH DAMAGE.
241541Srgrimes *
251541Srgrimes * $FreeBSD: head/sys/netinet/ip_fw2.c 141383 2005-02-06 11:13:59Z glebius $
261541Srgrimes */
271541Srgrimes
281541Srgrimes#define        DEB(x)
291541Srgrimes#define        DDB(x) x
3050477Speter
311541Srgrimes/*
321541Srgrimes * Implement IP packet firewall (new version)
33131840Sbrian */
3416333Sgpalmer
3541793Sluigi#if !defined(KLD_MODULE)
3630966Sjoerg#include "opt_ipfw.h"
3734746Speter#include "opt_ipdn.h"
3850561Sdes#include "opt_inet.h"
3955009Sshin#include "opt_ipsec.h"
40101095Srwatson#ifndef INET
4164060Sdarrenr#error IPFIREWALL requires INET.
4277574Skris#endif /* INET */
4316333Sgpalmer#endif
441541Srgrimes
451541Srgrimes#define IPFW2	1
46101095Srwatson#if IPFW2
471541Srgrimes#include <sys/param.h>
4841793Sluigi#include <sys/systm.h>
491541Srgrimes#include <sys/condvar.h>
501541Srgrimes#include <sys/malloc.h>
511541Srgrimes#include <sys/mbuf.h>
521541Srgrimes#include <sys/kernel.h>
531541Srgrimes#include <sys/jail.h>
547091Swollman#include <sys/module.h>
557090Sbde#include <sys/proc.h>
561541Srgrimes#include <sys/socket.h>
5764075Sache#include <sys/socketvar.h>
581541Srgrimes#include <sys/sysctl.h>
5983934Sbrooks#include <sys/syslog.h>
6030948Sjulian#include <sys/ucred.h>
6119622Sfenner#include <net/if.h>
621541Srgrimes#include <net/radix.h>
638426Swollman#include <net/route.h>
641541Srgrimes#include <netinet/in.h>
651541Srgrimes#include <netinet/in_systm.h>
661541Srgrimes#include <netinet/in_var.h>
677090Sbde#include <netinet/in_pcb.h>
681541Srgrimes#include <netinet/ip.h>
691541Srgrimes#include <netinet/ip_var.h>
701541Srgrimes#include <netinet/ip_icmp.h>
711541Srgrimes#include <netinet/ip_fw.h>
7218797Swollman#include <netinet/ip_divert.h>
731541Srgrimes#include <netinet/ip_dummynet.h>
742531Swollman#include <netinet/tcp.h>
7515680Sgpalmer#include <netinet/tcp_timer.h>
7615680Sgpalmer#include <netinet/tcp_var.h>
77126239Smlaier#include <netinet/tcpip.h>
7884516Sps#include <netinet/udp.h>
7915680Sgpalmer#include <netinet/udp_var.h>
8055009Sshin
8155009Sshin#include <netgraph/ng_ipfw.h>
8255009Sshin
8355009Sshin#include <altq/if_altq.h>
8455009Sshin
85105199Ssam#ifdef IPSEC
86105199Ssam#include <netinet6/ipsec.h>
87105199Ssam#endif
88105199Ssam
89105199Ssam#include <netinet/if_ether.h> /* XXX for ETHERTYPE_IP */
909209Swollman
912531Swollman#include <machine/in_cksum.h>	/* XXX for in_cksum */
9236192Sdg
9312296Sphk/*
9446381Sbillf * set_disable contains one bit per set value (0..31).
9512296Sphk * If the bit is set, all rules with the corresponding set
9613266Swollman * are disabled. Set RESVD_SET(31) is reserved for the default rule
9712296Sphk * and rules that are not deleted by the flush command,
9846381Sbillf * and CANNOT be disabled.
9912296Sphk * Rules in set RESVD_SET can only be deleted explicitly.
1001541Srgrimes */
10112296Sphkstatic u_int32_t set_disable;
10246381Sbillf
10312296Sphkstatic int fw_verbose;
10412296Sphkstatic int verbose_limit;
10512296Sphk
10646381Sbillfstatic struct callout ipfw_timeout;
10733440Sguidostatic uma_zone_t ipfw_dyn_rule_zone;
10833440Sguido#define	IPFW_DEFAULT_RULE	65535
10946381Sbillf
11046381Sbillf/*
11146381Sbillf * Data structure to cache our ucred related
11255009Sshin * information. This structure only gets used if
113129017Sandre * the user specified UID/GID based constraints in
114129017Sandre * a firewall rule.
115129017Sandre */
116129017Sandrestruct ip_fw_ugid {
11755009Sshin	gid_t		fw_groups[NGROUPS];
11855009Sshin	int		fw_ngroups;
11955009Sshin	uid_t		fw_uid;
12055009Sshin	int		fw_prid;
12155009Sshin};
122109843Ssilby
123109843Ssilbystruct ip_fw_chain {
12477665Sjesper	struct ip_fw	*rules;		/* list of rules */
125109843Ssilby	struct ip_fw	*reap;		/* list of rules to reap */
12677665Sjesper	struct mtx	mtx;		/* lock guarding rule list */
12777665Sjesper	int		busy_count;	/* busy count for rw locks */
128111244Ssilby	int		want_write;
129111244Ssilby	struct cv	cv;
130111244Ssilby};
131111244Ssilby#define	IPFW_LOCK_INIT(_chain) \
132111244Ssilby	mtx_init(&(_chain)->mtx, "IPFW static rules", NULL, \
133107081Ssilby		MTX_DEF | MTX_RECURSE)
134107081Ssilby#define	IPFW_LOCK_DESTROY(_chain)	mtx_destroy(&(_chain)->mtx)
135107081Ssilby#define	IPFW_WLOCK_ASSERT(_chain)	do {				\
136107081Ssilby	mtx_assert(&(_chain)->mtx, MA_OWNED);				\
137107081Ssilby	NET_ASSERT_GIANT();						\
13873399Struckman} while (0)
13973399Struckman
14073399Struckmanstatic __inline void
14173791StruckmanIPFW_RLOCK(struct ip_fw_chain *chain)
14273399Struckman{
14373626Struckman	mtx_lock(&chain->mtx);
14473791Struckman	chain->busy_count++;
14573791Struckman	mtx_unlock(&chain->mtx);
14673626Struckman}
14773626Struckman
14873626Struckmanstatic __inline void
14973626StruckmanIPFW_RUNLOCK(struct ip_fw_chain *chain)
15073399Struckman{
15173357Sjlemon	mtx_lock(&chain->mtx);
15273357Sjlemon	chain->busy_count--;
15373357Sjlemon	if (chain->busy_count == 0 && chain->want_write)
15473357Sjlemon		cv_signal(&chain->cv);
1551541Srgrimes	mtx_unlock(&chain->mtx);
15612296Sphk}
1571541Srgrimes
158120386Ssamstatic __inline void
159120386SsamIPFW_WLOCK(struct ip_fw_chain *chain)
160120386Ssam{
1611541Srgrimes	mtx_lock(&chain->mtx);
162111888Sjlemon	chain->want_write++;
16384102Sjlemon	while (chain->busy_count > 0)
16484102Sjlemon		cv_wait(&chain->cv, &chain->mtx);
1651541Srgrimes}
16682884Sjulian
1671541Srgrimesstatic __inline void
16884102SjlemonIPFW_WUNLOCK(struct ip_fw_chain *chain)
16984102Sjlemon{
17084102Sjlemon	chain->want_write--;
17184102Sjlemon	cv_signal(&chain->cv);
17247546Sdg	mtx_unlock(&chain->mtx);
17346381Sbillf}
17412296Sphk
17546381Sbillf/*
1761541Srgrimes * list of rules for layer 3
1772112Swollman */
17878667Srustatic struct ip_fw_chain layer3_chain;
17946381Sbillf
1802112SwollmanMALLOC_DEFINE(M_IPFW, "IpFw/IpAcct", "IpFw/IpAcct chain's");
18129480SacheMALLOC_DEFINE(M_IPFW_TBL, "ipfw_tbl", "IpFw tables");
18229480Sache
18329480Sachestruct table_entry {
18429480Sache	struct radix_node	rn[2];
18529480Sache	struct sockaddr_in	addr, mask;
18643305Sdillon	u_int32_t		value;
18729480Sache};
18874362Sphk
189119753Ssam#define	IPFW_TABLES_MAX		128
19029480Sachestatic struct {
191119753Ssam	struct radix_node_head	*rnh;
192119753Ssam	int			modified;
193121091Ssam} ipfw_tables[IPFW_TABLES_MAX];
194121091Ssam
195119753Ssamstatic int fw_debug = 1;
19612296Sphkstatic int autoinc_step = 100; /* bounded to 1..1000 in add_rule() */
19712296Sphk
19846381Sbillf#ifdef SYSCTL_NODE
19912296SphkSYSCTL_NODE(_net_inet_ip, OID_AUTO, fw, CTLFLAG_RW, 0, "Firewall");
20012296SphkSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, enable,
20144219Sdes    CTLFLAG_RW | CTLFLAG_SECURE3,
202122723Sandre    &fw_enable, 0, "Enable ipfw");
20344219SdesSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, autoinc_step, CTLFLAG_RW,
20444219Sdes    &autoinc_step, 0, "Rule number autincrement step");
20544219SdesSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, one_pass,
20644219Sdes    CTLFLAG_RW | CTLFLAG_SECURE3,
20718797Swollman    &fw_one_pass, 0,
20815026Sphk    "Only do a single pass through ipfw when using dummynet(4)");
20915026SphkSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, debug, CTLFLAG_RW,
21057117Sluigi    &fw_debug, 0, "Enable printing of debug ip_fw statements");
211107114SluigiSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose,
21214209Sphk    CTLFLAG_RW | CTLFLAG_SECURE3,
21384516Sps    &fw_verbose, 0, "Log matches to ipfw rules");
21484516SpsSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, verbose_limit, CTLFLAG_RW,
21541793Sluigi    &verbose_limit, 0, "Set upper limit of matches of ipfw rules logged");
216121093Ssam
21798701Sluigi/*
21898701Sluigi * Description of dynamic rules.
21998701Sluigi *
22098701Sluigi * Dynamic rules are stored in lists accessed through a hash table
22198701Sluigi * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
22298701Sluigi * be modified through the sysctl variable dyn_buckets which is
2231541Srgrimes * updated when the table becomes empty.
2241541Srgrimes *
2251541Srgrimes * XXX currently there is only one list, ipfw_dyn.
2261541Srgrimes *
2271541Srgrimes * When a packet is received, its address fields are first masked
228133390Sandre * with the mask defined for the rule, then hashed, then matched
2291541Srgrimes * against the entries in the corresponding list.
23012296Sphk * Dynamic rules can be used for different purposes:
2311541Srgrimes *  + stateful rules;
2321541Srgrimes *  + enforcing limits on the number of sessions;
2331541Srgrimes *  + in-kernel NAT (not implemented yet)
2341541Srgrimes *
2351541Srgrimes * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
2361541Srgrimes * measured in seconds and depending on the flags.
2371541Srgrimes *
23892723Salfred * The total number of dynamic rules is stored in dyn_count.
23998613Sluigi * The max number of dynamic rules is dyn_max. When we reach
24098613Sluigi * the maximum number of rules we do not create anymore. This is
241122708Sandre * done to avoid consuming too much memory, but also too much
24298613Sluigi * time when searching on each packet (ideally, we should try instead
24392723Salfred * to put a limit on the length of the list on each bucket...).
244133069Sandre *
24517072Sjulian * Each dynamic rule holds a pointer to the parent ipfw rule so
2461541Srgrimes * we know what action to perform. Dynamic rules are removed when
2471541Srgrimes * the parent rule is deleted. XXX we should make them survive.
2481541Srgrimes *
2491541Srgrimes * There are some limitations with dynamic rules -- we do not
2501541Srgrimes * obey the 'randomized match', and we do not do multiple
2511541Srgrimes * passes through the firewall. XXX check the latter!!!
2521541Srgrimes */
25382884Sjulianstatic ipfw_dyn_rule **ipfw_dyn_v = NULL;
2541541Srgrimesstatic u_int32_t dyn_buckets = 256; /* must be power of 2 */
2551541Srgrimesstatic u_int32_t curr_dyn_buckets = 256; /* must be power of 2 */
25620407Swollman
25784102Sjlemonstatic struct mtx ipfw_dyn_mtx;		/* mutex guarding dynamic rules */
25882884Sjulian#define	IPFW_DYN_LOCK_INIT() \
2591541Srgrimes	mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
2601541Srgrimes#define	IPFW_DYN_LOCK_DESTROY()	mtx_destroy(&ipfw_dyn_mtx)
2611541Srgrimes#define	IPFW_DYN_LOCK()		mtx_lock(&ipfw_dyn_mtx)
2621541Srgrimes#define	IPFW_DYN_UNLOCK()	mtx_unlock(&ipfw_dyn_mtx)
26382884Sjulian#define	IPFW_DYN_LOCK_ASSERT()	mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
26482884Sjulian
2651541Srgrimes/*
2661541Srgrimes * Timeouts for various events in handing dynamic rules.
2671541Srgrimes */
26829480Sachestatic u_int32_t dyn_ack_lifetime = 300;
269120386Ssamstatic u_int32_t dyn_syn_lifetime = 20;
270120386Ssamstatic u_int32_t dyn_fin_lifetime = 1;
271120386Ssamstatic u_int32_t dyn_rst_lifetime = 1;
272120386Ssamstatic u_int32_t dyn_udp_lifetime = 10;
273120386Ssamstatic u_int32_t dyn_short_lifetime = 5;
274120386Ssam
275120386Ssam/*
276120386Ssam * Keepalives are sent if dyn_keepalive is set. They are sent every
277119753Ssam * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
27829480Sache * seconds of lifetime of a rule.
27974362Sphk * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
28029480Sache * than dyn_keepalive_period.
281111244Ssilby */
282111244Ssilby
28329480Sachestatic u_int32_t dyn_keepalive_interval = 20;
28477574Skrisstatic u_int32_t dyn_keepalive_period = 5;
28534961Sphkstatic u_int32_t dyn_keepalive = 1;	/* do send keepalives */
28677574Skris
2871541Srgrimesstatic u_int32_t static_count;	/* # of static rules */
28893818Sjhbstatic u_int32_t static_len;	/* size in bytes of static rules */
289122320Ssamstatic u_int32_t dyn_count;		/* # of dynamic rules */
2901541Srgrimesstatic u_int32_t dyn_max = 4096;	/* max # of dynamic rules */
2911541Srgrimes
29298701SluigiSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets, CTLFLAG_RW,
2931541Srgrimes    &dyn_buckets, 0, "Number of dyn. buckets");
2941541SrgrimesSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets, CTLFLAG_RD,
2951541Srgrimes    &curr_dyn_buckets, 0, "Current Number of dyn. buckets");
29613929SwollmanSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_count, CTLFLAG_RD,
29713929Swollman    &dyn_count, 0, "Number of dyn. rules");
2981541SrgrimesSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_max, CTLFLAG_RW,
299122702Sandre    &dyn_max, 0, "Max number of dyn. rules");
30067334SjoeSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, static_count, CTLFLAG_RD,
30184102Sjlemon    &static_count, 0, "Number of static rules");
302122702SandreSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime, CTLFLAG_RW,
30322333Sbrian    &dyn_ack_lifetime, 0, "Lifetime of dyn. rules for acks");
30473172SjlemonSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime, CTLFLAG_RW,
305126239Smlaier    &dyn_syn_lifetime, 0, "Lifetime of dyn. rules for syn");
306126239SmlaierSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime, CTLFLAG_RW,
307126239Smlaier    &dyn_fin_lifetime, 0, "Lifetime of dyn. rules for fin");
30898613SluigiSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime, CTLFLAG_RW,
309122708Sandre    &dyn_rst_lifetime, 0, "Lifetime of dyn. rules for rst");
310121141SsamSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime, CTLFLAG_RW,
311121141Ssam    &dyn_udp_lifetime, 0, "Lifetime of dyn. rules for UDP");
312121141SsamSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime, CTLFLAG_RW,
313105199Ssam    &dyn_short_lifetime, 0, "Lifetime of dyn. rules for other situations");
314125952SmlaierSYSCTL_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive, CTLFLAG_RW,
315105199Ssam    &dyn_keepalive, 0, "Enable keepalives for dyn. rules");
316105199Ssam
317105199Ssam#endif /* SYSCTL_NODE */
318105199Ssam
3191541Srgrimes
32098613Sluigi/*
32198613Sluigi * This macro maps an ip pointer into a layer3 header pointer of type T
32254175Sarchie */
323125952Smlaier#define	L3HDR(T, ip) ((T *)((u_int32_t *)(ip) + (ip)->ip_hl))
324126239Smlaier
325128829Sdarrenrstatic __inline int
326126239Smlaiericmptype_match(struct ip *ip, ipfw_insn_u32 *cmd)
327125952Smlaier{
328126239Smlaier	int type = L3HDR(struct icmp,ip)->icmp_type;
329126239Smlaier
330126239Smlaier	return (type <= ICMP_MAXTYPE && (cmd->d[0] & (1<<type)) );
331125952Smlaier}
332126239Smlaier
333125952Smlaier#define TT	( (1 << ICMP_ECHO) | (1 << ICMP_ROUTERSOLICIT) | \
334125952Smlaier    (1 << ICMP_TSTAMP) | (1 << ICMP_IREQ) | (1 << ICMP_MASKREQ) )
335125952Smlaier
336125952Smlaierstatic int
33798613Sluigiis_icmp_query(struct ip *ip)
33898613Sluigi{
33998613Sluigi	int type = L3HDR(struct icmp, ip)->icmp_type;
3401541Srgrimes	return (type <= ICMP_MAXTYPE && (TT & (1<<type)) );
34118797Swollman}
34218797Swollman#undef TT
34318797Swollman
34418797Swollman/*
3451541Srgrimes * The following checks use two arrays of 8 or 16 bits to store the
346133481Sandre * bits that we want set or clear, respectively. They are in the
3471541Srgrimes * low and high half of cmd->arg1 or cmd->d[0].
34813929Swollman *
3491541Srgrimes * We scan options and store the bits we find set. We succeed if
3501541Srgrimes *
35118797Swollman *	(want_set & ~bits) == 0 && (want_clear & ~bits) == want_clear
352105586Sphk *
3531541Srgrimes * The code is sometimes optimized not to store additional variables.
3541541Srgrimes */
3551541Srgrimes
35618797Swollmanstatic int
357105586Sphkflags_match(ipfw_insn *cmd, u_int8_t bits)
3581541Srgrimes{
3591541Srgrimes	u_char want_clear;
3601541Srgrimes	bits = ~bits;
3611541Srgrimes
3621541Srgrimes	if ( ((cmd->arg1 & 0xff) & bits) != 0)
363133481Sandre		return 0; /* some bits we want set were clear */
3641541Srgrimes	want_clear = (cmd->arg1 >> 8) & 0xff;
36513929Swollman	if ( (want_clear & bits) != want_clear)
3661541Srgrimes		return 0; /* some bits we want clear were set */
3671541Srgrimes	return 1;
3681541Srgrimes}
36978064Sume
37078064Sumestatic int
37178064Sumeipopts_match(struct ip *ip, ipfw_insn *cmd)
37278064Sume{
37378064Sume	int optlen, bits = 0;
37478064Sume	u_char *cp = (u_char *)(ip + 1);
37578064Sume	int x = (ip->ip_hl << 2) - sizeof (struct ip);
37678064Sume
37778064Sume	for (; x > 0; x -= optlen, cp += optlen) {
37878064Sume		int opt = cp[IPOPT_OPTVAL];
37958698Sjlemon
38058698Sjlemon		if (opt == IPOPT_EOL)
38118797Swollman			break;
38258698Sjlemon		if (opt == IPOPT_NOP)
38358698Sjlemon			optlen = 1;
38458698Sjlemon		else {
38558698Sjlemon			optlen = cp[IPOPT_OLEN];
38658698Sjlemon			if (optlen <= 0 || optlen > x)
38718797Swollman				return 0; /* invalid or truncated */
38822333Sbrian		}
3891541Srgrimes		switch (opt) {
3901541Srgrimes
3911541Srgrimes		default:
3921541Srgrimes			break;
393130416Smlaier
394130416Smlaier		case IPOPT_LSRR:
395130416Smlaier			bits |= IP_FW_IPOPT_LSRR;
396130416Smlaier			break;
397130416Smlaier
398130416Smlaier		case IPOPT_SSRR:
3991541Srgrimes			bits |= IP_FW_IPOPT_SSRR;
4001541Srgrimes			break;
4011541Srgrimes
40290868Smike		case IPOPT_RR:
4031541Srgrimes			bits |= IP_FW_IPOPT_RR;
4041541Srgrimes			break;
4051541Srgrimes
4061541Srgrimes		case IPOPT_TS:
40790868Smike			bits |= IP_FW_IPOPT_TS;
4081541Srgrimes			break;
4091541Srgrimes		}
4101541Srgrimes	}
4111541Srgrimes	return (flags_match(cmd, bits));
4121541Srgrimes}
4131541Srgrimes
4141541Srgrimesstatic int
4151541Srgrimestcpopts_match(struct ip *ip, ipfw_insn *cmd)
41618797Swollman{
4171541Srgrimes	int optlen, bits = 0;
4181541Srgrimes	struct tcphdr *tcp = L3HDR(struct tcphdr,ip);
4191541Srgrimes	u_char *cp = (u_char *)(tcp + 1);
4201541Srgrimes	int x = (tcp->th_off << 2) - sizeof(struct tcphdr);
4211541Srgrimes
4221541Srgrimes	for (; x > 0; x -= optlen, cp += optlen) {
4231541Srgrimes		int opt = cp[0];
4241541Srgrimes		if (opt == TCPOPT_EOL)
4251541Srgrimes			break;
4261541Srgrimes		if (opt == TCPOPT_NOP)
427111275Ssam			optlen = 1;
428111275Ssam		else {
429111275Ssam			optlen = cp[1];
430111275Ssam			if (optlen <= 0)
431122062Sume				break;
432111275Ssam		}
433111275Ssam
434117897Ssam		switch (opt) {
435117897Ssam
436117897Ssam		default:
437117897Ssam			break;
438117897Ssam
439117897Ssam		case TCPOPT_MAXSEG:
440117897Ssam			bits |= IP_FW_TCPOPT_MSS;
44173626Struckman			break;
44273626Struckman
4435543Sugen		case TCPOPT_WINDOW:
4445543Sugen			bits |= IP_FW_TCPOPT_WINDOW;
4455543Sugen			break;
4465543Sugen
44717072Sjulian		case TCPOPT_SACK_PERMITTED:
44817758Ssos		case TCPOPT_SACK:
44941793Sluigi			bits |= IP_FW_TCPOPT_SACK;
4505543Sugen			break;
4515543Sugen
4525543Sugen		case TCPOPT_TIMESTAMP:
45341793Sluigi			bits |= IP_FW_TCPOPT_TS;
45441793Sluigi			break;
45564060Sdarrenr
45664060Sdarrenr		}
45724590Sdarrenr	}
458120386Ssam	return (flags_match(cmd, bits));
459121141Ssam}
460121141Ssam
461121141Ssamstatic int
462121141Ssamiface_match(struct ifnet *ifp, ipfw_insn_if *cmd)
46324590Sdarrenr{
464121141Ssam	if (ifp == NULL)	/* no iface with this packet, match fails */
465120386Ssam		return 0;
466120386Ssam	/* Check by name or by IP address */
467120386Ssam	if (cmd->name[0] != '\0') { /* match by name */
468120386Ssam		/* Check name */
469120386Ssam		if (cmd->p.glob) {
470120386Ssam			if (fnmatch(cmd->name, ifp->if_xname, 0) == 0)
471122708Sandre				return(1);
47264060Sdarrenr		} else {
4731541Srgrimes			if (strncmp(ifp->if_xname, cmd->name, IFNAMSIZ) == 0)
47486047Sluigi				return(1);
47537409Sjulian		}
47637409Sjulian	} else {
47737409Sjulian		struct ifaddr *ia;
47837409Sjulian
47998613Sluigi		/* XXX lock? */
48037409Sjulian		TAILQ_FOREACH(ia, &ifp->if_addrhead, ifa_link) {
48198613Sluigi			if (ia->ifa_addr == NULL)
48298613Sluigi				continue;
48398613Sluigi			if (ia->ifa_addr->sa_family != AF_INET)
48498613Sluigi				continue;
48598613Sluigi			if (cmd->p.ip.s_addr == ((struct sockaddr_in *)
48696245Sluigi			    (ia->ifa_addr))->sin_addr.s_addr)
48787915Sjlemon				return(1);	/* match */
48887915Sjlemon		}
48987915Sjlemon	}
49071909Sluigi	return(0);	/* no match, fail ... */
49196245Sluigi}
49298613Sluigi
49354175Sarchie/*
49486047Sluigi * The verify_path function checks if a route to the src exists and
49598666Sluigi * if it is reachable via ifp (when provided).
49698666Sluigi *
49754175Sarchie * The 'verrevpath' option checks that the interface that an IP packet
49841793Sluigi * arrives on is the same interface that traffic destined for the
49926359Sjulian * packet's source address would be routed out of.  The 'versrcreach'
50054175Sarchie * option just checks that the source address is reachable via any route
50154175Sarchie * (except default) in the routing table.  These two are a measure to block
50226359Sjulian * forged packets.  This is also commonly known as "anti-spoofing" or Unicast
50326359Sjulian * Reverse Path Forwarding (Unicast RFP) in Cisco-ese. The name of the knobs
50441793Sluigi * is purposely reminiscent of the Cisco IOS command,
50598613Sluigi *
50654175Sarchie *   ip verify unicast reverse-path
50737409Sjulian *   ip verify unicast source reachable-via any
50841793Sluigi *
50937409Sjulian * which implements the same functionality. But note that syntax is
51054175Sarchie * misleading. The check may be performed on all IP packets whether unicast,
51154175Sarchie * multicast, or broadcast.
51217072Sjulian */
51341793Sluigistatic int
51417072Sjulianverify_path(struct in_addr src, struct ifnet *ifp)
5151541Srgrimes{
5161541Srgrimes	struct route ro;
5171541Srgrimes	struct sockaddr_in *dst;
5181541Srgrimes
5191541Srgrimes	bzero(&ro, sizeof(ro));
5201541Srgrimes
5211541Srgrimes	dst = (struct sockaddr_in *)&(ro.ro_dst);
52298613Sluigi	dst->sin_family = AF_INET;
52313929Swollman	dst->sin_len = sizeof(*dst);
5241541Srgrimes	dst->sin_addr = src;
5252531Swollman	rtalloc_ign(&ro, RTF_CLONING);
5269209Swollman
5272531Swollman	if (ro.ro_rt == NULL)
5282531Swollman		return 0;
5292531Swollman
5302531Swollman	/* if ifp is provided, check for equality with rtentry */
5319209Swollman	if (ifp != NULL && ro.ro_rt->rt_ifp != ifp) {
5322531Swollman		RTFREE(ro.ro_rt);
5332531Swollman		return 0;
5341541Srgrimes	}
5351541Srgrimes
53643802Swollman	/* if no ifp provided, check if rtentry is not default route */
53743802Swollman	if (ifp == NULL &&
53843802Swollman	     satosin(rt_key(ro.ro_rt))->sin_addr.s_addr == INADDR_ANY) {
5391541Srgrimes		RTFREE(ro.ro_rt);
54043802Swollman		return 0;
54143802Swollman	}
54243802Swollman
54343802Swollman	/* or if this is a blackhole/reject route */
54473172Sjlemon	if (ifp == NULL && ro.ro_rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE)) {
54573172Sjlemon		RTFREE(ro.ro_rt);
54673172Sjlemon		return 0;
54773172Sjlemon	}
54898613Sluigi
54973172Sjlemon	/* found valid route */
55073399Struckman	RTFREE(ro.ro_rt);
55173399Struckman	return 1;
55273399Struckman}
55373399Struckman
55473402Struckman
55573402Struckmanstatic u_int64_t norule_counter;	/* counter for ipfw_log(NULL...) */
55673626Struckman
55786047Sluigi#define SNPARGS(buf, len) buf + len, sizeof(buf) > len ? sizeof(buf) - len : 0
55873626Struckman#define SNP(buf) buf, sizeof(buf)
55973626Struckman
56073791Struckman/*
56173626Struckman * We enter here when we have a rule with O_LOG.
56273626Struckman * XXX this function alone takes about 2Kbytes of code!
56373399Struckman */
56473399Struckmanstatic void
56583934Sbrooksipfw_log(struct ip_fw *f, u_int hlen, struct ether_header *eh,
56673402Struckman	struct mbuf *m, struct ifnet *oif)
567125785Smlaier{
56873399Struckman	char *action;
56984102Sjlemon	int limit_reached = 0;
57084102Sjlemon	char action2[40], proto[48], fragment[28];
57184102Sjlemon
57284102Sjlemon	fragment[0] = '\0';
57337409Sjulian	proto[0] = '\0';
57473399Struckman
57573399Struckman	if (f == NULL) {	/* bogus pkt */
57673399Struckman		if (verbose_limit != 0 && norule_counter >= verbose_limit)
57737409Sjulian			return;
57873399Struckman		norule_counter++;
57973399Struckman		if (norule_counter == verbose_limit)
58037409Sjulian			limit_reached = verbose_limit;
58184102Sjlemon		action = "Refuse";
58284102Sjlemon	} else {	/* O_LOG is the first action, find the real one */
58384102Sjlemon		ipfw_insn *cmd = ACTION_PTR(f);
58484102Sjlemon		ipfw_insn_log *l = (ipfw_insn_log *)cmd;
58584102Sjlemon
58684102Sjlemon		if (l->max_log != 0 && l->log_left == 0)
58784102Sjlemon			return;
58884102Sjlemon		l->log_left--;
58984102Sjlemon		if (l->log_left == 0)
590130685Sbms			limit_reached = l->max_log;
591130685Sbms		cmd += F_LEN(cmd);	/* point to first action */
59284102Sjlemon		if (cmd->opcode == O_ALTQ) {
59384102Sjlemon			ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
59484102Sjlemon
59584102Sjlemon			snprintf(SNPARGS(action2, 0), "Altq %d",
5961541Srgrimes				altq->qid);
59773172Sjlemon			cmd += F_LEN(cmd);
5981541Srgrimes		}
59973172Sjlemon		if (cmd->opcode == O_PROB)
6001541Srgrimes			cmd += F_LEN(cmd);
601131840Sbrian
602131840Sbrian		action = action2;
603131840Sbrian		switch (cmd->opcode) {
604131840Sbrian		case O_DENY:
6051541Srgrimes			action = "Deny";
6061541Srgrimes			break;
6071541Srgrimes
6081541Srgrimes		case O_REJECT:
6091541Srgrimes			if (cmd->arg1==ICMP_REJECT_RST)
6101541Srgrimes				action = "Reset";
6111541Srgrimes			else if (cmd->arg1==ICMP_UNREACH_HOST)
6121541Srgrimes				action = "Reject";
6131541Srgrimes			else
6141541Srgrimes				snprintf(SNPARGS(action2, 0), "Unreach %d",
6151541Srgrimes					cmd->arg1);
6161541Srgrimes			break;
6171541Srgrimes
618106968Sluigi		case O_ACCEPT:
619106968Sluigi			action = "Accept";
6201541Srgrimes			break;
6211541Srgrimes		case O_COUNT:
62213929Swollman			action = "Count";
6231541Srgrimes			break;
6241541Srgrimes		case O_DIVERT:
6251541Srgrimes			snprintf(SNPARGS(action2, 0), "Divert %d",
62696432Sdd				cmd->arg1);
6271541Srgrimes			break;
6281541Srgrimes		case O_TEE:
6291541Srgrimes			snprintf(SNPARGS(action2, 0), "Tee %d",
6301541Srgrimes				cmd->arg1);
6311541Srgrimes			break;
6321541Srgrimes		case O_SKIPTO:
6331541Srgrimes			snprintf(SNPARGS(action2, 0), "SkipTo %d",
6341541Srgrimes				cmd->arg1);
6351541Srgrimes			break;
6361541Srgrimes		case O_PIPE:
6371541Srgrimes			snprintf(SNPARGS(action2, 0), "Pipe %d",
6381541Srgrimes				cmd->arg1);
6391541Srgrimes			break;
64021932Swollman		case O_QUEUE:
6411541Srgrimes			snprintf(SNPARGS(action2, 0), "Queue %d",
64213929Swollman				cmd->arg1);
6431541Srgrimes			break;
6441541Srgrimes		case O_FORWARD_IP: {
6451541Srgrimes			ipfw_insn_sa *sa = (ipfw_insn_sa *)cmd;
6461541Srgrimes			int len;
6471541Srgrimes
6481541Srgrimes			len = snprintf(SNPARGS(action2, 0), "Forward to %s",
6491541Srgrimes				inet_ntoa(sa->sa.sin_addr));
6501541Srgrimes			if (sa->sa.sin_port)
6511541Srgrimes				snprintf(SNPARGS(action2, len), ":%d",
65255009Sshin				    sa->sa.sin_port);
65355009Sshin			}
65455009Sshin			break;
65555009Sshin		case O_NETGRAPH:
65655009Sshin			snprintf(SNPARGS(action2, 0), "Netgraph %d",
65755009Sshin				cmd->arg1);
65855009Sshin			break;
65955009Sshin		case O_NGTEE:
66055009Sshin			snprintf(SNPARGS(action2, 0), "Ngtee %d",
66155009Sshin				cmd->arg1);
66283934Sbrooks			break;
66355009Sshin		default:
6641541Srgrimes			action = "UNKNOWN";
6651541Srgrimes			break;
6661541Srgrimes		}
6671541Srgrimes	}
66872803Sjesper
66991271Sjedgar	if (hlen == 0) {	/* non-ip */
67091271Sjedgar		snprintf(SNPARGS(proto, 0), "MAC");
67191271Sjedgar	} else {
67291271Sjedgar		struct ip *ip = mtod(m, struct ip *);
67391271Sjedgar		/* these three are all aliases to the same thing */
67491271Sjedgar		struct icmp *const icmp = L3HDR(struct icmp, ip);
67591271Sjedgar		struct tcphdr *const tcp = (struct tcphdr *)icmp;
67691271Sjedgar		struct udphdr *const udp = (struct udphdr *)icmp;
67791271Sjedgar
67891271Sjedgar		int ip_off, offset, ip_len;
679105199Ssam
680105199Ssam		int len;
681105199Ssam
682105199Ssam		if (eh != NULL) { /* layer 2 packets are as on the wire */
683105199Ssam			ip_off = ntohs(ip->ip_off);
684105199Ssam			ip_len = ntohs(ip->ip_len);
685105199Ssam		} else {
686105199Ssam			ip_off = ip->ip_off;
687105199Ssam			ip_len = ip->ip_len;
688105199Ssam		}
689105199Ssam		offset = ip_off & IP_OFFMASK;
690105199Ssam		switch (ip->ip_p) {
691105199Ssam		case IPPROTO_TCP:
692105199Ssam			len = snprintf(SNPARGS(proto, 0), "TCP %s",
693105199Ssam			    inet_ntoa(ip->ip_src));
694105199Ssam			if (offset == 0)
695105199Ssam				snprintf(SNPARGS(proto, len), ":%d %s:%d",
696105199Ssam				    ntohs(tcp->th_sport),
697105199Ssam				    inet_ntoa(ip->ip_dst),
698105199Ssam				    ntohs(tcp->th_dport));
699105199Ssam			else
700105199Ssam				snprintf(SNPARGS(proto, len), " %s",
701105199Ssam				    inet_ntoa(ip->ip_dst));
702105199Ssam			break;
703105199Ssam
704105199Ssam		case IPPROTO_UDP:
705105199Ssam			len = snprintf(SNPARGS(proto, 0), "UDP %s",
706105199Ssam				inet_ntoa(ip->ip_src));
707122708Sandre			if (offset == 0)
70891271Sjedgar				snprintf(SNPARGS(proto, len), ":%d %s:%d",
70913929Swollman				    ntohs(udp->uh_sport),
7101541Srgrimes				    inet_ntoa(ip->ip_dst),
7111541Srgrimes				    ntohs(udp->uh_dport));
71288665Syar			else
71388665Syar				snprintf(SNPARGS(proto, len), " %s",
71488665Syar				    inet_ntoa(ip->ip_dst));
71588665Syar			break;
71688665Syar
71798613Sluigi		case IPPROTO_ICMP:
71898613Sluigi			if (offset == 0)
71988665Syar				len = snprintf(SNPARGS(proto, 0),
72088665Syar				    "ICMP:%u.%u ",
72188665Syar				    icmp->icmp_type, icmp->icmp_code);
72267334Sjoe			else
72367334Sjoe				len = snprintf(SNPARGS(proto, 0), "ICMP ");
72467334Sjoe			len += snprintf(SNPARGS(proto, len), "%s",
72567334Sjoe			    inet_ntoa(ip->ip_src));
72667334Sjoe			snprintf(SNPARGS(proto, len), " %s",
7273969Sjkh			    inet_ntoa(ip->ip_dst));
7281541Srgrimes			break;
729133069Sandre
730133069Sandre		default:
7311541Srgrimes			len = snprintf(SNPARGS(proto, 0), "P:%d %s", ip->ip_p,
73267620Sru			    inet_ntoa(ip->ip_src));
733133069Sandre			snprintf(SNPARGS(proto, len), " %s",
734133069Sandre			    inet_ntoa(ip->ip_dst));
73567620Sru			break;
73667620Sru		}
73767620Sru
738105586Sphk		if (ip_off & (IP_MF | IP_OFFMASK))
73927669Sbrian			snprintf(SNPARGS(fragment, 0), " (frag %d:%d@%d%s)",
74067620Sru			     ntohs(ip->ip_id), ip_len - (ip->ip_hl << 2),
741126239Smlaier			     offset << 3,
74290868Smike			     (ip_off & IP_MF) ? "+" : "");
74390868Smike	}
74467620Sru	if (oif || m->m_pkthdr.rcvif)
74568169Sru		log(LOG_SECURITY | LOG_INFO,
74668169Sru		    "ipfw: %d %s %s %s via %s%s\n",
74768169Sru		    f ? f->rulenum : -1,
74868169Sru		    action, proto, oif ? "out" : "in",
74990868Smike		    oif ? oif->if_xname : m->m_pkthdr.rcvif->if_xname,
75090868Smike		    fragment);
75167620Sru	else
75227669Sbrian		log(LOG_SECURITY | LOG_INFO,
753133069Sandre		    "ipfw: %d %s %s [no if info]%s\n",
7541541Srgrimes		    f ? f->rulenum : -1,
755133069Sandre		    action, proto, fragment);
756133069Sandre	if (limit_reached)
757133069Sandre		log(LOG_SECURITY | LOG_NOTICE,
758133069Sandre		    "ipfw: limit %d reached on entry %d\n",
759133069Sandre		    limit_reached, f ? f->rulenum : -1);
760133069Sandre}
76117072Sjulian
7621541Srgrimes/*
76354175Sarchie * IMPORTANT: the hash function for dynamic rules must be commutative
76417072Sjulian * in source and destination (ip,port), because rules are bidirectional
765126239Smlaier * and we want to find both in the same bucket.
76654175Sarchie */
767126239Smlaierstatic __inline int
76854175Sarchiehash_packet(struct ipfw_flow_id *id)
76954175Sarchie{
77054175Sarchie	u_int32_t i;
771126239Smlaier
772126239Smlaier	i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
773126239Smlaier	i &= (curr_dyn_buckets - 1);
77454175Sarchie	return i;
77554175Sarchie}
77654175Sarchie
77790868Smike/**
77890868Smike * unlink a dynamic rule from a chain. prev is a pointer to
77954175Sarchie * the previous one, q is a pointer to the rule to delete,
78054175Sarchie * head is a pointer to the head of the queue.
781126239Smlaier * Modifies q and potentially also head.
78226359Sjulian */
78331163Sjulian#define UNLINK_DYN_RULE(prev, head, q) {				\
78454175Sarchie	ipfw_dyn_rule *old_q = q;					\
78554175Sarchie									\
78654175Sarchie	/* remove a refcount to the parent */				\
78754175Sarchie	if (q->dyn_type == O_LIMIT)					\
78854175Sarchie		q->parent->count--;					\
78989809Scjc	DEB(printf("ipfw: unlink entry 0x%08x %d -> 0x%08x %d, %d left\n",\
79098613Sluigi		(q->id.src_ip), (q->id.src_port),			\
79198613Sluigi		(q->id.dst_ip), (q->id.dst_port), dyn_count-1 ); )	\
792126239Smlaier	if (prev != NULL)						\
793126239Smlaier		prev->next = q = q->next;				\
794126239Smlaier	else								\
795126239Smlaier		head = q = q->next;					\
79698613Sluigi	dyn_count--;							\
79789809Scjc	uma_zfree(ipfw_dyn_rule_zone, old_q); }
79831163Sjulian
79917072Sjulian#define TIME_LEQ(a,b)       ((int)((a)-(b)) <= 0)
80017072Sjulian
80178064Sume/**
80217072Sjulian * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
80378064Sume *
80478064Sume * If keep_me == NULL, rules are deleted even if not expired,
80578064Sume * otherwise only expired rules are removed.
80678064Sume *
80778064Sume * The value of the second parameter is also used to point to identify
80878064Sume * a rule we absolutely do not want to remove (e.g. because we are
80978064Sume * holding a reference to it -- this is the case with O_LIMIT_PARENT
81078064Sume * rules). The pointer is only used for comparison, so any non-null
81178064Sume * value will do.
81278064Sume */
813105199Ssamstatic void
814105199Ssamremove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
815105199Ssam{
816105199Ssam	static u_int32_t last_remove = 0;
817105199Ssam
818105199Ssam#define FORCE (keep_me == NULL)
819105199Ssam
820105199Ssam	ipfw_dyn_rule *prev, *q;
821105199Ssam	int i, pass = 0, max_pass = 0;
822105199Ssam
823105199Ssam	IPFW_DYN_LOCK_ASSERT();
824105199Ssam
825105199Ssam	if (ipfw_dyn_v == NULL || dyn_count == 0)
826105199Ssam		return;
827105199Ssam	/* do not expire more than once per second, it is useless */
828105199Ssam	if (!FORCE && last_remove == time_second)
829105199Ssam		return;
830105199Ssam	last_remove = time_second;
831105199Ssam
832105199Ssam	/*
833105199Ssam	 * because O_LIMIT refer to parent rules, during the first pass only
834105199Ssam	 * remove child and mark any pending LIMIT_PARENT, and remove
835105199Ssam	 * them in a second pass.
836105199Ssam	 */
837105199Ssamnext_pass:
838105199Ssam	for (i = 0 ; i < curr_dyn_buckets ; i++) {
839105199Ssam		for (prev=NULL, q = ipfw_dyn_v[i] ; q ; ) {
840105199Ssam			/*
841105199Ssam			 * Logic can become complex here, so we split tests.
842105199Ssam			 */
843105199Ssam			if (q == keep_me)
844105199Ssam				goto next;
845105199Ssam			if (rule != NULL && rule != q->rule)
846105199Ssam				goto next; /* not the one we are looking for */
847105199Ssam			if (q->dyn_type == O_LIMIT_PARENT) {
848105199Ssam				/*
849105199Ssam				 * handle parent in the second pass,
850105199Ssam				 * record we need one.
851105199Ssam				 */
85278064Sume				max_pass = 1;
85378064Sume				if (pass == 0)
8541541Srgrimes					goto next;
8551541Srgrimes				if (FORCE && q->count != 0 ) {
8561541Srgrimes					/* XXX should not happen! */
857126239Smlaier					printf("ipfw: OUCH! cannot remove rule,"
858126239Smlaier					     " count %d\n", q->count);
859126239Smlaier				}
860126239Smlaier			} else {
861126239Smlaier				if (!FORCE &&
862126239Smlaier				    !TIME_LEQ( q->expire, time_second ))
863126239Smlaier					goto next;
864126239Smlaier			}
865126239Smlaier             if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
866126239Smlaier                     UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
86713929Swollman                     continue;
8681541Srgrimes             }
8691541Srgrimesnext:
8701541Srgrimes			prev=q;
8711541Srgrimes			q=q->next;
87213929Swollman		}
87354175Sarchie	}
874133069Sandre	if (pass++ < max_pass)
875133069Sandre		goto next_pass;
876133069Sandre}
877133069Sandre
878133069Sandre
879133069Sandre/**
880133069Sandre * lookup a dynamic rule.
8811541Srgrimes */
88254175Sarchiestatic ipfw_dyn_rule *
883133069Sandrelookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
884133069Sandre	struct tcphdr *tcp)
8851541Srgrimes{
886133069Sandre	/*
887133069Sandre	 * stateful ipfw extensions.
888133069Sandre	 * Lookup into dynamic session queue
889133069Sandre	 */
890133069Sandre#define MATCH_REVERSE	0
891121684Sume#define MATCH_FORWARD	1
892133069Sandre#define MATCH_NONE	2
8931541Srgrimes#define MATCH_UNKNOWN	3
894133069Sandre	int i, dir = MATCH_NONE;
895133069Sandre	ipfw_dyn_rule *prev, *q=NULL;
896133069Sandre
897133069Sandre	IPFW_DYN_LOCK_ASSERT();
898133557Sandre
899133557Sandre	if (ipfw_dyn_v == NULL)
900133069Sandre		goto done;	/* not found */
901119753Ssam	i = hash_packet( pkt );
902133069Sandre	for (prev=NULL, q = ipfw_dyn_v[i] ; q != NULL ; ) {
903133069Sandre		if (q->dyn_type == O_LIMIT_PARENT && q->count)
904133069Sandre			goto next;
905133069Sandre		if (TIME_LEQ( q->expire, time_second)) { /* expire entry */
906133069Sandre			UNLINK_DYN_RULE(prev, ipfw_dyn_v[i], q);
907133069Sandre			continue;
908133069Sandre		}
9091541Srgrimes		if (pkt->proto == q->id.proto &&
910133069Sandre		    q->dyn_type != O_LIMIT_PARENT) {
911133069Sandre			if (pkt->src_ip == q->id.src_ip &&
912133069Sandre			    pkt->dst_ip == q->id.dst_ip &&
913133069Sandre			    pkt->src_port == q->id.src_port &&
914133069Sandre			    pkt->dst_port == q->id.dst_port ) {
915133069Sandre				dir = MATCH_FORWARD;
916133069Sandre				break;
917133069Sandre			}
918133069Sandre			if (pkt->src_ip == q->id.dst_ip &&
919133069Sandre			    pkt->dst_ip == q->id.src_ip &&
920133069Sandre			    pkt->src_port == q->id.dst_port &&
921133069Sandre			    pkt->dst_port == q->id.src_port ) {
922133069Sandre				dir = MATCH_REVERSE;
923133069Sandre				break;
924133069Sandre			}
925133069Sandre		}
926133069Sandrenext:
927133069Sandre		prev = q;
928133069Sandre		q = q->next;
929133069Sandre	}
930133069Sandre	if (q == NULL)
931133069Sandre		goto done; /* q = NULL, not found */
932133069Sandre
933133069Sandre	if ( prev != NULL) { /* found and not in front */
934133069Sandre		prev->next = q->next;
935133069Sandre		q->next = ipfw_dyn_v[i];
936133069Sandre		ipfw_dyn_v[i] = q;
937133069Sandre	}
938133069Sandre	if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
939133069Sandre		u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
940133069Sandre
941133069Sandre#define BOTH_SYN	(TH_SYN | (TH_SYN << 8))
942133069Sandre#define BOTH_FIN	(TH_FIN | (TH_FIN << 8))
943133069Sandre		q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
944133069Sandre		switch (q->state) {
945133069Sandre		case TH_SYN:				/* opening */
946133069Sandre			q->expire = time_second + dyn_syn_lifetime;
947133069Sandre			break;
948133069Sandre
949133069Sandre		case BOTH_SYN:			/* move to established */
950133069Sandre		case BOTH_SYN | TH_FIN :	/* one side tries to close */
951133069Sandre		case BOTH_SYN | (TH_FIN << 8) :
952133069Sandre 			if (tcp) {
953133069Sandre#define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
954133069Sandre			    u_int32_t ack = ntohl(tcp->th_ack);
955133069Sandre			    if (dir == MATCH_FORWARD) {
956133069Sandre				if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
957133069Sandre				    q->ack_fwd = ack;
958133069Sandre				else { /* ignore out-of-sequence */
959133069Sandre				    break;
960133069Sandre				}
961133069Sandre			    } else {
962133069Sandre				if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
963133069Sandre				    q->ack_rev = ack;
964133069Sandre				else { /* ignore out-of-sequence */
965133069Sandre				    break;
966133069Sandre				}
967133069Sandre			    }
968133069Sandre			}
969133069Sandre			q->expire = time_second + dyn_ack_lifetime;
970133069Sandre			break;
971133069Sandre
972133069Sandre		case BOTH_SYN | BOTH_FIN:	/* both sides closed */
973133069Sandre			if (dyn_fin_lifetime >= dyn_keepalive_period)
974133069Sandre				dyn_fin_lifetime = dyn_keepalive_period - 1;
975133069Sandre			q->expire = time_second + dyn_fin_lifetime;
976133069Sandre			break;
977133069Sandre
978133069Sandre		default:
979133069Sandre#if 0
980133069Sandre			/*
9811541Srgrimes			 * reset or some invalid combination, but can also
9821541Srgrimes			 * occur if we use keep-state the wrong way.
9831541Srgrimes			 */
9841541Srgrimes			if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
9851541Srgrimes				printf("invalid state: 0x%x\n", q->state);
9861541Srgrimes#endif
9871541Srgrimes			if (dyn_rst_lifetime >= dyn_keepalive_period)
9881541Srgrimes				dyn_rst_lifetime = dyn_keepalive_period - 1;
9891541Srgrimes			q->expire = time_second + dyn_rst_lifetime;
990115909Srwatson			break;
991111119Simp		}
9921541Srgrimes	} else if (pkt->proto == IPPROTO_UDP) {
9931541Srgrimes		q->expire = time_second + dyn_udp_lifetime;
994101095Srwatson	} else {
995112675Srwatson		/* other protocols */
996112675Srwatson		q->expire = time_second + dyn_short_lifetime;
997112675Srwatson	}
998112675Srwatsondone:
999101095Srwatson	if (match_direction)
1000101095Srwatson		*match_direction = dir;
100174362Sphk	return q;
100229480Sache}
1003111244Ssilby
10041541Srgrimesstatic ipfw_dyn_rule *
10051541Srgrimeslookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
10061541Srgrimes	struct tcphdr *tcp)
100738513Sdfr{
100838513Sdfr	ipfw_dyn_rule *q;
100941993Sluigi
101041993Sluigi	IPFW_DYN_LOCK();
101141993Sluigi	q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
1012101095Srwatson	if (q == NULL)
1013111244Ssilby		IPFW_DYN_UNLOCK();
1014101095Srwatson	/* NB: return table locked when q is not NULL */
1015101095Srwatson	return q;
1016101095Srwatson}
10171541Srgrimes
10181541Srgrimesstatic void
101938513Sdfrrealloc_dynamic_table(void)
102038513Sdfr{
10211541Srgrimes	IPFW_DYN_LOCK_ASSERT();
1022121684Sume
1023121684Sume	/*
1024121684Sume	 * Try reallocation, make sure we have a power of 2 and do
1025121684Sume	 * not allow more than 64k entries. In case of overflow,
1026121684Sume	 * default to 1024.
1027121684Sume	 */
1028121684Sume
1029121684Sume	if (dyn_buckets > 65536)
1030121684Sume		dyn_buckets = 1024;
1031121684Sume	if ((dyn_buckets & (dyn_buckets-1)) != 0) { /* not a power of 2 */
1032121684Sume		dyn_buckets = curr_dyn_buckets; /* reset */
1033121684Sume		return;
1034121684Sume	}
1035121684Sume	curr_dyn_buckets = dyn_buckets;
1036121684Sume	if (ipfw_dyn_v != NULL)
1037121684Sume		free(ipfw_dyn_v, M_IPFW);
10381541Srgrimes	for (;;) {
10391541Srgrimes		ipfw_dyn_v = malloc(curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
104038513Sdfr		       M_IPFW, M_NOWAIT | M_ZERO);
104138513Sdfr		if (ipfw_dyn_v != NULL || curr_dyn_buckets <= 2)
10421541Srgrimes			break;
10431541Srgrimes		curr_dyn_buckets /= 2;
10441541Srgrimes	}
10451541Srgrimes}
10461541Srgrimes
104741993Sluigi/**
104841993Sluigi * Install state of type 'type' for a dynamic session.
104958698Sjlemon * The hash table contains two type of rules:
105058698Sjlemon * - regular rules (O_KEEP_STATE)
105158698Sjlemon * - rules for sessions with limited number of sess per user
10521541Srgrimes *   (O_LIMIT). When they are created, the parent is
105338513Sdfr *   increased by 1, and decreased on delete. In this case,
105438513Sdfr *   the third parameter is the parent rule and not the chain.
10551541Srgrimes * - "parent" rules for the above (O_LIMIT_PARENT).
10561541Srgrimes */
10571541Srgrimesstatic ipfw_dyn_rule *
105855009Sshinadd_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
105958698Sjlemon{
10601541Srgrimes	ipfw_dyn_rule *r;
10611541Srgrimes	int i;
10621541Srgrimes
106341993Sluigi	IPFW_DYN_LOCK_ASSERT();
106441993Sluigi
106541993Sluigi	if (ipfw_dyn_v == NULL ||
106641993Sluigi	    (dyn_count == 0 && dyn_buckets != curr_dyn_buckets)) {
106741993Sluigi		realloc_dynamic_table();
10681541Srgrimes		if (ipfw_dyn_v == NULL)
10691541Srgrimes			return NULL; /* failed ! */
10701541Srgrimes	}
10711541Srgrimes	i = hash_packet(id);
10721541Srgrimes
10731541Srgrimes	r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
107438513Sdfr	if (r == NULL) {
107541993Sluigi		printf ("ipfw: sorry cannot allocate state\n");
1076111479Smaxim		return NULL;
107738513Sdfr	}
107838513Sdfr
107938513Sdfr	/* increase refcount on parent, and set pointer */
108038513Sdfr	if (dyn_type == O_LIMIT) {
108158698Sjlemon		ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
10821541Srgrimes		if ( parent->dyn_type != O_LIMIT_PARENT)
10831541Srgrimes			panic("invalid parent");
108438513Sdfr		parent->count++;
108541993Sluigi		r->parent = parent;
1086111478Smaxim		rule = parent->rule;
1087111244Ssilby	}
108838513Sdfr
10891541Srgrimes	r->id = *id;
10901541Srgrimes	r->expire = time_second + dyn_syn_lifetime;
109141993Sluigi	r->rule = rule;
109217072Sjulian	r->dyn_type = dyn_type;
109317072Sjulian	r->pcnt = r->bcnt = 0;
1094126239Smlaier	r->count = 0;
1095126239Smlaier
1096126239Smlaier	r->bucket = i;
1097126239Smlaier	r->next = ipfw_dyn_v[i];
1098126239Smlaier	ipfw_dyn_v[i] = r;
1099126239Smlaier	dyn_count++;
1100126239Smlaier	DEB(printf("ipfw: add dyn entry ty %d 0x%08x %d -> 0x%08x %d, total %d\n",
1101126239Smlaier	   dyn_type,
110298613Sluigi	   (r->id.src_ip), (r->id.src_port),
110317072Sjulian	   (r->id.dst_ip), (r->id.dst_port),
110417072Sjulian	   dyn_count ); )
110517072Sjulian	return r;
1106111244Ssilby}
1107111244Ssilby
1108111244Ssilby/**
1109111244Ssilby * lookup dynamic parent rule using pkt and rule as search keys.
1110111244Ssilby * If the lookup fails, then install one.
1111111244Ssilby */
1112111244Ssilbystatic ipfw_dyn_rule *
1113111244Ssilbylookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
11141541Srgrimes{
11151541Srgrimes	ipfw_dyn_rule *q;
111638513Sdfr	int i;
1117111244Ssilby
1118111478Smaxim	IPFW_DYN_LOCK_ASSERT();
1119111478Smaxim
1120111244Ssilby	if (ipfw_dyn_v) {
1121111478Smaxim		i = hash_packet( pkt );
1122133069Sandre		for (q = ipfw_dyn_v[i] ; q != NULL ; q=q->next)
1123111244Ssilby			if (q->dyn_type == O_LIMIT_PARENT &&
112438513Sdfr			    rule== q->rule &&
11251541Srgrimes			    pkt->proto == q->id.proto &&
112638513Sdfr			    pkt->src_ip == q->id.src_ip &&
1127111244Ssilby			    pkt->dst_ip == q->id.dst_ip &&
1128111478Smaxim			    pkt->src_port == q->id.src_port &&
1129111478Smaxim			    pkt->dst_port == q->id.dst_port) {
1130111244Ssilby				q->expire = time_second + dyn_short_lifetime;
1131111478Smaxim				DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
1132133069Sandre				return q;
1133111244Ssilby			}
11341541Srgrimes	}
11351541Srgrimes	return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
113619183Sfenner}
11371541Srgrimes
113838513Sdfr/**
113938513Sdfr * Install dynamic state for rule type cmd->o.opcode
1140105586Sphk *
114119183Sfenner * Returns 1 (failure) if state is not installed because of errors or because
1142111478Smaxim * session limitations are enforced.
114374362Sphk */
1144133069Sandrestatic int
114519183Sfennerinstall_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
114619183Sfenner	struct ip_fw_args *args)
114719183Sfenner{
114819183Sfenner	static int last_log;
114919183Sfenner
115038513Sdfr	ipfw_dyn_rule *q;
11511541Srgrimes
11521541Srgrimes	DEB(printf("ipfw: install state type %d 0x%08x %u -> 0x%08x %u\n",
11531541Srgrimes	    cmd->o.opcode,
115438513Sdfr	    (args->f_id.src_ip), (args->f_id.src_port),
115539043Sdfr	    (args->f_id.dst_ip), (args->f_id.dst_port) );)
115638513Sdfr
115738513Sdfr	IPFW_DYN_LOCK();
115839043Sdfr
115958698Sjlemon	q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
116058698Sjlemon
116165859Sjlemon	if (q != NULL) { /* should never occur */
11621541Srgrimes		if (last_log != time_second) {
1163101095Srwatson			last_log = time_second;
1164101095Srwatson			printf("ipfw: install_state: entry already present, done\n");
1165101095Srwatson		}
1166101095Srwatson		IPFW_DYN_UNLOCK();
11671541Srgrimes		return 0;
11681541Srgrimes	}
1169133069Sandre
1170133069Sandre	if (dyn_count >= dyn_max)
11711541Srgrimes		/*
11721541Srgrimes		 * Run out of slots, try to remove any expired rule.
1173133069Sandre		 */
117438513Sdfr		remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
117538513Sdfr
117674362Sphk	if (dyn_count >= dyn_max) {
117729480Sache		if (last_log != time_second) {
11781541Srgrimes			last_log = time_second;
1179105586Sphk			printf("ipfw: install_state: Too many dynamic rules\n");
1180105586Sphk		}
11811541Srgrimes		IPFW_DYN_UNLOCK();
1182103553Sphk		return 1; /* cannot install, notify caller */
1183103553Sphk	}
1184133069Sandre
1185133069Sandre	switch (cmd->o.opcode) {
118655009Sshin	case O_KEEP_STATE: /* bidir rule */
11871541Srgrimes		add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
11881541Srgrimes		break;
11891541Srgrimes
1190115909Srwatson	case O_LIMIT: /* limit number of sessions */
1191111244Ssilby	    {
11921541Srgrimes		u_int16_t limit_mask = cmd->limit_mask;
1193133069Sandre		struct ipfw_flow_id id;
1194133069Sandre		ipfw_dyn_rule *parent;
1195133069Sandre
119638513Sdfr		DEB(printf("ipfw: installing dyn-limit rule %d\n",
119738513Sdfr		    cmd->conn_limit);)
11981541Srgrimes
11991541Srgrimes		id.dst_ip = id.src_ip = 0;
12001541Srgrimes		id.dst_port = id.src_port = 0;
12011541Srgrimes		id.proto = args->f_id.proto;
12021541Srgrimes
12031541Srgrimes		if (limit_mask & DYN_SRC_ADDR)
120412296Sphk			id.src_ip = args->f_id.src_ip;
120574362Sphk		if (limit_mask & DYN_DST_ADDR)
120674362Sphk			id.dst_ip = args->f_id.dst_ip;
12071541Srgrimes		if (limit_mask & DYN_SRC_PORT)
12081541Srgrimes			id.src_port = args->f_id.src_port;
120938513Sdfr		if (limit_mask & DYN_DST_PORT)
12101541Srgrimes			id.dst_port = args->f_id.dst_port;
1211119753Ssam		parent = lookup_dyn_parent(&id, rule);
1212119753Ssam		if (parent == NULL) {
121338513Sdfr			printf("ipfw: add parent failed\n");
121438513Sdfr			return 1;
121538513Sdfr		}
121638513Sdfr		if (parent->count >= cmd->conn_limit) {
12171541Srgrimes			/*
121874362Sphk			 * See if we can remove some expired rule.
12191541Srgrimes			 */
122029480Sache			remove_dyn_rule(rule, parent);
12211541Srgrimes			if (parent->count >= cmd->conn_limit) {
12221541Srgrimes				if (fw_verbose && last_log != time_second) {
12231541Srgrimes					last_log = time_second;
12241541Srgrimes					log(LOG_SECURITY | LOG_DEBUG,
12251541Srgrimes					    "drop session, too many entries\n");
12261541Srgrimes				}
12271541Srgrimes				IPFW_DYN_UNLOCK();
12281541Srgrimes				return 1;
12291541Srgrimes			}
12301541Srgrimes		}
12311541Srgrimes		add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
12321541Srgrimes	    }
123329480Sache		break;
12341541Srgrimes	default:
1235119753Ssam		printf("ipfw: unknown dynamic rule type %u\n", cmd->o.opcode);
123629480Sache		IPFW_DYN_UNLOCK();
123774362Sphk		return 1;
123874362Sphk	}
123974362Sphk	lookup_dyn_rule_locked(&args->f_id, NULL, NULL); /* XXX just set lifetime */
124074362Sphk	IPFW_DYN_UNLOCK();
124174362Sphk	return 0;
124274362Sphk}
1243111478Smaxim
124474362Sphk/*
124529480Sache * Transmit a TCP packet, containing either a RST or a keepalive.
12461541Srgrimes * When flags & TH_RST, we are sending a RST packet, because of a
12471541Srgrimes * "reset" action matched the packet.
124877665Sjesper * Otherwise we are sending a keepalive, and flags & TH_
124977665Sjesper */
125077665Sjesperstatic void
125177665Sjespersend_pkt(struct ipfw_flow_id *id, u_int32_t seq, u_int32_t ack, int flags)
125277665Sjesper{
1253111541Ssilby	struct mbuf *m;
1254110178Ssilby	struct ip *ip;
1255111479Smaxim	struct tcphdr *tcp;
1256111478Smaxim
1257111478Smaxim	MGETHDR(m, M_DONTWAIT, MT_HEADER);
125877665Sjesper	if (m == 0)
125977665Sjesper		return;
126077665Sjesper	m->m_pkthdr.rcvif = (struct ifnet *)0;
126177665Sjesper	m->m_pkthdr.len = m->m_len = sizeof(struct ip) + sizeof(struct tcphdr);
1262119753Ssam	m->m_data += max_linkhdr;
12631541Srgrimes
12641541Srgrimes	ip = mtod(m, struct ip *);
12651541Srgrimes	bzero(ip, m->m_len);
12661541Srgrimes	tcp = (struct tcphdr *)(ip + 1); /* no IP options */
12671541Srgrimes	ip->ip_p = IPPROTO_TCP;
12681541Srgrimes	tcp->th_off = 5;
12691541Srgrimes	/*
12701541Srgrimes	 * Assume we are sending a RST (or a keepalive in the reverse
12711541Srgrimes	 * direction), swap src and destination addresses and ports.
127229480Sache	 */
127329480Sache	ip->ip_src.s_addr = htonl(id->dst_ip);
1274119753Ssam	ip->ip_dst.s_addr = htonl(id->src_ip);
127529480Sache	tcp->th_sport = htons(id->dst_port);
127674362Sphk	tcp->th_dport = htons(id->src_port);
1277111478Smaxim	if (flags & TH_RST) {	/* we are sending a RST */
1278111478Smaxim		if (flags & TH_ACK) {
127974362Sphk			tcp->th_seq = htonl(ack);
128029480Sache			tcp->th_ack = htonl(0);
12811541Srgrimes			tcp->th_flags = TH_RST;
1282119753Ssam		} else {
128312933Swollman			if (flags & TH_SYN)
12841541Srgrimes				seq++;
12851541Srgrimes			tcp->th_seq = htonl(0);
12861541Srgrimes			tcp->th_ack = htonl(seq);
12871541Srgrimes			tcp->th_flags = TH_RST | TH_ACK;
12881541Srgrimes		}
12891541Srgrimes	} else {
129088665Syar		/*
129188665Syar		 * We are sending a keepalive. flags & TH_SYN determines
129288665Syar		 * the direction, forward if set, reverse if clear.
129388665Syar		 * NOTE: seq and ack are always assumed to be correct
129488665Syar		 * as set by the caller. This may be confusing...
12951541Srgrimes		 */
12961541Srgrimes		if (flags & TH_SYN) {
12971541Srgrimes			/*
129812296Sphk			 * we have to rewrite the correct addresses!
129998613Sluigi			 */
13001541Srgrimes			ip->ip_dst.s_addr = htonl(id->dst_ip);
130198613Sluigi			ip->ip_src.s_addr = htonl(id->src_ip);
130298613Sluigi			tcp->th_dport = htons(id->dst_port);
130398613Sluigi			tcp->th_sport = htons(id->src_port);
13041541Srgrimes		}
13051541Srgrimes		tcp->th_seq = htonl(seq);
13061541Srgrimes		tcp->th_ack = htonl(ack);
130798701Sluigi		tcp->th_flags = TH_ACK;
13081541Srgrimes	}
1309129017Sandre	/*
1310129017Sandre	 * set ip_len to the payload size so we can compute
1311129017Sandre	 * the tcp checksum on the pseudoheader
1312129017Sandre	 * XXX check this, could save a couple of words ?
1313129017Sandre	 */
1314129017Sandre	ip->ip_len = htons(sizeof(struct tcphdr));
1315129017Sandre	tcp->th_sum = in_cksum(m, m->m_pkthdr.len);
1316129017Sandre	/*
1317129017Sandre	 * now fill fields left out earlier
13181541Srgrimes	 */
13191541Srgrimes	ip->ip_ttl = ip_defttl;
1320105586Sphk	ip->ip_len = m->m_pkthdr.len;
13211541Srgrimes	m->m_flags |= M_SKIP_FIREWALL;
13221541Srgrimes	ip_output(m, NULL, NULL, 0, NULL, NULL);
13231541Srgrimes}
13241541Srgrimes
13251541Srgrimes/*
13261541Srgrimes * sends a reject message, consuming the mbuf passed as an argument.
13271541Srgrimes */
132860304Sitojunstatic void
132960304Sitojunsend_reject(struct ip_fw_args *args, int code, int offset, int ip_len)
133060304Sitojun{
133160304Sitojun
13321541Srgrimes	if (code != ICMP_REJECT_RST) { /* Send an ICMP unreach */
133361183Sjlemon		/* We need the IP header in host order for icmp_error(). */
13341541Srgrimes		if (args->eh != NULL) {
13351541Srgrimes			struct ip *ip = mtod(args->m, struct ip *);
13361541Srgrimes			ip->ip_len = ntohs(ip->ip_len);
13371541Srgrimes			ip->ip_off = ntohs(ip->ip_off);
13381541Srgrimes		}
13391541Srgrimes		icmp_error(args->m, ICMP_UNREACH, code, 0L, 0);
13401541Srgrimes	} else if (offset == 0 && args->f_id.proto == IPPROTO_TCP) {
13411541Srgrimes		struct tcphdr *const tcp =
13421541Srgrimes		    L3HDR(struct tcphdr, mtod(args->m, struct ip *));
13431541Srgrimes		if ( (tcp->th_flags & TH_RST) == 0)
13441541Srgrimes			send_pkt(&(args->f_id), ntohl(tcp->th_seq),
13451541Srgrimes				ntohl(tcp->th_ack),
13461541Srgrimes				tcp->th_flags | TH_RST);
13471541Srgrimes		m_freem(args->m);
13481541Srgrimes	} else
13491541Srgrimes		m_freem(args->m);
13501541Srgrimes	args->m = NULL;
13511541Srgrimes}
13521541Srgrimes
13531541Srgrimes/**
135488665Syar *
135588665Syar * Given an ip_fw *, lookup_next_rule will return a pointer
135688665Syar * to the next rule, which can be either the jump
135788665Syar * target (for skipto instructions) or the next one in the list (in
135878064Sume * all other cases including a missing jump target).
135978064Sume * The result is also written in the "next_rule" field of the rule.
136078064Sume * Backward jumps are not allowed, so start looking from the next
136178064Sume * rule...
13621541Srgrimes *
13631541Srgrimes * This never returns NULL -- in case we do not have an exact match,
13641541Srgrimes * the next rule is returned. When the ruleset is changed,
13651541Srgrimes * pointers are flushed so we are always correct.
13661541Srgrimes */
13671541Srgrimes
13681541Srgrimesstatic struct ip_fw *
1369133481Sandrelookup_next_rule(struct ip_fw *me)
13701541Srgrimes{
13711541Srgrimes	struct ip_fw *rule = NULL;
13721541Srgrimes	ipfw_insn *cmd;
13731541Srgrimes
13741541Srgrimes	/* look for action, in case it is a skipto */
137530816Sguido	cmd = ACTION_PTR(me);
137630816Sguido	if (cmd->opcode == O_LOG)
13771541Srgrimes		cmd += F_LEN(cmd);
13781541Srgrimes	if (cmd->opcode == O_ALTQ)
13791541Srgrimes		cmd += F_LEN(cmd);
13801541Srgrimes	if ( cmd->opcode == O_SKIPTO )
13811541Srgrimes		for (rule = me->next; rule ; rule = rule->next)
13821541Srgrimes			if (rule->rulenum >= cmd->arg1)
13831541Srgrimes				break;
138460661Sjlemon	if (rule == NULL)			/* failure or not a skipto */
13851541Srgrimes		rule = me->next;
13861541Srgrimes	me->next_rule = rule;
13871541Srgrimes	return rule;
138833440Sguido}
138933440Sguido
13901541Srgrimesstatic void
13911541Srgrimesinit_tables(void)
13921541Srgrimes{
139388665Syar	int i;
139488665Syar
139588665Syar	for (i = 0; i < IPFW_TABLES_MAX; i++) {
139688665Syar		rn_inithead((void **)&ipfw_tables[i].rnh, 32);
13977091Swollman		ipfw_tables[i].modified = 1;
139837498Sdg	}
139937498Sdg}
140037498Sdg
140137498Sdgstatic int
140237498Sdgadd_table_entry(u_int16_t tbl, in_addr_t addr, u_int8_t mlen, u_int32_t value)
140330790Sguido{
140437498Sdg	struct radix_node_head *rnh;
140537498Sdg	struct table_entry *ent;
140637498Sdg
140737498Sdg	if (tbl >= IPFW_TABLES_MAX)
140837498Sdg		return (EINVAL);
140937498Sdg	rnh = ipfw_tables[tbl].rnh;
141037498Sdg	ent = malloc(sizeof(*ent), M_IPFW_TBL, M_NOWAIT | M_ZERO);
141137498Sdg	if (ent == NULL)
141237498Sdg		return (ENOMEM);
141337498Sdg	ent->value = value;
141437498Sdg	ent->addr.sin_len = ent->mask.sin_len = 8;
141588665Syar	ent->mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
141688665Syar	ent->addr.sin_addr.s_addr = addr & ent->mask.sin_addr.s_addr;
141788665Syar	RADIX_NODE_HEAD_LOCK(rnh);
141837498Sdg	if (rnh->rnh_addaddr(&ent->addr, &ent->mask, rnh, (void *)ent) ==
141937498Sdg	    NULL) {
142037498Sdg		RADIX_NODE_HEAD_UNLOCK(rnh);
142137498Sdg		free(ent, M_IPFW_TBL);
14227091Swollman		return (EEXIST);
14237091Swollman	}
14241541Srgrimes	ipfw_tables[tbl].modified = 1;
14251541Srgrimes	RADIX_NODE_HEAD_UNLOCK(rnh);
14261541Srgrimes	return (0);
14278384Sdg}
14281541Srgrimes
14297091Swollmanstatic int
14301541Srgrimesdel_table_entry(u_int16_t tbl, in_addr_t addr, u_int8_t mlen)
14311541Srgrimes{
14321541Srgrimes	struct radix_node_head *rnh;
1433133481Sandre	struct table_entry *ent;
14341541Srgrimes	struct sockaddr_in sa, mask;
14351541Srgrimes
1436122708Sandre	if (tbl >= IPFW_TABLES_MAX)
1437133481Sandre		return (EINVAL);
14381541Srgrimes	rnh = ipfw_tables[tbl].rnh;
14391541Srgrimes	sa.sin_len = mask.sin_len = 8;
14401541Srgrimes	mask.sin_addr.s_addr = htonl(mlen ? ~((1 << (32 - mlen)) - 1) : 0);
14411541Srgrimes	sa.sin_addr.s_addr = addr & mask.sin_addr.s_addr;
14421541Srgrimes	RADIX_NODE_HEAD_LOCK(rnh);
14438384Sdg	ent = (struct table_entry *)rnh->rnh_deladdr(&sa, &mask, rnh);
14448384Sdg	if (ent == NULL) {
14451541Srgrimes		RADIX_NODE_HEAD_UNLOCK(rnh);
14461541Srgrimes		return (ESRCH);
14471541Srgrimes	}
14481541Srgrimes	ipfw_tables[tbl].modified = 1;
14491541Srgrimes	RADIX_NODE_HEAD_UNLOCK(rnh);
14501541Srgrimes	free(ent, M_IPFW_TBL);
14511541Srgrimes	return (0);
14521541Srgrimes}
145388665Syar
145488665Syarstatic int
145588665Syarflush_table_entry(struct radix_node *rn, void *arg)
145688665Syar{
145761183Sjlemon	struct radix_node_head * const rnh = arg;
145861183Sjlemon	struct table_entry *ent;
145961183Sjlemon
146061183Sjlemon	ent = (struct table_entry *)
14611541Srgrimes	    rnh->rnh_deladdr(rn->rn_key, rn->rn_mask, rnh);
14621541Srgrimes	if (ent != NULL)
14631541Srgrimes		free(ent, M_IPFW_TBL);
14641541Srgrimes	return (0);
14651541Srgrimes}
14661541Srgrimes
14671541Srgrimesstatic int
14681541Srgrimesflush_table(u_int16_t tbl)
146960661Sjlemon{
14701541Srgrimes	struct radix_node_head *rnh;
14718384Sdg
14721541Srgrimes	if (tbl >= IPFW_TABLES_MAX)
14731541Srgrimes		return (EINVAL);
14741541Srgrimes	rnh = ipfw_tables[tbl].rnh;
14751541Srgrimes	RADIX_NODE_HEAD_LOCK(rnh);
14761541Srgrimes	rnh->rnh_walktree(rnh, flush_table_entry, rnh);
1477133481Sandre	ipfw_tables[tbl].modified = 1;
1478133481Sandre	RADIX_NODE_HEAD_UNLOCK(rnh);
14791541Srgrimes	return (0);
14801541Srgrimes}
14811541Srgrimes
14821541Srgrimesstatic void
14838384Sdgflush_tables(void)
14848384Sdg{
14851541Srgrimes	u_int16_t tbl;
14861541Srgrimes
14871541Srgrimes	for (tbl = 0; tbl < IPFW_TABLES_MAX; tbl++)
14881541Srgrimes		flush_table(tbl);
148988665Syar}
149088665Syar
149188665Syarstatic int
149288665Syarlookup_table(u_int16_t tbl, in_addr_t addr, u_int32_t *val)
14931541Srgrimes{
149485467Sjlemon	struct radix_node_head *rnh;
149585467Sjlemon	struct table_entry *ent;
14961541Srgrimes	struct sockaddr_in sa;
149778064Sume	static in_addr_t last_addr;
149885467Sjlemon	static int last_tbl;
149985467Sjlemon	static int last_match;
150078064Sume	static u_int32_t last_value;
150178064Sume
150285467Sjlemon	if (tbl >= IPFW_TABLES_MAX)
150385467Sjlemon		return (0);
150485467Sjlemon	if (tbl == last_tbl && addr == last_addr &&
150585467Sjlemon	    !ipfw_tables[tbl].modified) {
15061541Srgrimes		if (last_match)
150778064Sume			*val = last_value;
15081541Srgrimes		return (last_match);
15091541Srgrimes	}
151085467Sjlemon	rnh = ipfw_tables[tbl].rnh;
151185467Sjlemon	sa.sin_len = 8;
151285467Sjlemon	sa.sin_addr.s_addr = addr;
15131541Srgrimes	RADIX_NODE_HEAD_LOCK(rnh);
15141541Srgrimes	ipfw_tables[tbl].modified = 0;
15151541Srgrimes	ent = (struct table_entry *)(rnh->rnh_lookup(&sa, NULL, rnh));
15161541Srgrimes	RADIX_NODE_HEAD_UNLOCK(rnh);
15171541Srgrimes	last_addr = addr;
151885467Sjlemon	last_tbl = tbl;
151985467Sjlemon	if (ent != NULL) {
152085467Sjlemon		last_value = *val = ent->value;
15211541Srgrimes		last_match = 1;
152278064Sume		return (1);
15231541Srgrimes	}
15241541Srgrimes	last_match = 0;
15251541Srgrimes	return (0);
1526133481Sandre}
15271541Srgrimes
15288384Sdgstatic int
15298384Sdgcount_table_entry(struct radix_node *rn, void *arg)
153085467Sjlemon{
1531104774Smaxim	u_int32_t * const cnt = arg;
15321541Srgrimes
15331541Srgrimes	(*cnt)++;
15341541Srgrimes	return (0);
153585467Sjlemon}
153685467Sjlemon
153785467Sjlemonstatic int
15381541Srgrimescount_table(u_int32_t tbl, u_int32_t *cnt)
153978064Sume{
15408384Sdg	struct radix_node_head *rnh;
15411541Srgrimes
1542133481Sandre	if (tbl >= IPFW_TABLES_MAX)
15431541Srgrimes		return (EINVAL);
154485467Sjlemon	rnh = ipfw_tables[tbl].rnh;
1545104774Smaxim	*cnt = 0;
15461541Srgrimes	RADIX_NODE_HEAD_LOCK(rnh);
15471541Srgrimes	rnh->rnh_walktree(rnh, count_table_entry, cnt);
15481541Srgrimes	RADIX_NODE_HEAD_UNLOCK(rnh);
154985467Sjlemon	return (0);
15501541Srgrimes}
15511541Srgrimes
15521541Srgrimesstatic int
155385467Sjlemondump_table_entry(struct radix_node *rn, void *arg)
155485467Sjlemon{
15551541Srgrimes	struct table_entry * const n = (struct table_entry *)rn;
15561541Srgrimes	ipfw_table * const tbl = arg;
155733268Sache	ipfw_table_entry *ent;
1558122708Sandre
15591541Srgrimes	if (tbl->cnt == tbl->size)
15601541Srgrimes		return (1);
15611541Srgrimes	ent = &tbl->ent[tbl->cnt];
15621541Srgrimes	ent->tbl = tbl->tbl;
15631541Srgrimes	if (in_nullhost(n->mask.sin_addr))
15641541Srgrimes		ent->masklen = 0;
15651541Srgrimes	else
15661541Srgrimes		ent->masklen = 33 - ffs(ntohl(n->mask.sin_addr.s_addr));
15671541Srgrimes	ent->addr = n->addr.sin_addr.s_addr;
15681541Srgrimes	ent->value = n->value;
15691541Srgrimes	tbl->cnt++;
15701541Srgrimes	return (0);
15711541Srgrimes}
157287120Sru
1573122708Sandrestatic int
157487120Srudump_table(ipfw_table *tbl)
15751541Srgrimes{
1576122922Sandre	struct radix_node_head *rnh;
1577122708Sandre
1578122708Sandre	if (tbl->tbl >= IPFW_TABLES_MAX)
15791541Srgrimes		return (EINVAL);
1580122996Sandre	rnh = ipfw_tables[tbl->tbl].rnh;
1581122922Sandre	tbl->cnt = 0;
1582122708Sandre	RADIX_NODE_HEAD_LOCK(rnh);
1583122708Sandre	rnh->rnh_walktree(rnh, dump_table_entry, tbl);
1584122708Sandre	RADIX_NODE_HEAD_UNLOCK(rnh);
1585122922Sandre	return (0);
15861541Srgrimes}
1587122922Sandre
1588122708Sandrestatic void
15891541Srgrimesfill_ugid_cache(struct inpcb *inp, struct ip_fw_ugid *ugp)
1590122922Sandre{
1591122922Sandre	struct ucred *cr;
1592122708Sandre
15931541Srgrimes	if (inp->inp_socket != NULL) {
15941541Srgrimes		cr = inp->inp_socket->so_cred;
15951541Srgrimes		ugp->fw_prid = jailed(cr) ?
15961541Srgrimes		    cr->cr_prison->pr_id : -1;
15971541Srgrimes		ugp->fw_uid = cr->cr_uid;
15981541Srgrimes		ugp->fw_ngroups = cr->cr_ngroups;
1599104094Sphk		bcopy(cr->cr_groups, ugp->fw_groups,
16001541Srgrimes		    sizeof(ugp->fw_groups));
16011541Srgrimes	}
16021541Srgrimes}
16031541Srgrimes
16041541Srgrimesstatic int
16051541Srgrimescheck_uidgid(ipfw_insn_u32 *insn,
16061541Srgrimes	int proto, struct ifnet *oif,
16071541Srgrimes	struct in_addr dst_ip, u_int16_t dst_port,
16081541Srgrimes	struct in_addr src_ip, u_int16_t src_port,
16091541Srgrimes	struct ip_fw_ugid *ugp, int *lookup, struct inpcb *inp)
16101541Srgrimes{
16111541Srgrimes	struct inpcbinfo *pi;
16121541Srgrimes	int wildcard;
161316206Sbde	struct inpcb *pcb;
16141541Srgrimes	int match;
16151541Srgrimes	gid_t *gp;
16161541Srgrimes
16171541Srgrimes	/*
16181541Srgrimes	 * Check to see if the UDP or TCP stack supplied us with
16191541Srgrimes	 * the PCB. If so, rather then holding a lock and looking
16201541Srgrimes	 * up the PCB, we can use the one that was supplied.
16211541Srgrimes	 */
16221541Srgrimes	if (inp && *lookup == 0) {
16231541Srgrimes		INP_LOCK_ASSERT(inp);
16241541Srgrimes		if (inp->inp_socket != NULL) {
16251541Srgrimes			fill_ugid_cache(inp, ugp);
16261541Srgrimes			*lookup = 1;
16271541Srgrimes		}
16281541Srgrimes	}
16291541Srgrimes	/*
16301541Srgrimes	 * If we have already been here and the packet has no
1631111119Simp	 * PCB entry associated with it, then we can safely
1632133481Sandre	 * assume that this is a no match.
16331541Srgrimes	 */
16341541Srgrimes	if (*lookup == -1)
16351541Srgrimes		return (0);
16361541Srgrimes	if (proto == IPPROTO_TCP) {
16371541Srgrimes		wildcard = 0;
16381541Srgrimes		pi = &tcbinfo;
16391541Srgrimes	} else if (proto == IPPROTO_UDP) {
16401541Srgrimes		wildcard = 1;
16411541Srgrimes		pi = &udbinfo;
16421541Srgrimes	} else
16431541Srgrimes		return 0;
16441541Srgrimes	match = 0;
16451541Srgrimes	if (*lookup == 0) {
16461541Srgrimes		INP_INFO_RLOCK(pi);
16471541Srgrimes		pcb =  (oif) ?
16481541Srgrimes			in_pcblookup_hash(pi,
16491541Srgrimes				dst_ip, htons(dst_port),
16501541Srgrimes				src_ip, htons(src_port),
16511541Srgrimes				wildcard, oif) :
165241993Sluigi			in_pcblookup_hash(pi,
16531541Srgrimes				src_ip, htons(src_port),
16541541Srgrimes				dst_ip, htons(dst_port),
16551541Srgrimes				wildcard, NULL);
16561541Srgrimes		if (pcb != NULL) {
16571541Srgrimes			INP_LOCK(pcb);
16581541Srgrimes			if (pcb->inp_socket != NULL) {
16591541Srgrimes				fill_ugid_cache(pcb, ugp);
16608384Sdg				*lookup = 1;
16618384Sdg			}
16621541Srgrimes			INP_UNLOCK(pcb);
16631541Srgrimes		}
16641541Srgrimes		INP_INFO_RUNLOCK(pi);
16651541Srgrimes		if (*lookup == 0) {
16661541Srgrimes			/*
16671541Srgrimes			 * If the lookup did not yield any results, there
16681541Srgrimes			 * is no sense in coming back and trying again. So
16691541Srgrimes			 * we can set lookup to -1 and ensure that we wont
16701541Srgrimes			 * bother the pcb system again.
16711541Srgrimes			 */
167241993Sluigi			*lookup = -1;
16731541Srgrimes			return (0);
16741541Srgrimes		}
16751541Srgrimes	}
16761541Srgrimes	if (insn->o.opcode == O_UID)
16771541Srgrimes		match = (ugp->fw_uid == (uid_t)insn->d[0]);
16781541Srgrimes	else if (insn->o.opcode == O_GID) {
16791541Srgrimes		for (gp = ugp->fw_groups;
16801541Srgrimes			gp < &ugp->fw_groups[ugp->fw_ngroups]; gp++)
16811541Srgrimes			if (*gp == (gid_t)insn->d[0]) {
168241993Sluigi				match = 1;
16831541Srgrimes				break;
16841541Srgrimes			}
16851541Srgrimes	} else if (insn->o.opcode == O_JAIL)
16861541Srgrimes		match = (ugp->fw_prid == (int)insn->d[0]);
16871541Srgrimes	return match;
16881541Srgrimes}
16891541Srgrimes
16901541Srgrimes/*
16911541Srgrimes * The main check routine for the firewall.
16921541Srgrimes *
16931541Srgrimes * All arguments are in args so we can modify them and return them
16941541Srgrimes * back to the caller.
16951541Srgrimes *
16961541Srgrimes * Parameters:
16971541Srgrimes *
16981541Srgrimes *	args->m	(in/out) The packet; we set to NULL when/if we nuke it.
16991541Srgrimes *		Starts with the IP header.
17001541Srgrimes *	args->eh (in)	Mac header if present, or NULL for layer3 packet.
17011541Srgrimes *	args->oif	Outgoing interface, or NULL if packet is incoming.
17021541Srgrimes *		The incoming interface is in the mbuf. (in)
17031541Srgrimes *	args->divert_rule (in/out)
1704105586Sphk *		Skip up to the first rule past this rule number;
17051541Srgrimes *		upon return, non-zero port number for divert or tee.
17061541Srgrimes *
17078384Sdg *	args->rule	Pointer to the last matching rule (in/out)
17081541Srgrimes *	args->next_hop	Socket we are forwarding to (out).
17091541Srgrimes *	args->f_id	Addresses grabbed from the packet (out)
17101541Srgrimes * 	args->cookie	a cookie depending on rule action
1711105586Sphk *
1712105586Sphk * Return value:
17131541Srgrimes *
17141541Srgrimes *	IP_FW_PASS	the packet must be accepted
17151541Srgrimes *	IP_FW_DENY	the packet must be dropped
17161541Srgrimes *	IP_FW_DIVERT	divert packet, port in m_tag
17171541Srgrimes *	IP_FW_TEE	tee packet, port in m_tag
17181541Srgrimes *	IP_FW_DUMMYNET	to dummynet, pipe in args->cookie
17191541Srgrimes *	IP_FW_NETGRAPH	into netgraph, cookie args->cookie
1720116462Ssilby *
172182445Sjesper */
17221541Srgrimes
17231541Srgrimesint
17241541Srgrimesipfw_chk(struct ip_fw_args *args)
17251541Srgrimes{
17261541Srgrimes	/*
17271541Srgrimes	 * Local variables hold state during the processing of a packet.
17281541Srgrimes	 *
17291541Srgrimes	 * IMPORTANT NOTE: to speed up the processing of rules, there
17301541Srgrimes	 * are some assumption on the values of the variables, which
17311541Srgrimes	 * are documented here. Should you change them, please check
17321541Srgrimes	 * the implementation of the various instructions to make sure
17331541Srgrimes	 * that they still work.
17341541Srgrimes	 *
17351541Srgrimes	 * args->eh	The MAC header. It is non-null for a layer2
17361541Srgrimes	 *	packet, it is NULL for a layer-3 packet.
17371541Srgrimes	 *
173812296Sphk	 * m | args->m	Pointer to the mbuf, as received from the caller.
1739122708Sandre	 *	It may change if ipfw_chk() does an m_pullup, or if it
17401541Srgrimes	 *	consumes the packet because it calls send_reject().
174198613Sluigi	 *	XXX This has to change, so that ipfw_chk() never modifies
1742122708Sandre	 *	or consumes the buffer.
17431549Srgrimes	 * ip	is simply an alias of the value of m, and it is kept
17441541Srgrimes	 *	in sync with it (the packet is	supposed to start with
17451541Srgrimes	 *	the ip header).
174688593Sjulian	 */
17471541Srgrimes	struct mbuf *m = args->m;
1748105199Ssam	struct ip *ip = mtod(m, struct ip *);
174955009Sshin
175055009Sshin	/*
17511541Srgrimes	 * For rules which contain uid/gid or jail constraints, cache
175288593Sjulian	 * a copy of the users credentials after the pcb lookup has been
175388593Sjulian	 * executed. This will speed up the processing of rules with
175488593Sjulian	 * these types of constraints, as well as decrease contention
175588593Sjulian	 * on pcb related locks.
175698613Sluigi	 */
175788593Sjulian	struct ip_fw_ugid fw_ugid_cache;
17581541Srgrimes	int ugid_lookup = 0;
17591541Srgrimes
17603969Sjkh	/*
176188593Sjulian	 * divinput_flags	If non-zero, set to the IP_FW_DIVERT_*_FLAG
176238373Sbde	 *	associated with a packet input on a divert socket.  This
17631541Srgrimes	 *	will allow to distinguish traffic and its direction when
17643969Sjkh	 *	it originates from a divert socket.
17653969Sjkh	 */
176688593Sjulian	u_int divinput_flags = 0;
17671541Srgrimes
17681541Srgrimes	/*
17691541Srgrimes	 * oif | args->oif	If NULL, ipfw_chk has been called on the
17701541Srgrimes	 *	inbound path (ether_input, bdg_forward, ip_input).
177144219Sdes	 *	If non-NULL, ipfw_chk has been called on the outbound path
177244219Sdes	 *	(ether_output, ip_output).
177344219Sdes	 */
177444219Sdes	struct ifnet *oif = args->oif;
177544219Sdes
1776122708Sandre	struct ip_fw *f = NULL;		/* matching rule */
177744219Sdes	int retval = 0;
177844219Sdes
177944219Sdes	/*
17801541Srgrimes	 * hlen	The length of the IPv4 header.
178144219Sdes	 *	hlen >0 means we have an IPv4 packet.
17821541Srgrimes	 */
1783133481Sandre	u_int hlen = 0;		/* hlen >0 means we have an IP pkt */
1784122708Sandre
178574415Sru	/*
1786122708Sandre	 * offset	The offset of a fragment. offset != 0 means that
17871541Srgrimes	 *	we have a fragment at this offset of an IPv4 packet.
17881541Srgrimes	 *	offset == 0 means that (if this is an IPv4 packet)
178973996Siedowse	 *	this is the first or only fragment.
179073996Siedowse	 */
179173996Siedowse	u_short offset = 0;
179298701Sluigi
179398701Sluigi	/*
179498701Sluigi	 * Local copies of addresses. They are only valid if we have
179598701Sluigi	 * an IP packet.
179698701Sluigi	 *
179798701Sluigi	 * proto	The protocol. Set to 0 for non-ip packets,
179898701Sluigi	 *	or to the protocol read from the packet otherwise.
179973996Siedowse	 *	proto != 0 means that we have an IPv4 packet.
180073996Siedowse	 *
180173996Siedowse	 * src_port, dst_port	port numbers, in HOST format. Only
180273996Siedowse	 *	valid for TCP and UDP packets.
18031541Srgrimes	 *
1804111119Simp	 * src_ip, dst_ip	ip addresses, in NETWORK format.
1805111119Simp	 *	Only valid for IPv4 packets.
1806108466Ssam	 */
1807108466Ssam	u_int8_t proto;
1808108466Ssam	u_int16_t src_port = 0, dst_port = 0;	/* NOTE: host format	*/
1809108466Ssam	struct in_addr src_ip, dst_ip;		/* NOTE: network format	*/
1810108466Ssam	u_int16_t ip_len=0;
1811108466Ssam	int pktlen;
1812108466Ssam	int dyn_dir = MATCH_UNKNOWN;
1813108466Ssam	ipfw_dyn_rule *q = NULL;
1814108466Ssam	struct ip_fw_chain *chain = &layer3_chain;
181573996Siedowse	struct m_tag *mtag;
1816105586Sphk
181773996Siedowse	if (m->m_flags & M_SKIP_FIREWALL)
1818130580Sbms		return (IP_FW_PASS);	/* accept */
181973996Siedowse	/*
182073996Siedowse	 * dyn_dir = MATCH_UNKNOWN when rules unchecked,
18211541Srgrimes	 * 	MATCH_NONE when checked and not matched (q = NULL),
182265327Sru	 *	MATCH_FORWARD or MATCH_REVERSE otherwise (q != NULL)
182365327Sru	 */
182465327Sru
182565327Sru	pktlen = m->m_pkthdr.len;
182665327Sru	if (args->eh == NULL ||		/* layer 3 packet */
182765327Sru		( m->m_pkthdr.len >= sizeof(struct ip) &&
182865327Sru		    ntohs(args->eh->ether_type) == ETHERTYPE_IP))
182965327Sru			hlen = ip->ip_hl << 2;
18301541Srgrimes
18311541Srgrimes	/*
18321541Srgrimes	 * Collect parameters into local variables for faster matching.
18331541Srgrimes	 */
18341541Srgrimes	if (hlen == 0) {	/* do not grab addresses for non-ip pkts */
18351541Srgrimes		proto = args->f_id.proto = 0;	/* mark f_id invalid */
18361541Srgrimes		goto after_ip_checks;
18371541Srgrimes	}
1838122708Sandre
1839122708Sandre	proto = args->f_id.proto = ip->ip_p;
1840122708Sandre	src_ip = ip->ip_src;
1841122708Sandre	dst_ip = ip->ip_dst;
1842122708Sandre	if (args->eh != NULL) { /* layer 2 packets are as on the wire */
1843122708Sandre		offset = ntohs(ip->ip_off) & IP_OFFMASK;
1844122996Sandre		ip_len = ntohs(ip->ip_len);
1845122708Sandre	} else {
1846122708Sandre		offset = ip->ip_off & IP_OFFMASK;
1847122708Sandre		ip_len = ip->ip_len;
1848122708Sandre	}
1849122921Sandre	pktlen = ip_len < pktlen ? ip_len : pktlen;
1850122708Sandre
1851122708Sandre#define PULLUP_TO(len)						\
1852122708Sandre		do {						\
1853122708Sandre			if ((m)->m_len < (len)) {		\
1854122708Sandre			    args->m = m = m_pullup(m, (len));	\
1855122708Sandre			    if (m == 0)				\
18561541Srgrimes				goto pullup_failed;		\
1857122708Sandre			    ip = mtod(m, struct ip *);		\
18581541Srgrimes			}					\
1859122708Sandre		} while (0)
1860122708Sandre
1861122708Sandre	if (offset == 0) {
1862122708Sandre		switch (proto) {
1863122708Sandre		case IPPROTO_TCP:
1864122708Sandre		    {
1865122708Sandre			struct tcphdr *tcp;
1866122708Sandre
1867122708Sandre			PULLUP_TO(hlen + sizeof(struct tcphdr));
18681541Srgrimes			tcp = L3HDR(struct tcphdr, ip);
1869122708Sandre			dst_port = tcp->th_dport;
1870122708Sandre			src_port = tcp->th_sport;
18711541Srgrimes			args->f_id.flags = tcp->th_flags;
1872122708Sandre			}
18731541Srgrimes			break;
1874122708Sandre
1875122708Sandre		case IPPROTO_UDP:
18761541Srgrimes		    {
18771541Srgrimes			struct udphdr *udp;
1878101268Sluigi
1879126239Smlaier			PULLUP_TO(hlen + sizeof(struct udphdr));
1880126239Smlaier			udp = L3HDR(struct udphdr, ip);
1881126239Smlaier			dst_port = udp->uh_dport;
1882126239Smlaier			src_port = udp->uh_sport;
1883126239Smlaier			}
1884126239Smlaier			break;
1885126239Smlaier
1886126239Smlaier		case IPPROTO_ICMP:
1887101268Sluigi			PULLUP_TO(hlen + 4);	/* type, code and checksum. */
1888122708Sandre			args->f_id.flags = L3HDR(struct icmp, ip)->icmp_type;
18891541Srgrimes			break;
18901541Srgrimes
18911541Srgrimes		default:
18921541Srgrimes			break;
18931541Srgrimes		}
18941541Srgrimes#undef PULLUP_TO
18951541Srgrimes	}
1896122702Sandre
18971541Srgrimes	args->f_id.src_ip = ntohl(src_ip.s_addr);
18981541Srgrimes	args->f_id.dst_ip = ntohl(dst_ip.s_addr);
18991541Srgrimes	args->f_id.src_port = src_port = ntohs(src_port);
19001541Srgrimes	args->f_id.dst_port = dst_port = ntohs(dst_port);
19011541Srgrimes
19021541Srgrimesafter_ip_checks:
19031541Srgrimes	IPFW_RLOCK(chain);
19041541Srgrimes	mtag = m_tag_find(m, PACKET_TAG_DIVERT, NULL);
19051541Srgrimes	if (args->rule) {
19061541Srgrimes		/*
19071541Srgrimes		 * Packet has already been tagged. Look for the next rule
19081541Srgrimes		 * to restart processing.
19091541Srgrimes		 *
19101541Srgrimes		 * If fw_one_pass != 0 then just accept it.
19111541Srgrimes		 * XXX should not happen here, but optimized out in
19121541Srgrimes		 * the caller.
19131541Srgrimes		 */
19141541Srgrimes		if (fw_one_pass) {
19151541Srgrimes			IPFW_RUNLOCK(chain);
19161541Srgrimes			return (IP_FW_PASS);
19171541Srgrimes		}
19181541Srgrimes
19191541Srgrimes		f = args->rule->next_rule;
19201541Srgrimes		if (f == NULL)
19211541Srgrimes			f = lookup_next_rule(args->rule);
19221541Srgrimes	} else {
1923122708Sandre		/*
192455009Sshin		 * Find the starting rule. It can be either the first
192555009Sshin		 * one, or the one after divert_rule if asked so.
192655009Sshin		 */
192755009Sshin		int skipto = mtag ? divert_cookie(mtag) : 0;
192855009Sshin
192955009Sshin		f = chain->rules;
1930122708Sandre		if (args->eh == NULL && skipto != 0) {
193155009Sshin			if (skipto >= IPFW_DEFAULT_RULE) {
193255009Sshin				IPFW_RUNLOCK(chain);
193355009Sshin				return (IP_FW_DENY); /* invalid */
1934122708Sandre			}
193555009Sshin			while (f && f->rulenum <= skipto)
1936122708Sandre				f = f->next;
193755009Sshin			if (f == NULL) {	/* drop packet */
193855009Sshin				IPFW_RUNLOCK(chain);
1939122708Sandre				return (IP_FW_DENY);
1940122708Sandre			}
1941122708Sandre		}
1942105199Ssam	}
1943105199Ssam	/* reset divert rule to avoid confusion later */
1944122708Sandre	if (mtag) {
1945122708Sandre		divinput_flags = divert_info(mtag) &
1946122708Sandre		    (IP_FW_DIVERT_OUTPUT_FLAG | IP_FW_DIVERT_LOOPBACK_FLAG);
1947122708Sandre		m_tag_delete(m, mtag);
1948105199Ssam	}
1949105199Ssam
1950105199Ssam	/*
1951105199Ssam	 * Now scan the rules, and parse microinstructions for each rule.
1952105199Ssam	 */
1953105199Ssam	for (; f; f = f->next) {
1954105199Ssam		int l, cmdlen;
1955105199Ssam		ipfw_insn *cmd;
1956105199Ssam		int skip_or; /* skip rest of OR block */
1957105199Ssam
1958105199Ssamagain:
1959105199Ssam		if (set_disable & (1 << f->set) )
1960105199Ssam			continue;
1961105199Ssam
1962105199Ssam		skip_or = 0;
1963105199Ssam		for (l = f->cmd_len, cmd = f->cmd ; l > 0 ;
1964105199Ssam		    l -= cmdlen, cmd += cmdlen) {
1965105199Ssam			int match;
1966122708Sandre
1967122708Sandre			/*
1968105199Ssam			 * check_body is a jump target used when we find a
1969130581Sbms			 * CHECK_STATE, and need to jump to the body of
1970130581Sbms			 * the target rule.
1971122708Sandre			 */
1972105199Ssam
1973105199Ssamcheck_body:
1974105199Ssam			cmdlen = F_LEN(cmd);
1975105199Ssam			/*
1976105199Ssam			 * An OR block (insn_1 || .. || insn_n) has the
1977122708Sandre			 * F_OR bit set in all but the last instruction.
1978122708Sandre			 * The first match will set "skip_or", and cause
1979122708Sandre			 * the following instructions to be skipped until
1980105199Ssam			 * past the one with the F_OR bit clear.
1981122708Sandre			 */
1982122708Sandre			if (skip_or) {		/* skip this instruction */
1983122708Sandre				if ((cmd->len & F_OR) == 0)
1984122708Sandre					skip_or = 0;	/* next one is good */
1985122708Sandre				continue;
1986122708Sandre			}
1987122708Sandre			match = 0; /* set to 1 if we succeed */
1988105199Ssam
1989122708Sandre			switch (cmd->opcode) {
19901541Srgrimes			/*
19911541Srgrimes			 * The first set of opcodes compares the packet's
19921541Srgrimes			 * fields with some pattern, setting 'match' if a
19931541Srgrimes			 * match is found. At the end of the loop there is
1994107081Ssilby			 * logic to deal with F_NOT and F_OR flags associated
1995107081Ssilby			 * with the opcode.
1996107081Ssilby			 */
1997107081Ssilby			case O_NOP:
1998107081Ssilby				match = 1;
1999107081Ssilby				break;
2000107081Ssilby
2001107081Ssilby			case O_FORWARD_MAC:
2002107081Ssilby				printf("ipfw: opcode %d unimplemented\n",
2003107081Ssilby				    cmd->opcode);
2004107081Ssilby				break;
2005107081Ssilby
2006107081Ssilby			case O_GID:
2007107081Ssilby			case O_UID:
2008107081Ssilby			case O_JAIL:
20091541Srgrimes				/*
201060612Sru				 * We only check offset == 0 && proto != 0,
201160612Sru				 * as this ensures that we have an IPv4
201260612Sru				 * packet with the ports info.
201360612Sru				 */
20141541Srgrimes				if (offset!=0)
20151541Srgrimes					break;
20161541Srgrimes				if (proto == IPPROTO_TCP ||
20171541Srgrimes				    proto == IPPROTO_UDP)
201819622Sfenner					match = check_uidgid(
201919622Sfenner						    (ipfw_insn_u32 *)cmd,
202019622Sfenner						    proto, oif,
202119622Sfenner						    dst_ip, dst_port,
202219622Sfenner						    src_ip, src_port, &fw_ugid_cache,
202319622Sfenner						    &ugid_lookup, args->inp);
202419622Sfenner				break;
2025125264Sphk
2026125264Sphk			case O_RECV:
202719622Sfenner				match = iface_match(m->m_pkthdr.rcvif,
2028125264Sphk				    (ipfw_insn_if *)cmd);
2029125264Sphk				break;
2030125264Sphk
2031125264Sphk			case O_XMIT:
2032125264Sphk				match = iface_match(oif, (ipfw_insn_if *)cmd);
2033125264Sphk				break;
2034125264Sphk
2035125264Sphk			case O_VIA:
2036125264Sphk				match = iface_match(oif ? oif :
2037125264Sphk				    m->m_pkthdr.rcvif, (ipfw_insn_if *)cmd);
2038125264Sphk				break;
2039125264Sphk
2040125264Sphk			case O_MACADDR2:
2041125264Sphk				if (args->eh != NULL) {	/* have MAC header */
2042125264Sphk					u_int32_t *want = (u_int32_t *)
2043125264Sphk						((ipfw_insn_mac *)cmd)->addr;
204497658Stanimura					u_int32_t *mask = (u_int32_t *)
204519622Sfenner						((ipfw_insn_mac *)cmd)->mask;
204619622Sfenner					u_int32_t *hdr = (u_int32_t *)args->eh;
204719622Sfenner
204819622Sfenner					match =
204919622Sfenner					    ( want[0] == (hdr[0] & mask[0]) &&
205019622Sfenner					      want[1] == (hdr[1] & mask[1]) &&
2051114258Smdodd					      want[2] == (hdr[2] & mask[2]) );
2052114258Smdodd				}
2053114258Smdodd				break;
2054114258Smdodd
2055114258Smdodd			case O_MAC_TYPE:
2056114258Smdodd				if (args->eh != NULL) {
205719622Sfenner					u_int16_t t =
205819622Sfenner					    ntohs(args->eh->ether_type);
205919622Sfenner					u_int16_t *p =
206019622Sfenner					    ((ipfw_insn_u16 *)cmd)->ports;
206119622Sfenner					int i;
206219622Sfenner
206319622Sfenner					for (i = cmdlen - 1; !match && i>0;
206419622Sfenner					    i--, p += 2)
206519622Sfenner						match = (t>=p[0] && t<=p[1]);
206619622Sfenner				}
206719622Sfenner				break;
206819622Sfenner
206919622Sfenner			case O_FRAG:
207019622Sfenner				match = (hlen > 0 && offset != 0);
207119622Sfenner				break;
207219622Sfenner
207319622Sfenner			case O_IN:	/* "out" is "not in" */
207419622Sfenner				match = (oif == NULL);
207519622Sfenner				break;
207619622Sfenner
207719622Sfenner			case O_LAYER2:
207830948Sjulian				match = (args->eh != NULL);
207930948Sjulian				break;
208030948Sjulian
208130948Sjulian			case O_DIVERTED:
208230948Sjulian				match = (cmd->arg1 & 1 && divinput_flags &
208330948Sjulian				    IP_FW_DIVERT_LOOPBACK_FLAG) ||
208430948Sjulian					(cmd->arg1 & 2 && divinput_flags &
208519622Sfenner				    IP_FW_DIVERT_OUTPUT_FLAG);
208630948Sjulian				break;
208730948Sjulian
208883130Sjlemon			case O_PROTO:
208983130Sjlemon				/*
209030948Sjulian				 * We do not allow an arg of 0 so the
209130948Sjulian				 * check of "proto" only suffices.
209230948Sjulian				 */
209330948Sjulian				match = (proto == cmd->arg1);
209430948Sjulian				break;
209530948Sjulian
209630948Sjulian			case O_IP_SRC:
209730948Sjulian				match = (hlen > 0 &&
209830948Sjulian				    ((ipfw_insn_ip *)cmd)->addr.s_addr ==
209930948Sjulian				    src_ip.s_addr);
210030948Sjulian				break;
210130948Sjulian
210230948Sjulian			case O_IP_SRC_LOOKUP:
210330948Sjulian			case O_IP_DST_LOOKUP:
210430948Sjulian				if (hlen > 0) {
210530948Sjulian				    uint32_t a =
210630948Sjulian					(cmd->opcode == O_IP_DST_LOOKUP) ?
210719622Sfenner					    dst_ip.s_addr : src_ip.s_addr;
210819622Sfenner				    uint32_t v;
210919622Sfenner
211019622Sfenner				    match = lookup_table(cmd->arg1, a, &v);
211119622Sfenner				    if (!match)
211219622Sfenner					break;
211398701Sluigi				    if (cmdlen == F_INSN_SIZE(ipfw_insn_u32))
211498701Sluigi					match =
211598701Sluigi					    ((ipfw_insn_u32 *)cmd)->d[0] == v;
211698701Sluigi				}
211798701Sluigi				break;
211898701Sluigi
211998701Sluigi			case O_IP_SRC_MASK:
212098701Sluigi			case O_IP_DST_MASK:
212198701Sluigi				if (hlen > 0) {
21221541Srgrimes				    uint32_t a =
21232531Swollman					(cmd->opcode == O_IP_DST_MASK) ?
21242531Swollman					    dst_ip.s_addr : src_ip.s_addr;
21252531Swollman				    uint32_t *p = ((ipfw_insn_u32 *)cmd)->d;
21262531Swollman				    int i = cmdlen-1;
2127106968Sluigi
21282531Swollman				    for (; !match && i>0; i-= 2, p+= 2)
21292531Swollman					match = (p[0] == (a & p[1]));
2130106968Sluigi				}
21312531Swollman				break;
21322531Swollman
21339209Swollman			case O_IP_SRC_ME:
21349209Swollman				if (hlen > 0) {
21359209Swollman					struct ifnet *tif;
21369209Swollman
21379209Swollman					INADDR_TO_IFP(src_ip, tif);
21389209Swollman					match = (tif != NULL);
21399209Swollman				}
21409209Swollman				break;
21412531Swollman
21422531Swollman			case O_IP_DST_SET:
21432531Swollman			case O_IP_SRC_SET:
21442531Swollman				if (hlen > 0) {
21452531Swollman					u_int32_t *d = (u_int32_t *)(cmd+1);
21462531Swollman					u_int32_t addr =
21472531Swollman					    cmd->opcode == O_IP_DST_SET ?
21482531Swollman						args->f_id.dst_ip :
21499209Swollman						args->f_id.src_ip;
21509209Swollman
21519209Swollman					    if (addr < d[0])
21529209Swollman						    break;
21539209Swollman					    addr -= d[0]; /* subtract base */
21549209Swollman					    match = (addr < cmd->arg1) &&
21559209Swollman						( d[ 1 + (addr>>5)] &
21569209Swollman						  (1<<(addr & 0x1f)) );
21572531Swollman				}
21582531Swollman				break;
2159106968Sluigi
2160106968Sluigi			case O_IP_DST:
2161106968Sluigi				match = (hlen > 0 &&
2162106968Sluigi				    ((ipfw_insn_ip *)cmd)->addr.s_addr ==
2163106968Sluigi				    dst_ip.s_addr);
2164106968Sluigi				break;
2165106968Sluigi
2166106968Sluigi			case O_IP_DST_ME:
2167106968Sluigi				if (hlen > 0) {
2168106968Sluigi					struct ifnet *tif;
2169106968Sluigi
2170106968Sluigi					INADDR_TO_IFP(dst_ip, tif);
2171106968Sluigi					match = (tif != NULL);
2172106968Sluigi				}
2173106968Sluigi				break;
2174106968Sluigi
2175106968Sluigi			case O_IP_SRCPORT:
2176106968Sluigi			case O_IP_DSTPORT:
2177106968Sluigi				/*
2178106968Sluigi				 * offset == 0 && proto != 0 is enough
2179106968Sluigi				 * to guarantee that we have an IPv4
2180106968Sluigi				 * packet with port info.
2181106968Sluigi				 */
2182106968Sluigi				if ((proto==IPPROTO_UDP || proto==IPPROTO_TCP)
2183106968Sluigi				    && offset == 0) {
2184106968Sluigi					u_int16_t x =
2185					    (cmd->opcode == O_IP_SRCPORT) ?
2186						src_port : dst_port ;
2187					u_int16_t *p =
2188					    ((ipfw_insn_u16 *)cmd)->ports;
2189					int i;
2190
2191					for (i = cmdlen - 1; !match && i>0;
2192					    i--, p += 2)
2193						match = (x>=p[0] && x<=p[1]);
2194				}
2195				break;
2196
2197			case O_ICMPTYPE:
2198				match = (offset == 0 && proto==IPPROTO_ICMP &&
2199				    icmptype_match(ip, (ipfw_insn_u32 *)cmd) );
2200				break;
2201
2202			case O_IPOPT:
2203				match = (hlen > 0 && ipopts_match(ip, cmd) );
2204				break;
2205
2206			case O_IPVER:
2207				match = (hlen > 0 && cmd->arg1 == ip->ip_v);
2208				break;
2209
2210			case O_IPID:
2211			case O_IPLEN:
2212			case O_IPTTL:
2213				if (hlen > 0) {	/* only for IP packets */
2214				    uint16_t x;
2215				    uint16_t *p;
2216				    int i;
2217
2218				    if (cmd->opcode == O_IPLEN)
2219					x = ip_len;
2220				    else if (cmd->opcode == O_IPTTL)
2221					x = ip->ip_ttl;
2222				    else /* must be IPID */
2223					x = ntohs(ip->ip_id);
2224				    if (cmdlen == 1) {
2225					match = (cmd->arg1 == x);
2226					break;
2227				    }
2228				    /* otherwise we have ranges */
2229				    p = ((ipfw_insn_u16 *)cmd)->ports;
2230				    i = cmdlen - 1;
2231				    for (; !match && i>0; i--, p += 2)
2232					match = (x >= p[0] && x <= p[1]);
2233				}
2234				break;
2235
2236			case O_IPPRECEDENCE:
2237				match = (hlen > 0 &&
2238				    (cmd->arg1 == (ip->ip_tos & 0xe0)) );
2239				break;
2240
2241			case O_IPTOS:
2242				match = (hlen > 0 &&
2243				    flags_match(cmd, ip->ip_tos));
2244				break;
2245
2246			case O_TCPDATALEN:
2247				if (proto == IPPROTO_TCP && offset == 0) {
2248				    struct tcphdr *tcp;
2249				    uint16_t x;
2250				    uint16_t *p;
2251				    int i;
2252
2253				    tcp = L3HDR(struct tcphdr,ip);
2254				    x = ip_len -
2255					((ip->ip_hl + tcp->th_off) << 2);
2256				    if (cmdlen == 1) {
2257					match = (cmd->arg1 == x);
2258					break;
2259				    }
2260				    /* otherwise we have ranges */
2261				    p = ((ipfw_insn_u16 *)cmd)->ports;
2262				    i = cmdlen - 1;
2263				    for (; !match && i>0; i--, p += 2)
2264					match = (x >= p[0] && x <= p[1]);
2265				}
2266				break;
2267
2268			case O_TCPFLAGS:
2269				match = (proto == IPPROTO_TCP && offset == 0 &&
2270				    flags_match(cmd,
2271					L3HDR(struct tcphdr,ip)->th_flags));
2272				break;
2273
2274			case O_TCPOPTS:
2275				match = (proto == IPPROTO_TCP && offset == 0 &&
2276				    tcpopts_match(ip, cmd));
2277				break;
2278
2279			case O_TCPSEQ:
2280				match = (proto == IPPROTO_TCP && offset == 0 &&
2281				    ((ipfw_insn_u32 *)cmd)->d[0] ==
2282					L3HDR(struct tcphdr,ip)->th_seq);
2283				break;
2284
2285			case O_TCPACK:
2286				match = (proto == IPPROTO_TCP && offset == 0 &&
2287				    ((ipfw_insn_u32 *)cmd)->d[0] ==
2288					L3HDR(struct tcphdr,ip)->th_ack);
2289				break;
2290
2291			case O_TCPWIN:
2292				match = (proto == IPPROTO_TCP && offset == 0 &&
2293				    cmd->arg1 ==
2294					L3HDR(struct tcphdr,ip)->th_win);
2295				break;
2296
2297			case O_ESTAB:
2298				/* reject packets which have SYN only */
2299				/* XXX should i also check for TH_ACK ? */
2300				match = (proto == IPPROTO_TCP && offset == 0 &&
2301				    (L3HDR(struct tcphdr,ip)->th_flags &
2302				     (TH_RST | TH_ACK | TH_SYN)) != TH_SYN);
2303				break;
2304
2305			case O_ALTQ: {
2306				struct altq_tag *at;
2307				ipfw_insn_altq *altq = (ipfw_insn_altq *)cmd;
2308
2309				match = 1;
2310				mtag = m_tag_get(PACKET_TAG_PF_QID,
2311						sizeof(struct altq_tag),
2312						M_NOWAIT);
2313				if (mtag == NULL) {
2314					/*
2315					 * Let the packet fall back to the
2316					 * default ALTQ.
2317					 */
2318					break;
2319				}
2320				at = (struct altq_tag *)(mtag+1);
2321				at->qid = altq->qid;
2322				if (hlen != 0)
2323					at->af = AF_INET;
2324				else
2325					at->af = AF_LINK;
2326				at->hdr = ip;
2327				m_tag_prepend(m, mtag);
2328				break;
2329			}
2330
2331			case O_LOG:
2332				if (fw_verbose)
2333					ipfw_log(f, hlen, args->eh, m, oif);
2334				match = 1;
2335				break;
2336
2337			case O_PROB:
2338				match = (random()<((ipfw_insn_u32 *)cmd)->d[0]);
2339				break;
2340
2341			case O_VERREVPATH:
2342				/* Outgoing packets automatically pass/match */
2343				match = (hlen > 0 && ((oif != NULL) ||
2344				    (m->m_pkthdr.rcvif == NULL) ||
2345				    verify_path(src_ip, m->m_pkthdr.rcvif)));
2346				break;
2347
2348			case O_VERSRCREACH:
2349				/* Outgoing packets automatically pass/match */
2350				match = (hlen > 0 && ((oif != NULL) ||
2351				     verify_path(src_ip, NULL)));
2352				break;
2353
2354			case O_ANTISPOOF:
2355				/* Outgoing packets automatically pass/match */
2356				if (oif == NULL && hlen > 0 &&
2357				    in_localaddr(src_ip))
2358					match = verify_path(src_ip,
2359							m->m_pkthdr.rcvif);
2360				else
2361					match = 1;
2362				break;
2363
2364			case O_IPSEC:
2365#ifdef FAST_IPSEC
2366				match = (m_tag_find(m,
2367				    PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL);
2368#endif
2369#ifdef IPSEC
2370				match = (ipsec_getnhist(m) != 0);
2371#endif
2372				/* otherwise no match */
2373				break;
2374
2375			/*
2376			 * The second set of opcodes represents 'actions',
2377			 * i.e. the terminal part of a rule once the packet
2378			 * matches all previous patterns.
2379			 * Typically there is only one action for each rule,
2380			 * and the opcode is stored at the end of the rule
2381			 * (but there are exceptions -- see below).
2382			 *
2383			 * In general, here we set retval and terminate the
2384			 * outer loop (would be a 'break 3' in some language,
2385			 * but we need to do a 'goto done').
2386			 *
2387			 * Exceptions:
2388			 * O_COUNT and O_SKIPTO actions:
2389			 *   instead of terminating, we jump to the next rule
2390			 *   ('goto next_rule', equivalent to a 'break 2'),
2391			 *   or to the SKIPTO target ('goto again' after
2392			 *   having set f, cmd and l), respectively.
2393			 *
2394			 * O_LOG and O_ALTQ action parameters:
2395			 *   perform some action and set match = 1;
2396			 *
2397			 * O_LIMIT and O_KEEP_STATE: these opcodes are
2398			 *   not real 'actions', and are stored right
2399			 *   before the 'action' part of the rule.
2400			 *   These opcodes try to install an entry in the
2401			 *   state tables; if successful, we continue with
2402			 *   the next opcode (match=1; break;), otherwise
2403			 *   the packet *   must be dropped
2404			 *   ('goto done' after setting retval);
2405			 *
2406			 * O_PROBE_STATE and O_CHECK_STATE: these opcodes
2407			 *   cause a lookup of the state table, and a jump
2408			 *   to the 'action' part of the parent rule
2409			 *   ('goto check_body') if an entry is found, or
2410			 *   (CHECK_STATE only) a jump to the next rule if
2411			 *   the entry is not found ('goto next_rule').
2412			 *   The result of the lookup is cached to make
2413			 *   further instances of these opcodes are
2414			 *   effectively NOPs.
2415			 */
2416			case O_LIMIT:
2417			case O_KEEP_STATE:
2418				if (install_state(f,
2419				    (ipfw_insn_limit *)cmd, args)) {
2420					retval = IP_FW_DENY;
2421					goto done; /* error/limit violation */
2422				}
2423				match = 1;
2424				break;
2425
2426			case O_PROBE_STATE:
2427			case O_CHECK_STATE:
2428				/*
2429				 * dynamic rules are checked at the first
2430				 * keep-state or check-state occurrence,
2431				 * with the result being stored in dyn_dir.
2432				 * The compiler introduces a PROBE_STATE
2433				 * instruction for us when we have a
2434				 * KEEP_STATE (because PROBE_STATE needs
2435				 * to be run first).
2436				 */
2437				if (dyn_dir == MATCH_UNKNOWN &&
2438				    (q = lookup_dyn_rule(&args->f_id,
2439				     &dyn_dir, proto == IPPROTO_TCP ?
2440					L3HDR(struct tcphdr, ip) : NULL))
2441					!= NULL) {
2442					/*
2443					 * Found dynamic entry, update stats
2444					 * and jump to the 'action' part of
2445					 * the parent rule.
2446					 */
2447					q->pcnt++;
2448					q->bcnt += pktlen;
2449					f = q->rule;
2450					cmd = ACTION_PTR(f);
2451					l = f->cmd_len - f->act_ofs;
2452					IPFW_DYN_UNLOCK();
2453					goto check_body;
2454				}
2455				/*
2456				 * Dynamic entry not found. If CHECK_STATE,
2457				 * skip to next rule, if PROBE_STATE just
2458				 * ignore and continue with next opcode.
2459				 */
2460				if (cmd->opcode == O_CHECK_STATE)
2461					goto next_rule;
2462				match = 1;
2463				break;
2464
2465			case O_ACCEPT:
2466				retval = 0;	/* accept */
2467				goto done;
2468
2469			case O_PIPE:
2470			case O_QUEUE:
2471				args->rule = f; /* report matching rule */
2472				args->cookie = cmd->arg1;
2473				retval = IP_FW_DUMMYNET;
2474				goto done;
2475
2476			case O_DIVERT:
2477			case O_TEE: {
2478				struct divert_tag *dt;
2479
2480				if (args->eh) /* not on layer 2 */
2481					break;
2482				mtag = m_tag_get(PACKET_TAG_DIVERT,
2483						sizeof(struct divert_tag),
2484						M_NOWAIT);
2485				if (mtag == NULL) {
2486					/* XXX statistic */
2487					/* drop packet */
2488					IPFW_RUNLOCK(chain);
2489					return (IP_FW_DENY);
2490				}
2491				dt = (struct divert_tag *)(mtag+1);
2492				dt->cookie = f->rulenum;
2493				dt->info = cmd->arg1;
2494				m_tag_prepend(m, mtag);
2495				retval = (cmd->opcode == O_DIVERT) ?
2496				    IP_FW_DIVERT : IP_FW_TEE;
2497				goto done;
2498			}
2499
2500			case O_COUNT:
2501			case O_SKIPTO:
2502				f->pcnt++;	/* update stats */
2503				f->bcnt += pktlen;
2504				f->timestamp = time_second;
2505				if (cmd->opcode == O_COUNT)
2506					goto next_rule;
2507				/* handle skipto */
2508				if (f->next_rule == NULL)
2509					lookup_next_rule(f);
2510				f = f->next_rule;
2511				goto again;
2512
2513			case O_REJECT:
2514				/*
2515				 * Drop the packet and send a reject notice
2516				 * if the packet is not ICMP (or is an ICMP
2517				 * query), and it is not multicast/broadcast.
2518				 */
2519				if (hlen > 0 &&
2520				    (proto != IPPROTO_ICMP ||
2521				     is_icmp_query(ip)) &&
2522				    !(m->m_flags & (M_BCAST|M_MCAST)) &&
2523				    !IN_MULTICAST(ntohl(dst_ip.s_addr))) {
2524					send_reject(args, cmd->arg1,
2525					    offset,ip_len);
2526					m = args->m;
2527				}
2528				/* FALLTHROUGH */
2529			case O_DENY:
2530				retval = IP_FW_DENY;
2531				goto done;
2532
2533			case O_FORWARD_IP:
2534				if (args->eh)	/* not valid on layer2 pkts */
2535					break;
2536				if (!q || dyn_dir == MATCH_FORWARD)
2537					args->next_hop =
2538					    &((ipfw_insn_sa *)cmd)->sa;
2539				retval = IP_FW_PASS;
2540				goto done;
2541
2542			case O_NETGRAPH:
2543			case O_NGTEE:
2544				args->rule = f;	/* report matching rule */
2545				args->cookie = cmd->arg1;
2546				retval = (cmd->opcode == O_NETGRAPH) ?
2547				    IP_FW_NETGRAPH : IP_FW_NGTEE;
2548				goto done;
2549
2550			default:
2551				panic("-- unknown opcode %d\n", cmd->opcode);
2552			} /* end of switch() on opcodes */
2553
2554			if (cmd->len & F_NOT)
2555				match = !match;
2556
2557			if (match) {
2558				if (cmd->len & F_OR)
2559					skip_or = 1;
2560			} else {
2561				if (!(cmd->len & F_OR)) /* not an OR block, */
2562					break;		/* try next rule    */
2563			}
2564
2565		}	/* end of inner for, scan opcodes */
2566
2567next_rule:;		/* try next rule		*/
2568
2569	}		/* end of outer for, scan rules */
2570	printf("ipfw: ouch!, skip past end of rules, denying packet\n");
2571	IPFW_RUNLOCK(chain);
2572	return (IP_FW_DENY);
2573
2574done:
2575	/* Update statistics */
2576	f->pcnt++;
2577	f->bcnt += pktlen;
2578	f->timestamp = time_second;
2579	IPFW_RUNLOCK(chain);
2580	return (retval);
2581
2582pullup_failed:
2583	if (fw_verbose)
2584		printf("ipfw: pullup failed\n");
2585	return (IP_FW_DENY);
2586}
2587
2588/*
2589 * When a rule is added/deleted, clear the next_rule pointers in all rules.
2590 * These will be reconstructed on the fly as packets are matched.
2591 */
2592static void
2593flush_rule_ptrs(struct ip_fw_chain *chain)
2594{
2595	struct ip_fw *rule;
2596
2597	IPFW_WLOCK_ASSERT(chain);
2598
2599	for (rule = chain->rules; rule; rule = rule->next)
2600		rule->next_rule = NULL;
2601}
2602
2603/*
2604 * When pipes/queues are deleted, clear the "pipe_ptr" pointer to a given
2605 * pipe/queue, or to all of them (match == NULL).
2606 */
2607void
2608flush_pipe_ptrs(struct dn_flow_set *match)
2609{
2610	struct ip_fw *rule;
2611
2612	IPFW_WLOCK(&layer3_chain);
2613	for (rule = layer3_chain.rules; rule; rule = rule->next) {
2614		ipfw_insn_pipe *cmd = (ipfw_insn_pipe *)ACTION_PTR(rule);
2615
2616		if (cmd->o.opcode != O_PIPE && cmd->o.opcode != O_QUEUE)
2617			continue;
2618		/*
2619		 * XXX Use bcmp/bzero to handle pipe_ptr to overcome
2620		 * possible alignment problems on 64-bit architectures.
2621		 * This code is seldom used so we do not worry too
2622		 * much about efficiency.
2623		 */
2624		if (match == NULL ||
2625		    !bcmp(&cmd->pipe_ptr, &match, sizeof(match)) )
2626			bzero(&cmd->pipe_ptr, sizeof(cmd->pipe_ptr));
2627	}
2628	IPFW_WUNLOCK(&layer3_chain);
2629}
2630
2631/*
2632 * Add a new rule to the list. Copy the rule into a malloc'ed area, then
2633 * possibly create a rule number and add the rule to the list.
2634 * Update the rule_number in the input struct so the caller knows it as well.
2635 */
2636static int
2637add_rule(struct ip_fw_chain *chain, struct ip_fw *input_rule)
2638{
2639	struct ip_fw *rule, *f, *prev;
2640	int l = RULESIZE(input_rule);
2641
2642	if (chain->rules == NULL && input_rule->rulenum != IPFW_DEFAULT_RULE)
2643		return (EINVAL);
2644
2645	rule = malloc(l, M_IPFW, M_NOWAIT | M_ZERO);
2646	if (rule == NULL)
2647		return (ENOSPC);
2648
2649	bcopy(input_rule, rule, l);
2650
2651	rule->next = NULL;
2652	rule->next_rule = NULL;
2653
2654	rule->pcnt = 0;
2655	rule->bcnt = 0;
2656	rule->timestamp = 0;
2657
2658	IPFW_WLOCK(chain);
2659
2660	if (chain->rules == NULL) {	/* default rule */
2661		chain->rules = rule;
2662		goto done;
2663        }
2664
2665	/*
2666	 * If rulenum is 0, find highest numbered rule before the
2667	 * default rule, and add autoinc_step
2668	 */
2669	if (autoinc_step < 1)
2670		autoinc_step = 1;
2671	else if (autoinc_step > 1000)
2672		autoinc_step = 1000;
2673	if (rule->rulenum == 0) {
2674		/*
2675		 * locate the highest numbered rule before default
2676		 */
2677		for (f = chain->rules; f; f = f->next) {
2678			if (f->rulenum == IPFW_DEFAULT_RULE)
2679				break;
2680			rule->rulenum = f->rulenum;
2681		}
2682		if (rule->rulenum < IPFW_DEFAULT_RULE - autoinc_step)
2683			rule->rulenum += autoinc_step;
2684		input_rule->rulenum = rule->rulenum;
2685	}
2686
2687	/*
2688	 * Now insert the new rule in the right place in the sorted list.
2689	 */
2690	for (prev = NULL, f = chain->rules; f; prev = f, f = f->next) {
2691		if (f->rulenum > rule->rulenum) { /* found the location */
2692			if (prev) {
2693				rule->next = f;
2694				prev->next = rule;
2695			} else { /* head insert */
2696				rule->next = chain->rules;
2697				chain->rules = rule;
2698			}
2699			break;
2700		}
2701	}
2702	flush_rule_ptrs(chain);
2703done:
2704	static_count++;
2705	static_len += l;
2706	IPFW_WUNLOCK(chain);
2707	DEB(printf("ipfw: installed rule %d, static count now %d\n",
2708		rule->rulenum, static_count);)
2709	return (0);
2710}
2711
2712/**
2713 * Remove a static rule (including derived * dynamic rules)
2714 * and place it on the ``reap list'' for later reclamation.
2715 * The caller is in charge of clearing rule pointers to avoid
2716 * dangling pointers.
2717 * @return a pointer to the next entry.
2718 * Arguments are not checked, so they better be correct.
2719 */
2720static struct ip_fw *
2721remove_rule(struct ip_fw_chain *chain, struct ip_fw *rule, struct ip_fw *prev)
2722{
2723	struct ip_fw *n;
2724	int l = RULESIZE(rule);
2725
2726	IPFW_WLOCK_ASSERT(chain);
2727
2728	n = rule->next;
2729	IPFW_DYN_LOCK();
2730	remove_dyn_rule(rule, NULL /* force removal */);
2731	IPFW_DYN_UNLOCK();
2732	if (prev == NULL)
2733		chain->rules = n;
2734	else
2735		prev->next = n;
2736	static_count--;
2737	static_len -= l;
2738
2739	rule->next = chain->reap;
2740	chain->reap = rule;
2741
2742	return n;
2743}
2744
2745/**
2746 * Reclaim storage associated with a list of rules.  This is
2747 * typically the list created using remove_rule.
2748 */
2749static void
2750reap_rules(struct ip_fw *head)
2751{
2752	struct ip_fw *rule;
2753
2754	while ((rule = head) != NULL) {
2755		head = head->next;
2756		if (DUMMYNET_LOADED)
2757			ip_dn_ruledel_ptr(rule);
2758		free(rule, M_IPFW);
2759	}
2760}
2761
2762/*
2763 * Remove all rules from a chain (except rules in set RESVD_SET
2764 * unless kill_default = 1).  The caller is responsible for
2765 * reclaiming storage for the rules left in chain->reap.
2766 */
2767static void
2768free_chain(struct ip_fw_chain *chain, int kill_default)
2769{
2770	struct ip_fw *prev, *rule;
2771
2772	IPFW_WLOCK_ASSERT(chain);
2773
2774	flush_rule_ptrs(chain); /* more efficient to do outside the loop */
2775	for (prev = NULL, rule = chain->rules; rule ; )
2776		if (kill_default || rule->set != RESVD_SET)
2777			rule = remove_rule(chain, rule, prev);
2778		else {
2779			prev = rule;
2780			rule = rule->next;
2781		}
2782}
2783
2784/**
2785 * Remove all rules with given number, and also do set manipulation.
2786 * Assumes chain != NULL && *chain != NULL.
2787 *
2788 * The argument is an u_int32_t. The low 16 bit are the rule or set number,
2789 * the next 8 bits are the new set, the top 8 bits are the command:
2790 *
2791 *	0	delete rules with given number
2792 *	1	delete rules with given set number
2793 *	2	move rules with given number to new set
2794 *	3	move rules with given set number to new set
2795 *	4	swap sets with given numbers
2796 */
2797static int
2798del_entry(struct ip_fw_chain *chain, u_int32_t arg)
2799{
2800	struct ip_fw *prev = NULL, *rule;
2801	u_int16_t rulenum;	/* rule or old_set */
2802	u_int8_t cmd, new_set;
2803
2804	rulenum = arg & 0xffff;
2805	cmd = (arg >> 24) & 0xff;
2806	new_set = (arg >> 16) & 0xff;
2807
2808	if (cmd > 4)
2809		return EINVAL;
2810	if (new_set > RESVD_SET)
2811		return EINVAL;
2812	if (cmd == 0 || cmd == 2) {
2813		if (rulenum >= IPFW_DEFAULT_RULE)
2814			return EINVAL;
2815	} else {
2816		if (rulenum > RESVD_SET)	/* old_set */
2817			return EINVAL;
2818	}
2819
2820	IPFW_WLOCK(chain);
2821	rule = chain->rules;
2822	chain->reap = NULL;
2823	switch (cmd) {
2824	case 0:	/* delete rules with given number */
2825		/*
2826		 * locate first rule to delete
2827		 */
2828		for (; rule->rulenum < rulenum; prev = rule, rule = rule->next)
2829			;
2830		if (rule->rulenum != rulenum) {
2831			IPFW_WUNLOCK(chain);
2832			return EINVAL;
2833		}
2834
2835		/*
2836		 * flush pointers outside the loop, then delete all matching
2837		 * rules. prev remains the same throughout the cycle.
2838		 */
2839		flush_rule_ptrs(chain);
2840		while (rule->rulenum == rulenum)
2841			rule = remove_rule(chain, rule, prev);
2842		break;
2843
2844	case 1:	/* delete all rules with given set number */
2845		flush_rule_ptrs(chain);
2846		rule = chain->rules;
2847		while (rule->rulenum < IPFW_DEFAULT_RULE)
2848			if (rule->set == rulenum)
2849				rule = remove_rule(chain, rule, prev);
2850			else {
2851				prev = rule;
2852				rule = rule->next;
2853			}
2854		break;
2855
2856	case 2:	/* move rules with given number to new set */
2857		rule = chain->rules;
2858		for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
2859			if (rule->rulenum == rulenum)
2860				rule->set = new_set;
2861		break;
2862
2863	case 3: /* move rules with given set number to new set */
2864		for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
2865			if (rule->set == rulenum)
2866				rule->set = new_set;
2867		break;
2868
2869	case 4: /* swap two sets */
2870		for (; rule->rulenum < IPFW_DEFAULT_RULE; rule = rule->next)
2871			if (rule->set == rulenum)
2872				rule->set = new_set;
2873			else if (rule->set == new_set)
2874				rule->set = rulenum;
2875		break;
2876	}
2877	/*
2878	 * Look for rules to reclaim.  We grab the list before
2879	 * releasing the lock then reclaim them w/o the lock to
2880	 * avoid a LOR with dummynet.
2881	 */
2882	rule = chain->reap;
2883	chain->reap = NULL;
2884	IPFW_WUNLOCK(chain);
2885	if (rule)
2886		reap_rules(rule);
2887	return 0;
2888}
2889
2890/*
2891 * Clear counters for a specific rule.
2892 * The enclosing "table" is assumed locked.
2893 */
2894static void
2895clear_counters(struct ip_fw *rule, int log_only)
2896{
2897	ipfw_insn_log *l = (ipfw_insn_log *)ACTION_PTR(rule);
2898
2899	if (log_only == 0) {
2900		rule->bcnt = rule->pcnt = 0;
2901		rule->timestamp = 0;
2902	}
2903	if (l->o.opcode == O_LOG)
2904		l->log_left = l->max_log;
2905}
2906
2907/**
2908 * Reset some or all counters on firewall rules.
2909 * @arg frwl is null to clear all entries, or contains a specific
2910 * rule number.
2911 * @arg log_only is 1 if we only want to reset logs, zero otherwise.
2912 */
2913static int
2914zero_entry(struct ip_fw_chain *chain, int rulenum, int log_only)
2915{
2916	struct ip_fw *rule;
2917	char *msg;
2918
2919	IPFW_WLOCK(chain);
2920	if (rulenum == 0) {
2921		norule_counter = 0;
2922		for (rule = chain->rules; rule; rule = rule->next)
2923			clear_counters(rule, log_only);
2924		msg = log_only ? "ipfw: All logging counts reset.\n" :
2925				"ipfw: Accounting cleared.\n";
2926	} else {
2927		int cleared = 0;
2928		/*
2929		 * We can have multiple rules with the same number, so we
2930		 * need to clear them all.
2931		 */
2932		for (rule = chain->rules; rule; rule = rule->next)
2933			if (rule->rulenum == rulenum) {
2934				while (rule && rule->rulenum == rulenum) {
2935					clear_counters(rule, log_only);
2936					rule = rule->next;
2937				}
2938				cleared = 1;
2939				break;
2940			}
2941		if (!cleared) {	/* we did not find any matching rules */
2942			IPFW_WUNLOCK(chain);
2943			return (EINVAL);
2944		}
2945		msg = log_only ? "ipfw: Entry %d logging count reset.\n" :
2946				"ipfw: Entry %d cleared.\n";
2947	}
2948	IPFW_WUNLOCK(chain);
2949
2950	if (fw_verbose)
2951		log(LOG_SECURITY | LOG_NOTICE, msg, rulenum);
2952	return (0);
2953}
2954
2955/*
2956 * Check validity of the structure before insert.
2957 * Fortunately rules are simple, so this mostly need to check rule sizes.
2958 */
2959static int
2960check_ipfw_struct(struct ip_fw *rule, int size)
2961{
2962	int l, cmdlen = 0;
2963	int have_action=0;
2964	ipfw_insn *cmd;
2965
2966	if (size < sizeof(*rule)) {
2967		printf("ipfw: rule too short\n");
2968		return (EINVAL);
2969	}
2970	/* first, check for valid size */
2971	l = RULESIZE(rule);
2972	if (l != size) {
2973		printf("ipfw: size mismatch (have %d want %d)\n", size, l);
2974		return (EINVAL);
2975	}
2976	if (rule->act_ofs >= rule->cmd_len) {
2977		printf("ipfw: bogus action offset (%u > %u)\n",
2978		    rule->act_ofs, rule->cmd_len - 1);
2979		return (EINVAL);
2980	}
2981	/*
2982	 * Now go for the individual checks. Very simple ones, basically only
2983	 * instruction sizes.
2984	 */
2985	for (l = rule->cmd_len, cmd = rule->cmd ;
2986			l > 0 ; l -= cmdlen, cmd += cmdlen) {
2987		cmdlen = F_LEN(cmd);
2988		if (cmdlen > l) {
2989			printf("ipfw: opcode %d size truncated\n",
2990			    cmd->opcode);
2991			return EINVAL;
2992		}
2993		DEB(printf("ipfw: opcode %d\n", cmd->opcode);)
2994		switch (cmd->opcode) {
2995		case O_PROBE_STATE:
2996		case O_KEEP_STATE:
2997		case O_PROTO:
2998		case O_IP_SRC_ME:
2999		case O_IP_DST_ME:
3000		case O_LAYER2:
3001		case O_IN:
3002		case O_FRAG:
3003		case O_DIVERTED:
3004		case O_IPOPT:
3005		case O_IPTOS:
3006		case O_IPPRECEDENCE:
3007		case O_IPVER:
3008		case O_TCPWIN:
3009		case O_TCPFLAGS:
3010		case O_TCPOPTS:
3011		case O_ESTAB:
3012		case O_VERREVPATH:
3013		case O_VERSRCREACH:
3014		case O_ANTISPOOF:
3015		case O_IPSEC:
3016			if (cmdlen != F_INSN_SIZE(ipfw_insn))
3017				goto bad_size;
3018			break;
3019
3020		case O_UID:
3021		case O_GID:
3022		case O_JAIL:
3023		case O_IP_SRC:
3024		case O_IP_DST:
3025		case O_TCPSEQ:
3026		case O_TCPACK:
3027		case O_PROB:
3028		case O_ICMPTYPE:
3029			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3030				goto bad_size;
3031			break;
3032
3033		case O_LIMIT:
3034			if (cmdlen != F_INSN_SIZE(ipfw_insn_limit))
3035				goto bad_size;
3036			break;
3037
3038		case O_LOG:
3039			if (cmdlen != F_INSN_SIZE(ipfw_insn_log))
3040				goto bad_size;
3041
3042			((ipfw_insn_log *)cmd)->log_left =
3043			    ((ipfw_insn_log *)cmd)->max_log;
3044
3045			break;
3046
3047		case O_IP_SRC_MASK:
3048		case O_IP_DST_MASK:
3049			/* only odd command lengths */
3050			if ( !(cmdlen & 1) || cmdlen > 31)
3051				goto bad_size;
3052			break;
3053
3054		case O_IP_SRC_SET:
3055		case O_IP_DST_SET:
3056			if (cmd->arg1 == 0 || cmd->arg1 > 256) {
3057				printf("ipfw: invalid set size %d\n",
3058					cmd->arg1);
3059				return EINVAL;
3060			}
3061			if (cmdlen != F_INSN_SIZE(ipfw_insn_u32) +
3062			    (cmd->arg1+31)/32 )
3063				goto bad_size;
3064			break;
3065
3066		case O_IP_SRC_LOOKUP:
3067		case O_IP_DST_LOOKUP:
3068			if (cmd->arg1 >= IPFW_TABLES_MAX) {
3069				printf("ipfw: invalid table number %d\n",
3070				    cmd->arg1);
3071				return (EINVAL);
3072			}
3073			if (cmdlen != F_INSN_SIZE(ipfw_insn) &&
3074			    cmdlen != F_INSN_SIZE(ipfw_insn_u32))
3075				goto bad_size;
3076			break;
3077
3078		case O_MACADDR2:
3079			if (cmdlen != F_INSN_SIZE(ipfw_insn_mac))
3080				goto bad_size;
3081			break;
3082
3083		case O_NOP:
3084		case O_IPID:
3085		case O_IPTTL:
3086		case O_IPLEN:
3087		case O_TCPDATALEN:
3088			if (cmdlen < 1 || cmdlen > 31)
3089				goto bad_size;
3090			break;
3091
3092		case O_MAC_TYPE:
3093		case O_IP_SRCPORT:
3094		case O_IP_DSTPORT: /* XXX artificial limit, 30 port pairs */
3095			if (cmdlen < 2 || cmdlen > 31)
3096				goto bad_size;
3097			break;
3098
3099		case O_RECV:
3100		case O_XMIT:
3101		case O_VIA:
3102			if (cmdlen != F_INSN_SIZE(ipfw_insn_if))
3103				goto bad_size;
3104			break;
3105
3106		case O_ALTQ:
3107			if (cmdlen != F_INSN_SIZE(ipfw_insn_altq))
3108				goto bad_size;
3109			break;
3110
3111		case O_PIPE:
3112		case O_QUEUE:
3113			if (cmdlen != F_INSN_SIZE(ipfw_insn_pipe))
3114				goto bad_size;
3115			goto check_action;
3116
3117		case O_FORWARD_IP:
3118#ifdef	IPFIREWALL_FORWARD
3119			if (cmdlen != F_INSN_SIZE(ipfw_insn_sa))
3120				goto bad_size;
3121			goto check_action;
3122#else
3123			return EINVAL;
3124#endif
3125
3126		case O_DIVERT:
3127		case O_TEE:
3128			if (ip_divert_ptr == NULL)
3129				return EINVAL;
3130			else
3131				goto check_size;
3132		case O_NETGRAPH:
3133		case O_NGTEE:
3134			if (!NG_IPFW_LOADED)
3135				return EINVAL;
3136			else
3137				goto check_size;
3138		case O_FORWARD_MAC: /* XXX not implemented yet */
3139		case O_CHECK_STATE:
3140		case O_COUNT:
3141		case O_ACCEPT:
3142		case O_DENY:
3143		case O_REJECT:
3144		case O_SKIPTO:
3145check_size:
3146			if (cmdlen != F_INSN_SIZE(ipfw_insn))
3147				goto bad_size;
3148check_action:
3149			if (have_action) {
3150				printf("ipfw: opcode %d, multiple actions"
3151					" not allowed\n",
3152					cmd->opcode);
3153				return EINVAL;
3154			}
3155			have_action = 1;
3156			if (l != cmdlen) {
3157				printf("ipfw: opcode %d, action must be"
3158					" last opcode\n",
3159					cmd->opcode);
3160				return EINVAL;
3161			}
3162			break;
3163		default:
3164			printf("ipfw: opcode %d, unknown opcode\n",
3165				cmd->opcode);
3166			return EINVAL;
3167		}
3168	}
3169	if (have_action == 0) {
3170		printf("ipfw: missing action\n");
3171		return EINVAL;
3172	}
3173	return 0;
3174
3175bad_size:
3176	printf("ipfw: opcode %d size %d wrong\n",
3177		cmd->opcode, cmdlen);
3178	return EINVAL;
3179}
3180
3181/*
3182 * Copy the static and dynamic rules to the supplied buffer
3183 * and return the amount of space actually used.
3184 */
3185static size_t
3186ipfw_getrules(struct ip_fw_chain *chain, void *buf, size_t space)
3187{
3188	char *bp = buf;
3189	char *ep = bp + space;
3190	struct ip_fw *rule;
3191	int i;
3192
3193	/* XXX this can take a long time and locking will block packet flow */
3194	IPFW_RLOCK(chain);
3195	for (rule = chain->rules; rule ; rule = rule->next) {
3196		/*
3197		 * Verify the entry fits in the buffer in case the
3198		 * rules changed between calculating buffer space and
3199		 * now.  This would be better done using a generation
3200		 * number but should suffice for now.
3201		 */
3202		i = RULESIZE(rule);
3203		if (bp + i <= ep) {
3204			bcopy(rule, bp, i);
3205			bcopy(&set_disable, &(((struct ip_fw *)bp)->next_rule),
3206			    sizeof(set_disable));
3207			bp += i;
3208		}
3209	}
3210	IPFW_RUNLOCK(chain);
3211	if (ipfw_dyn_v) {
3212		ipfw_dyn_rule *p, *last = NULL;
3213
3214		IPFW_DYN_LOCK();
3215		for (i = 0 ; i < curr_dyn_buckets; i++)
3216			for (p = ipfw_dyn_v[i] ; p != NULL; p = p->next) {
3217				if (bp + sizeof *p <= ep) {
3218					ipfw_dyn_rule *dst =
3219						(ipfw_dyn_rule *)bp;
3220					bcopy(p, dst, sizeof *p);
3221					bcopy(&(p->rule->rulenum), &(dst->rule),
3222					    sizeof(p->rule->rulenum));
3223					/*
3224					 * store a non-null value in "next".
3225					 * The userland code will interpret a
3226					 * NULL here as a marker
3227					 * for the last dynamic rule.
3228					 */
3229					bcopy(&dst, &dst->next, sizeof(dst));
3230					last = dst;
3231					dst->expire =
3232					    TIME_LEQ(dst->expire, time_second) ?
3233						0 : dst->expire - time_second ;
3234					bp += sizeof(ipfw_dyn_rule);
3235				}
3236			}
3237		IPFW_DYN_UNLOCK();
3238		if (last != NULL) /* mark last dynamic rule */
3239			bzero(&last->next, sizeof(last));
3240	}
3241	return (bp - (char *)buf);
3242}
3243
3244
3245/**
3246 * {set|get}sockopt parser.
3247 */
3248static int
3249ipfw_ctl(struct sockopt *sopt)
3250{
3251#define	RULE_MAXSIZE	(256*sizeof(u_int32_t))
3252	int error, rule_num;
3253	size_t size;
3254	struct ip_fw *buf, *rule;
3255	u_int32_t rulenum[2];
3256
3257	error = suser(sopt->sopt_td);
3258	if (error)
3259		return (error);
3260
3261	/*
3262	 * Disallow modifications in really-really secure mode, but still allow
3263	 * the logging counters to be reset.
3264	 */
3265	if (sopt->sopt_name == IP_FW_ADD ||
3266	    (sopt->sopt_dir == SOPT_SET && sopt->sopt_name != IP_FW_RESETLOG)) {
3267#if __FreeBSD_version >= 500034
3268		error = securelevel_ge(sopt->sopt_td->td_ucred, 3);
3269		if (error)
3270			return (error);
3271#else /* FreeBSD 4.x */
3272		if (securelevel >= 3)
3273			return (EPERM);
3274#endif
3275	}
3276
3277	error = 0;
3278
3279	switch (sopt->sopt_name) {
3280	case IP_FW_GET:
3281		/*
3282		 * pass up a copy of the current rules. Static rules
3283		 * come first (the last of which has number IPFW_DEFAULT_RULE),
3284		 * followed by a possibly empty list of dynamic rule.
3285		 * The last dynamic rule has NULL in the "next" field.
3286		 *
3287		 * Note that the calculated size is used to bound the
3288		 * amount of data returned to the user.  The rule set may
3289		 * change between calculating the size and returning the
3290		 * data in which case we'll just return what fits.
3291		 */
3292		size = static_len;	/* size of static rules */
3293		if (ipfw_dyn_v)		/* add size of dyn.rules */
3294			size += (dyn_count * sizeof(ipfw_dyn_rule));
3295
3296		/*
3297		 * XXX todo: if the user passes a short length just to know
3298		 * how much room is needed, do not bother filling up the
3299		 * buffer, just jump to the sooptcopyout.
3300		 */
3301		buf = malloc(size, M_TEMP, M_WAITOK);
3302		error = sooptcopyout(sopt, buf,
3303				ipfw_getrules(&layer3_chain, buf, size));
3304		free(buf, M_TEMP);
3305		break;
3306
3307	case IP_FW_FLUSH:
3308		/*
3309		 * Normally we cannot release the lock on each iteration.
3310		 * We could do it here only because we start from the head all
3311		 * the times so there is no risk of missing some entries.
3312		 * On the other hand, the risk is that we end up with
3313		 * a very inconsistent ruleset, so better keep the lock
3314		 * around the whole cycle.
3315		 *
3316		 * XXX this code can be improved by resetting the head of
3317		 * the list to point to the default rule, and then freeing
3318		 * the old list without the need for a lock.
3319		 */
3320
3321		IPFW_WLOCK(&layer3_chain);
3322		layer3_chain.reap = NULL;
3323		free_chain(&layer3_chain, 0 /* keep default rule */);
3324		rule = layer3_chain.reap, layer3_chain.reap = NULL;
3325		IPFW_WUNLOCK(&layer3_chain);
3326		if (layer3_chain.reap != NULL)
3327			reap_rules(rule);
3328		break;
3329
3330	case IP_FW_ADD:
3331		rule = malloc(RULE_MAXSIZE, M_TEMP, M_WAITOK);
3332		error = sooptcopyin(sopt, rule, RULE_MAXSIZE,
3333			sizeof(struct ip_fw) );
3334		if (error == 0)
3335			error = check_ipfw_struct(rule, sopt->sopt_valsize);
3336		if (error == 0) {
3337			error = add_rule(&layer3_chain, rule);
3338			size = RULESIZE(rule);
3339			if (!error && sopt->sopt_dir == SOPT_GET)
3340				error = sooptcopyout(sopt, rule, size);
3341		}
3342		free(rule, M_TEMP);
3343		break;
3344
3345	case IP_FW_DEL:
3346		/*
3347		 * IP_FW_DEL is used for deleting single rules or sets,
3348		 * and (ab)used to atomically manipulate sets. Argument size
3349		 * is used to distinguish between the two:
3350		 *    sizeof(u_int32_t)
3351		 *	delete single rule or set of rules,
3352		 *	or reassign rules (or sets) to a different set.
3353		 *    2*sizeof(u_int32_t)
3354		 *	atomic disable/enable sets.
3355		 *	first u_int32_t contains sets to be disabled,
3356		 *	second u_int32_t contains sets to be enabled.
3357		 */
3358		error = sooptcopyin(sopt, rulenum,
3359			2*sizeof(u_int32_t), sizeof(u_int32_t));
3360		if (error)
3361			break;
3362		size = sopt->sopt_valsize;
3363		if (size == sizeof(u_int32_t))	/* delete or reassign */
3364			error = del_entry(&layer3_chain, rulenum[0]);
3365		else if (size == 2*sizeof(u_int32_t)) /* set enable/disable */
3366			set_disable =
3367			    (set_disable | rulenum[0]) & ~rulenum[1] &
3368			    ~(1<<RESVD_SET); /* set RESVD_SET always enabled */
3369		else
3370			error = EINVAL;
3371		break;
3372
3373	case IP_FW_ZERO:
3374	case IP_FW_RESETLOG: /* argument is an int, the rule number */
3375		rule_num = 0;
3376		if (sopt->sopt_val != 0) {
3377		    error = sooptcopyin(sopt, &rule_num,
3378			    sizeof(int), sizeof(int));
3379		    if (error)
3380			break;
3381		}
3382		error = zero_entry(&layer3_chain, rule_num,
3383			sopt->sopt_name == IP_FW_RESETLOG);
3384		break;
3385
3386	case IP_FW_TABLE_ADD:
3387		{
3388			ipfw_table_entry ent;
3389
3390			error = sooptcopyin(sopt, &ent,
3391			    sizeof(ent), sizeof(ent));
3392			if (error)
3393				break;
3394			error = add_table_entry(ent.tbl, ent.addr,
3395			    ent.masklen, ent.value);
3396		}
3397		break;
3398
3399	case IP_FW_TABLE_DEL:
3400		{
3401			ipfw_table_entry ent;
3402
3403			error = sooptcopyin(sopt, &ent,
3404			    sizeof(ent), sizeof(ent));
3405			if (error)
3406				break;
3407			error = del_table_entry(ent.tbl, ent.addr, ent.masklen);
3408		}
3409		break;
3410
3411	case IP_FW_TABLE_FLUSH:
3412		{
3413			u_int16_t tbl;
3414
3415			error = sooptcopyin(sopt, &tbl,
3416			    sizeof(tbl), sizeof(tbl));
3417			if (error)
3418				break;
3419			error = flush_table(tbl);
3420		}
3421		break;
3422
3423	case IP_FW_TABLE_GETSIZE:
3424		{
3425			u_int32_t tbl, cnt;
3426
3427			if ((error = sooptcopyin(sopt, &tbl, sizeof(tbl),
3428			    sizeof(tbl))))
3429				break;
3430			if ((error = count_table(tbl, &cnt)))
3431				break;
3432			error = sooptcopyout(sopt, &cnt, sizeof(cnt));
3433		}
3434		break;
3435
3436	case IP_FW_TABLE_LIST:
3437		{
3438			ipfw_table *tbl;
3439
3440			if (sopt->sopt_valsize < sizeof(*tbl)) {
3441				error = EINVAL;
3442				break;
3443			}
3444			size = sopt->sopt_valsize;
3445			tbl = malloc(size, M_TEMP, M_WAITOK);
3446			if (tbl == NULL) {
3447				error = ENOMEM;
3448				break;
3449			}
3450			error = sooptcopyin(sopt, tbl, size, sizeof(*tbl));
3451			if (error) {
3452				free(tbl, M_TEMP);
3453				break;
3454			}
3455			tbl->size = (size - sizeof(*tbl)) /
3456			    sizeof(ipfw_table_entry);
3457			error = dump_table(tbl);
3458			if (error) {
3459				free(tbl, M_TEMP);
3460				break;
3461			}
3462			error = sooptcopyout(sopt, tbl, size);
3463			free(tbl, M_TEMP);
3464		}
3465		break;
3466
3467	default:
3468		printf("ipfw: ipfw_ctl invalid option %d\n", sopt->sopt_name);
3469		error = EINVAL;
3470	}
3471
3472	return (error);
3473#undef RULE_MAXSIZE
3474}
3475
3476/**
3477 * dummynet needs a reference to the default rule, because rules can be
3478 * deleted while packets hold a reference to them. When this happens,
3479 * dummynet changes the reference to the default rule (it could well be a
3480 * NULL pointer, but this way we do not need to check for the special
3481 * case, plus here he have info on the default behaviour).
3482 */
3483struct ip_fw *ip_fw_default_rule;
3484
3485/*
3486 * This procedure is only used to handle keepalives. It is invoked
3487 * every dyn_keepalive_period
3488 */
3489static void
3490ipfw_tick(void * __unused unused)
3491{
3492	int i;
3493	ipfw_dyn_rule *q;
3494
3495	if (dyn_keepalive == 0 || ipfw_dyn_v == NULL || dyn_count == 0)
3496		goto done;
3497
3498	IPFW_DYN_LOCK();
3499	for (i = 0 ; i < curr_dyn_buckets ; i++) {
3500		for (q = ipfw_dyn_v[i] ; q ; q = q->next ) {
3501			if (q->dyn_type == O_LIMIT_PARENT)
3502				continue;
3503			if (q->id.proto != IPPROTO_TCP)
3504				continue;
3505			if ( (q->state & BOTH_SYN) != BOTH_SYN)
3506				continue;
3507			if (TIME_LEQ( time_second+dyn_keepalive_interval,
3508			    q->expire))
3509				continue;	/* too early */
3510			if (TIME_LEQ(q->expire, time_second))
3511				continue;	/* too late, rule expired */
3512
3513			send_pkt(&(q->id), q->ack_rev - 1, q->ack_fwd, TH_SYN);
3514			send_pkt(&(q->id), q->ack_fwd - 1, q->ack_rev, 0);
3515		}
3516	}
3517	IPFW_DYN_UNLOCK();
3518done:
3519	callout_reset(&ipfw_timeout, dyn_keepalive_period*hz, ipfw_tick, NULL);
3520}
3521
3522int
3523ipfw_init(void)
3524{
3525	struct ip_fw default_rule;
3526	int error;
3527
3528	layer3_chain.rules = NULL;
3529	layer3_chain.want_write = 0;
3530	layer3_chain.busy_count = 0;
3531	cv_init(&layer3_chain.cv, "Condition variable for IPFW rw locks");
3532	IPFW_LOCK_INIT(&layer3_chain);
3533	ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule zone",
3534	    sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
3535	    UMA_ALIGN_PTR, 0);
3536	IPFW_DYN_LOCK_INIT();
3537	callout_init(&ipfw_timeout, debug_mpsafenet ? CALLOUT_MPSAFE : 0);
3538
3539	bzero(&default_rule, sizeof default_rule);
3540
3541	default_rule.act_ofs = 0;
3542	default_rule.rulenum = IPFW_DEFAULT_RULE;
3543	default_rule.cmd_len = 1;
3544	default_rule.set = RESVD_SET;
3545
3546	default_rule.cmd[0].len = 1;
3547	default_rule.cmd[0].opcode =
3548#ifdef IPFIREWALL_DEFAULT_TO_ACCEPT
3549				1 ? O_ACCEPT :
3550#endif
3551				O_DENY;
3552
3553	error = add_rule(&layer3_chain, &default_rule);
3554	if (error != 0) {
3555		printf("ipfw2: error %u initializing default rule "
3556			"(support disabled)\n", error);
3557		IPFW_DYN_LOCK_DESTROY();
3558		IPFW_LOCK_DESTROY(&layer3_chain);
3559		return (error);
3560	}
3561
3562	ip_fw_default_rule = layer3_chain.rules;
3563	printf("ipfw2 initialized, divert %s, "
3564		"rule-based forwarding "
3565#ifdef IPFIREWALL_FORWARD
3566		"enabled, "
3567#else
3568		"disabled, "
3569#endif
3570		"default to %s, logging ",
3571#ifdef IPDIVERT
3572		"enabled",
3573#else
3574		"loadable",
3575#endif
3576		default_rule.cmd[0].opcode == O_ACCEPT ? "accept" : "deny");
3577
3578#ifdef IPFIREWALL_VERBOSE
3579	fw_verbose = 1;
3580#endif
3581#ifdef IPFIREWALL_VERBOSE_LIMIT
3582	verbose_limit = IPFIREWALL_VERBOSE_LIMIT;
3583#endif
3584	if (fw_verbose == 0)
3585		printf("disabled\n");
3586	else if (verbose_limit == 0)
3587		printf("unlimited\n");
3588	else
3589		printf("limited to %d packets/entry by default\n",
3590		    verbose_limit);
3591
3592	init_tables();
3593	ip_fw_ctl_ptr = ipfw_ctl;
3594	ip_fw_chk_ptr = ipfw_chk;
3595	callout_reset(&ipfw_timeout, hz, ipfw_tick, NULL);
3596
3597	return (0);
3598}
3599
3600void
3601ipfw_destroy(void)
3602{
3603	struct ip_fw *reap;
3604
3605	ip_fw_chk_ptr = NULL;
3606	ip_fw_ctl_ptr = NULL;
3607	callout_drain(&ipfw_timeout);
3608	IPFW_WLOCK(&layer3_chain);
3609	layer3_chain.reap = NULL;
3610	free_chain(&layer3_chain, 1 /* kill default rule */);
3611	reap = layer3_chain.reap, layer3_chain.reap = NULL;
3612	IPFW_WUNLOCK(&layer3_chain);
3613	if (reap != NULL)
3614		reap_rules(reap);
3615	flush_tables();
3616	IPFW_DYN_LOCK_DESTROY();
3617	uma_zdestroy(ipfw_dyn_rule_zone);
3618	IPFW_LOCK_DESTROY(&layer3_chain);
3619	printf("IP firewall unloaded\n");
3620}
3621
3622#endif /* IPFW2 */
3623