ip_fw_dynamic.c revision 242834
1/*-
2 * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 *    notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 *    notice, this list of conditions and the following disclaimer in the
11 *    documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
23 * SUCH DAMAGE.
24 */
25
26#include <sys/cdefs.h>
27__FBSDID("$FreeBSD: head/sys/netpfil/ipfw/ip_fw_dynamic.c 242834 2012-11-09 18:23:38Z melifaro $");
28
29#define        DEB(x)
30#define        DDB(x) x
31
32/*
33 * Dynamic rule support for ipfw
34 */
35
36#include "opt_ipfw.h"
37#include "opt_inet.h"
38#ifndef INET
39#error IPFIREWALL requires INET.
40#endif /* INET */
41#include "opt_inet6.h"
42
43#include <sys/param.h>
44#include <sys/systm.h>
45#include <sys/malloc.h>
46#include <sys/mbuf.h>
47#include <sys/kernel.h>
48#include <sys/lock.h>
49#include <sys/socket.h>
50#include <sys/sysctl.h>
51#include <sys/syslog.h>
52#include <net/ethernet.h> /* for ETHERTYPE_IP */
53#include <net/if.h>
54#include <net/vnet.h>
55
56#include <netinet/in.h>
57#include <netinet/ip.h>
58#include <netinet/ip_var.h>	/* ip_defttl */
59#include <netinet/ip_fw.h>
60#include <netinet/tcp_var.h>
61#include <netinet/udp.h>
62
63#include <netinet/ip6.h>	/* IN6_ARE_ADDR_EQUAL */
64#ifdef INET6
65#include <netinet6/in6_var.h>
66#include <netinet6/ip6_var.h>
67#endif
68
69#include <netpfil/ipfw/ip_fw_private.h>
70
71#include <machine/in_cksum.h>	/* XXX for in_cksum */
72
73#ifdef MAC
74#include <security/mac/mac_framework.h>
75#endif
76
77/*
78 * Description of dynamic rules.
79 *
80 * Dynamic rules are stored in lists accessed through a hash table
81 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
82 * be modified through the sysctl variable dyn_buckets which is
83 * updated when the table becomes empty.
84 *
85 * XXX currently there is only one list, ipfw_dyn.
86 *
87 * When a packet is received, its address fields are first masked
88 * with the mask defined for the rule, then hashed, then matched
89 * against the entries in the corresponding list.
90 * Dynamic rules can be used for different purposes:
91 *  + stateful rules;
92 *  + enforcing limits on the number of sessions;
93 *  + in-kernel NAT (not implemented yet)
94 *
95 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
96 * measured in seconds and depending on the flags.
97 *
98 * The total number of dynamic rules is stored in dyn_count.
99 * The max number of dynamic rules is dyn_max. When we reach
100 * the maximum number of rules we do not create anymore. This is
101 * done to avoid consuming too much memory, but also too much
102 * time when searching on each packet (ideally, we should try instead
103 * to put a limit on the length of the list on each bucket...).
104 *
105 * Each dynamic rule holds a pointer to the parent ipfw rule so
106 * we know what action to perform. Dynamic rules are removed when
107 * the parent rule is deleted. XXX we should make them survive.
108 *
109 * There are some limitations with dynamic rules -- we do not
110 * obey the 'randomized match', and we do not do multiple
111 * passes through the firewall. XXX check the latter!!!
112 */
113
114/*
115 * Static variables followed by global ones
116 */
117static VNET_DEFINE(ipfw_dyn_rule **, ipfw_dyn_v);
118static VNET_DEFINE(u_int32_t, dyn_buckets);
119static VNET_DEFINE(u_int32_t, curr_dyn_buckets);
120static VNET_DEFINE(struct callout, ipfw_timeout);
121#define	V_ipfw_dyn_v			VNET(ipfw_dyn_v)
122#define	V_dyn_buckets			VNET(dyn_buckets)
123#define	V_curr_dyn_buckets		VNET(curr_dyn_buckets)
124#define V_ipfw_timeout                  VNET(ipfw_timeout)
125
126static uma_zone_t ipfw_dyn_rule_zone;
127#ifndef __FreeBSD__
128DEFINE_SPINLOCK(ipfw_dyn_mtx);
129#else
130static struct mtx ipfw_dyn_mtx;		/* mutex guarding dynamic rules */
131#endif
132
133#define	IPFW_DYN_LOCK_INIT() \
134	mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
135#define	IPFW_DYN_LOCK_DESTROY()	mtx_destroy(&ipfw_dyn_mtx)
136#define	IPFW_DYN_LOCK()		mtx_lock(&ipfw_dyn_mtx)
137#define	IPFW_DYN_UNLOCK()	mtx_unlock(&ipfw_dyn_mtx)
138#define	IPFW_DYN_LOCK_ASSERT()	mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
139
140void
141ipfw_dyn_unlock(void)
142{
143	IPFW_DYN_UNLOCK();
144}
145
146/*
147 * Timeouts for various events in handing dynamic rules.
148 */
149static VNET_DEFINE(u_int32_t, dyn_ack_lifetime);
150static VNET_DEFINE(u_int32_t, dyn_syn_lifetime);
151static VNET_DEFINE(u_int32_t, dyn_fin_lifetime);
152static VNET_DEFINE(u_int32_t, dyn_rst_lifetime);
153static VNET_DEFINE(u_int32_t, dyn_udp_lifetime);
154static VNET_DEFINE(u_int32_t, dyn_short_lifetime);
155
156#define	V_dyn_ack_lifetime		VNET(dyn_ack_lifetime)
157#define	V_dyn_syn_lifetime		VNET(dyn_syn_lifetime)
158#define	V_dyn_fin_lifetime		VNET(dyn_fin_lifetime)
159#define	V_dyn_rst_lifetime		VNET(dyn_rst_lifetime)
160#define	V_dyn_udp_lifetime		VNET(dyn_udp_lifetime)
161#define	V_dyn_short_lifetime		VNET(dyn_short_lifetime)
162
163/*
164 * Keepalives are sent if dyn_keepalive is set. They are sent every
165 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
166 * seconds of lifetime of a rule.
167 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
168 * than dyn_keepalive_period.
169 */
170
171static VNET_DEFINE(u_int32_t, dyn_keepalive_interval);
172static VNET_DEFINE(u_int32_t, dyn_keepalive_period);
173static VNET_DEFINE(u_int32_t, dyn_keepalive);
174
175#define	V_dyn_keepalive_interval	VNET(dyn_keepalive_interval)
176#define	V_dyn_keepalive_period		VNET(dyn_keepalive_period)
177#define	V_dyn_keepalive			VNET(dyn_keepalive)
178
179static VNET_DEFINE(u_int32_t, dyn_count);	/* # of dynamic rules */
180static VNET_DEFINE(u_int32_t, dyn_max);		/* max # of dynamic rules */
181
182#define	V_dyn_count			VNET(dyn_count)
183#define	V_dyn_max			VNET(dyn_max)
184
185#ifdef SYSCTL_NODE
186
187SYSBEGIN(f2)
188
189SYSCTL_DECL(_net_inet_ip_fw);
190SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_buckets,
191    CTLFLAG_RW, &VNET_NAME(dyn_buckets), 0,
192    "Number of dyn. buckets");
193SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets,
194    CTLFLAG_RD, &VNET_NAME(curr_dyn_buckets), 0,
195    "Current Number of dyn. buckets");
196SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_count,
197    CTLFLAG_RD, &VNET_NAME(dyn_count), 0,
198    "Number of dyn. rules");
199SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_max,
200    CTLFLAG_RW, &VNET_NAME(dyn_max), 0,
201    "Max number of dyn. rules");
202SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime,
203    CTLFLAG_RW, &VNET_NAME(dyn_ack_lifetime), 0,
204    "Lifetime of dyn. rules for acks");
205SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime,
206    CTLFLAG_RW, &VNET_NAME(dyn_syn_lifetime), 0,
207    "Lifetime of dyn. rules for syn");
208SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
209    CTLFLAG_RW, &VNET_NAME(dyn_fin_lifetime), 0,
210    "Lifetime of dyn. rules for fin");
211SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
212    CTLFLAG_RW, &VNET_NAME(dyn_rst_lifetime), 0,
213    "Lifetime of dyn. rules for rst");
214SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime,
215    CTLFLAG_RW, &VNET_NAME(dyn_udp_lifetime), 0,
216    "Lifetime of dyn. rules for UDP");
217SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime,
218    CTLFLAG_RW, &VNET_NAME(dyn_short_lifetime), 0,
219    "Lifetime of dyn. rules for other situations");
220SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive,
221    CTLFLAG_RW, &VNET_NAME(dyn_keepalive), 0,
222    "Enable keepalives for dyn. rules");
223
224SYSEND
225
226#endif /* SYSCTL_NODE */
227
228
229static __inline int
230hash_packet6(struct ipfw_flow_id *id)
231{
232	u_int32_t i;
233	i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
234	    (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
235	    (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
236	    (id->src_ip6.__u6_addr.__u6_addr32[3]) ^
237	    (id->dst_port) ^ (id->src_port);
238	return i;
239}
240
241/*
242 * IMPORTANT: the hash function for dynamic rules must be commutative
243 * in source and destination (ip,port), because rules are bidirectional
244 * and we want to find both in the same bucket.
245 */
246static __inline int
247hash_packet(struct ipfw_flow_id *id)
248{
249	u_int32_t i;
250
251#ifdef INET6
252	if (IS_IP6_FLOW_ID(id))
253		i = hash_packet6(id);
254	else
255#endif /* INET6 */
256	i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
257	i &= (V_curr_dyn_buckets - 1);
258	return i;
259}
260
261/**
262 * Print customizable flow id description via log(9) facility.
263 */
264static void
265print_dyn_rule_flags(struct ipfw_flow_id *id, int dyn_type, int log_flags,
266    char *prefix, char *postfix)
267{
268	struct in_addr da;
269#ifdef INET6
270	char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN];
271#else
272	char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
273#endif
274
275#ifdef INET6
276	if (IS_IP6_FLOW_ID(id)) {
277		ip6_sprintf(src, &id->src_ip6);
278		ip6_sprintf(dst, &id->dst_ip6);
279	} else
280#endif
281	{
282		da.s_addr = htonl(id->src_ip);
283		inet_ntop(AF_INET, &da, src, sizeof(src));
284		da.s_addr = htonl(id->dst_ip);
285		inet_ntop(AF_INET, &da, dst, sizeof(dst));
286	}
287	log(log_flags, "ipfw: %s type %d %s %d -> %s %d, %d %s\n",
288	    prefix, dyn_type, src, id->src_port, dst,
289	    id->dst_port, V_dyn_count, postfix);
290}
291
292#define	print_dyn_rule(id, dtype, prefix, postfix)	\
293	print_dyn_rule_flags(id, dtype, LOG_DEBUG, prefix, postfix)
294
295/**
296 * unlink a dynamic rule from a chain. prev is a pointer to
297 * the previous one, q is a pointer to the rule to delete,
298 * head is a pointer to the head of the queue.
299 * Modifies q and potentially also head.
300 */
301#define UNLINK_DYN_RULE(prev, head, q) {				\
302	ipfw_dyn_rule *old_q = q;					\
303									\
304	/* remove a refcount to the parent */				\
305	if (q->dyn_type == O_LIMIT)					\
306		q->parent->count--;					\
307	V_dyn_count--;							\
308	DEB(print_dyn_rule(&q->id, q->dyn_type, "unlink entry", "left");) \
309	if (prev != NULL)						\
310		prev->next = q = q->next;				\
311	else								\
312		head = q = q->next;					\
313	uma_zfree(ipfw_dyn_rule_zone, old_q); }
314
315#define TIME_LEQ(a,b)       ((int)((a)-(b)) <= 0)
316
317/**
318 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
319 *
320 * If keep_me == NULL, rules are deleted even if not expired,
321 * otherwise only expired rules are removed.
322 *
323 * The value of the second parameter is also used to point to identify
324 * a rule we absolutely do not want to remove (e.g. because we are
325 * holding a reference to it -- this is the case with O_LIMIT_PARENT
326 * rules). The pointer is only used for comparison, so any non-null
327 * value will do.
328 */
329static void
330remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
331{
332	static u_int32_t last_remove = 0;
333
334#define FORCE (keep_me == NULL)
335
336	ipfw_dyn_rule *prev, *q;
337	int i, pass = 0, max_pass = 0;
338
339	IPFW_DYN_LOCK_ASSERT();
340
341	if (V_ipfw_dyn_v == NULL || V_dyn_count == 0)
342		return;
343	/* do not expire more than once per second, it is useless */
344	if (!FORCE && last_remove == time_uptime)
345		return;
346	last_remove = time_uptime;
347
348	/*
349	 * because O_LIMIT refer to parent rules, during the first pass only
350	 * remove child and mark any pending LIMIT_PARENT, and remove
351	 * them in a second pass.
352	 */
353next_pass:
354	for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
355		for (prev=NULL, q = V_ipfw_dyn_v[i] ; q ; ) {
356			/*
357			 * Logic can become complex here, so we split tests.
358			 */
359			if (q == keep_me)
360				goto next;
361			if (rule != NULL && rule != q->rule)
362				goto next; /* not the one we are looking for */
363			if (q->dyn_type == O_LIMIT_PARENT) {
364				/*
365				 * handle parent in the second pass,
366				 * record we need one.
367				 */
368				max_pass = 1;
369				if (pass == 0)
370					goto next;
371				if (FORCE && q->count != 0 ) {
372					/* XXX should not happen! */
373					printf("ipfw: OUCH! cannot remove rule,"
374					     " count %d\n", q->count);
375				}
376			} else {
377				if (!FORCE &&
378				    !TIME_LEQ( q->expire, time_uptime ))
379					goto next;
380			}
381             if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
382                     UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
383                     continue;
384             }
385next:
386			prev=q;
387			q=q->next;
388		}
389	}
390	if (pass++ < max_pass)
391		goto next_pass;
392}
393
394void
395ipfw_remove_dyn_children(struct ip_fw *rule)
396{
397	IPFW_DYN_LOCK();
398	remove_dyn_rule(rule, NULL /* force removal */);
399	IPFW_DYN_UNLOCK();
400}
401
402/*
403 * Lookup a dynamic rule, locked version.
404 */
405static ipfw_dyn_rule *
406lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
407    struct tcphdr *tcp)
408{
409	/*
410	 * Stateful ipfw extensions.
411	 * Lookup into dynamic session queue.
412	 */
413#define MATCH_REVERSE	0
414#define MATCH_FORWARD	1
415#define MATCH_NONE	2
416#define MATCH_UNKNOWN	3
417	int i, dir = MATCH_NONE;
418	ipfw_dyn_rule *prev, *q = NULL;
419
420	IPFW_DYN_LOCK_ASSERT();
421
422	if (V_ipfw_dyn_v == NULL)
423		goto done;				/* not found */
424	i = hash_packet(pkt);
425	for (prev = NULL, q = V_ipfw_dyn_v[i]; q != NULL;) {
426		if (q->dyn_type == O_LIMIT_PARENT && q->count)
427			goto next;
428		if (TIME_LEQ(q->expire, time_uptime)) {	/* expire entry */
429			UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
430			continue;
431		}
432		if (pkt->proto != q->id.proto || q->dyn_type == O_LIMIT_PARENT)
433			goto next;
434
435		if (IS_IP6_FLOW_ID(pkt)) {
436			if (IN6_ARE_ADDR_EQUAL(&pkt->src_ip6, &q->id.src_ip6) &&
437			    IN6_ARE_ADDR_EQUAL(&pkt->dst_ip6, &q->id.dst_ip6) &&
438			    pkt->src_port == q->id.src_port &&
439			    pkt->dst_port == q->id.dst_port) {
440				dir = MATCH_FORWARD;
441				break;
442			}
443			if (IN6_ARE_ADDR_EQUAL(&pkt->src_ip6, &q->id.dst_ip6) &&
444			    IN6_ARE_ADDR_EQUAL(&pkt->dst_ip6, &q->id.src_ip6) &&
445			    pkt->src_port == q->id.dst_port &&
446			    pkt->dst_port == q->id.src_port) {
447				dir = MATCH_REVERSE;
448				break;
449			}
450		} else {
451			if (pkt->src_ip == q->id.src_ip &&
452			    pkt->dst_ip == q->id.dst_ip &&
453			    pkt->src_port == q->id.src_port &&
454			    pkt->dst_port == q->id.dst_port) {
455				dir = MATCH_FORWARD;
456				break;
457			}
458			if (pkt->src_ip == q->id.dst_ip &&
459			    pkt->dst_ip == q->id.src_ip &&
460			    pkt->src_port == q->id.dst_port &&
461			    pkt->dst_port == q->id.src_port) {
462				dir = MATCH_REVERSE;
463				break;
464			}
465		}
466next:
467		prev = q;
468		q = q->next;
469	}
470	if (q == NULL)
471		goto done;	/* q = NULL, not found */
472
473	if (prev != NULL) {	/* found and not in front */
474		prev->next = q->next;
475		q->next = V_ipfw_dyn_v[i];
476		V_ipfw_dyn_v[i] = q;
477	}
478	if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
479		uint32_t ack;
480		u_char flags = pkt->_flags & (TH_FIN | TH_SYN | TH_RST);
481
482#define BOTH_SYN	(TH_SYN | (TH_SYN << 8))
483#define BOTH_FIN	(TH_FIN | (TH_FIN << 8))
484#define	TCP_FLAGS	(TH_FLAGS | (TH_FLAGS << 8))
485#define	ACK_FWD		0x10000			/* fwd ack seen */
486#define	ACK_REV		0x20000			/* rev ack seen */
487
488		q->state |= (dir == MATCH_FORWARD) ? flags : (flags << 8);
489		switch (q->state & TCP_FLAGS) {
490		case TH_SYN:			/* opening */
491			q->expire = time_uptime + V_dyn_syn_lifetime;
492			break;
493
494		case BOTH_SYN:			/* move to established */
495		case BOTH_SYN | TH_FIN:		/* one side tries to close */
496		case BOTH_SYN | (TH_FIN << 8):
497#define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
498			if (tcp == NULL)
499				break;
500
501			ack = ntohl(tcp->th_ack);
502			if (dir == MATCH_FORWARD) {
503				if (q->ack_fwd == 0 ||
504				    _SEQ_GE(ack, q->ack_fwd)) {
505					q->ack_fwd = ack;
506					q->state |= ACK_FWD;
507				}
508			} else {
509				if (q->ack_rev == 0 ||
510				    _SEQ_GE(ack, q->ack_rev)) {
511					q->ack_rev = ack;
512					q->state |= ACK_REV;
513				}
514			}
515			if ((q->state & (ACK_FWD | ACK_REV)) ==
516			    (ACK_FWD | ACK_REV)) {
517				q->expire = time_uptime + V_dyn_ack_lifetime;
518				q->state &= ~(ACK_FWD | ACK_REV);
519			}
520			break;
521
522		case BOTH_SYN | BOTH_FIN:	/* both sides closed */
523			if (V_dyn_fin_lifetime >= V_dyn_keepalive_period)
524				V_dyn_fin_lifetime = V_dyn_keepalive_period - 1;
525			q->expire = time_uptime + V_dyn_fin_lifetime;
526			break;
527
528		default:
529#if 0
530			/*
531			 * reset or some invalid combination, but can also
532			 * occur if we use keep-state the wrong way.
533			 */
534			if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
535				printf("invalid state: 0x%x\n", q->state);
536#endif
537			if (V_dyn_rst_lifetime >= V_dyn_keepalive_period)
538				V_dyn_rst_lifetime = V_dyn_keepalive_period - 1;
539			q->expire = time_uptime + V_dyn_rst_lifetime;
540			break;
541		}
542	} else if (pkt->proto == IPPROTO_UDP) {
543		q->expire = time_uptime + V_dyn_udp_lifetime;
544	} else {
545		/* other protocols */
546		q->expire = time_uptime + V_dyn_short_lifetime;
547	}
548done:
549	if (match_direction != NULL)
550		*match_direction = dir;
551	return (q);
552}
553
554ipfw_dyn_rule *
555ipfw_lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
556    struct tcphdr *tcp)
557{
558	ipfw_dyn_rule *q;
559
560	IPFW_DYN_LOCK();
561	q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
562	if (q == NULL)
563		IPFW_DYN_UNLOCK();
564	/* NB: return table locked when q is not NULL */
565	return q;
566}
567
568static void
569realloc_dynamic_table(void)
570{
571	IPFW_DYN_LOCK_ASSERT();
572
573	/*
574	 * Try reallocation, make sure we have a power of 2 and do
575	 * not allow more than 64k entries. In case of overflow,
576	 * default to 1024.
577	 */
578
579	if (V_dyn_buckets > 65536)
580		V_dyn_buckets = 1024;
581	if ((V_dyn_buckets & (V_dyn_buckets-1)) != 0) { /* not a power of 2 */
582		V_dyn_buckets = V_curr_dyn_buckets; /* reset */
583		return;
584	}
585	V_curr_dyn_buckets = V_dyn_buckets;
586	if (V_ipfw_dyn_v != NULL)
587		free(V_ipfw_dyn_v, M_IPFW);
588	for (;;) {
589		V_ipfw_dyn_v = malloc(V_curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
590		       M_IPFW, M_NOWAIT | M_ZERO);
591		if (V_ipfw_dyn_v != NULL || V_curr_dyn_buckets <= 2)
592			break;
593		V_curr_dyn_buckets /= 2;
594	}
595}
596
597/**
598 * Install state of type 'type' for a dynamic session.
599 * The hash table contains two type of rules:
600 * - regular rules (O_KEEP_STATE)
601 * - rules for sessions with limited number of sess per user
602 *   (O_LIMIT). When they are created, the parent is
603 *   increased by 1, and decreased on delete. In this case,
604 *   the third parameter is the parent rule and not the chain.
605 * - "parent" rules for the above (O_LIMIT_PARENT).
606 */
607static ipfw_dyn_rule *
608add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
609{
610	ipfw_dyn_rule *r;
611	int i;
612
613	IPFW_DYN_LOCK_ASSERT();
614
615	if (V_ipfw_dyn_v == NULL ||
616	    (V_dyn_count == 0 && V_dyn_buckets != V_curr_dyn_buckets)) {
617		realloc_dynamic_table();
618		if (V_ipfw_dyn_v == NULL)
619			return NULL; /* failed ! */
620	}
621	i = hash_packet(id);
622
623	r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
624	if (r == NULL) {
625		printf ("ipfw: sorry cannot allocate state\n");
626		return NULL;
627	}
628
629	/* increase refcount on parent, and set pointer */
630	if (dyn_type == O_LIMIT) {
631		ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
632		if ( parent->dyn_type != O_LIMIT_PARENT)
633			panic("invalid parent");
634		parent->count++;
635		r->parent = parent;
636		rule = parent->rule;
637	}
638
639	r->id = *id;
640	r->expire = time_uptime + V_dyn_syn_lifetime;
641	r->rule = rule;
642	r->dyn_type = dyn_type;
643	r->pcnt = r->bcnt = 0;
644	r->count = 0;
645
646	r->bucket = i;
647	r->next = V_ipfw_dyn_v[i];
648	V_ipfw_dyn_v[i] = r;
649	V_dyn_count++;
650	DEB(print_dyn_rule(id, dyn_type, "add dyn entry", "total");)
651	return r;
652}
653
654/**
655 * lookup dynamic parent rule using pkt and rule as search keys.
656 * If the lookup fails, then install one.
657 */
658static ipfw_dyn_rule *
659lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
660{
661	ipfw_dyn_rule *q;
662	int i;
663
664	IPFW_DYN_LOCK_ASSERT();
665
666	if (V_ipfw_dyn_v) {
667		int is_v6 = IS_IP6_FLOW_ID(pkt);
668		i = hash_packet( pkt );
669		for (q = V_ipfw_dyn_v[i] ; q != NULL ; q=q->next)
670			if (q->dyn_type == O_LIMIT_PARENT &&
671			    rule== q->rule &&
672			    pkt->proto == q->id.proto &&
673			    pkt->src_port == q->id.src_port &&
674			    pkt->dst_port == q->id.dst_port &&
675			    (
676				(is_v6 &&
677				 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
678					&(q->id.src_ip6)) &&
679				 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
680					&(q->id.dst_ip6))) ||
681				(!is_v6 &&
682				 pkt->src_ip == q->id.src_ip &&
683				 pkt->dst_ip == q->id.dst_ip)
684			    )
685			) {
686				q->expire = time_uptime + V_dyn_short_lifetime;
687				DEB(print_dyn_rule(pkt, q->dyn_type,
688				    "lookup_dyn_parent found", "");)
689				return q;
690			}
691	}
692	return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
693}
694
695/**
696 * Install dynamic state for rule type cmd->o.opcode
697 *
698 * Returns 1 (failure) if state is not installed because of errors or because
699 * session limitations are enforced.
700 */
701int
702ipfw_install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
703    struct ip_fw_args *args, uint32_t tablearg)
704{
705	static int last_log;
706	ipfw_dyn_rule *q;
707
708	DEB(print_dyn_rule(&args->f_id, cmd->o.opcode, "install_state", "");)
709
710	IPFW_DYN_LOCK();
711
712	q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
713
714	if (q != NULL) {	/* should never occur */
715		DEB(
716		if (last_log != time_uptime) {
717			last_log = time_uptime;
718			printf("ipfw: %s: entry already present, done\n",
719			    __func__);
720		})
721		IPFW_DYN_UNLOCK();
722		return (0);
723	}
724
725	if (V_dyn_count >= V_dyn_max)
726		/* Run out of slots, try to remove any expired rule. */
727		remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
728
729	if (V_dyn_count >= V_dyn_max) {
730		if (last_log != time_uptime) {
731			last_log = time_uptime;
732			printf("ipfw: %s: Too many dynamic rules\n", __func__);
733		}
734		IPFW_DYN_UNLOCK();
735		return (1);	/* cannot install, notify caller */
736	}
737
738	switch (cmd->o.opcode) {
739	case O_KEEP_STATE:	/* bidir rule */
740		add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
741		break;
742
743	case O_LIMIT: {		/* limit number of sessions */
744		struct ipfw_flow_id id;
745		ipfw_dyn_rule *parent;
746		uint32_t conn_limit;
747		uint16_t limit_mask = cmd->limit_mask;
748
749		conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ?
750		    tablearg : cmd->conn_limit;
751
752		DEB(
753		if (cmd->conn_limit == IP_FW_TABLEARG)
754			printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
755			    "(tablearg)\n", __func__, conn_limit);
756		else
757			printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
758			    __func__, conn_limit);
759		)
760
761		id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
762		id.proto = args->f_id.proto;
763		id.addr_type = args->f_id.addr_type;
764		id.fib = M_GETFIB(args->m);
765
766		if (IS_IP6_FLOW_ID (&(args->f_id))) {
767			if (limit_mask & DYN_SRC_ADDR)
768				id.src_ip6 = args->f_id.src_ip6;
769			if (limit_mask & DYN_DST_ADDR)
770				id.dst_ip6 = args->f_id.dst_ip6;
771		} else {
772			if (limit_mask & DYN_SRC_ADDR)
773				id.src_ip = args->f_id.src_ip;
774			if (limit_mask & DYN_DST_ADDR)
775				id.dst_ip = args->f_id.dst_ip;
776		}
777		if (limit_mask & DYN_SRC_PORT)
778			id.src_port = args->f_id.src_port;
779		if (limit_mask & DYN_DST_PORT)
780			id.dst_port = args->f_id.dst_port;
781		if ((parent = lookup_dyn_parent(&id, rule)) == NULL) {
782			printf("ipfw: %s: add parent failed\n", __func__);
783			IPFW_DYN_UNLOCK();
784			return (1);
785		}
786
787		if (parent->count >= conn_limit) {
788			/* See if we can remove some expired rule. */
789			remove_dyn_rule(rule, parent);
790			if (parent->count >= conn_limit) {
791				if (V_fw_verbose && last_log != time_uptime) {
792					last_log = time_uptime;
793					char sbuf[24];
794					last_log = time_uptime;
795					snprintf(sbuf, sizeof(sbuf),
796					    "%d drop session",
797					    parent->rule->rulenum);
798					print_dyn_rule_flags(&args->f_id,
799					    cmd->o.opcode,
800					    LOG_SECURITY | LOG_DEBUG,
801					    sbuf, "too many entries");
802				}
803				IPFW_DYN_UNLOCK();
804				return (1);
805			}
806		}
807		add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
808		break;
809	}
810	default:
811		printf("ipfw: %s: unknown dynamic rule type %u\n",
812		    __func__, cmd->o.opcode);
813		IPFW_DYN_UNLOCK();
814		return (1);
815	}
816
817	/* XXX just set lifetime */
818	lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
819
820	IPFW_DYN_UNLOCK();
821	return (0);
822}
823
824/*
825 * Generate a TCP packet, containing either a RST or a keepalive.
826 * When flags & TH_RST, we are sending a RST packet, because of a
827 * "reset" action matched the packet.
828 * Otherwise we are sending a keepalive, and flags & TH_
829 * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
830 * so that MAC can label the reply appropriately.
831 */
832struct mbuf *
833ipfw_send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
834    u_int32_t ack, int flags)
835{
836	struct mbuf *m = NULL;		/* stupid compiler */
837	int len, dir;
838	struct ip *h = NULL;		/* stupid compiler */
839#ifdef INET6
840	struct ip6_hdr *h6 = NULL;
841#endif
842	struct tcphdr *th = NULL;
843
844	MGETHDR(m, M_DONTWAIT, MT_DATA);
845	if (m == NULL)
846		return (NULL);
847
848	M_SETFIB(m, id->fib);
849#ifdef MAC
850	if (replyto != NULL)
851		mac_netinet_firewall_reply(replyto, m);
852	else
853		mac_netinet_firewall_send(m);
854#else
855	(void)replyto;		/* don't warn about unused arg */
856#endif
857
858	switch (id->addr_type) {
859	case 4:
860		len = sizeof(struct ip) + sizeof(struct tcphdr);
861		break;
862#ifdef INET6
863	case 6:
864		len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
865		break;
866#endif
867	default:
868		/* XXX: log me?!? */
869		FREE_PKT(m);
870		return (NULL);
871	}
872	dir = ((flags & (TH_SYN | TH_RST)) == TH_SYN);
873
874	m->m_data += max_linkhdr;
875	m->m_flags |= M_SKIP_FIREWALL;
876	m->m_pkthdr.len = m->m_len = len;
877	m->m_pkthdr.rcvif = NULL;
878	bzero(m->m_data, len);
879
880	switch (id->addr_type) {
881	case 4:
882		h = mtod(m, struct ip *);
883
884		/* prepare for checksum */
885		h->ip_p = IPPROTO_TCP;
886		h->ip_len = htons(sizeof(struct tcphdr));
887		if (dir) {
888			h->ip_src.s_addr = htonl(id->src_ip);
889			h->ip_dst.s_addr = htonl(id->dst_ip);
890		} else {
891			h->ip_src.s_addr = htonl(id->dst_ip);
892			h->ip_dst.s_addr = htonl(id->src_ip);
893		}
894
895		th = (struct tcphdr *)(h + 1);
896		break;
897#ifdef INET6
898	case 6:
899		h6 = mtod(m, struct ip6_hdr *);
900
901		/* prepare for checksum */
902		h6->ip6_nxt = IPPROTO_TCP;
903		h6->ip6_plen = htons(sizeof(struct tcphdr));
904		if (dir) {
905			h6->ip6_src = id->src_ip6;
906			h6->ip6_dst = id->dst_ip6;
907		} else {
908			h6->ip6_src = id->dst_ip6;
909			h6->ip6_dst = id->src_ip6;
910		}
911
912		th = (struct tcphdr *)(h6 + 1);
913		break;
914#endif
915	}
916
917	if (dir) {
918		th->th_sport = htons(id->src_port);
919		th->th_dport = htons(id->dst_port);
920	} else {
921		th->th_sport = htons(id->dst_port);
922		th->th_dport = htons(id->src_port);
923	}
924	th->th_off = sizeof(struct tcphdr) >> 2;
925
926	if (flags & TH_RST) {
927		if (flags & TH_ACK) {
928			th->th_seq = htonl(ack);
929			th->th_flags = TH_RST;
930		} else {
931			if (flags & TH_SYN)
932				seq++;
933			th->th_ack = htonl(seq);
934			th->th_flags = TH_RST | TH_ACK;
935		}
936	} else {
937		/*
938		 * Keepalive - use caller provided sequence numbers
939		 */
940		th->th_seq = htonl(seq);
941		th->th_ack = htonl(ack);
942		th->th_flags = TH_ACK;
943	}
944
945	switch (id->addr_type) {
946	case 4:
947		th->th_sum = in_cksum(m, len);
948
949		/* finish the ip header */
950		h->ip_v = 4;
951		h->ip_hl = sizeof(*h) >> 2;
952		h->ip_tos = IPTOS_LOWDELAY;
953		h->ip_off = htons(0);
954		h->ip_len = htons(len);
955		h->ip_ttl = V_ip_defttl;
956		h->ip_sum = 0;
957		break;
958#ifdef INET6
959	case 6:
960		th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(*h6),
961		    sizeof(struct tcphdr));
962
963		/* finish the ip6 header */
964		h6->ip6_vfc |= IPV6_VERSION;
965		h6->ip6_hlim = IPV6_DEFHLIM;
966		break;
967#endif
968	}
969
970	return (m);
971}
972
973/*
974 * Queue keepalive packets for given dynamic rule
975 */
976static struct mbuf **
977ipfw_dyn_send_ka(struct mbuf **mtailp, ipfw_dyn_rule *q)
978{
979	struct mbuf *m_rev, *m_fwd;
980
981	m_rev = (q->state & ACK_REV) ? NULL :
982	    ipfw_send_pkt(NULL, &(q->id), q->ack_rev - 1, q->ack_fwd, TH_SYN);
983	m_fwd = (q->state & ACK_FWD) ? NULL :
984	    ipfw_send_pkt(NULL, &(q->id), q->ack_fwd - 1, q->ack_rev, 0);
985
986	if (m_rev != NULL) {
987		*mtailp = m_rev;
988		mtailp = &(*mtailp)->m_nextpkt;
989	}
990	if (m_fwd != NULL) {
991		*mtailp = m_fwd;
992		mtailp = &(*mtailp)->m_nextpkt;
993	}
994
995	return (mtailp);
996}
997
998/*
999 * This procedure is only used to handle keepalives. It is invoked
1000 * every dyn_keepalive_period
1001 */
1002static void
1003ipfw_tick(void * vnetx)
1004{
1005	struct mbuf *m0, *m, *mnext, **mtailp;
1006	struct ip *h;
1007	int i;
1008	ipfw_dyn_rule *q;
1009#ifdef VIMAGE
1010	struct vnet *vp = vnetx;
1011#endif
1012
1013	CURVNET_SET(vp);
1014	if (V_dyn_keepalive == 0 || V_ipfw_dyn_v == NULL || V_dyn_count == 0)
1015		goto done;
1016
1017	/*
1018	 * We make a chain of packets to go out here -- not deferring
1019	 * until after we drop the IPFW dynamic rule lock would result
1020	 * in a lock order reversal with the normal packet input -> ipfw
1021	 * call stack.
1022	 */
1023	m0 = NULL;
1024	mtailp = &m0;
1025	IPFW_DYN_LOCK();
1026	for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
1027		for (q = V_ipfw_dyn_v[i] ; q ; q = q->next ) {
1028			if (q->dyn_type == O_LIMIT_PARENT)
1029				continue;
1030			if (TIME_LEQ(q->expire, time_uptime))
1031				continue;	/* too late, rule expired */
1032
1033			if (q->id.proto != IPPROTO_TCP)
1034				continue;
1035			if ( (q->state & BOTH_SYN) != BOTH_SYN)
1036				continue;
1037			if (TIME_LEQ(time_uptime + V_dyn_keepalive_interval,
1038			    q->expire))
1039				continue;	/* too early */
1040
1041			mtailp = ipfw_dyn_send_ka(mtailp, q);
1042		}
1043	}
1044	IPFW_DYN_UNLOCK();
1045
1046	/* Send keepalive packets if any */
1047	for (m = m0; m != NULL; m = mnext) {
1048		mnext = m->m_nextpkt;
1049		m->m_nextpkt = NULL;
1050		h = mtod(m, struct ip *);
1051		if (h->ip_v == 4)
1052			ip_output(m, NULL, NULL, 0, NULL, NULL);
1053#ifdef INET6
1054		else
1055			ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
1056#endif
1057	}
1058done:
1059	callout_reset_on(&V_ipfw_timeout, V_dyn_keepalive_period * hz,
1060		      ipfw_tick, vnetx, 0);
1061	CURVNET_RESTORE();
1062}
1063
1064void
1065ipfw_dyn_attach(void)
1066{
1067        ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
1068            sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
1069            UMA_ALIGN_PTR, 0);
1070
1071        IPFW_DYN_LOCK_INIT();
1072}
1073
1074void
1075ipfw_dyn_detach(void)
1076{
1077        uma_zdestroy(ipfw_dyn_rule_zone);
1078        IPFW_DYN_LOCK_DESTROY();
1079}
1080
1081void
1082ipfw_dyn_init(void)
1083{
1084        V_ipfw_dyn_v = NULL;
1085        V_dyn_buckets = 256;    /* must be power of 2 */
1086        V_curr_dyn_buckets = 256; /* must be power of 2 */
1087
1088        V_dyn_ack_lifetime = 300;
1089        V_dyn_syn_lifetime = 20;
1090        V_dyn_fin_lifetime = 1;
1091        V_dyn_rst_lifetime = 1;
1092        V_dyn_udp_lifetime = 10;
1093        V_dyn_short_lifetime = 5;
1094
1095        V_dyn_keepalive_interval = 20;
1096        V_dyn_keepalive_period = 5;
1097        V_dyn_keepalive = 1;    /* do send keepalives */
1098
1099        V_dyn_max = 4096;       /* max # of dynamic rules */
1100        callout_init(&V_ipfw_timeout, CALLOUT_MPSAFE);
1101        callout_reset_on(&V_ipfw_timeout, hz, ipfw_tick, curvnet, 0);
1102}
1103
1104void
1105ipfw_dyn_uninit(int pass)
1106{
1107	if (pass == 0)
1108		callout_drain(&V_ipfw_timeout);
1109	else {
1110		if (V_ipfw_dyn_v != NULL)
1111			free(V_ipfw_dyn_v, M_IPFW);
1112	}
1113}
1114
1115int
1116ipfw_dyn_len(void)
1117{
1118	return (V_ipfw_dyn_v == NULL) ? 0 :
1119		(V_dyn_count * sizeof(ipfw_dyn_rule));
1120}
1121
1122void
1123ipfw_get_dynamic(char **pbp, const char *ep)
1124{
1125	ipfw_dyn_rule *p, *last = NULL;
1126	char *bp;
1127	int i;
1128
1129	if (V_ipfw_dyn_v == NULL)
1130		return;
1131	bp = *pbp;
1132
1133	IPFW_DYN_LOCK();
1134	for (i = 0 ; i < V_curr_dyn_buckets; i++)
1135		for (p = V_ipfw_dyn_v[i] ; p != NULL; p = p->next) {
1136			if (bp + sizeof *p <= ep) {
1137				ipfw_dyn_rule *dst =
1138					(ipfw_dyn_rule *)bp;
1139				bcopy(p, dst, sizeof *p);
1140				bcopy(&(p->rule->rulenum), &(dst->rule),
1141				    sizeof(p->rule->rulenum));
1142				/*
1143				 * store set number into high word of
1144				 * dst->rule pointer.
1145				 */
1146				bcopy(&(p->rule->set),
1147				    (char *)&dst->rule +
1148				    sizeof(p->rule->rulenum),
1149				    sizeof(p->rule->set));
1150				/*
1151				 * store a non-null value in "next".
1152				 * The userland code will interpret a
1153				 * NULL here as a marker
1154				 * for the last dynamic rule.
1155				 */
1156				bcopy(&dst, &dst->next, sizeof(dst));
1157				last = dst;
1158				dst->expire =
1159				    TIME_LEQ(dst->expire, time_uptime) ?
1160					0 : dst->expire - time_uptime ;
1161				bp += sizeof(ipfw_dyn_rule);
1162			}
1163		}
1164	IPFW_DYN_UNLOCK();
1165	if (last != NULL) /* mark last dynamic rule */
1166		bzero(&last->next, sizeof(last));
1167	*pbp = bp;
1168}
1169/* end of file */
1170