xref: /freebsd/sys/netpfil/ipfw/ip_fw_dynamic.c (revision b6a05070fa77edc7ce6e60b61623fd806e807be6)
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$");
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/ktr.h>
49 #include <sys/lock.h>
50 #include <sys/rmlock.h>
51 #include <sys/socket.h>
52 #include <sys/sysctl.h>
53 #include <sys/syslog.h>
54 #include <net/ethernet.h> /* for ETHERTYPE_IP */
55 #include <net/if.h>
56 #include <net/if_var.h>
57 #include <net/vnet.h>
58 
59 #include <netinet/in.h>
60 #include <netinet/ip.h>
61 #include <netinet/ip_var.h>	/* ip_defttl */
62 #include <netinet/ip_fw.h>
63 #include <netinet/tcp_var.h>
64 #include <netinet/udp.h>
65 
66 #include <netinet/ip6.h>	/* IN6_ARE_ADDR_EQUAL */
67 #ifdef INET6
68 #include <netinet6/in6_var.h>
69 #include <netinet6/ip6_var.h>
70 #endif
71 
72 #include <netpfil/ipfw/ip_fw_private.h>
73 
74 #include <machine/in_cksum.h>	/* XXX for in_cksum */
75 
76 #ifdef MAC
77 #include <security/mac/mac_framework.h>
78 #endif
79 
80 /*
81  * Description of dynamic rules.
82  *
83  * Dynamic rules are stored in lists accessed through a hash table
84  * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
85  * be modified through the sysctl variable dyn_buckets which is
86  * updated when the table becomes empty.
87  *
88  * XXX currently there is only one list, ipfw_dyn.
89  *
90  * When a packet is received, its address fields are first masked
91  * with the mask defined for the rule, then hashed, then matched
92  * against the entries in the corresponding list.
93  * Dynamic rules can be used for different purposes:
94  *  + stateful rules;
95  *  + enforcing limits on the number of sessions;
96  *  + in-kernel NAT (not implemented yet)
97  *
98  * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
99  * measured in seconds and depending on the flags.
100  *
101  * The total number of dynamic rules is equal to UMA zone items count.
102  * The max number of dynamic rules is dyn_max. When we reach
103  * the maximum number of rules we do not create anymore. This is
104  * done to avoid consuming too much memory, but also too much
105  * time when searching on each packet (ideally, we should try instead
106  * to put a limit on the length of the list on each bucket...).
107  *
108  * Each dynamic rule holds a pointer to the parent ipfw rule so
109  * we know what action to perform. Dynamic rules are removed when
110  * the parent rule is deleted. This can be changed by dyn_keep_states
111  * sysctl.
112  *
113  * There are some limitations with dynamic rules -- we do not
114  * obey the 'randomized match', and we do not do multiple
115  * passes through the firewall. XXX check the latter!!!
116  */
117 
118 struct ipfw_dyn_bucket {
119 	struct mtx	mtx;		/* Bucket protecting lock */
120 	ipfw_dyn_rule	*head;		/* Pointer to first rule */
121 };
122 
123 /*
124  * Static variables followed by global ones
125  */
126 static VNET_DEFINE(struct ipfw_dyn_bucket *, ipfw_dyn_v);
127 static VNET_DEFINE(u_int32_t, dyn_buckets_max);
128 static VNET_DEFINE(u_int32_t, curr_dyn_buckets);
129 static VNET_DEFINE(struct callout, ipfw_timeout);
130 #define	V_ipfw_dyn_v			VNET(ipfw_dyn_v)
131 #define	V_dyn_buckets_max		VNET(dyn_buckets_max)
132 #define	V_curr_dyn_buckets		VNET(curr_dyn_buckets)
133 #define V_ipfw_timeout                  VNET(ipfw_timeout)
134 
135 static VNET_DEFINE(uma_zone_t, ipfw_dyn_rule_zone);
136 #define	V_ipfw_dyn_rule_zone		VNET(ipfw_dyn_rule_zone)
137 
138 #define	IPFW_BUCK_LOCK_INIT(b)	\
139 	mtx_init(&(b)->mtx, "IPFW dynamic bucket", NULL, MTX_DEF)
140 #define	IPFW_BUCK_LOCK_DESTROY(b)	\
141 	mtx_destroy(&(b)->mtx)
142 #define	IPFW_BUCK_LOCK(i)	mtx_lock(&V_ipfw_dyn_v[(i)].mtx)
143 #define	IPFW_BUCK_UNLOCK(i)	mtx_unlock(&V_ipfw_dyn_v[(i)].mtx)
144 #define	IPFW_BUCK_ASSERT(i)	mtx_assert(&V_ipfw_dyn_v[(i)].mtx, MA_OWNED)
145 
146 
147 static VNET_DEFINE(int, dyn_keep_states);
148 #define	V_dyn_keep_states		VNET(dyn_keep_states)
149 
150 /*
151  * Timeouts for various events in handing dynamic rules.
152  */
153 static VNET_DEFINE(u_int32_t, dyn_ack_lifetime);
154 static VNET_DEFINE(u_int32_t, dyn_syn_lifetime);
155 static VNET_DEFINE(u_int32_t, dyn_fin_lifetime);
156 static VNET_DEFINE(u_int32_t, dyn_rst_lifetime);
157 static VNET_DEFINE(u_int32_t, dyn_udp_lifetime);
158 static VNET_DEFINE(u_int32_t, dyn_short_lifetime);
159 
160 #define	V_dyn_ack_lifetime		VNET(dyn_ack_lifetime)
161 #define	V_dyn_syn_lifetime		VNET(dyn_syn_lifetime)
162 #define	V_dyn_fin_lifetime		VNET(dyn_fin_lifetime)
163 #define	V_dyn_rst_lifetime		VNET(dyn_rst_lifetime)
164 #define	V_dyn_udp_lifetime		VNET(dyn_udp_lifetime)
165 #define	V_dyn_short_lifetime		VNET(dyn_short_lifetime)
166 
167 /*
168  * Keepalives are sent if dyn_keepalive is set. They are sent every
169  * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
170  * seconds of lifetime of a rule.
171  * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
172  * than dyn_keepalive_period.
173  */
174 
175 static VNET_DEFINE(u_int32_t, dyn_keepalive_interval);
176 static VNET_DEFINE(u_int32_t, dyn_keepalive_period);
177 static VNET_DEFINE(u_int32_t, dyn_keepalive);
178 static VNET_DEFINE(time_t, dyn_keepalive_last);
179 
180 #define	V_dyn_keepalive_interval	VNET(dyn_keepalive_interval)
181 #define	V_dyn_keepalive_period		VNET(dyn_keepalive_period)
182 #define	V_dyn_keepalive			VNET(dyn_keepalive)
183 #define	V_dyn_keepalive_last		VNET(dyn_keepalive_last)
184 
185 static VNET_DEFINE(u_int32_t, dyn_max);		/* max # of dynamic rules */
186 
187 #define	DYN_COUNT			uma_zone_get_cur(V_ipfw_dyn_rule_zone)
188 #define	V_dyn_max			VNET(dyn_max)
189 
190 /* for userspace, we emulate the uma_zone_counter with ipfw_dyn_count */
191 static int ipfw_dyn_count;	/* number of objects */
192 
193 #ifdef USERSPACE /* emulation of UMA object counters for userspace */
194 #define uma_zone_get_cur(x)	ipfw_dyn_count
195 #endif /* USERSPACE */
196 
197 static int last_log;	/* Log ratelimiting */
198 
199 static void ipfw_dyn_tick(void *vnetx);
200 static void check_dyn_rules(struct ip_fw_chain *, ipfw_range_tlv *, int, int);
201 #ifdef SYSCTL_NODE
202 
203 static int sysctl_ipfw_dyn_count(SYSCTL_HANDLER_ARGS);
204 static int sysctl_ipfw_dyn_max(SYSCTL_HANDLER_ARGS);
205 
206 SYSBEGIN(f2)
207 
208 SYSCTL_DECL(_net_inet_ip_fw);
209 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, dyn_buckets,
210     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_buckets_max), 0,
211     "Max number of dyn. buckets");
212 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets,
213     CTLFLAG_VNET | CTLFLAG_RD, &VNET_NAME(curr_dyn_buckets), 0,
214     "Current Number of dyn. buckets");
215 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_count,
216     CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RD, 0, 0, sysctl_ipfw_dyn_count, "IU",
217     "Number of dyn. rules");
218 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_max,
219     CTLFLAG_VNET | CTLTYPE_UINT | CTLFLAG_RW, 0, 0, sysctl_ipfw_dyn_max, "IU",
220     "Max number of dyn. rules");
221 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime,
222     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_ack_lifetime), 0,
223     "Lifetime of dyn. rules for acks");
224 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime,
225     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_syn_lifetime), 0,
226     "Lifetime of dyn. rules for syn");
227 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
228     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_fin_lifetime), 0,
229     "Lifetime of dyn. rules for fin");
230 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
231     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_rst_lifetime), 0,
232     "Lifetime of dyn. rules for rst");
233 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime,
234     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_udp_lifetime), 0,
235     "Lifetime of dyn. rules for UDP");
236 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime,
237     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_short_lifetime), 0,
238     "Lifetime of dyn. rules for other situations");
239 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive,
240     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_keepalive), 0,
241     "Enable keepalives for dyn. rules");
242 SYSCTL_UINT(_net_inet_ip_fw, OID_AUTO, dyn_keep_states,
243     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_keep_states), 0,
244     "Do not flush dynamic states on rule deletion");
245 
246 SYSEND
247 
248 #endif /* SYSCTL_NODE */
249 
250 
251 #ifdef INET6
252 static __inline int
253 hash_packet6(struct ipfw_flow_id *id)
254 {
255 	u_int32_t i;
256 	i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
257 	    (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
258 	    (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
259 	    (id->src_ip6.__u6_addr.__u6_addr32[3]) ^
260 	    (id->dst_port) ^ (id->src_port);
261 	return i;
262 }
263 #endif
264 
265 /*
266  * IMPORTANT: the hash function for dynamic rules must be commutative
267  * in source and destination (ip,port), because rules are bidirectional
268  * and we want to find both in the same bucket.
269  */
270 static __inline int
271 hash_packet(struct ipfw_flow_id *id, int buckets)
272 {
273 	u_int32_t i;
274 
275 #ifdef INET6
276 	if (IS_IP6_FLOW_ID(id))
277 		i = hash_packet6(id);
278 	else
279 #endif /* INET6 */
280 	i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
281 	i &= (buckets - 1);
282 	return i;
283 }
284 
285 /**
286  * Print customizable flow id description via log(9) facility.
287  */
288 static void
289 print_dyn_rule_flags(struct ipfw_flow_id *id, int dyn_type, int log_flags,
290     char *prefix, char *postfix)
291 {
292 	struct in_addr da;
293 #ifdef INET6
294 	char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN];
295 #else
296 	char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
297 #endif
298 
299 #ifdef INET6
300 	if (IS_IP6_FLOW_ID(id)) {
301 		ip6_sprintf(src, &id->src_ip6);
302 		ip6_sprintf(dst, &id->dst_ip6);
303 	} else
304 #endif
305 	{
306 		da.s_addr = htonl(id->src_ip);
307 		inet_ntop(AF_INET, &da, src, sizeof(src));
308 		da.s_addr = htonl(id->dst_ip);
309 		inet_ntop(AF_INET, &da, dst, sizeof(dst));
310 	}
311 	log(log_flags, "ipfw: %s type %d %s %d -> %s %d, %d %s\n",
312 	    prefix, dyn_type, src, id->src_port, dst,
313 	    id->dst_port, DYN_COUNT, postfix);
314 }
315 
316 #define	print_dyn_rule(id, dtype, prefix, postfix)	\
317 	print_dyn_rule_flags(id, dtype, LOG_DEBUG, prefix, postfix)
318 
319 #define TIME_LEQ(a,b)       ((int)((a)-(b)) <= 0)
320 #define TIME_LE(a,b)       ((int)((a)-(b)) < 0)
321 
322 /*
323  * Lookup a dynamic rule, locked version.
324  */
325 static ipfw_dyn_rule *
326 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int i, int *match_direction,
327     struct tcphdr *tcp)
328 {
329 	/*
330 	 * Stateful ipfw extensions.
331 	 * Lookup into dynamic session queue.
332 	 */
333 #define MATCH_REVERSE	0
334 #define MATCH_FORWARD	1
335 #define MATCH_NONE	2
336 #define MATCH_UNKNOWN	3
337 	int dir = MATCH_NONE;
338 	ipfw_dyn_rule *prev, *q = NULL;
339 
340 	IPFW_BUCK_ASSERT(i);
341 
342 	for (prev = NULL, q = V_ipfw_dyn_v[i].head; q; prev = q, q = q->next) {
343 		if (q->dyn_type == O_LIMIT_PARENT && q->count)
344 			continue;
345 
346 		if (pkt->proto != q->id.proto || q->dyn_type == O_LIMIT_PARENT)
347 			continue;
348 
349 		if (IS_IP6_FLOW_ID(pkt)) {
350 			if (IN6_ARE_ADDR_EQUAL(&pkt->src_ip6, &q->id.src_ip6) &&
351 			    IN6_ARE_ADDR_EQUAL(&pkt->dst_ip6, &q->id.dst_ip6) &&
352 			    pkt->src_port == q->id.src_port &&
353 			    pkt->dst_port == q->id.dst_port) {
354 				dir = MATCH_FORWARD;
355 				break;
356 			}
357 			if (IN6_ARE_ADDR_EQUAL(&pkt->src_ip6, &q->id.dst_ip6) &&
358 			    IN6_ARE_ADDR_EQUAL(&pkt->dst_ip6, &q->id.src_ip6) &&
359 			    pkt->src_port == q->id.dst_port &&
360 			    pkt->dst_port == q->id.src_port) {
361 				dir = MATCH_REVERSE;
362 				break;
363 			}
364 		} else {
365 			if (pkt->src_ip == q->id.src_ip &&
366 			    pkt->dst_ip == q->id.dst_ip &&
367 			    pkt->src_port == q->id.src_port &&
368 			    pkt->dst_port == q->id.dst_port) {
369 				dir = MATCH_FORWARD;
370 				break;
371 			}
372 			if (pkt->src_ip == q->id.dst_ip &&
373 			    pkt->dst_ip == q->id.src_ip &&
374 			    pkt->src_port == q->id.dst_port &&
375 			    pkt->dst_port == q->id.src_port) {
376 				dir = MATCH_REVERSE;
377 				break;
378 			}
379 		}
380 	}
381 	if (q == NULL)
382 		goto done;	/* q = NULL, not found */
383 
384 	if (prev != NULL) {	/* found and not in front */
385 		prev->next = q->next;
386 		q->next = V_ipfw_dyn_v[i].head;
387 		V_ipfw_dyn_v[i].head = q;
388 	}
389 	if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
390 		uint32_t ack;
391 		u_char flags = pkt->_flags & (TH_FIN | TH_SYN | TH_RST);
392 
393 #define BOTH_SYN	(TH_SYN | (TH_SYN << 8))
394 #define BOTH_FIN	(TH_FIN | (TH_FIN << 8))
395 #define	TCP_FLAGS	(TH_FLAGS | (TH_FLAGS << 8))
396 #define	ACK_FWD		0x10000			/* fwd ack seen */
397 #define	ACK_REV		0x20000			/* rev ack seen */
398 
399 		q->state |= (dir == MATCH_FORWARD) ? flags : (flags << 8);
400 		switch (q->state & TCP_FLAGS) {
401 		case TH_SYN:			/* opening */
402 			q->expire = time_uptime + V_dyn_syn_lifetime;
403 			break;
404 
405 		case BOTH_SYN:			/* move to established */
406 		case BOTH_SYN | TH_FIN:		/* one side tries to close */
407 		case BOTH_SYN | (TH_FIN << 8):
408 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
409 			if (tcp == NULL)
410 				break;
411 
412 			ack = ntohl(tcp->th_ack);
413 			if (dir == MATCH_FORWARD) {
414 				if (q->ack_fwd == 0 ||
415 				    _SEQ_GE(ack, q->ack_fwd)) {
416 					q->ack_fwd = ack;
417 					q->state |= ACK_FWD;
418 				}
419 			} else {
420 				if (q->ack_rev == 0 ||
421 				    _SEQ_GE(ack, q->ack_rev)) {
422 					q->ack_rev = ack;
423 					q->state |= ACK_REV;
424 				}
425 			}
426 			if ((q->state & (ACK_FWD | ACK_REV)) ==
427 			    (ACK_FWD | ACK_REV)) {
428 				q->expire = time_uptime + V_dyn_ack_lifetime;
429 				q->state &= ~(ACK_FWD | ACK_REV);
430 			}
431 			break;
432 
433 		case BOTH_SYN | BOTH_FIN:	/* both sides closed */
434 			if (V_dyn_fin_lifetime >= V_dyn_keepalive_period)
435 				V_dyn_fin_lifetime = V_dyn_keepalive_period - 1;
436 			q->expire = time_uptime + V_dyn_fin_lifetime;
437 			break;
438 
439 		default:
440 #if 0
441 			/*
442 			 * reset or some invalid combination, but can also
443 			 * occur if we use keep-state the wrong way.
444 			 */
445 			if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
446 				printf("invalid state: 0x%x\n", q->state);
447 #endif
448 			if (V_dyn_rst_lifetime >= V_dyn_keepalive_period)
449 				V_dyn_rst_lifetime = V_dyn_keepalive_period - 1;
450 			q->expire = time_uptime + V_dyn_rst_lifetime;
451 			break;
452 		}
453 	} else if (pkt->proto == IPPROTO_UDP) {
454 		q->expire = time_uptime + V_dyn_udp_lifetime;
455 	} else {
456 		/* other protocols */
457 		q->expire = time_uptime + V_dyn_short_lifetime;
458 	}
459 done:
460 	if (match_direction != NULL)
461 		*match_direction = dir;
462 	return (q);
463 }
464 
465 ipfw_dyn_rule *
466 ipfw_lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
467     struct tcphdr *tcp)
468 {
469 	ipfw_dyn_rule *q;
470 	int i;
471 
472 	i = hash_packet(pkt, V_curr_dyn_buckets);
473 
474 	IPFW_BUCK_LOCK(i);
475 	q = lookup_dyn_rule_locked(pkt, i, match_direction, tcp);
476 	if (q == NULL)
477 		IPFW_BUCK_UNLOCK(i);
478 	/* NB: return table locked when q is not NULL */
479 	return q;
480 }
481 
482 /*
483  * Unlock bucket mtx
484  * @p - pointer to dynamic rule
485  */
486 void
487 ipfw_dyn_unlock(ipfw_dyn_rule *q)
488 {
489 
490 	IPFW_BUCK_UNLOCK(q->bucket);
491 }
492 
493 static int
494 resize_dynamic_table(struct ip_fw_chain *chain, int nbuckets)
495 {
496 	int i, k, nbuckets_old;
497 	ipfw_dyn_rule *q;
498 	struct ipfw_dyn_bucket *dyn_v, *dyn_v_old;
499 
500 	/* Check if given number is power of 2 and less than 64k */
501 	if ((nbuckets > 65536) || (!powerof2(nbuckets)))
502 		return 1;
503 
504 	CTR3(KTR_NET, "%s: resize dynamic hash: %d -> %d", __func__,
505 	    V_curr_dyn_buckets, nbuckets);
506 
507 	/* Allocate and initialize new hash */
508 	dyn_v = malloc(nbuckets * sizeof(ipfw_dyn_rule), M_IPFW,
509 	    M_WAITOK | M_ZERO);
510 
511 	for (i = 0 ; i < nbuckets; i++)
512 		IPFW_BUCK_LOCK_INIT(&dyn_v[i]);
513 
514 	/*
515 	 * Call upper half lock, as get_map() do to ease
516 	 * read-only access to dynamic rules hash from sysctl
517 	 */
518 	IPFW_UH_WLOCK(chain);
519 
520 	/*
521 	 * Acquire chain write lock to permit hash access
522 	 * for main traffic path without additional locks
523 	 */
524 	IPFW_WLOCK(chain);
525 
526 	/* Save old values */
527 	nbuckets_old = V_curr_dyn_buckets;
528 	dyn_v_old = V_ipfw_dyn_v;
529 
530 	/* Skip relinking if array is not set up */
531 	if (V_ipfw_dyn_v == NULL)
532 		V_curr_dyn_buckets = 0;
533 
534 	/* Re-link all dynamic states */
535 	for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
536 		while (V_ipfw_dyn_v[i].head != NULL) {
537 			/* Remove from current chain */
538 			q = V_ipfw_dyn_v[i].head;
539 			V_ipfw_dyn_v[i].head = q->next;
540 
541 			/* Get new hash value */
542 			k = hash_packet(&q->id, nbuckets);
543 			q->bucket = k;
544 			/* Add to the new head */
545 			q->next = dyn_v[k].head;
546 			dyn_v[k].head = q;
547              }
548 	}
549 
550 	/* Update current pointers/buckets values */
551 	V_curr_dyn_buckets = nbuckets;
552 	V_ipfw_dyn_v = dyn_v;
553 
554 	IPFW_WUNLOCK(chain);
555 
556 	IPFW_UH_WUNLOCK(chain);
557 
558 	/* Start periodic callout on initial creation */
559 	if (dyn_v_old == NULL) {
560         	callout_reset_on(&V_ipfw_timeout, hz, ipfw_dyn_tick, curvnet, 0);
561 		return (0);
562 	}
563 
564 	/* Destroy all mutexes */
565 	for (i = 0 ; i < nbuckets_old ; i++)
566 		IPFW_BUCK_LOCK_DESTROY(&dyn_v_old[i]);
567 
568 	/* Free old hash */
569 	free(dyn_v_old, M_IPFW);
570 
571 	return 0;
572 }
573 
574 /**
575  * Install state of type 'type' for a dynamic session.
576  * The hash table contains two type of rules:
577  * - regular rules (O_KEEP_STATE)
578  * - rules for sessions with limited number of sess per user
579  *   (O_LIMIT). When they are created, the parent is
580  *   increased by 1, and decreased on delete. In this case,
581  *   the third parameter is the parent rule and not the chain.
582  * - "parent" rules for the above (O_LIMIT_PARENT).
583  */
584 static ipfw_dyn_rule *
585 add_dyn_rule(struct ipfw_flow_id *id, int i, u_int8_t dyn_type, struct ip_fw *rule)
586 {
587 	ipfw_dyn_rule *r;
588 
589 	IPFW_BUCK_ASSERT(i);
590 
591 	r = uma_zalloc(V_ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
592 	if (r == NULL) {
593 		if (last_log != time_uptime) {
594 			last_log = time_uptime;
595 			log(LOG_DEBUG,
596 			    "ipfw: Cannot allocate dynamic state, "
597 			    "consider increasing net.inet.ip.fw.dyn_max\n");
598 		}
599 		return NULL;
600 	}
601 	ipfw_dyn_count++;
602 
603 	/*
604 	 * refcount on parent is already incremented, so
605 	 * it is safe to use parent unlocked.
606 	 */
607 	if (dyn_type == O_LIMIT) {
608 		ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
609 		if ( parent->dyn_type != O_LIMIT_PARENT)
610 			panic("invalid parent");
611 		r->parent = parent;
612 		rule = parent->rule;
613 	}
614 
615 	r->id = *id;
616 	r->expire = time_uptime + V_dyn_syn_lifetime;
617 	r->rule = rule;
618 	r->dyn_type = dyn_type;
619 	IPFW_ZERO_DYN_COUNTER(r);
620 	r->count = 0;
621 
622 	r->bucket = i;
623 	r->next = V_ipfw_dyn_v[i].head;
624 	V_ipfw_dyn_v[i].head = r;
625 	DEB(print_dyn_rule(id, dyn_type, "add dyn entry", "total");)
626 	return r;
627 }
628 
629 /**
630  * lookup dynamic parent rule using pkt and rule as search keys.
631  * If the lookup fails, then install one.
632  */
633 static ipfw_dyn_rule *
634 lookup_dyn_parent(struct ipfw_flow_id *pkt, int *pindex, struct ip_fw *rule)
635 {
636 	ipfw_dyn_rule *q;
637 	int i, is_v6;
638 
639 	is_v6 = IS_IP6_FLOW_ID(pkt);
640 	i = hash_packet( pkt, V_curr_dyn_buckets );
641 	*pindex = i;
642 	IPFW_BUCK_LOCK(i);
643 	for (q = V_ipfw_dyn_v[i].head ; q != NULL ; q=q->next)
644 		if (q->dyn_type == O_LIMIT_PARENT &&
645 		    rule== q->rule &&
646 		    pkt->proto == q->id.proto &&
647 		    pkt->src_port == q->id.src_port &&
648 		    pkt->dst_port == q->id.dst_port &&
649 		    (
650 			(is_v6 &&
651 			 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
652 				&(q->id.src_ip6)) &&
653 			 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
654 				&(q->id.dst_ip6))) ||
655 			(!is_v6 &&
656 			 pkt->src_ip == q->id.src_ip &&
657 			 pkt->dst_ip == q->id.dst_ip)
658 		    )
659 		) {
660 			q->expire = time_uptime + V_dyn_short_lifetime;
661 			DEB(print_dyn_rule(pkt, q->dyn_type,
662 			    "lookup_dyn_parent found", "");)
663 			return q;
664 		}
665 
666 	/* Add virtual limiting rule */
667 	return add_dyn_rule(pkt, i, O_LIMIT_PARENT, rule);
668 }
669 
670 /**
671  * Install dynamic state for rule type cmd->o.opcode
672  *
673  * Returns 1 (failure) if state is not installed because of errors or because
674  * session limitations are enforced.
675  */
676 int
677 ipfw_install_state(struct ip_fw_chain *chain, struct ip_fw *rule,
678     ipfw_insn_limit *cmd, struct ip_fw_args *args, uint32_t tablearg)
679 {
680 	ipfw_dyn_rule *q;
681 	int i;
682 
683 	DEB(print_dyn_rule(&args->f_id, cmd->o.opcode, "install_state", "");)
684 
685 	i = hash_packet(&args->f_id, V_curr_dyn_buckets);
686 
687 	IPFW_BUCK_LOCK(i);
688 
689 	q = lookup_dyn_rule_locked(&args->f_id, i, NULL, NULL);
690 
691 	if (q != NULL) {	/* should never occur */
692 		DEB(
693 		if (last_log != time_uptime) {
694 			last_log = time_uptime;
695 			printf("ipfw: %s: entry already present, done\n",
696 			    __func__);
697 		})
698 		IPFW_BUCK_UNLOCK(i);
699 		return (0);
700 	}
701 
702 	/*
703 	 * State limiting is done via uma(9) zone limiting.
704 	 * Save pointer to newly-installed rule and reject
705 	 * packet if add_dyn_rule() returned NULL.
706 	 * Note q is currently set to NULL.
707 	 */
708 
709 	switch (cmd->o.opcode) {
710 	case O_KEEP_STATE:	/* bidir rule */
711 		q = add_dyn_rule(&args->f_id, i, O_KEEP_STATE, rule);
712 		break;
713 
714 	case O_LIMIT: {		/* limit number of sessions */
715 		struct ipfw_flow_id id;
716 		ipfw_dyn_rule *parent;
717 		uint32_t conn_limit;
718 		uint16_t limit_mask = cmd->limit_mask;
719 		int pindex;
720 
721 		conn_limit = IP_FW_ARG_TABLEARG(chain, cmd->conn_limit, limit);
722 
723 		DEB(
724 		if (cmd->conn_limit == IP_FW_TARG)
725 			printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
726 			    "(tablearg)\n", __func__, conn_limit);
727 		else
728 			printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
729 			    __func__, conn_limit);
730 		)
731 
732 		id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
733 		id.proto = args->f_id.proto;
734 		id.addr_type = args->f_id.addr_type;
735 		id.fib = M_GETFIB(args->m);
736 
737 		if (IS_IP6_FLOW_ID (&(args->f_id))) {
738 			bzero(&id.src_ip6, sizeof(id.src_ip6));
739 			bzero(&id.dst_ip6, sizeof(id.dst_ip6));
740 
741 			if (limit_mask & DYN_SRC_ADDR)
742 				id.src_ip6 = args->f_id.src_ip6;
743 			if (limit_mask & DYN_DST_ADDR)
744 				id.dst_ip6 = args->f_id.dst_ip6;
745 		} else {
746 			if (limit_mask & DYN_SRC_ADDR)
747 				id.src_ip = args->f_id.src_ip;
748 			if (limit_mask & DYN_DST_ADDR)
749 				id.dst_ip = args->f_id.dst_ip;
750 		}
751 		if (limit_mask & DYN_SRC_PORT)
752 			id.src_port = args->f_id.src_port;
753 		if (limit_mask & DYN_DST_PORT)
754 			id.dst_port = args->f_id.dst_port;
755 
756 		/*
757 		 * We have to release lock for previous bucket to
758 		 * avoid possible deadlock
759 		 */
760 		IPFW_BUCK_UNLOCK(i);
761 
762 		if ((parent = lookup_dyn_parent(&id, &pindex, rule)) == NULL) {
763 			printf("ipfw: %s: add parent failed\n", __func__);
764 			IPFW_BUCK_UNLOCK(pindex);
765 			return (1);
766 		}
767 
768 		if (parent->count >= conn_limit) {
769 			if (V_fw_verbose && last_log != time_uptime) {
770 				last_log = time_uptime;
771 				char sbuf[24];
772 				last_log = time_uptime;
773 				snprintf(sbuf, sizeof(sbuf),
774 				    "%d drop session",
775 				    parent->rule->rulenum);
776 				print_dyn_rule_flags(&args->f_id,
777 				    cmd->o.opcode,
778 				    LOG_SECURITY | LOG_DEBUG,
779 				    sbuf, "too many entries");
780 			}
781 			IPFW_BUCK_UNLOCK(pindex);
782 			return (1);
783 		}
784 		/* Increment counter on parent */
785 		parent->count++;
786 		IPFW_BUCK_UNLOCK(pindex);
787 
788 		IPFW_BUCK_LOCK(i);
789 		q = add_dyn_rule(&args->f_id, i, O_LIMIT, (struct ip_fw *)parent);
790 		if (q == NULL) {
791 			/* Decrement index and notify caller */
792 			IPFW_BUCK_UNLOCK(i);
793 			IPFW_BUCK_LOCK(pindex);
794 			parent->count--;
795 			IPFW_BUCK_UNLOCK(pindex);
796 			return (1);
797 		}
798 		break;
799 	}
800 	default:
801 		printf("ipfw: %s: unknown dynamic rule type %u\n",
802 		    __func__, cmd->o.opcode);
803 	}
804 
805 	if (q == NULL) {
806 		IPFW_BUCK_UNLOCK(i);
807 		return (1);	/* Notify caller about failure */
808 	}
809 
810 	/* XXX just set lifetime */
811 	lookup_dyn_rule_locked(&args->f_id, i, NULL, NULL);
812 
813 	IPFW_BUCK_UNLOCK(i);
814 	return (0);
815 }
816 
817 /*
818  * Generate a TCP packet, containing either a RST or a keepalive.
819  * When flags & TH_RST, we are sending a RST packet, because of a
820  * "reset" action matched the packet.
821  * Otherwise we are sending a keepalive, and flags & TH_
822  * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
823  * so that MAC can label the reply appropriately.
824  */
825 struct mbuf *
826 ipfw_send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
827     u_int32_t ack, int flags)
828 {
829 	struct mbuf *m = NULL;		/* stupid compiler */
830 	int len, dir;
831 	struct ip *h = NULL;		/* stupid compiler */
832 #ifdef INET6
833 	struct ip6_hdr *h6 = NULL;
834 #endif
835 	struct tcphdr *th = NULL;
836 
837 	MGETHDR(m, M_NOWAIT, MT_DATA);
838 	if (m == NULL)
839 		return (NULL);
840 
841 	M_SETFIB(m, id->fib);
842 #ifdef MAC
843 	if (replyto != NULL)
844 		mac_netinet_firewall_reply(replyto, m);
845 	else
846 		mac_netinet_firewall_send(m);
847 #else
848 	(void)replyto;		/* don't warn about unused arg */
849 #endif
850 
851 	switch (id->addr_type) {
852 	case 4:
853 		len = sizeof(struct ip) + sizeof(struct tcphdr);
854 		break;
855 #ifdef INET6
856 	case 6:
857 		len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
858 		break;
859 #endif
860 	default:
861 		/* XXX: log me?!? */
862 		FREE_PKT(m);
863 		return (NULL);
864 	}
865 	dir = ((flags & (TH_SYN | TH_RST)) == TH_SYN);
866 
867 	m->m_data += max_linkhdr;
868 	m->m_flags |= M_SKIP_FIREWALL;
869 	m->m_pkthdr.len = m->m_len = len;
870 	m->m_pkthdr.rcvif = NULL;
871 	bzero(m->m_data, len);
872 
873 	switch (id->addr_type) {
874 	case 4:
875 		h = mtod(m, struct ip *);
876 
877 		/* prepare for checksum */
878 		h->ip_p = IPPROTO_TCP;
879 		h->ip_len = htons(sizeof(struct tcphdr));
880 		if (dir) {
881 			h->ip_src.s_addr = htonl(id->src_ip);
882 			h->ip_dst.s_addr = htonl(id->dst_ip);
883 		} else {
884 			h->ip_src.s_addr = htonl(id->dst_ip);
885 			h->ip_dst.s_addr = htonl(id->src_ip);
886 		}
887 
888 		th = (struct tcphdr *)(h + 1);
889 		break;
890 #ifdef INET6
891 	case 6:
892 		h6 = mtod(m, struct ip6_hdr *);
893 
894 		/* prepare for checksum */
895 		h6->ip6_nxt = IPPROTO_TCP;
896 		h6->ip6_plen = htons(sizeof(struct tcphdr));
897 		if (dir) {
898 			h6->ip6_src = id->src_ip6;
899 			h6->ip6_dst = id->dst_ip6;
900 		} else {
901 			h6->ip6_src = id->dst_ip6;
902 			h6->ip6_dst = id->src_ip6;
903 		}
904 
905 		th = (struct tcphdr *)(h6 + 1);
906 		break;
907 #endif
908 	}
909 
910 	if (dir) {
911 		th->th_sport = htons(id->src_port);
912 		th->th_dport = htons(id->dst_port);
913 	} else {
914 		th->th_sport = htons(id->dst_port);
915 		th->th_dport = htons(id->src_port);
916 	}
917 	th->th_off = sizeof(struct tcphdr) >> 2;
918 
919 	if (flags & TH_RST) {
920 		if (flags & TH_ACK) {
921 			th->th_seq = htonl(ack);
922 			th->th_flags = TH_RST;
923 		} else {
924 			if (flags & TH_SYN)
925 				seq++;
926 			th->th_ack = htonl(seq);
927 			th->th_flags = TH_RST | TH_ACK;
928 		}
929 	} else {
930 		/*
931 		 * Keepalive - use caller provided sequence numbers
932 		 */
933 		th->th_seq = htonl(seq);
934 		th->th_ack = htonl(ack);
935 		th->th_flags = TH_ACK;
936 	}
937 
938 	switch (id->addr_type) {
939 	case 4:
940 		th->th_sum = in_cksum(m, len);
941 
942 		/* finish the ip header */
943 		h->ip_v = 4;
944 		h->ip_hl = sizeof(*h) >> 2;
945 		h->ip_tos = IPTOS_LOWDELAY;
946 		h->ip_off = htons(0);
947 		h->ip_len = htons(len);
948 		h->ip_ttl = V_ip_defttl;
949 		h->ip_sum = 0;
950 		break;
951 #ifdef INET6
952 	case 6:
953 		th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(*h6),
954 		    sizeof(struct tcphdr));
955 
956 		/* finish the ip6 header */
957 		h6->ip6_vfc |= IPV6_VERSION;
958 		h6->ip6_hlim = IPV6_DEFHLIM;
959 		break;
960 #endif
961 	}
962 
963 	return (m);
964 }
965 
966 /*
967  * Queue keepalive packets for given dynamic rule
968  */
969 static struct mbuf **
970 ipfw_dyn_send_ka(struct mbuf **mtailp, ipfw_dyn_rule *q)
971 {
972 	struct mbuf *m_rev, *m_fwd;
973 
974 	m_rev = (q->state & ACK_REV) ? NULL :
975 	    ipfw_send_pkt(NULL, &(q->id), q->ack_rev - 1, q->ack_fwd, TH_SYN);
976 	m_fwd = (q->state & ACK_FWD) ? NULL :
977 	    ipfw_send_pkt(NULL, &(q->id), q->ack_fwd - 1, q->ack_rev, 0);
978 
979 	if (m_rev != NULL) {
980 		*mtailp = m_rev;
981 		mtailp = &(*mtailp)->m_nextpkt;
982 	}
983 	if (m_fwd != NULL) {
984 		*mtailp = m_fwd;
985 		mtailp = &(*mtailp)->m_nextpkt;
986 	}
987 
988 	return (mtailp);
989 }
990 
991 /*
992  * This procedure is used to perform various maintance
993  * on dynamic hash list. Currently it is called every second.
994  */
995 static void
996 ipfw_dyn_tick(void * vnetx)
997 {
998 	struct ip_fw_chain *chain;
999 	int check_ka = 0;
1000 #ifdef VIMAGE
1001 	struct vnet *vp = vnetx;
1002 #endif
1003 
1004 	CURVNET_SET(vp);
1005 
1006 	chain = &V_layer3_chain;
1007 
1008 	/* Run keepalive checks every keepalive_period iff ka is enabled */
1009 	if ((V_dyn_keepalive_last + V_dyn_keepalive_period <= time_uptime) &&
1010 	    (V_dyn_keepalive != 0)) {
1011 		V_dyn_keepalive_last = time_uptime;
1012 		check_ka = 1;
1013 	}
1014 
1015 	check_dyn_rules(chain, NULL, check_ka, 1);
1016 
1017 	callout_reset_on(&V_ipfw_timeout, hz, ipfw_dyn_tick, vnetx, 0);
1018 
1019 	CURVNET_RESTORE();
1020 }
1021 
1022 
1023 /*
1024  * Walk thru all dynamic states doing generic maintance:
1025  * 1) free expired states
1026  * 2) free all states based on deleted rule / set
1027  * 3) send keepalives for states if needed
1028  *
1029  * @chain - pointer to current ipfw rules chain
1030  * @rule - delete all states originated by given rule if != NULL
1031  * @set - delete all states originated by any rule in set @set if != RESVD_SET
1032  * @check_ka - perform checking/sending keepalives
1033  * @timer - indicate call from timer routine.
1034  *
1035  * Timer routine must call this function unlocked to permit
1036  * sending keepalives/resizing table.
1037  *
1038  * Others has to call function with IPFW_UH_WLOCK held.
1039  * Additionally, function assume that dynamic rule/set is
1040  * ALREADY deleted so no new states can be generated by
1041  * 'deleted' rules.
1042  *
1043  * Write lock is needed to ensure that unused parent rules
1044  * are not freed by other instance (see stage 2, 3)
1045  */
1046 static void
1047 check_dyn_rules(struct ip_fw_chain *chain, ipfw_range_tlv *rt,
1048     int check_ka, int timer)
1049 {
1050 	struct mbuf *m0, *m, *mnext, **mtailp;
1051 	struct ip *h;
1052 	int i, dyn_count, new_buckets = 0, max_buckets;
1053 	int expired = 0, expired_limits = 0, parents = 0, total = 0;
1054 	ipfw_dyn_rule *q, *q_prev, *q_next;
1055 	ipfw_dyn_rule *exp_head, **exptailp;
1056 	ipfw_dyn_rule *exp_lhead, **expltailp;
1057 
1058 	KASSERT(V_ipfw_dyn_v != NULL, ("%s: dynamic table not allocated",
1059 	    __func__));
1060 
1061 	/* Avoid possible LOR */
1062 	KASSERT(!check_ka || timer, ("%s: keepalive check with lock held",
1063 	    __func__));
1064 
1065 	/*
1066 	 * Do not perform any checks if we currently have no dynamic states
1067 	 */
1068 	if (DYN_COUNT == 0)
1069 		return;
1070 
1071 	/* Expired states */
1072 	exp_head = NULL;
1073 	exptailp = &exp_head;
1074 
1075 	/* Expired limit states */
1076 	exp_lhead = NULL;
1077 	expltailp = &exp_lhead;
1078 
1079 	/*
1080 	 * We make a chain of packets to go out here -- not deferring
1081 	 * until after we drop the IPFW dynamic rule lock would result
1082 	 * in a lock order reversal with the normal packet input -> ipfw
1083 	 * call stack.
1084 	 */
1085 	m0 = NULL;
1086 	mtailp = &m0;
1087 
1088 	/* Protect from hash resizing */
1089 	if (timer != 0)
1090 		IPFW_UH_WLOCK(chain);
1091 	else
1092 		IPFW_UH_WLOCK_ASSERT(chain);
1093 
1094 #define	NEXT_RULE()	{ q_prev = q; q = q->next ; continue; }
1095 
1096 	/* Stage 1: perform requested deletion */
1097 	for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
1098 		IPFW_BUCK_LOCK(i);
1099 		for (q = V_ipfw_dyn_v[i].head, q_prev = q; q ; ) {
1100 			/* account every rule */
1101 			total++;
1102 
1103 			/* Skip parent rules at all */
1104 			if (q->dyn_type == O_LIMIT_PARENT) {
1105 				parents++;
1106 				NEXT_RULE();
1107 			}
1108 
1109 			/*
1110 			 * Remove rules which are:
1111 			 * 1) expired
1112 			 * 2) matches deletion range
1113 			 */
1114 			if ((TIME_LEQ(q->expire, time_uptime)) ||
1115 			    (rt != NULL && ipfw_match_range(q->rule, rt))) {
1116 				if (TIME_LE(time_uptime, q->expire) &&
1117 				    q->dyn_type == O_KEEP_STATE &&
1118 				    V_dyn_keep_states != 0) {
1119 					/*
1120 					 * Do not delete state if
1121 					 * it is not expired and
1122 					 * dyn_keep_states is ON.
1123 					 * However we need to re-link it
1124 					 * to any other stable rule
1125 					 */
1126 					q->rule = chain->default_rule;
1127 					NEXT_RULE();
1128 				}
1129 
1130 				/* Unlink q from current list */
1131 				q_next = q->next;
1132 				if (q == V_ipfw_dyn_v[i].head)
1133 					V_ipfw_dyn_v[i].head = q_next;
1134 				else
1135 					q_prev->next = q_next;
1136 
1137 				q->next = NULL;
1138 
1139 				/* queue q to expire list */
1140 				if (q->dyn_type != O_LIMIT) {
1141 					*exptailp = q;
1142 					exptailp = &(*exptailp)->next;
1143 					DEB(print_dyn_rule(&q->id, q->dyn_type,
1144 					    "unlink entry", "left");
1145 					)
1146 				} else {
1147 					/* Separate list for limit rules */
1148 					*expltailp = q;
1149 					expltailp = &(*expltailp)->next;
1150 					expired_limits++;
1151 					DEB(print_dyn_rule(&q->id, q->dyn_type,
1152 					    "unlink limit entry", "left");
1153 					)
1154 				}
1155 
1156 				q = q_next;
1157 				expired++;
1158 				continue;
1159 			}
1160 
1161 			/*
1162 			 * Check if we need to send keepalive:
1163 			 * we need to ensure if is time to do KA,
1164 			 * this is established TCP session, and
1165 			 * expire time is within keepalive interval
1166 			 */
1167 			if ((check_ka != 0) && (q->id.proto == IPPROTO_TCP) &&
1168 			    ((q->state & BOTH_SYN) == BOTH_SYN) &&
1169 			    (TIME_LEQ(q->expire, time_uptime +
1170 			      V_dyn_keepalive_interval)))
1171 				mtailp = ipfw_dyn_send_ka(mtailp, q);
1172 
1173 			NEXT_RULE();
1174 		}
1175 		IPFW_BUCK_UNLOCK(i);
1176 	}
1177 
1178 	/* Stage 2: decrement counters from O_LIMIT parents */
1179 	if (expired_limits != 0) {
1180 		/*
1181 		 * XXX: Note that deleting set with more than one
1182 		 * heavily-used LIMIT rules can result in overwhelming
1183 		 * locking due to lack of per-hash value sorting
1184 		 *
1185 		 * We should probably think about:
1186 		 * 1) pre-allocating hash of size, say,
1187 		 * MAX(16, V_curr_dyn_buckets / 1024)
1188 		 * 2) checking if expired_limits is large enough
1189 		 * 3) If yes, init hash (or its part), re-link
1190 		 * current list and start decrementing procedure in
1191 		 * each bucket separately
1192 		 */
1193 
1194 		/*
1195 		 * Small optimization: do not unlock bucket until
1196 		 * we see the next item resides in different bucket
1197 		 */
1198 		if (exp_lhead != NULL) {
1199 			i = exp_lhead->parent->bucket;
1200 			IPFW_BUCK_LOCK(i);
1201 		}
1202 		for (q = exp_lhead; q != NULL; q = q->next) {
1203 			if (i != q->parent->bucket) {
1204 				IPFW_BUCK_UNLOCK(i);
1205 				i = q->parent->bucket;
1206 				IPFW_BUCK_LOCK(i);
1207 			}
1208 
1209 			/* Decrease parent refcount */
1210 			q->parent->count--;
1211 		}
1212 		if (exp_lhead != NULL)
1213 			IPFW_BUCK_UNLOCK(i);
1214 	}
1215 
1216 	/*
1217 	 * We protectet ourselves from unused parent deletion
1218 	 * (from the timer function) by holding UH write lock.
1219 	 */
1220 
1221 	/* Stage 3: remove unused parent rules */
1222 	if ((parents != 0) && (expired != 0)) {
1223 		for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
1224 			IPFW_BUCK_LOCK(i);
1225 			for (q = V_ipfw_dyn_v[i].head, q_prev = q ; q ; ) {
1226 				if (q->dyn_type != O_LIMIT_PARENT)
1227 					NEXT_RULE();
1228 
1229 				if (q->count != 0)
1230 					NEXT_RULE();
1231 
1232 				/* Parent rule without consumers */
1233 
1234 				/* Unlink q from current list */
1235 				q_next = q->next;
1236 				if (q == V_ipfw_dyn_v[i].head)
1237 					V_ipfw_dyn_v[i].head = q_next;
1238 				else
1239 					q_prev->next = q_next;
1240 
1241 				q->next = NULL;
1242 
1243 				/* Add to expired list */
1244 				*exptailp = q;
1245 				exptailp = &(*exptailp)->next;
1246 
1247 				DEB(print_dyn_rule(&q->id, q->dyn_type,
1248 				    "unlink parent entry", "left");
1249 				)
1250 
1251 				expired++;
1252 
1253 				q = q_next;
1254 			}
1255 			IPFW_BUCK_UNLOCK(i);
1256 		}
1257 	}
1258 
1259 #undef NEXT_RULE
1260 
1261 	if (timer != 0) {
1262 		/*
1263 		 * Check if we need to resize hash:
1264 		 * if current number of states exceeds number of buckes in hash,
1265 		 * grow hash size to the minimum power of 2 which is bigger than
1266 		 * current states count. Limit hash size by 64k.
1267 		 */
1268 		max_buckets = (V_dyn_buckets_max > 65536) ?
1269 		    65536 : V_dyn_buckets_max;
1270 
1271 		dyn_count = DYN_COUNT;
1272 
1273 		if ((dyn_count > V_curr_dyn_buckets * 2) &&
1274 		    (dyn_count < max_buckets)) {
1275 			new_buckets = V_curr_dyn_buckets;
1276 			while (new_buckets < dyn_count) {
1277 				new_buckets *= 2;
1278 
1279 				if (new_buckets >= max_buckets)
1280 					break;
1281 			}
1282 		}
1283 
1284 		IPFW_UH_WUNLOCK(chain);
1285 	}
1286 
1287 	/* Finally delete old states ad limits if any */
1288 	for (q = exp_head; q != NULL; q = q_next) {
1289 		q_next = q->next;
1290 		uma_zfree(V_ipfw_dyn_rule_zone, q);
1291 		ipfw_dyn_count--;
1292 	}
1293 
1294 	for (q = exp_lhead; q != NULL; q = q_next) {
1295 		q_next = q->next;
1296 		uma_zfree(V_ipfw_dyn_rule_zone, q);
1297 		ipfw_dyn_count--;
1298 	}
1299 
1300 	/*
1301 	 * The rest code MUST be called from timer routine only
1302 	 * without holding any locks
1303 	 */
1304 	if (timer == 0)
1305 		return;
1306 
1307 	/* Send keepalive packets if any */
1308 	for (m = m0; m != NULL; m = mnext) {
1309 		mnext = m->m_nextpkt;
1310 		m->m_nextpkt = NULL;
1311 		h = mtod(m, struct ip *);
1312 		if (h->ip_v == 4)
1313 			ip_output(m, NULL, NULL, 0, NULL, NULL);
1314 #ifdef INET6
1315 		else
1316 			ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
1317 #endif
1318 	}
1319 
1320 	/* Run table resize without holding any locks */
1321 	if (new_buckets != 0)
1322 		resize_dynamic_table(chain, new_buckets);
1323 }
1324 
1325 /*
1326  * Deletes all dynamic rules originated by given rule or all rules in
1327  * given set. Specify RESVD_SET to indicate set should not be used.
1328  * @chain - pointer to current ipfw rules chain
1329  * @rr - delete all states originated by rules in matched range.
1330  *
1331  * Function has to be called with IPFW_UH_WLOCK held.
1332  * Additionally, function assume that dynamic rule/set is
1333  * ALREADY deleted so no new states can be generated by
1334  * 'deleted' rules.
1335  */
1336 void
1337 ipfw_expire_dyn_rules(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1338 {
1339 
1340 	check_dyn_rules(chain, rt, 0, 0);
1341 }
1342 
1343 /*
1344  * Check if rule contains at least one dynamic opcode.
1345  *
1346  * Returns 1 if such opcode is found, 0 otherwise.
1347  */
1348 int
1349 ipfw_is_dyn_rule(struct ip_fw *rule)
1350 {
1351 	int cmdlen, l;
1352 	ipfw_insn *cmd;
1353 
1354 	l = rule->cmd_len;
1355 	cmd = rule->cmd;
1356 	cmdlen = 0;
1357 	for ( ;	l > 0 ; l -= cmdlen, cmd += cmdlen) {
1358 		cmdlen = F_LEN(cmd);
1359 
1360 		switch (cmd->opcode) {
1361 		case O_LIMIT:
1362 		case O_KEEP_STATE:
1363 		case O_PROBE_STATE:
1364 		case O_CHECK_STATE:
1365 			return (1);
1366 		}
1367 	}
1368 
1369 	return (0);
1370 }
1371 
1372 void
1373 ipfw_dyn_init(struct ip_fw_chain *chain)
1374 {
1375 
1376         V_ipfw_dyn_v = NULL;
1377         V_dyn_buckets_max = 256; /* must be power of 2 */
1378         V_curr_dyn_buckets = 256; /* must be power of 2 */
1379 
1380         V_dyn_ack_lifetime = 300;
1381         V_dyn_syn_lifetime = 20;
1382         V_dyn_fin_lifetime = 1;
1383         V_dyn_rst_lifetime = 1;
1384         V_dyn_udp_lifetime = 10;
1385         V_dyn_short_lifetime = 5;
1386 
1387         V_dyn_keepalive_interval = 20;
1388         V_dyn_keepalive_period = 5;
1389         V_dyn_keepalive = 1;    /* do send keepalives */
1390 	V_dyn_keepalive_last = time_uptime;
1391 
1392         V_dyn_max = 16384; /* max # of dynamic rules */
1393 
1394 	V_ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
1395 	    sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
1396 	    UMA_ALIGN_PTR, 0);
1397 
1398 	/* Enforce limit on dynamic rules */
1399 	uma_zone_set_max(V_ipfw_dyn_rule_zone, V_dyn_max);
1400 
1401         callout_init(&V_ipfw_timeout, 1);
1402 
1403 	/*
1404 	 * This can potentially be done on first dynamic rule
1405 	 * being added to chain.
1406 	 */
1407 	resize_dynamic_table(chain, V_curr_dyn_buckets);
1408 }
1409 
1410 void
1411 ipfw_dyn_uninit(int pass)
1412 {
1413 	int i;
1414 
1415 	if (pass == 0) {
1416 		callout_drain(&V_ipfw_timeout);
1417 		return;
1418 	}
1419 
1420 	if (V_ipfw_dyn_v != NULL) {
1421 		/*
1422 		 * Skip deleting all dynamic states -
1423 		 * uma_zdestroy() does this more efficiently;
1424 		 */
1425 
1426 		/* Destroy all mutexes */
1427 		for (i = 0 ; i < V_curr_dyn_buckets ; i++)
1428 			IPFW_BUCK_LOCK_DESTROY(&V_ipfw_dyn_v[i]);
1429 		free(V_ipfw_dyn_v, M_IPFW);
1430 		V_ipfw_dyn_v = NULL;
1431 	}
1432 
1433         uma_zdestroy(V_ipfw_dyn_rule_zone);
1434 }
1435 
1436 #ifdef SYSCTL_NODE
1437 /*
1438  * Get/set maximum number of dynamic states in given VNET instance.
1439  */
1440 static int
1441 sysctl_ipfw_dyn_max(SYSCTL_HANDLER_ARGS)
1442 {
1443 	int error;
1444 	unsigned int nstates;
1445 
1446 	nstates = V_dyn_max;
1447 
1448 	error = sysctl_handle_int(oidp, &nstates, 0, req);
1449 	/* Read operation or some error */
1450 	if ((error != 0) || (req->newptr == NULL))
1451 		return (error);
1452 
1453 	V_dyn_max = nstates;
1454 	uma_zone_set_max(V_ipfw_dyn_rule_zone, V_dyn_max);
1455 
1456 	return (0);
1457 }
1458 
1459 /*
1460  * Get current number of dynamic states in given VNET instance.
1461  */
1462 static int
1463 sysctl_ipfw_dyn_count(SYSCTL_HANDLER_ARGS)
1464 {
1465 	int error;
1466 	unsigned int nstates;
1467 
1468 	nstates = DYN_COUNT;
1469 
1470 	error = sysctl_handle_int(oidp, &nstates, 0, req);
1471 
1472 	return (error);
1473 }
1474 #endif
1475 
1476 /*
1477  * Returns size of dynamic states in legacy format
1478  */
1479 int
1480 ipfw_dyn_len(void)
1481 {
1482 
1483 	return (V_ipfw_dyn_v == NULL) ? 0 :
1484 		(DYN_COUNT * sizeof(ipfw_dyn_rule));
1485 }
1486 
1487 /*
1488  * Returns number of dynamic states.
1489  * Used by dump format v1 (current).
1490  */
1491 int
1492 ipfw_dyn_get_count(void)
1493 {
1494 
1495 	return (V_ipfw_dyn_v == NULL) ? 0 : DYN_COUNT;
1496 }
1497 
1498 static void
1499 export_dyn_rule(ipfw_dyn_rule *src, ipfw_dyn_rule *dst)
1500 {
1501 
1502 	memcpy(dst, src, sizeof(*src));
1503 	memcpy(&(dst->rule), &(src->rule->rulenum), sizeof(src->rule->rulenum));
1504 	/*
1505 	 * store set number into high word of
1506 	 * dst->rule pointer.
1507 	 */
1508 	memcpy((char *)&dst->rule + sizeof(src->rule->rulenum),
1509 	    &(src->rule->set), sizeof(src->rule->set));
1510 	/*
1511 	 * store a non-null value in "next".
1512 	 * The userland code will interpret a
1513 	 * NULL here as a marker
1514 	 * for the last dynamic rule.
1515 	 */
1516 	memcpy(&dst->next, &dst, sizeof(dst));
1517 	dst->expire =
1518 	    TIME_LEQ(dst->expire, time_uptime) ?  0 : dst->expire - time_uptime;
1519 }
1520 
1521 /*
1522  * Fills int buffer given by @sd with dynamic states.
1523  * Used by dump format v1 (current).
1524  *
1525  * Returns 0 on success.
1526  */
1527 int
1528 ipfw_dump_states(struct ip_fw_chain *chain, struct sockopt_data *sd)
1529 {
1530 	ipfw_dyn_rule *p;
1531 	ipfw_obj_dyntlv *dst, *last;
1532 	ipfw_obj_ctlv *ctlv;
1533 	int i;
1534 	size_t sz;
1535 
1536 	if (V_ipfw_dyn_v == NULL)
1537 		return (0);
1538 
1539 	IPFW_UH_RLOCK_ASSERT(chain);
1540 
1541 	ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
1542 	if (ctlv == NULL)
1543 		return (ENOMEM);
1544 	sz = sizeof(ipfw_obj_dyntlv);
1545 	ctlv->head.type = IPFW_TLV_DYNSTATE_LIST;
1546 	ctlv->objsize = sz;
1547 	last = NULL;
1548 
1549 	for (i = 0 ; i < V_curr_dyn_buckets; i++) {
1550 		IPFW_BUCK_LOCK(i);
1551 		for (p = V_ipfw_dyn_v[i].head ; p != NULL; p = p->next) {
1552 			dst = (ipfw_obj_dyntlv *)ipfw_get_sopt_space(sd, sz);
1553 			if (dst == NULL) {
1554 				IPFW_BUCK_UNLOCK(i);
1555 				return (ENOMEM);
1556 			}
1557 
1558 			export_dyn_rule(p, &dst->state);
1559 			dst->head.length = sz;
1560 			dst->head.type = IPFW_TLV_DYN_ENT;
1561 			last = dst;
1562 		}
1563 		IPFW_BUCK_UNLOCK(i);
1564 	}
1565 
1566 	if (last != NULL) /* mark last dynamic rule */
1567 		last->head.flags = IPFW_DF_LAST;
1568 
1569 	return (0);
1570 }
1571 
1572 /*
1573  * Fill given buffer with dynamic states (legacy format).
1574  * IPFW_UH_RLOCK has to be held while calling.
1575  */
1576 void
1577 ipfw_get_dynamic(struct ip_fw_chain *chain, char **pbp, const char *ep)
1578 {
1579 	ipfw_dyn_rule *p, *last = NULL;
1580 	char *bp;
1581 	int i;
1582 
1583 	if (V_ipfw_dyn_v == NULL)
1584 		return;
1585 	bp = *pbp;
1586 
1587 	IPFW_UH_RLOCK_ASSERT(chain);
1588 
1589 	for (i = 0 ; i < V_curr_dyn_buckets; i++) {
1590 		IPFW_BUCK_LOCK(i);
1591 		for (p = V_ipfw_dyn_v[i].head ; p != NULL; p = p->next) {
1592 			if (bp + sizeof *p <= ep) {
1593 				ipfw_dyn_rule *dst =
1594 					(ipfw_dyn_rule *)bp;
1595 
1596 				export_dyn_rule(p, dst);
1597 				last = dst;
1598 				bp += sizeof(ipfw_dyn_rule);
1599 			}
1600 		}
1601 		IPFW_BUCK_UNLOCK(i);
1602 	}
1603 
1604 	if (last != NULL) /* mark last dynamic rule */
1605 		bzero(&last->next, sizeof(last));
1606 	*pbp = bp;
1607 }
1608 /* end of file */
1609