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