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