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