xref: /freebsd/sys/netpfil/ipfw/ip_fw_dynamic.c (revision 18849b5da0c5eaa88500b457be05b038813b51b1)
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 static void
323 dyn_update_proto_state(ipfw_dyn_rule *q, const struct ipfw_flow_id *id,
324     const struct tcphdr *tcp, int dir)
325 {
326 	uint32_t ack;
327 	u_char flags;
328 
329 	if (id->proto == IPPROTO_TCP) {
330 		flags = id->_flags & (TH_FIN | TH_SYN | TH_RST);
331 #define BOTH_SYN	(TH_SYN | (TH_SYN << 8))
332 #define BOTH_FIN	(TH_FIN | (TH_FIN << 8))
333 #define	TCP_FLAGS	(TH_FLAGS | (TH_FLAGS << 8))
334 #define	ACK_FWD		0x10000			/* fwd ack seen */
335 #define	ACK_REV		0x20000			/* rev ack seen */
336 
337 		q->state |= (dir == MATCH_FORWARD) ? flags : (flags << 8);
338 		switch (q->state & TCP_FLAGS) {
339 		case TH_SYN:			/* opening */
340 			q->expire = time_uptime + V_dyn_syn_lifetime;
341 			break;
342 
343 		case BOTH_SYN:			/* move to established */
344 		case BOTH_SYN | TH_FIN:		/* one side tries to close */
345 		case BOTH_SYN | (TH_FIN << 8):
346 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
347 			if (tcp == NULL)
348 				break;
349 
350 			ack = ntohl(tcp->th_ack);
351 			if (dir == MATCH_FORWARD) {
352 				if (q->ack_fwd == 0 ||
353 				    _SEQ_GE(ack, q->ack_fwd)) {
354 					q->ack_fwd = ack;
355 					q->state |= ACK_FWD;
356 				}
357 			} else {
358 				if (q->ack_rev == 0 ||
359 				    _SEQ_GE(ack, q->ack_rev)) {
360 					q->ack_rev = ack;
361 					q->state |= ACK_REV;
362 				}
363 			}
364 			if ((q->state & (ACK_FWD | ACK_REV)) ==
365 			    (ACK_FWD | ACK_REV)) {
366 				q->expire = time_uptime + V_dyn_ack_lifetime;
367 				q->state &= ~(ACK_FWD | ACK_REV);
368 			}
369 			break;
370 
371 		case BOTH_SYN | BOTH_FIN:	/* both sides closed */
372 			if (V_dyn_fin_lifetime >= V_dyn_keepalive_period)
373 				V_dyn_fin_lifetime =
374 				    V_dyn_keepalive_period - 1;
375 			q->expire = time_uptime + V_dyn_fin_lifetime;
376 			break;
377 
378 		default:
379 #if 0
380 			/*
381 			 * reset or some invalid combination, but can also
382 			 * occur if we use keep-state the wrong way.
383 			 */
384 			if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
385 				printf("invalid state: 0x%x\n", q->state);
386 #endif
387 			if (V_dyn_rst_lifetime >= V_dyn_keepalive_period)
388 				V_dyn_rst_lifetime =
389 				    V_dyn_keepalive_period - 1;
390 			q->expire = time_uptime + V_dyn_rst_lifetime;
391 			break;
392 		}
393 	} else if (id->proto == IPPROTO_UDP) {
394 		q->expire = time_uptime + V_dyn_udp_lifetime;
395 	} else {
396 		/* other protocols */
397 		q->expire = time_uptime + V_dyn_short_lifetime;
398 	}
399 }
400 
401 /*
402  * Lookup a dynamic rule, locked version.
403  */
404 static ipfw_dyn_rule *
405 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int i, int *match_direction,
406     struct tcphdr *tcp)
407 {
408 	/*
409 	 * Stateful ipfw extensions.
410 	 * Lookup into dynamic session queue.
411 	 */
412 	ipfw_dyn_rule *prev, *q = NULL;
413 	int dir;
414 
415 	IPFW_BUCK_ASSERT(i);
416 
417 	dir = MATCH_NONE;
418 	for (prev = NULL, q = V_ipfw_dyn_v[i].head; q; prev = q, q = q->next) {
419 		if (q->dyn_type == O_LIMIT_PARENT && q->count)
420 			continue;
421 
422 		if (pkt->proto != q->id.proto || q->dyn_type == O_LIMIT_PARENT)
423 			continue;
424 
425 		if (IS_IP6_FLOW_ID(pkt)) {
426 			if (IN6_ARE_ADDR_EQUAL(&pkt->src_ip6, &q->id.src_ip6) &&
427 			    IN6_ARE_ADDR_EQUAL(&pkt->dst_ip6, &q->id.dst_ip6) &&
428 			    pkt->src_port == q->id.src_port &&
429 			    pkt->dst_port == q->id.dst_port) {
430 				dir = MATCH_FORWARD;
431 				break;
432 			}
433 			if (IN6_ARE_ADDR_EQUAL(&pkt->src_ip6, &q->id.dst_ip6) &&
434 			    IN6_ARE_ADDR_EQUAL(&pkt->dst_ip6, &q->id.src_ip6) &&
435 			    pkt->src_port == q->id.dst_port &&
436 			    pkt->dst_port == q->id.src_port) {
437 				dir = MATCH_REVERSE;
438 				break;
439 			}
440 		} else {
441 			if (pkt->src_ip == q->id.src_ip &&
442 			    pkt->dst_ip == q->id.dst_ip &&
443 			    pkt->src_port == q->id.src_port &&
444 			    pkt->dst_port == q->id.dst_port) {
445 				dir = MATCH_FORWARD;
446 				break;
447 			}
448 			if (pkt->src_ip == q->id.dst_ip &&
449 			    pkt->dst_ip == q->id.src_ip &&
450 			    pkt->src_port == q->id.dst_port &&
451 			    pkt->dst_port == q->id.src_port) {
452 				dir = MATCH_REVERSE;
453 				break;
454 			}
455 		}
456 	}
457 	if (q == NULL)
458 		goto done;	/* q = NULL, not found */
459 
460 	if (prev != NULL) {	/* found and not in front */
461 		prev->next = q->next;
462 		q->next = V_ipfw_dyn_v[i].head;
463 		V_ipfw_dyn_v[i].head = q;
464 	}
465 
466 	/* update state according to flags */
467 	dyn_update_proto_state(q, pkt, tcp, dir);
468 done:
469 	if (match_direction != NULL)
470 		*match_direction = dir;
471 	return (q);
472 }
473 
474 ipfw_dyn_rule *
475 ipfw_lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
476     struct tcphdr *tcp)
477 {
478 	ipfw_dyn_rule *q;
479 	int i;
480 
481 	i = hash_packet(pkt, V_curr_dyn_buckets);
482 
483 	IPFW_BUCK_LOCK(i);
484 	q = lookup_dyn_rule_locked(pkt, i, match_direction, tcp);
485 	if (q == NULL)
486 		IPFW_BUCK_UNLOCK(i);
487 	/* NB: return table locked when q is not NULL */
488 	return q;
489 }
490 
491 /*
492  * Unlock bucket mtx
493  * @p - pointer to dynamic rule
494  */
495 void
496 ipfw_dyn_unlock(ipfw_dyn_rule *q)
497 {
498 
499 	IPFW_BUCK_UNLOCK(q->bucket);
500 }
501 
502 static int
503 resize_dynamic_table(struct ip_fw_chain *chain, int nbuckets)
504 {
505 	int i, k, nbuckets_old;
506 	ipfw_dyn_rule *q;
507 	struct ipfw_dyn_bucket *dyn_v, *dyn_v_old;
508 
509 	/* Check if given number is power of 2 and less than 64k */
510 	if ((nbuckets > 65536) || (!powerof2(nbuckets)))
511 		return 1;
512 
513 	CTR3(KTR_NET, "%s: resize dynamic hash: %d -> %d", __func__,
514 	    V_curr_dyn_buckets, nbuckets);
515 
516 	/* Allocate and initialize new hash */
517 	dyn_v = malloc(nbuckets * sizeof(*dyn_v), M_IPFW,
518 	    M_WAITOK | M_ZERO);
519 
520 	for (i = 0 ; i < nbuckets; i++)
521 		IPFW_BUCK_LOCK_INIT(&dyn_v[i]);
522 
523 	/*
524 	 * Call upper half lock, as get_map() do to ease
525 	 * read-only access to dynamic rules hash from sysctl
526 	 */
527 	IPFW_UH_WLOCK(chain);
528 
529 	/*
530 	 * Acquire chain write lock to permit hash access
531 	 * for main traffic path without additional locks
532 	 */
533 	IPFW_WLOCK(chain);
534 
535 	/* Save old values */
536 	nbuckets_old = V_curr_dyn_buckets;
537 	dyn_v_old = V_ipfw_dyn_v;
538 
539 	/* Skip relinking if array is not set up */
540 	if (V_ipfw_dyn_v == NULL)
541 		V_curr_dyn_buckets = 0;
542 
543 	/* Re-link all dynamic states */
544 	for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
545 		while (V_ipfw_dyn_v[i].head != NULL) {
546 			/* Remove from current chain */
547 			q = V_ipfw_dyn_v[i].head;
548 			V_ipfw_dyn_v[i].head = q->next;
549 
550 			/* Get new hash value */
551 			k = hash_packet(&q->id, nbuckets);
552 			q->bucket = k;
553 			/* Add to the new head */
554 			q->next = dyn_v[k].head;
555 			dyn_v[k].head = q;
556              }
557 	}
558 
559 	/* Update current pointers/buckets values */
560 	V_curr_dyn_buckets = nbuckets;
561 	V_ipfw_dyn_v = dyn_v;
562 
563 	IPFW_WUNLOCK(chain);
564 
565 	IPFW_UH_WUNLOCK(chain);
566 
567 	/* Start periodic callout on initial creation */
568 	if (dyn_v_old == NULL) {
569         	callout_reset_on(&V_ipfw_timeout, hz, ipfw_dyn_tick, curvnet, 0);
570 		return (0);
571 	}
572 
573 	/* Destroy all mutexes */
574 	for (i = 0 ; i < nbuckets_old ; i++)
575 		IPFW_BUCK_LOCK_DESTROY(&dyn_v_old[i]);
576 
577 	/* Free old hash */
578 	free(dyn_v_old, M_IPFW);
579 
580 	return 0;
581 }
582 
583 /**
584  * Install state of type 'type' for a dynamic session.
585  * The hash table contains two type of rules:
586  * - regular rules (O_KEEP_STATE)
587  * - rules for sessions with limited number of sess per user
588  *   (O_LIMIT). When they are created, the parent is
589  *   increased by 1, and decreased on delete. In this case,
590  *   the third parameter is the parent rule and not the chain.
591  * - "parent" rules for the above (O_LIMIT_PARENT).
592  */
593 static ipfw_dyn_rule *
594 add_dyn_rule(struct ipfw_flow_id *id, int i, u_int8_t dyn_type, struct ip_fw *rule)
595 {
596 	ipfw_dyn_rule *r;
597 
598 	IPFW_BUCK_ASSERT(i);
599 
600 	r = uma_zalloc(V_ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
601 	if (r == NULL) {
602 		if (last_log != time_uptime) {
603 			last_log = time_uptime;
604 			log(LOG_DEBUG,
605 			    "ipfw: Cannot allocate dynamic state, "
606 			    "consider increasing net.inet.ip.fw.dyn_max\n");
607 		}
608 		return NULL;
609 	}
610 	ipfw_dyn_count++;
611 
612 	/*
613 	 * refcount on parent is already incremented, so
614 	 * it is safe to use parent unlocked.
615 	 */
616 	if (dyn_type == O_LIMIT) {
617 		ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
618 		if ( parent->dyn_type != O_LIMIT_PARENT)
619 			panic("invalid parent");
620 		r->parent = parent;
621 		rule = parent->rule;
622 	}
623 
624 	r->id = *id;
625 	r->expire = time_uptime + V_dyn_syn_lifetime;
626 	r->rule = rule;
627 	r->dyn_type = dyn_type;
628 	IPFW_ZERO_DYN_COUNTER(r);
629 	r->count = 0;
630 
631 	r->bucket = i;
632 	r->next = V_ipfw_dyn_v[i].head;
633 	V_ipfw_dyn_v[i].head = r;
634 	DEB(print_dyn_rule(id, dyn_type, "add dyn entry", "total");)
635 	return r;
636 }
637 
638 /**
639  * lookup dynamic parent rule using pkt and rule as search keys.
640  * If the lookup fails, then install one.
641  */
642 static ipfw_dyn_rule *
643 lookup_dyn_parent(struct ipfw_flow_id *pkt, int *pindex, struct ip_fw *rule)
644 {
645 	ipfw_dyn_rule *q;
646 	int i, is_v6;
647 
648 	is_v6 = IS_IP6_FLOW_ID(pkt);
649 	i = hash_packet( pkt, V_curr_dyn_buckets );
650 	*pindex = i;
651 	IPFW_BUCK_LOCK(i);
652 	for (q = V_ipfw_dyn_v[i].head ; q != NULL ; q=q->next)
653 		if (q->dyn_type == O_LIMIT_PARENT &&
654 		    rule== q->rule &&
655 		    pkt->proto == q->id.proto &&
656 		    pkt->src_port == q->id.src_port &&
657 		    pkt->dst_port == q->id.dst_port &&
658 		    (
659 			(is_v6 &&
660 			 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
661 				&(q->id.src_ip6)) &&
662 			 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
663 				&(q->id.dst_ip6))) ||
664 			(!is_v6 &&
665 			 pkt->src_ip == q->id.src_ip &&
666 			 pkt->dst_ip == q->id.dst_ip)
667 		    )
668 		) {
669 			q->expire = time_uptime + V_dyn_short_lifetime;
670 			DEB(print_dyn_rule(pkt, q->dyn_type,
671 			    "lookup_dyn_parent found", "");)
672 			return q;
673 		}
674 
675 	/* Add virtual limiting rule */
676 	return add_dyn_rule(pkt, i, O_LIMIT_PARENT, rule);
677 }
678 
679 /**
680  * Install dynamic state for rule type cmd->o.opcode
681  *
682  * Returns 1 (failure) if state is not installed because of errors or because
683  * session limitations are enforced.
684  */
685 int
686 ipfw_install_state(struct ip_fw_chain *chain, struct ip_fw *rule,
687     ipfw_insn_limit *cmd, struct ip_fw_args *args, uint32_t tablearg)
688 {
689 	ipfw_dyn_rule *q;
690 	int i, dir;
691 
692 	DEB(print_dyn_rule(&args->f_id, cmd->o.opcode, "install_state", "");)
693 
694 	i = hash_packet(&args->f_id, V_curr_dyn_buckets);
695 
696 	IPFW_BUCK_LOCK(i);
697 
698 	q = lookup_dyn_rule_locked(&args->f_id, i, &dir, NULL);
699 	if (q != NULL) {	/* should never occur */
700 		DEB(
701 		if (last_log != time_uptime) {
702 			last_log = time_uptime;
703 			printf("ipfw: %s: entry already present, done\n",
704 			    __func__);
705 		})
706 		IPFW_BUCK_UNLOCK(i);
707 		return (0);
708 	}
709 
710 	/*
711 	 * State limiting is done via uma(9) zone limiting.
712 	 * Save pointer to newly-installed rule and reject
713 	 * packet if add_dyn_rule() returned NULL.
714 	 * Note q is currently set to NULL.
715 	 */
716 
717 	switch (cmd->o.opcode) {
718 	case O_KEEP_STATE:	/* bidir rule */
719 		q = add_dyn_rule(&args->f_id, i, O_KEEP_STATE, rule);
720 		break;
721 
722 	case O_LIMIT: {		/* limit number of sessions */
723 		struct ipfw_flow_id id;
724 		ipfw_dyn_rule *parent;
725 		uint32_t conn_limit;
726 		uint16_t limit_mask = cmd->limit_mask;
727 		int pindex;
728 
729 		conn_limit = IP_FW_ARG_TABLEARG(chain, cmd->conn_limit, limit);
730 
731 		DEB(
732 		if (cmd->conn_limit == IP_FW_TARG)
733 			printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
734 			    "(tablearg)\n", __func__, conn_limit);
735 		else
736 			printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
737 			    __func__, conn_limit);
738 		)
739 
740 		id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
741 		id.proto = args->f_id.proto;
742 		id.addr_type = args->f_id.addr_type;
743 		id.fib = M_GETFIB(args->m);
744 
745 		if (IS_IP6_FLOW_ID (&(args->f_id))) {
746 			bzero(&id.src_ip6, sizeof(id.src_ip6));
747 			bzero(&id.dst_ip6, sizeof(id.dst_ip6));
748 
749 			if (limit_mask & DYN_SRC_ADDR)
750 				id.src_ip6 = args->f_id.src_ip6;
751 			if (limit_mask & DYN_DST_ADDR)
752 				id.dst_ip6 = args->f_id.dst_ip6;
753 		} else {
754 			if (limit_mask & DYN_SRC_ADDR)
755 				id.src_ip = args->f_id.src_ip;
756 			if (limit_mask & DYN_DST_ADDR)
757 				id.dst_ip = args->f_id.dst_ip;
758 		}
759 		if (limit_mask & DYN_SRC_PORT)
760 			id.src_port = args->f_id.src_port;
761 		if (limit_mask & DYN_DST_PORT)
762 			id.dst_port = args->f_id.dst_port;
763 
764 		/*
765 		 * We have to release lock for previous bucket to
766 		 * avoid possible deadlock
767 		 */
768 		IPFW_BUCK_UNLOCK(i);
769 
770 		if ((parent = lookup_dyn_parent(&id, &pindex, rule)) == NULL) {
771 			printf("ipfw: %s: add parent failed\n", __func__);
772 			IPFW_BUCK_UNLOCK(pindex);
773 			return (1);
774 		}
775 
776 		if (parent->count >= conn_limit) {
777 			if (V_fw_verbose && last_log != time_uptime) {
778 				last_log = time_uptime;
779 				char sbuf[24];
780 				last_log = time_uptime;
781 				snprintf(sbuf, sizeof(sbuf),
782 				    "%d drop session",
783 				    parent->rule->rulenum);
784 				print_dyn_rule_flags(&args->f_id,
785 				    cmd->o.opcode,
786 				    LOG_SECURITY | LOG_DEBUG,
787 				    sbuf, "too many entries");
788 			}
789 			IPFW_BUCK_UNLOCK(pindex);
790 			return (1);
791 		}
792 		/* Increment counter on parent */
793 		parent->count++;
794 		IPFW_BUCK_UNLOCK(pindex);
795 
796 		IPFW_BUCK_LOCK(i);
797 		q = add_dyn_rule(&args->f_id, i, O_LIMIT,
798 		    (struct ip_fw *)parent);
799 		if (q == NULL) {
800 			/* Decrement index and notify caller */
801 			IPFW_BUCK_UNLOCK(i);
802 			IPFW_BUCK_LOCK(pindex);
803 			parent->count--;
804 			IPFW_BUCK_UNLOCK(pindex);
805 			return (1);
806 		}
807 		break;
808 	}
809 	default:
810 		printf("ipfw: %s: unknown dynamic rule type %u\n",
811 		    __func__, cmd->o.opcode);
812 	}
813 
814 	if (q == NULL) {
815 		IPFW_BUCK_UNLOCK(i);
816 		return (1);	/* Notify caller about failure */
817 	}
818 
819 	dyn_update_proto_state(q, &args->f_id, NULL, dir);
820 	IPFW_BUCK_UNLOCK(i);
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  */
832 struct mbuf *
833 ipfw_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_NOWAIT, 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  */
976 static struct mbuf **
977 ipfw_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 used to perform various maintenance
1000  * on dynamic hash list. Currently it is called every second.
1001  */
1002 static void
1003 ipfw_dyn_tick(void * vnetx)
1004 {
1005 	struct ip_fw_chain *chain;
1006 	int check_ka = 0;
1007 #ifdef VIMAGE
1008 	struct vnet *vp = vnetx;
1009 #endif
1010 
1011 	CURVNET_SET(vp);
1012 
1013 	chain = &V_layer3_chain;
1014 
1015 	/* Run keepalive checks every keepalive_period iff ka is enabled */
1016 	if ((V_dyn_keepalive_last + V_dyn_keepalive_period <= time_uptime) &&
1017 	    (V_dyn_keepalive != 0)) {
1018 		V_dyn_keepalive_last = time_uptime;
1019 		check_ka = 1;
1020 	}
1021 
1022 	check_dyn_rules(chain, NULL, check_ka, 1);
1023 
1024 	callout_reset_on(&V_ipfw_timeout, hz, ipfw_dyn_tick, vnetx, 0);
1025 
1026 	CURVNET_RESTORE();
1027 }
1028 
1029 
1030 /*
1031  * Walk through all dynamic states doing generic maintenance:
1032  * 1) free expired states
1033  * 2) free all states based on deleted rule / set
1034  * 3) send keepalives for states if needed
1035  *
1036  * @chain - pointer to current ipfw rules chain
1037  * @rule - delete all states originated by given rule if != NULL
1038  * @set - delete all states originated by any rule in set @set if != RESVD_SET
1039  * @check_ka - perform checking/sending keepalives
1040  * @timer - indicate call from timer routine.
1041  *
1042  * Timer routine must call this function unlocked to permit
1043  * sending keepalives/resizing table.
1044  *
1045  * Others has to call function with IPFW_UH_WLOCK held.
1046  * Additionally, function assume that dynamic rule/set is
1047  * ALREADY deleted so no new states can be generated by
1048  * 'deleted' rules.
1049  *
1050  * Write lock is needed to ensure that unused parent rules
1051  * are not freed by other instance (see stage 2, 3)
1052  */
1053 static void
1054 check_dyn_rules(struct ip_fw_chain *chain, ipfw_range_tlv *rt,
1055     int check_ka, int timer)
1056 {
1057 	struct mbuf *m0, *m, *mnext, **mtailp;
1058 	struct ip *h;
1059 	int i, dyn_count, new_buckets = 0, max_buckets;
1060 	int expired = 0, expired_limits = 0, parents = 0, total = 0;
1061 	ipfw_dyn_rule *q, *q_prev, *q_next;
1062 	ipfw_dyn_rule *exp_head, **exptailp;
1063 	ipfw_dyn_rule *exp_lhead, **expltailp;
1064 
1065 	KASSERT(V_ipfw_dyn_v != NULL, ("%s: dynamic table not allocated",
1066 	    __func__));
1067 
1068 	/* Avoid possible LOR */
1069 	KASSERT(!check_ka || timer, ("%s: keepalive check with lock held",
1070 	    __func__));
1071 
1072 	/*
1073 	 * Do not perform any checks if we currently have no dynamic states
1074 	 */
1075 	if (DYN_COUNT == 0)
1076 		return;
1077 
1078 	/* Expired states */
1079 	exp_head = NULL;
1080 	exptailp = &exp_head;
1081 
1082 	/* Expired limit states */
1083 	exp_lhead = NULL;
1084 	expltailp = &exp_lhead;
1085 
1086 	/*
1087 	 * We make a chain of packets to go out here -- not deferring
1088 	 * until after we drop the IPFW dynamic rule lock would result
1089 	 * in a lock order reversal with the normal packet input -> ipfw
1090 	 * call stack.
1091 	 */
1092 	m0 = NULL;
1093 	mtailp = &m0;
1094 
1095 	/* Protect from hash resizing */
1096 	if (timer != 0)
1097 		IPFW_UH_WLOCK(chain);
1098 	else
1099 		IPFW_UH_WLOCK_ASSERT(chain);
1100 
1101 #define	NEXT_RULE()	{ q_prev = q; q = q->next ; continue; }
1102 
1103 	/* Stage 1: perform requested deletion */
1104 	for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
1105 		IPFW_BUCK_LOCK(i);
1106 		for (q = V_ipfw_dyn_v[i].head, q_prev = q; q ; ) {
1107 			/* account every rule */
1108 			total++;
1109 
1110 			/* Skip parent rules at all */
1111 			if (q->dyn_type == O_LIMIT_PARENT) {
1112 				parents++;
1113 				NEXT_RULE();
1114 			}
1115 
1116 			/*
1117 			 * Remove rules which are:
1118 			 * 1) expired
1119 			 * 2) matches deletion range
1120 			 */
1121 			if ((TIME_LEQ(q->expire, time_uptime)) ||
1122 			    (rt != NULL && ipfw_match_range(q->rule, rt))) {
1123 				if (TIME_LE(time_uptime, q->expire) &&
1124 				    q->dyn_type == O_KEEP_STATE &&
1125 				    V_dyn_keep_states != 0) {
1126 					/*
1127 					 * Do not delete state if
1128 					 * it is not expired and
1129 					 * dyn_keep_states is ON.
1130 					 * However we need to re-link it
1131 					 * to any other stable rule
1132 					 */
1133 					q->rule = chain->default_rule;
1134 					NEXT_RULE();
1135 				}
1136 
1137 				/* Unlink q from current list */
1138 				q_next = q->next;
1139 				if (q == V_ipfw_dyn_v[i].head)
1140 					V_ipfw_dyn_v[i].head = q_next;
1141 				else
1142 					q_prev->next = q_next;
1143 
1144 				q->next = NULL;
1145 
1146 				/* queue q to expire list */
1147 				if (q->dyn_type != O_LIMIT) {
1148 					*exptailp = q;
1149 					exptailp = &(*exptailp)->next;
1150 					DEB(print_dyn_rule(&q->id, q->dyn_type,
1151 					    "unlink entry", "left");
1152 					)
1153 				} else {
1154 					/* Separate list for limit rules */
1155 					*expltailp = q;
1156 					expltailp = &(*expltailp)->next;
1157 					expired_limits++;
1158 					DEB(print_dyn_rule(&q->id, q->dyn_type,
1159 					    "unlink limit entry", "left");
1160 					)
1161 				}
1162 
1163 				q = q_next;
1164 				expired++;
1165 				continue;
1166 			}
1167 
1168 			/*
1169 			 * Check if we need to send keepalive:
1170 			 * we need to ensure if is time to do KA,
1171 			 * this is established TCP session, and
1172 			 * expire time is within keepalive interval
1173 			 */
1174 			if ((check_ka != 0) && (q->id.proto == IPPROTO_TCP) &&
1175 			    ((q->state & BOTH_SYN) == BOTH_SYN) &&
1176 			    (TIME_LEQ(q->expire, time_uptime +
1177 			      V_dyn_keepalive_interval)))
1178 				mtailp = ipfw_dyn_send_ka(mtailp, q);
1179 
1180 			NEXT_RULE();
1181 		}
1182 		IPFW_BUCK_UNLOCK(i);
1183 	}
1184 
1185 	/* Stage 2: decrement counters from O_LIMIT parents */
1186 	if (expired_limits != 0) {
1187 		/*
1188 		 * XXX: Note that deleting set with more than one
1189 		 * heavily-used LIMIT rules can result in overwhelming
1190 		 * locking due to lack of per-hash value sorting
1191 		 *
1192 		 * We should probably think about:
1193 		 * 1) pre-allocating hash of size, say,
1194 		 * MAX(16, V_curr_dyn_buckets / 1024)
1195 		 * 2) checking if expired_limits is large enough
1196 		 * 3) If yes, init hash (or its part), re-link
1197 		 * current list and start decrementing procedure in
1198 		 * each bucket separately
1199 		 */
1200 
1201 		/*
1202 		 * Small optimization: do not unlock bucket until
1203 		 * we see the next item resides in different bucket
1204 		 */
1205 		if (exp_lhead != NULL) {
1206 			i = exp_lhead->parent->bucket;
1207 			IPFW_BUCK_LOCK(i);
1208 		}
1209 		for (q = exp_lhead; q != NULL; q = q->next) {
1210 			if (i != q->parent->bucket) {
1211 				IPFW_BUCK_UNLOCK(i);
1212 				i = q->parent->bucket;
1213 				IPFW_BUCK_LOCK(i);
1214 			}
1215 
1216 			/* Decrease parent refcount */
1217 			q->parent->count--;
1218 		}
1219 		if (exp_lhead != NULL)
1220 			IPFW_BUCK_UNLOCK(i);
1221 	}
1222 
1223 	/*
1224 	 * We protectet ourselves from unused parent deletion
1225 	 * (from the timer function) by holding UH write lock.
1226 	 */
1227 
1228 	/* Stage 3: remove unused parent rules */
1229 	if ((parents != 0) && (expired != 0)) {
1230 		for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
1231 			IPFW_BUCK_LOCK(i);
1232 			for (q = V_ipfw_dyn_v[i].head, q_prev = q ; q ; ) {
1233 				if (q->dyn_type != O_LIMIT_PARENT)
1234 					NEXT_RULE();
1235 
1236 				if (q->count != 0)
1237 					NEXT_RULE();
1238 
1239 				/* Parent rule without consumers */
1240 
1241 				/* Unlink q from current list */
1242 				q_next = q->next;
1243 				if (q == V_ipfw_dyn_v[i].head)
1244 					V_ipfw_dyn_v[i].head = q_next;
1245 				else
1246 					q_prev->next = q_next;
1247 
1248 				q->next = NULL;
1249 
1250 				/* Add to expired list */
1251 				*exptailp = q;
1252 				exptailp = &(*exptailp)->next;
1253 
1254 				DEB(print_dyn_rule(&q->id, q->dyn_type,
1255 				    "unlink parent entry", "left");
1256 				)
1257 
1258 				expired++;
1259 
1260 				q = q_next;
1261 			}
1262 			IPFW_BUCK_UNLOCK(i);
1263 		}
1264 	}
1265 
1266 #undef NEXT_RULE
1267 
1268 	if (timer != 0) {
1269 		/*
1270 		 * Check if we need to resize hash:
1271 		 * if current number of states exceeds number of buckes in hash,
1272 		 * grow hash size to the minimum power of 2 which is bigger than
1273 		 * current states count. Limit hash size by 64k.
1274 		 */
1275 		max_buckets = (V_dyn_buckets_max > 65536) ?
1276 		    65536 : V_dyn_buckets_max;
1277 
1278 		dyn_count = DYN_COUNT;
1279 
1280 		if ((dyn_count > V_curr_dyn_buckets * 2) &&
1281 		    (dyn_count < max_buckets)) {
1282 			new_buckets = V_curr_dyn_buckets;
1283 			while (new_buckets < dyn_count) {
1284 				new_buckets *= 2;
1285 
1286 				if (new_buckets >= max_buckets)
1287 					break;
1288 			}
1289 		}
1290 
1291 		IPFW_UH_WUNLOCK(chain);
1292 	}
1293 
1294 	/* Finally delete old states ad limits if any */
1295 	for (q = exp_head; q != NULL; q = q_next) {
1296 		q_next = q->next;
1297 		uma_zfree(V_ipfw_dyn_rule_zone, q);
1298 		ipfw_dyn_count--;
1299 	}
1300 
1301 	for (q = exp_lhead; q != NULL; q = q_next) {
1302 		q_next = q->next;
1303 		uma_zfree(V_ipfw_dyn_rule_zone, q);
1304 		ipfw_dyn_count--;
1305 	}
1306 
1307 	/*
1308 	 * The rest code MUST be called from timer routine only
1309 	 * without holding any locks
1310 	 */
1311 	if (timer == 0)
1312 		return;
1313 
1314 	/* Send keepalive packets if any */
1315 	for (m = m0; m != NULL; m = mnext) {
1316 		mnext = m->m_nextpkt;
1317 		m->m_nextpkt = NULL;
1318 		h = mtod(m, struct ip *);
1319 		if (h->ip_v == 4)
1320 			ip_output(m, NULL, NULL, 0, NULL, NULL);
1321 #ifdef INET6
1322 		else
1323 			ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
1324 #endif
1325 	}
1326 
1327 	/* Run table resize without holding any locks */
1328 	if (new_buckets != 0)
1329 		resize_dynamic_table(chain, new_buckets);
1330 }
1331 
1332 /*
1333  * Deletes all dynamic rules originated by given rule or all rules in
1334  * given set. Specify RESVD_SET to indicate set should not be used.
1335  * @chain - pointer to current ipfw rules chain
1336  * @rr - delete all states originated by rules in matched range.
1337  *
1338  * Function has to be called with IPFW_UH_WLOCK held.
1339  * Additionally, function assume that dynamic rule/set is
1340  * ALREADY deleted so no new states can be generated by
1341  * 'deleted' rules.
1342  */
1343 void
1344 ipfw_expire_dyn_rules(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
1345 {
1346 
1347 	check_dyn_rules(chain, rt, 0, 0);
1348 }
1349 
1350 /*
1351  * Check if rule contains at least one dynamic opcode.
1352  *
1353  * Returns 1 if such opcode is found, 0 otherwise.
1354  */
1355 int
1356 ipfw_is_dyn_rule(struct ip_fw *rule)
1357 {
1358 	int cmdlen, l;
1359 	ipfw_insn *cmd;
1360 
1361 	l = rule->cmd_len;
1362 	cmd = rule->cmd;
1363 	cmdlen = 0;
1364 	for ( ;	l > 0 ; l -= cmdlen, cmd += cmdlen) {
1365 		cmdlen = F_LEN(cmd);
1366 
1367 		switch (cmd->opcode) {
1368 		case O_LIMIT:
1369 		case O_KEEP_STATE:
1370 		case O_PROBE_STATE:
1371 		case O_CHECK_STATE:
1372 			return (1);
1373 		}
1374 	}
1375 
1376 	return (0);
1377 }
1378 
1379 void
1380 ipfw_dyn_init(struct ip_fw_chain *chain)
1381 {
1382 
1383         V_ipfw_dyn_v = NULL;
1384         V_dyn_buckets_max = 256; /* must be power of 2 */
1385         V_curr_dyn_buckets = 256; /* must be power of 2 */
1386 
1387         V_dyn_ack_lifetime = 300;
1388         V_dyn_syn_lifetime = 20;
1389         V_dyn_fin_lifetime = 1;
1390         V_dyn_rst_lifetime = 1;
1391         V_dyn_udp_lifetime = 10;
1392         V_dyn_short_lifetime = 5;
1393 
1394         V_dyn_keepalive_interval = 20;
1395         V_dyn_keepalive_period = 5;
1396         V_dyn_keepalive = 1;    /* do send keepalives */
1397 	V_dyn_keepalive_last = time_uptime;
1398 
1399         V_dyn_max = 16384; /* max # of dynamic rules */
1400 
1401 	V_ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
1402 	    sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
1403 	    UMA_ALIGN_PTR, 0);
1404 
1405 	/* Enforce limit on dynamic rules */
1406 	uma_zone_set_max(V_ipfw_dyn_rule_zone, V_dyn_max);
1407 
1408         callout_init(&V_ipfw_timeout, 1);
1409 
1410 	/*
1411 	 * This can potentially be done on first dynamic rule
1412 	 * being added to chain.
1413 	 */
1414 	resize_dynamic_table(chain, V_curr_dyn_buckets);
1415 }
1416 
1417 void
1418 ipfw_dyn_uninit(int pass)
1419 {
1420 	int i;
1421 
1422 	if (pass == 0) {
1423 		callout_drain(&V_ipfw_timeout);
1424 		return;
1425 	}
1426 
1427 	if (V_ipfw_dyn_v != NULL) {
1428 		/*
1429 		 * Skip deleting all dynamic states -
1430 		 * uma_zdestroy() does this more efficiently;
1431 		 */
1432 
1433 		/* Destroy all mutexes */
1434 		for (i = 0 ; i < V_curr_dyn_buckets ; i++)
1435 			IPFW_BUCK_LOCK_DESTROY(&V_ipfw_dyn_v[i]);
1436 		free(V_ipfw_dyn_v, M_IPFW);
1437 		V_ipfw_dyn_v = NULL;
1438 	}
1439 
1440         uma_zdestroy(V_ipfw_dyn_rule_zone);
1441 }
1442 
1443 #ifdef SYSCTL_NODE
1444 /*
1445  * Get/set maximum number of dynamic states in given VNET instance.
1446  */
1447 static int
1448 sysctl_ipfw_dyn_max(SYSCTL_HANDLER_ARGS)
1449 {
1450 	int error;
1451 	unsigned int nstates;
1452 
1453 	nstates = V_dyn_max;
1454 
1455 	error = sysctl_handle_int(oidp, &nstates, 0, req);
1456 	/* Read operation or some error */
1457 	if ((error != 0) || (req->newptr == NULL))
1458 		return (error);
1459 
1460 	V_dyn_max = nstates;
1461 	uma_zone_set_max(V_ipfw_dyn_rule_zone, V_dyn_max);
1462 
1463 	return (0);
1464 }
1465 
1466 /*
1467  * Get current number of dynamic states in given VNET instance.
1468  */
1469 static int
1470 sysctl_ipfw_dyn_count(SYSCTL_HANDLER_ARGS)
1471 {
1472 	int error;
1473 	unsigned int nstates;
1474 
1475 	nstates = DYN_COUNT;
1476 
1477 	error = sysctl_handle_int(oidp, &nstates, 0, req);
1478 
1479 	return (error);
1480 }
1481 #endif
1482 
1483 /*
1484  * Returns size of dynamic states in legacy format
1485  */
1486 int
1487 ipfw_dyn_len(void)
1488 {
1489 
1490 	return (V_ipfw_dyn_v == NULL) ? 0 :
1491 		(DYN_COUNT * sizeof(ipfw_dyn_rule));
1492 }
1493 
1494 /*
1495  * Returns number of dynamic states.
1496  * Used by dump format v1 (current).
1497  */
1498 int
1499 ipfw_dyn_get_count(void)
1500 {
1501 
1502 	return (V_ipfw_dyn_v == NULL) ? 0 : DYN_COUNT;
1503 }
1504 
1505 static void
1506 export_dyn_rule(ipfw_dyn_rule *src, ipfw_dyn_rule *dst)
1507 {
1508 
1509 	memcpy(dst, src, sizeof(*src));
1510 	memcpy(&(dst->rule), &(src->rule->rulenum), sizeof(src->rule->rulenum));
1511 	/*
1512 	 * store set number into high word of
1513 	 * dst->rule pointer.
1514 	 */
1515 	memcpy((char *)&dst->rule + sizeof(src->rule->rulenum),
1516 	    &(src->rule->set), sizeof(src->rule->set));
1517 	/*
1518 	 * store a non-null value in "next".
1519 	 * The userland code will interpret a
1520 	 * NULL here as a marker
1521 	 * for the last dynamic rule.
1522 	 */
1523 	memcpy(&dst->next, &dst, sizeof(dst));
1524 	dst->expire =
1525 	    TIME_LEQ(dst->expire, time_uptime) ?  0 : dst->expire - time_uptime;
1526 }
1527 
1528 /*
1529  * Fills int buffer given by @sd with dynamic states.
1530  * Used by dump format v1 (current).
1531  *
1532  * Returns 0 on success.
1533  */
1534 int
1535 ipfw_dump_states(struct ip_fw_chain *chain, struct sockopt_data *sd)
1536 {
1537 	ipfw_dyn_rule *p;
1538 	ipfw_obj_dyntlv *dst, *last;
1539 	ipfw_obj_ctlv *ctlv;
1540 	int i;
1541 	size_t sz;
1542 
1543 	if (V_ipfw_dyn_v == NULL)
1544 		return (0);
1545 
1546 	IPFW_UH_RLOCK_ASSERT(chain);
1547 
1548 	ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
1549 	if (ctlv == NULL)
1550 		return (ENOMEM);
1551 	sz = sizeof(ipfw_obj_dyntlv);
1552 	ctlv->head.type = IPFW_TLV_DYNSTATE_LIST;
1553 	ctlv->objsize = sz;
1554 	last = NULL;
1555 
1556 	for (i = 0 ; i < V_curr_dyn_buckets; i++) {
1557 		IPFW_BUCK_LOCK(i);
1558 		for (p = V_ipfw_dyn_v[i].head ; p != NULL; p = p->next) {
1559 			dst = (ipfw_obj_dyntlv *)ipfw_get_sopt_space(sd, sz);
1560 			if (dst == NULL) {
1561 				IPFW_BUCK_UNLOCK(i);
1562 				return (ENOMEM);
1563 			}
1564 
1565 			export_dyn_rule(p, &dst->state);
1566 			dst->head.length = sz;
1567 			dst->head.type = IPFW_TLV_DYN_ENT;
1568 			last = dst;
1569 		}
1570 		IPFW_BUCK_UNLOCK(i);
1571 	}
1572 
1573 	if (last != NULL) /* mark last dynamic rule */
1574 		last->head.flags = IPFW_DF_LAST;
1575 
1576 	return (0);
1577 }
1578 
1579 /*
1580  * Fill given buffer with dynamic states (legacy format).
1581  * IPFW_UH_RLOCK has to be held while calling.
1582  */
1583 void
1584 ipfw_get_dynamic(struct ip_fw_chain *chain, char **pbp, const char *ep)
1585 {
1586 	ipfw_dyn_rule *p, *last = NULL;
1587 	char *bp;
1588 	int i;
1589 
1590 	if (V_ipfw_dyn_v == NULL)
1591 		return;
1592 	bp = *pbp;
1593 
1594 	IPFW_UH_RLOCK_ASSERT(chain);
1595 
1596 	for (i = 0 ; i < V_curr_dyn_buckets; i++) {
1597 		IPFW_BUCK_LOCK(i);
1598 		for (p = V_ipfw_dyn_v[i].head ; p != NULL; p = p->next) {
1599 			if (bp + sizeof *p <= ep) {
1600 				ipfw_dyn_rule *dst =
1601 					(ipfw_dyn_rule *)bp;
1602 
1603 				export_dyn_rule(p, dst);
1604 				last = dst;
1605 				bp += sizeof(ipfw_dyn_rule);
1606 			}
1607 		}
1608 		IPFW_BUCK_UNLOCK(i);
1609 	}
1610 
1611 	if (last != NULL) /* mark last dynamic rule */
1612 		bzero(&last->next, sizeof(last));
1613 	*pbp = bp;
1614 }
1615 /* end of file */
1616