1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2017-2018 Yandex LLC
5  * Copyright (c) 2017-2018 Andrey V. Elsukov <[email protected]>
6  * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32 
33 #include "opt_inet.h"
34 #include "opt_inet6.h"
35 #include "opt_ipfw.h"
36 #ifndef INET
37 #error IPFIREWALL requires INET.
38 #endif /* INET */
39 
40 #include <sys/param.h>
41 #include <sys/systm.h>
42 #include <sys/hash.h>
43 #include <sys/mbuf.h>
44 #include <sys/kernel.h>
45 #include <sys/lock.h>
46 #include <sys/pcpu.h>
47 #include <sys/queue.h>
48 #include <sys/rmlock.h>
49 #include <sys/smp.h>
50 #include <sys/socket.h>
51 #include <sys/sysctl.h>
52 #include <sys/syslog.h>
53 #include <net/ethernet.h>
54 #include <net/if.h>
55 #include <net/if_var.h>
56 #include <net/pfil.h>
57 #include <net/vnet.h>
58 
59 #include <netinet/in.h>
60 #include <netinet/ip.h>
61 #include <netinet/ip_var.h>
62 #include <netinet/ip_fw.h>
63 #include <netinet/tcp_var.h>
64 #include <netinet/udp.h>
65 
66 #include <netinet/ip6.h>	/* IN6_ARE_ADDR_EQUAL */
67 #ifdef INET6
68 #include <netinet6/in6_var.h>
69 #include <netinet6/ip6_var.h>
70 #include <netinet6/scope6_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 states.
83  *
84  * Dynamic states are stored in lists accessed through a hash tables
85  * whose size is curr_dyn_buckets. This value can be modified through
86  * the sysctl variable dyn_buckets.
87  *
88  * Currently there are four tables: dyn_ipv4, dyn_ipv6, dyn_ipv4_parent,
89  * and dyn_ipv6_parent.
90  *
91  * When a packet is received, its address fields hashed, then matched
92  * against the entries in the corresponding list by addr_type.
93  * Dynamic states can be used for different purposes:
94  *  + stateful rules;
95  *  + enforcing limits on the number of sessions;
96  *  + in-kernel NAT (not implemented yet)
97  *
98  * The lifetime of dynamic states is regulated by dyn_*_lifetime,
99  * measured in seconds and depending on the flags.
100  *
101  * The total number of dynamic states is equal to UMA zone items count.
102  * The max number of dynamic states is dyn_max. When we reach
103  * the maximum number of rules we do not create anymore. This is
104  * done to avoid consuming too much memory, but also too much
105  * time when searching on each packet (ideally, we should try instead
106  * to put a limit on the length of the list on each bucket...).
107  *
108  * Each state holds a pointer to the parent ipfw rule so we know what
109  * action to perform. Dynamic rules are removed when the parent rule is
110  * deleted.
111  *
112  * There are some limitations with dynamic rules -- we do not
113  * obey the 'randomized match', and we do not do multiple
114  * passes through the firewall. XXX check the latter!!!
115  */
116 
117 /* By default use jenkins hash function */
118 #define	IPFIREWALL_JENKINSHASH
119 
120 #define	DYN_COUNTER_INC(d, dir, pktlen)	do {	\
121 	(d)->pcnt_ ## dir++;			\
122 	(d)->bcnt_ ## dir += pktlen;		\
123 	} while (0)
124 
125 #define	DYN_REFERENCED		0x01
126 /*
127  * DYN_REFERENCED flag is used to show that state keeps reference to named
128  * object, and this reference should be released when state becomes expired.
129  */
130 
131 struct dyn_data {
132 	void		*parent;	/* pointer to parent rule */
133 	uint32_t	chain_id;	/* cached ruleset id */
134 	uint32_t	f_pos;		/* cached rule index */
135 
136 	uint32_t	hashval;	/* hash value used for hash resize */
137 	uint16_t	fibnum;		/* fib used to send keepalives */
138 	uint8_t		_pad[3];
139 	uint8_t		flags;		/* internal flags */
140 	uint16_t	rulenum;	/* parent rule number */
141 	uint32_t	ruleid;		/* parent rule id */
142 
143 	uint32_t	state;		/* TCP session state and flags */
144 	uint32_t	ack_fwd;	/* most recent ACKs in forward */
145 	uint32_t	ack_rev;	/* and reverse direction (used */
146 					/* to generate keepalives) */
147 	uint32_t	sync;		/* synchronization time */
148 	uint32_t	expire;		/* expire time */
149 
150 	uint64_t	pcnt_fwd;	/* bytes counter in forward */
151 	uint64_t	bcnt_fwd;	/* packets counter in forward */
152 	uint64_t	pcnt_rev;	/* bytes counter in reverse */
153 	uint64_t	bcnt_rev;	/* packets counter in reverse */
154 };
155 
156 #define	DPARENT_COUNT_DEC(p)	do {			\
157 	MPASS(p->count > 0);				\
158 	ck_pr_dec_32(&(p)->count);			\
159 } while (0)
160 #define	DPARENT_COUNT_INC(p)	ck_pr_inc_32(&(p)->count)
161 #define	DPARENT_COUNT(p)	ck_pr_load_32(&(p)->count)
162 struct dyn_parent {
163 	void		*parent;	/* pointer to parent rule */
164 	uint32_t	count;		/* number of linked states */
165 	uint8_t		_pad[2];
166 	uint16_t	rulenum;	/* parent rule number */
167 	uint32_t	ruleid;		/* parent rule id */
168 	uint32_t	hashval;	/* hash value used for hash resize */
169 	uint32_t	expire;		/* expire time */
170 };
171 
172 struct dyn_ipv4_state {
173 	uint8_t		type;		/* State type */
174 	uint8_t		proto;		/* UL Protocol */
175 	uint16_t	kidx;		/* named object index */
176 	uint16_t	sport, dport;	/* ULP source and destination ports */
177 	in_addr_t	src, dst;	/* IPv4 source and destination */
178 
179 	union {
180 		struct dyn_data	*data;
181 		struct dyn_parent *limit;
182 	};
183 	CK_SLIST_ENTRY(dyn_ipv4_state)	entry;
184 	SLIST_ENTRY(dyn_ipv4_state)	expired;
185 };
186 CK_SLIST_HEAD(dyn_ipv4ck_slist, dyn_ipv4_state);
187 VNET_DEFINE_STATIC(struct dyn_ipv4ck_slist *, dyn_ipv4);
188 VNET_DEFINE_STATIC(struct dyn_ipv4ck_slist *, dyn_ipv4_parent);
189 
190 SLIST_HEAD(dyn_ipv4_slist, dyn_ipv4_state);
191 VNET_DEFINE_STATIC(struct dyn_ipv4_slist, dyn_expired_ipv4);
192 #define	V_dyn_ipv4			VNET(dyn_ipv4)
193 #define	V_dyn_ipv4_parent		VNET(dyn_ipv4_parent)
194 #define	V_dyn_expired_ipv4		VNET(dyn_expired_ipv4)
195 
196 #ifdef INET6
197 struct dyn_ipv6_state {
198 	uint8_t		type;		/* State type */
199 	uint8_t		proto;		/* UL Protocol */
200 	uint16_t	kidx;		/* named object index */
201 	uint16_t	sport, dport;	/* ULP source and destination ports */
202 	struct in6_addr	src, dst;	/* IPv6 source and destination */
203 	uint32_t	zoneid;		/* IPv6 scope zone id */
204 	union {
205 		struct dyn_data	*data;
206 		struct dyn_parent *limit;
207 	};
208 	CK_SLIST_ENTRY(dyn_ipv6_state)	entry;
209 	SLIST_ENTRY(dyn_ipv6_state)	expired;
210 };
211 CK_SLIST_HEAD(dyn_ipv6ck_slist, dyn_ipv6_state);
212 VNET_DEFINE_STATIC(struct dyn_ipv6ck_slist *, dyn_ipv6);
213 VNET_DEFINE_STATIC(struct dyn_ipv6ck_slist *, dyn_ipv6_parent);
214 
215 SLIST_HEAD(dyn_ipv6_slist, dyn_ipv6_state);
216 VNET_DEFINE_STATIC(struct dyn_ipv6_slist, dyn_expired_ipv6);
217 #define	V_dyn_ipv6			VNET(dyn_ipv6)
218 #define	V_dyn_ipv6_parent		VNET(dyn_ipv6_parent)
219 #define	V_dyn_expired_ipv6		VNET(dyn_expired_ipv6)
220 #endif /* INET6 */
221 
222 /*
223  * Per-CPU pointer indicates that specified state is currently in use
224  * and must not be reclaimed by expiration callout.
225  */
226 static void **dyn_hp_cache;
227 DPCPU_DEFINE_STATIC(void *, dyn_hp);
228 #define	DYNSTATE_GET(cpu)	ck_pr_load_ptr(DPCPU_ID_PTR((cpu), dyn_hp))
229 #define	DYNSTATE_PROTECT(v)	ck_pr_store_ptr(DPCPU_PTR(dyn_hp), (v))
230 #define	DYNSTATE_RELEASE()	DYNSTATE_PROTECT(NULL)
231 #define	DYNSTATE_CRITICAL_ENTER()	critical_enter()
232 #define	DYNSTATE_CRITICAL_EXIT()	do {	\
233 	DYNSTATE_RELEASE();			\
234 	critical_exit();			\
235 } while (0);
236 
237 /*
238  * We keep two version numbers, one is updated when new entry added to
239  * the list. Second is updated when an entry deleted from the list.
240  * Versions are updated under bucket lock.
241  *
242  * Bucket "add" version number is used to know, that in the time between
243  * state lookup (i.e. ipfw_dyn_lookup_state()) and the followed state
244  * creation (i.e. ipfw_dyn_install_state()) another concurrent thread did
245  * not install some state in this bucket. Using this info we can avoid
246  * additional state lookup, because we are sure that we will not install
247  * the state twice.
248  *
249  * Also doing the tracking of bucket "del" version during lookup we can
250  * be sure, that state entry was not unlinked and freed in time between
251  * we read the state pointer and protect it with hazard pointer.
252  *
253  * An entry unlinked from CK list keeps unchanged until it is freed.
254  * Unlinked entries are linked into expired lists using "expired" field.
255  */
256 
257 /*
258  * dyn_expire_lock is used to protect access to dyn_expired_xxx lists.
259  * dyn_bucket_lock is used to get write access to lists in specific bucket.
260  * Currently one dyn_bucket_lock is used for all ipv4, ipv4_parent, ipv6,
261  * and ipv6_parent lists.
262  */
263 VNET_DEFINE_STATIC(struct mtx, dyn_expire_lock);
264 VNET_DEFINE_STATIC(struct mtx *, dyn_bucket_lock);
265 #define	V_dyn_expire_lock		VNET(dyn_expire_lock)
266 #define	V_dyn_bucket_lock		VNET(dyn_bucket_lock)
267 
268 /*
269  * Bucket's add/delete generation versions.
270  */
271 VNET_DEFINE_STATIC(uint32_t *, dyn_ipv4_add);
272 VNET_DEFINE_STATIC(uint32_t *, dyn_ipv4_del);
273 VNET_DEFINE_STATIC(uint32_t *, dyn_ipv4_parent_add);
274 VNET_DEFINE_STATIC(uint32_t *, dyn_ipv4_parent_del);
275 #define	V_dyn_ipv4_add			VNET(dyn_ipv4_add)
276 #define	V_dyn_ipv4_del			VNET(dyn_ipv4_del)
277 #define	V_dyn_ipv4_parent_add		VNET(dyn_ipv4_parent_add)
278 #define	V_dyn_ipv4_parent_del		VNET(dyn_ipv4_parent_del)
279 
280 #ifdef INET6
281 VNET_DEFINE_STATIC(uint32_t *, dyn_ipv6_add);
282 VNET_DEFINE_STATIC(uint32_t *, dyn_ipv6_del);
283 VNET_DEFINE_STATIC(uint32_t *, dyn_ipv6_parent_add);
284 VNET_DEFINE_STATIC(uint32_t *, dyn_ipv6_parent_del);
285 #define	V_dyn_ipv6_add			VNET(dyn_ipv6_add)
286 #define	V_dyn_ipv6_del			VNET(dyn_ipv6_del)
287 #define	V_dyn_ipv6_parent_add		VNET(dyn_ipv6_parent_add)
288 #define	V_dyn_ipv6_parent_del		VNET(dyn_ipv6_parent_del)
289 #endif /* INET6 */
290 
291 #define	DYN_BUCKET(h, b)		((h) & (b - 1))
292 #define	DYN_BUCKET_VERSION(b, v)	ck_pr_load_32(&V_dyn_ ## v[(b)])
293 #define	DYN_BUCKET_VERSION_BUMP(b, v)	ck_pr_inc_32(&V_dyn_ ## v[(b)])
294 
295 #define	DYN_BUCKET_LOCK_INIT(lock, b)		\
296     mtx_init(&lock[(b)], "IPFW dynamic bucket", NULL, MTX_DEF)
297 #define	DYN_BUCKET_LOCK_DESTROY(lock, b)	mtx_destroy(&lock[(b)])
298 #define	DYN_BUCKET_LOCK(b)	mtx_lock(&V_dyn_bucket_lock[(b)])
299 #define	DYN_BUCKET_UNLOCK(b)	mtx_unlock(&V_dyn_bucket_lock[(b)])
300 #define	DYN_BUCKET_ASSERT(b)	mtx_assert(&V_dyn_bucket_lock[(b)], MA_OWNED)
301 
302 #define	DYN_EXPIRED_LOCK_INIT()		\
303     mtx_init(&V_dyn_expire_lock, "IPFW expired states list", NULL, MTX_DEF)
304 #define	DYN_EXPIRED_LOCK_DESTROY()	mtx_destroy(&V_dyn_expire_lock)
305 #define	DYN_EXPIRED_LOCK()		mtx_lock(&V_dyn_expire_lock)
306 #define	DYN_EXPIRED_UNLOCK()		mtx_unlock(&V_dyn_expire_lock)
307 
308 VNET_DEFINE_STATIC(uint32_t, dyn_buckets_max);
309 VNET_DEFINE_STATIC(uint32_t, curr_dyn_buckets);
310 VNET_DEFINE_STATIC(struct callout, dyn_timeout);
311 #define	V_dyn_buckets_max		VNET(dyn_buckets_max)
312 #define	V_curr_dyn_buckets		VNET(curr_dyn_buckets)
313 #define	V_dyn_timeout			VNET(dyn_timeout)
314 
315 /* Maximum length of states chain in a bucket */
316 VNET_DEFINE_STATIC(uint32_t, curr_max_length);
317 #define	V_curr_max_length		VNET(curr_max_length)
318 
319 VNET_DEFINE_STATIC(uint32_t, dyn_keep_states);
320 #define	V_dyn_keep_states		VNET(dyn_keep_states)
321 
322 VNET_DEFINE_STATIC(uma_zone_t, dyn_data_zone);
323 VNET_DEFINE_STATIC(uma_zone_t, dyn_parent_zone);
324 VNET_DEFINE_STATIC(uma_zone_t, dyn_ipv4_zone);
325 #ifdef INET6
326 VNET_DEFINE_STATIC(uma_zone_t, dyn_ipv6_zone);
327 #define	V_dyn_ipv6_zone			VNET(dyn_ipv6_zone)
328 #endif /* INET6 */
329 #define	V_dyn_data_zone			VNET(dyn_data_zone)
330 #define	V_dyn_parent_zone		VNET(dyn_parent_zone)
331 #define	V_dyn_ipv4_zone			VNET(dyn_ipv4_zone)
332 
333 /*
334  * Timeouts for various events in handing dynamic rules.
335  */
336 VNET_DEFINE_STATIC(uint32_t, dyn_ack_lifetime);
337 VNET_DEFINE_STATIC(uint32_t, dyn_syn_lifetime);
338 VNET_DEFINE_STATIC(uint32_t, dyn_fin_lifetime);
339 VNET_DEFINE_STATIC(uint32_t, dyn_rst_lifetime);
340 VNET_DEFINE_STATIC(uint32_t, dyn_udp_lifetime);
341 VNET_DEFINE_STATIC(uint32_t, dyn_short_lifetime);
342 
343 #define	V_dyn_ack_lifetime		VNET(dyn_ack_lifetime)
344 #define	V_dyn_syn_lifetime		VNET(dyn_syn_lifetime)
345 #define	V_dyn_fin_lifetime		VNET(dyn_fin_lifetime)
346 #define	V_dyn_rst_lifetime		VNET(dyn_rst_lifetime)
347 #define	V_dyn_udp_lifetime		VNET(dyn_udp_lifetime)
348 #define	V_dyn_short_lifetime		VNET(dyn_short_lifetime)
349 
350 /*
351  * Keepalives are sent if dyn_keepalive is set. They are sent every
352  * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
353  * seconds of lifetime of a rule.
354  * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
355  * than dyn_keepalive_period.
356  */
357 VNET_DEFINE_STATIC(uint32_t, dyn_keepalive_interval);
358 VNET_DEFINE_STATIC(uint32_t, dyn_keepalive_period);
359 VNET_DEFINE_STATIC(uint32_t, dyn_keepalive);
360 VNET_DEFINE_STATIC(time_t, dyn_keepalive_last);
361 
362 #define	V_dyn_keepalive_interval	VNET(dyn_keepalive_interval)
363 #define	V_dyn_keepalive_period		VNET(dyn_keepalive_period)
364 #define	V_dyn_keepalive			VNET(dyn_keepalive)
365 #define	V_dyn_keepalive_last		VNET(dyn_keepalive_last)
366 
367 VNET_DEFINE_STATIC(uint32_t, dyn_max);		/* max # of dynamic states */
368 VNET_DEFINE_STATIC(uint32_t, dyn_count);	/* number of states */
369 VNET_DEFINE_STATIC(uint32_t, dyn_parent_max);	/* max # of parent states */
370 VNET_DEFINE_STATIC(uint32_t, dyn_parent_count);	/* number of parent states */
371 
372 #define	V_dyn_max			VNET(dyn_max)
373 #define	V_dyn_count			VNET(dyn_count)
374 #define	V_dyn_parent_max		VNET(dyn_parent_max)
375 #define	V_dyn_parent_count		VNET(dyn_parent_count)
376 
377 #define	DYN_COUNT_DEC(name)	do {			\
378 	MPASS((V_ ## name) > 0);			\
379 	ck_pr_dec_32(&(V_ ## name));			\
380 } while (0)
381 #define	DYN_COUNT_INC(name)	ck_pr_inc_32(&(V_ ## name))
382 #define	DYN_COUNT(name)		ck_pr_load_32(&(V_ ## name))
383 
384 static time_t last_log;	/* Log ratelimiting */
385 
386 /*
387  * Get/set maximum number of dynamic states in given VNET instance.
388  */
389 static int
sysctl_dyn_max(SYSCTL_HANDLER_ARGS)390 sysctl_dyn_max(SYSCTL_HANDLER_ARGS)
391 {
392 	uint32_t nstates;
393 	int error;
394 
395 	nstates = V_dyn_max;
396 	error = sysctl_handle_32(oidp, &nstates, 0, req);
397 	/* Read operation or some error */
398 	if ((error != 0) || (req->newptr == NULL))
399 		return (error);
400 
401 	V_dyn_max = nstates;
402 	uma_zone_set_max(V_dyn_data_zone, V_dyn_max);
403 	return (0);
404 }
405 
406 static int
sysctl_dyn_parent_max(SYSCTL_HANDLER_ARGS)407 sysctl_dyn_parent_max(SYSCTL_HANDLER_ARGS)
408 {
409 	uint32_t nstates;
410 	int error;
411 
412 	nstates = V_dyn_parent_max;
413 	error = sysctl_handle_32(oidp, &nstates, 0, req);
414 	/* Read operation or some error */
415 	if ((error != 0) || (req->newptr == NULL))
416 		return (error);
417 
418 	V_dyn_parent_max = nstates;
419 	uma_zone_set_max(V_dyn_parent_zone, V_dyn_parent_max);
420 	return (0);
421 }
422 
423 static int
sysctl_dyn_buckets(SYSCTL_HANDLER_ARGS)424 sysctl_dyn_buckets(SYSCTL_HANDLER_ARGS)
425 {
426 	uint32_t nbuckets;
427 	int error;
428 
429 	nbuckets = V_dyn_buckets_max;
430 	error = sysctl_handle_32(oidp, &nbuckets, 0, req);
431 	/* Read operation or some error */
432 	if ((error != 0) || (req->newptr == NULL))
433 		return (error);
434 
435 	if (nbuckets > 256)
436 		V_dyn_buckets_max = 1 << fls(nbuckets - 1);
437 	else
438 		return (EINVAL);
439 	return (0);
440 }
441 
442 SYSCTL_DECL(_net_inet_ip_fw);
443 
444 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_count,
445     CTLFLAG_VNET | CTLFLAG_RD, &VNET_NAME(dyn_count), 0,
446     "Current number of dynamic states.");
447 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_parent_count,
448     CTLFLAG_VNET | CTLFLAG_RD, &VNET_NAME(dyn_parent_count), 0,
449     "Current number of parent states. ");
450 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets,
451     CTLFLAG_VNET | CTLFLAG_RD, &VNET_NAME(curr_dyn_buckets), 0,
452     "Current number of buckets for states hash table.");
453 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, curr_max_length,
454     CTLFLAG_VNET | CTLFLAG_RD, &VNET_NAME(curr_max_length), 0,
455     "Current maximum length of states chains in hash buckets.");
456 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_buckets,
457     CTLFLAG_VNET | CTLTYPE_U32 | CTLFLAG_RW, 0, 0, sysctl_dyn_buckets,
458     "IU", "Max number of buckets for dynamic states hash table.");
459 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_max,
460     CTLFLAG_VNET | CTLTYPE_U32 | CTLFLAG_RW, 0, 0, sysctl_dyn_max,
461     "IU", "Max number of dynamic states.");
462 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_parent_max,
463     CTLFLAG_VNET | CTLTYPE_U32 | CTLFLAG_RW, 0, 0, sysctl_dyn_parent_max,
464     "IU", "Max number of parent dynamic states.");
465 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime,
466     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_ack_lifetime), 0,
467     "Lifetime of dynamic states for TCP ACK.");
468 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime,
469     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_syn_lifetime), 0,
470     "Lifetime of dynamic states for TCP SYN.");
471 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
472     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_fin_lifetime), 0,
473     "Lifetime of dynamic states for TCP FIN.");
474 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
475     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_rst_lifetime), 0,
476     "Lifetime of dynamic states for TCP RST.");
477 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime,
478     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_udp_lifetime), 0,
479     "Lifetime of dynamic states for UDP.");
480 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime,
481     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_short_lifetime), 0,
482     "Lifetime of dynamic states for other situations.");
483 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_keepalive,
484     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_keepalive), 0,
485     "Enable keepalives for dynamic states.");
486 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_keep_states,
487     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_keep_states), 0,
488     "Do not flush dynamic states on rule deletion");
489 
490 
491 #ifdef IPFIREWALL_DYNDEBUG
492 #define	DYN_DEBUG(fmt, ...)	do {			\
493 	printf("%s: " fmt "\n", __func__, __VA_ARGS__);	\
494 } while (0)
495 #else
496 #define	DYN_DEBUG(fmt, ...)
497 #endif /* !IPFIREWALL_DYNDEBUG */
498 
499 #ifdef INET6
500 /* Functions to work with IPv6 states */
501 static struct dyn_ipv6_state *dyn_lookup_ipv6_state(
502     const struct ipfw_flow_id *, uint32_t, const void *,
503     struct ipfw_dyn_info *, int);
504 static int dyn_lookup_ipv6_state_locked(const struct ipfw_flow_id *,
505     uint32_t, const void *, int, uint32_t, uint16_t);
506 static struct dyn_ipv6_state *dyn_alloc_ipv6_state(
507     const struct ipfw_flow_id *, uint32_t, uint16_t, uint8_t);
508 static int dyn_add_ipv6_state(void *, uint32_t, uint16_t,
509     const struct ipfw_flow_id *, uint32_t, const void *, int, uint32_t,
510     struct ipfw_dyn_info *, uint16_t, uint16_t, uint8_t);
511 static void dyn_export_ipv6_state(const struct dyn_ipv6_state *,
512     ipfw_dyn_rule *);
513 
514 static uint32_t dyn_getscopeid(const struct ip_fw_args *);
515 static void dyn_make_keepalive_ipv6(struct mbuf *, const struct in6_addr *,
516     const struct in6_addr *, uint32_t, uint32_t, uint32_t, uint16_t,
517     uint16_t);
518 static void dyn_enqueue_keepalive_ipv6(struct mbufq *,
519     const struct dyn_ipv6_state *);
520 static void dyn_send_keepalive_ipv6(struct ip_fw_chain *);
521 
522 static struct dyn_ipv6_state *dyn_lookup_ipv6_parent(
523     const struct ipfw_flow_id *, uint32_t, const void *, uint32_t, uint16_t,
524     uint32_t);
525 static struct dyn_ipv6_state *dyn_lookup_ipv6_parent_locked(
526     const struct ipfw_flow_id *, uint32_t, const void *, uint32_t, uint16_t,
527     uint32_t);
528 static struct dyn_ipv6_state *dyn_add_ipv6_parent(void *, uint32_t, uint16_t,
529     const struct ipfw_flow_id *, uint32_t, uint32_t, uint32_t, uint16_t);
530 #endif /* INET6 */
531 
532 /* Functions to work with limit states */
533 static void *dyn_get_parent_state(const struct ipfw_flow_id *, uint32_t,
534     struct ip_fw *, uint32_t, uint32_t, uint16_t);
535 static struct dyn_ipv4_state *dyn_lookup_ipv4_parent(
536     const struct ipfw_flow_id *, const void *, uint32_t, uint16_t, uint32_t);
537 static struct dyn_ipv4_state *dyn_lookup_ipv4_parent_locked(
538     const struct ipfw_flow_id *, const void *, uint32_t, uint16_t, uint32_t);
539 static struct dyn_parent *dyn_alloc_parent(void *, uint32_t, uint16_t,
540     uint32_t);
541 static struct dyn_ipv4_state *dyn_add_ipv4_parent(void *, uint32_t, uint16_t,
542     const struct ipfw_flow_id *, uint32_t, uint32_t, uint16_t);
543 
544 static void dyn_tick(void *);
545 static void dyn_expire_states(struct ip_fw_chain *, ipfw_range_tlv *);
546 static void dyn_free_states(struct ip_fw_chain *);
547 static void dyn_export_parent(const struct dyn_parent *, uint16_t, uint8_t,
548     ipfw_dyn_rule *);
549 static void dyn_export_data(const struct dyn_data *, uint16_t, uint8_t,
550     uint8_t, ipfw_dyn_rule *);
551 static uint32_t dyn_update_tcp_state(struct dyn_data *,
552     const struct ipfw_flow_id *, const struct tcphdr *, int);
553 static void dyn_update_proto_state(struct dyn_data *,
554     const struct ipfw_flow_id *, const void *, int, int);
555 
556 /* Functions to work with IPv4 states */
557 struct dyn_ipv4_state *dyn_lookup_ipv4_state(const struct ipfw_flow_id *,
558     const void *, struct ipfw_dyn_info *, int);
559 static int dyn_lookup_ipv4_state_locked(const struct ipfw_flow_id *,
560     const void *, int, uint32_t, uint16_t);
561 static struct dyn_ipv4_state *dyn_alloc_ipv4_state(
562     const struct ipfw_flow_id *, uint16_t, uint8_t);
563 static int dyn_add_ipv4_state(void *, uint32_t, uint16_t,
564     const struct ipfw_flow_id *, const void *, int, uint32_t,
565     struct ipfw_dyn_info *, uint16_t, uint16_t, uint8_t);
566 static void dyn_export_ipv4_state(const struct dyn_ipv4_state *,
567     ipfw_dyn_rule *);
568 
569 /*
570  * Named states support.
571  */
572 static char *default_state_name = "default";
573 struct dyn_state_obj {
574 	struct named_object	no;
575 	char			name[64];
576 };
577 
578 #define	DYN_STATE_OBJ(ch, cmd)	\
579     ((struct dyn_state_obj *)SRV_OBJECT(ch, (cmd)->arg1))
580 /*
581  * Classifier callback.
582  * Return 0 if opcode contains object that should be referenced
583  * or rewritten.
584  */
585 static int
dyn_classify(ipfw_insn * cmd,uint16_t * puidx,uint8_t * ptype)586 dyn_classify(ipfw_insn *cmd, uint16_t *puidx, uint8_t *ptype)
587 {
588 
589 	DYN_DEBUG("opcode %d, arg1 %d", cmd->opcode, cmd->arg1);
590 	/* Don't rewrite "check-state any" */
591 	if (cmd->arg1 == 0 &&
592 	    cmd->opcode == O_CHECK_STATE)
593 		return (1);
594 
595 	*puidx = cmd->arg1;
596 	*ptype = 0;
597 	return (0);
598 }
599 
600 static void
dyn_update(ipfw_insn * cmd,uint16_t idx)601 dyn_update(ipfw_insn *cmd, uint16_t idx)
602 {
603 
604 	cmd->arg1 = idx;
605 	DYN_DEBUG("opcode %d, arg1 %d", cmd->opcode, cmd->arg1);
606 }
607 
608 static int
dyn_findbyname(struct ip_fw_chain * ch,struct tid_info * ti,struct named_object ** pno)609 dyn_findbyname(struct ip_fw_chain *ch, struct tid_info *ti,
610     struct named_object **pno)
611 {
612 	ipfw_obj_ntlv *ntlv;
613 	const char *name;
614 
615 	DYN_DEBUG("uidx %d", ti->uidx);
616 	if (ti->uidx != 0) {
617 		if (ti->tlvs == NULL)
618 			return (EINVAL);
619 		/* Search ntlv in the buffer provided by user */
620 		ntlv = ipfw_find_name_tlv_type(ti->tlvs, ti->tlen, ti->uidx,
621 		    IPFW_TLV_STATE_NAME);
622 		if (ntlv == NULL)
623 			return (EINVAL);
624 		name = ntlv->name;
625 	} else
626 		name = default_state_name;
627 	/*
628 	 * Search named object with corresponding name.
629 	 * Since states objects are global - ignore the set value
630 	 * and use zero instead.
631 	 */
632 	*pno = ipfw_objhash_lookup_name_type(CHAIN_TO_SRV(ch), 0,
633 	    IPFW_TLV_STATE_NAME, name);
634 	/*
635 	 * We always return success here.
636 	 * The caller will check *pno and mark object as unresolved,
637 	 * then it will automatically create "default" object.
638 	 */
639 	return (0);
640 }
641 
642 static struct named_object *
dyn_findbykidx(struct ip_fw_chain * ch,uint16_t idx)643 dyn_findbykidx(struct ip_fw_chain *ch, uint16_t idx)
644 {
645 
646 	DYN_DEBUG("kidx %d", idx);
647 	return (ipfw_objhash_lookup_kidx(CHAIN_TO_SRV(ch), idx));
648 }
649 
650 static int
dyn_create(struct ip_fw_chain * ch,struct tid_info * ti,uint16_t * pkidx)651 dyn_create(struct ip_fw_chain *ch, struct tid_info *ti,
652     uint16_t *pkidx)
653 {
654 	struct namedobj_instance *ni;
655 	struct dyn_state_obj *obj;
656 	struct named_object *no;
657 	ipfw_obj_ntlv *ntlv;
658 	char *name;
659 
660 	DYN_DEBUG("uidx %d", ti->uidx);
661 	if (ti->uidx != 0) {
662 		if (ti->tlvs == NULL)
663 			return (EINVAL);
664 		ntlv = ipfw_find_name_tlv_type(ti->tlvs, ti->tlen, ti->uidx,
665 		    IPFW_TLV_STATE_NAME);
666 		if (ntlv == NULL)
667 			return (EINVAL);
668 		name = ntlv->name;
669 	} else
670 		name = default_state_name;
671 
672 	ni = CHAIN_TO_SRV(ch);
673 	obj = malloc(sizeof(*obj), M_IPFW, M_WAITOK | M_ZERO);
674 	obj->no.name = obj->name;
675 	obj->no.etlv = IPFW_TLV_STATE_NAME;
676 	strlcpy(obj->name, name, sizeof(obj->name));
677 
678 	IPFW_UH_WLOCK(ch);
679 	no = ipfw_objhash_lookup_name_type(ni, 0,
680 	    IPFW_TLV_STATE_NAME, name);
681 	if (no != NULL) {
682 		/*
683 		 * Object is already created.
684 		 * Just return its kidx and bump refcount.
685 		 */
686 		*pkidx = no->kidx;
687 		no->refcnt++;
688 		IPFW_UH_WUNLOCK(ch);
689 		free(obj, M_IPFW);
690 		DYN_DEBUG("\tfound kidx %d", *pkidx);
691 		return (0);
692 	}
693 	if (ipfw_objhash_alloc_idx(ni, &obj->no.kidx) != 0) {
694 		DYN_DEBUG("\talloc_idx failed for %s", name);
695 		IPFW_UH_WUNLOCK(ch);
696 		free(obj, M_IPFW);
697 		return (ENOSPC);
698 	}
699 	ipfw_objhash_add(ni, &obj->no);
700 	SRV_OBJECT(ch, obj->no.kidx) = obj;
701 	obj->no.refcnt++;
702 	*pkidx = obj->no.kidx;
703 	IPFW_UH_WUNLOCK(ch);
704 	DYN_DEBUG("\tcreated kidx %d", *pkidx);
705 	return (0);
706 }
707 
708 static void
dyn_destroy(struct ip_fw_chain * ch,struct named_object * no)709 dyn_destroy(struct ip_fw_chain *ch, struct named_object *no)
710 {
711 	struct dyn_state_obj *obj;
712 
713 	IPFW_UH_WLOCK_ASSERT(ch);
714 
715 	KASSERT(no->etlv == IPFW_TLV_STATE_NAME,
716 	    ("%s: wrong object type %u", __func__, no->etlv));
717 	KASSERT(no->refcnt == 1,
718 	    ("Destroying object '%s' (type %u, idx %u) with refcnt %u",
719 	    no->name, no->etlv, no->kidx, no->refcnt));
720 	DYN_DEBUG("kidx %d", no->kidx);
721 	obj = SRV_OBJECT(ch, no->kidx);
722 	SRV_OBJECT(ch, no->kidx) = NULL;
723 	ipfw_objhash_del(CHAIN_TO_SRV(ch), no);
724 	ipfw_objhash_free_idx(CHAIN_TO_SRV(ch), no->kidx);
725 
726 	free(obj, M_IPFW);
727 }
728 
729 static struct opcode_obj_rewrite dyn_opcodes[] = {
730 	{
731 		O_KEEP_STATE, IPFW_TLV_STATE_NAME,
732 		dyn_classify, dyn_update,
733 		dyn_findbyname, dyn_findbykidx,
734 		dyn_create, dyn_destroy
735 	},
736 	{
737 		O_CHECK_STATE, IPFW_TLV_STATE_NAME,
738 		dyn_classify, dyn_update,
739 		dyn_findbyname, dyn_findbykidx,
740 		dyn_create, dyn_destroy
741 	},
742 	{
743 		O_PROBE_STATE, IPFW_TLV_STATE_NAME,
744 		dyn_classify, dyn_update,
745 		dyn_findbyname, dyn_findbykidx,
746 		dyn_create, dyn_destroy
747 	},
748 	{
749 		O_LIMIT, IPFW_TLV_STATE_NAME,
750 		dyn_classify, dyn_update,
751 		dyn_findbyname, dyn_findbykidx,
752 		dyn_create, dyn_destroy
753 	},
754 };
755 
756 /*
757  * IMPORTANT: the hash function for dynamic rules must be commutative
758  * in source and destination (ip,port), because rules are bidirectional
759  * and we want to find both in the same bucket.
760  */
761 #ifndef IPFIREWALL_JENKINSHASH
762 static __inline uint32_t
hash_packet(const struct ipfw_flow_id * id)763 hash_packet(const struct ipfw_flow_id *id)
764 {
765 	uint32_t i;
766 
767 #ifdef INET6
768 	if (IS_IP6_FLOW_ID(id))
769 		i = ntohl((id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
770 		    (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
771 		    (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
772 		    (id->src_ip6.__u6_addr.__u6_addr32[3]));
773 	else
774 #endif /* INET6 */
775 	i = (id->dst_ip) ^ (id->src_ip);
776 	i ^= (id->dst_port) ^ (id->src_port);
777 	return (i);
778 }
779 
780 static __inline uint32_t
hash_parent(const struct ipfw_flow_id * id,const void * rule)781 hash_parent(const struct ipfw_flow_id *id, const void *rule)
782 {
783 
784 	return (hash_packet(id) ^ ((uintptr_t)rule));
785 }
786 
787 #else /* IPFIREWALL_JENKINSHASH */
788 
789 VNET_DEFINE_STATIC(uint32_t, dyn_hashseed);
790 #define	V_dyn_hashseed		VNET(dyn_hashseed)
791 
792 static __inline int
addrcmp4(const struct ipfw_flow_id * id)793 addrcmp4(const struct ipfw_flow_id *id)
794 {
795 
796 	if (id->src_ip < id->dst_ip)
797 		return (0);
798 	if (id->src_ip > id->dst_ip)
799 		return (1);
800 	if (id->src_port <= id->dst_port)
801 		return (0);
802 	return (1);
803 }
804 
805 #ifdef INET6
806 static __inline int
addrcmp6(const struct ipfw_flow_id * id)807 addrcmp6(const struct ipfw_flow_id *id)
808 {
809 	int ret;
810 
811 	ret = memcmp(&id->src_ip6, &id->dst_ip6, sizeof(struct in6_addr));
812 	if (ret < 0)
813 		return (0);
814 	if (ret > 0)
815 		return (1);
816 	if (id->src_port <= id->dst_port)
817 		return (0);
818 	return (1);
819 }
820 
821 static __inline uint32_t
hash_packet6(const struct ipfw_flow_id * id)822 hash_packet6(const struct ipfw_flow_id *id)
823 {
824 	struct tuple6 {
825 		struct in6_addr	addr[2];
826 		uint16_t	port[2];
827 	} t6;
828 
829 	if (addrcmp6(id) == 0) {
830 		t6.addr[0] = id->src_ip6;
831 		t6.addr[1] = id->dst_ip6;
832 		t6.port[0] = id->src_port;
833 		t6.port[1] = id->dst_port;
834 	} else {
835 		t6.addr[0] = id->dst_ip6;
836 		t6.addr[1] = id->src_ip6;
837 		t6.port[0] = id->dst_port;
838 		t6.port[1] = id->src_port;
839 	}
840 	return (jenkins_hash32((const uint32_t *)&t6,
841 	    sizeof(t6) / sizeof(uint32_t), V_dyn_hashseed));
842 }
843 #endif
844 
845 static __inline uint32_t
hash_packet(const struct ipfw_flow_id * id)846 hash_packet(const struct ipfw_flow_id *id)
847 {
848 	struct tuple4 {
849 		in_addr_t	addr[2];
850 		uint16_t	port[2];
851 	} t4;
852 
853 	if (IS_IP4_FLOW_ID(id)) {
854 		/* All fields are in host byte order */
855 		if (addrcmp4(id) == 0) {
856 			t4.addr[0] = id->src_ip;
857 			t4.addr[1] = id->dst_ip;
858 			t4.port[0] = id->src_port;
859 			t4.port[1] = id->dst_port;
860 		} else {
861 			t4.addr[0] = id->dst_ip;
862 			t4.addr[1] = id->src_ip;
863 			t4.port[0] = id->dst_port;
864 			t4.port[1] = id->src_port;
865 		}
866 		return (jenkins_hash32((const uint32_t *)&t4,
867 		    sizeof(t4) / sizeof(uint32_t), V_dyn_hashseed));
868 	} else
869 #ifdef INET6
870 	if (IS_IP6_FLOW_ID(id))
871 		return (hash_packet6(id));
872 #endif
873 	return (0);
874 }
875 
876 static __inline uint32_t
hash_parent(const struct ipfw_flow_id * id,const void * rule)877 hash_parent(const struct ipfw_flow_id *id, const void *rule)
878 {
879 
880 	return (jenkins_hash32((const uint32_t *)&rule,
881 	    sizeof(rule) / sizeof(uint32_t), hash_packet(id)));
882 }
883 #endif /* IPFIREWALL_JENKINSHASH */
884 
885 /*
886  * Print customizable flow id description via log(9) facility.
887  */
888 static void
print_dyn_rule_flags(const struct ipfw_flow_id * id,int dyn_type,int log_flags,char * prefix,char * postfix)889 print_dyn_rule_flags(const struct ipfw_flow_id *id, int dyn_type,
890     int log_flags, char *prefix, char *postfix)
891 {
892 	struct in_addr da;
893 #ifdef INET6
894 	char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN];
895 #else
896 	char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
897 #endif
898 
899 #ifdef INET6
900 	if (IS_IP6_FLOW_ID(id)) {
901 		ip6_sprintf(src, &id->src_ip6);
902 		ip6_sprintf(dst, &id->dst_ip6);
903 	} else
904 #endif
905 	{
906 		da.s_addr = htonl(id->src_ip);
907 		inet_ntop(AF_INET, &da, src, sizeof(src));
908 		da.s_addr = htonl(id->dst_ip);
909 		inet_ntop(AF_INET, &da, dst, sizeof(dst));
910 	}
911 	log(log_flags, "ipfw: %s type %d %s %d -> %s %d, %d %s\n",
912 	    prefix, dyn_type, src, id->src_port, dst,
913 	    id->dst_port, V_dyn_count, postfix);
914 }
915 
916 #define	print_dyn_rule(id, dtype, prefix, postfix)	\
917 	print_dyn_rule_flags(id, dtype, LOG_DEBUG, prefix, postfix)
918 
919 #define	TIME_LEQ(a,b)	((int)((a)-(b)) <= 0)
920 #define	TIME_LE(a,b)	((int)((a)-(b)) < 0)
921 #define	_SEQ_GE(a,b)	((int)((a)-(b)) >= 0)
922 #define	BOTH_SYN	(TH_SYN | (TH_SYN << 8))
923 #define	BOTH_FIN	(TH_FIN | (TH_FIN << 8))
924 #define	TCP_FLAGS	(TH_FLAGS | (TH_FLAGS << 8))
925 #define	ACK_FWD		0x00010000	/* fwd ack seen */
926 #define	ACK_REV		0x00020000	/* rev ack seen */
927 #define	ACK_BOTH	(ACK_FWD | ACK_REV)
928 
929 static uint32_t
dyn_update_tcp_state(struct dyn_data * data,const struct ipfw_flow_id * pkt,const struct tcphdr * tcp,int dir)930 dyn_update_tcp_state(struct dyn_data *data, const struct ipfw_flow_id *pkt,
931     const struct tcphdr *tcp, int dir)
932 {
933 	uint32_t ack, expire;
934 	uint32_t state, old;
935 	uint8_t th_flags;
936 
937 	expire = data->expire;
938 	old = state = data->state;
939 	th_flags = pkt->_flags & (TH_FIN | TH_SYN | TH_RST);
940 	state |= (dir == MATCH_FORWARD) ? th_flags: (th_flags << 8);
941 	switch (state & TCP_FLAGS) {
942 	case TH_SYN:			/* opening */
943 		expire = time_uptime + V_dyn_syn_lifetime;
944 		break;
945 
946 	case BOTH_SYN:			/* move to established */
947 	case BOTH_SYN | TH_FIN:		/* one side tries to close */
948 	case BOTH_SYN | (TH_FIN << 8):
949 		if (tcp == NULL)
950 			break;
951 		ack = ntohl(tcp->th_ack);
952 		if (dir == MATCH_FORWARD) {
953 			if (data->ack_fwd == 0 ||
954 			    _SEQ_GE(ack, data->ack_fwd)) {
955 				state |= ACK_FWD;
956 				if (data->ack_fwd != ack)
957 					ck_pr_store_32(&data->ack_fwd, ack);
958 			}
959 		} else {
960 			if (data->ack_rev == 0 ||
961 			    _SEQ_GE(ack, data->ack_rev)) {
962 				state |= ACK_REV;
963 				if (data->ack_rev != ack)
964 					ck_pr_store_32(&data->ack_rev, ack);
965 			}
966 		}
967 		if ((state & ACK_BOTH) == ACK_BOTH) {
968 			/*
969 			 * Set expire time to V_dyn_ack_lifetime only if
970 			 * we got ACKs for both directions.
971 			 * We use XOR here to avoid possible state
972 			 * overwriting in concurrent thread.
973 			 */
974 			expire = time_uptime + V_dyn_ack_lifetime;
975 			ck_pr_xor_32(&data->state, ACK_BOTH);
976 		} else if ((data->state & ACK_BOTH) != (state & ACK_BOTH))
977 			ck_pr_or_32(&data->state, state & ACK_BOTH);
978 		break;
979 
980 	case BOTH_SYN | BOTH_FIN:	/* both sides closed */
981 		if (V_dyn_fin_lifetime >= V_dyn_keepalive_period)
982 			V_dyn_fin_lifetime = V_dyn_keepalive_period - 1;
983 		expire = time_uptime + V_dyn_fin_lifetime;
984 		break;
985 
986 	default:
987 		if (V_dyn_keepalive != 0 &&
988 		    V_dyn_rst_lifetime >= V_dyn_keepalive_period)
989 			V_dyn_rst_lifetime = V_dyn_keepalive_period - 1;
990 		expire = time_uptime + V_dyn_rst_lifetime;
991 	}
992 	/* Save TCP state if it was changed */
993 	if ((state & TCP_FLAGS) != (old & TCP_FLAGS))
994 		ck_pr_or_32(&data->state, state & TCP_FLAGS);
995 	return (expire);
996 }
997 
998 /*
999  * Update ULP specific state.
1000  * For TCP we keep sequence numbers and flags. For other protocols
1001  * currently we update only expire time. Packets and bytes counters
1002  * are also updated here.
1003  */
1004 static void
dyn_update_proto_state(struct dyn_data * data,const struct ipfw_flow_id * pkt,const void * ulp,int pktlen,int dir)1005 dyn_update_proto_state(struct dyn_data *data, const struct ipfw_flow_id *pkt,
1006     const void *ulp, int pktlen, int dir)
1007 {
1008 	uint32_t expire;
1009 
1010 	/* NOTE: we are in critical section here. */
1011 	switch (pkt->proto) {
1012 	case IPPROTO_UDP:
1013 	case IPPROTO_UDPLITE:
1014 		expire = time_uptime + V_dyn_udp_lifetime;
1015 		break;
1016 	case IPPROTO_TCP:
1017 		expire = dyn_update_tcp_state(data, pkt, ulp, dir);
1018 		break;
1019 	default:
1020 		expire = time_uptime + V_dyn_short_lifetime;
1021 	}
1022 	/*
1023 	 * Expiration timer has the per-second granularity, no need to update
1024 	 * it every time when state is matched.
1025 	 */
1026 	if (data->expire != expire)
1027 		ck_pr_store_32(&data->expire, expire);
1028 
1029 	if (dir == MATCH_FORWARD)
1030 		DYN_COUNTER_INC(data, fwd, pktlen);
1031 	else
1032 		DYN_COUNTER_INC(data, rev, pktlen);
1033 }
1034 
1035 /*
1036  * Lookup IPv4 state.
1037  * Must be called in critical section.
1038  */
1039 struct dyn_ipv4_state *
dyn_lookup_ipv4_state(const struct ipfw_flow_id * pkt,const void * ulp,struct ipfw_dyn_info * info,int pktlen)1040 dyn_lookup_ipv4_state(const struct ipfw_flow_id *pkt, const void *ulp,
1041     struct ipfw_dyn_info *info, int pktlen)
1042 {
1043 	struct dyn_ipv4_state *s;
1044 	uint32_t version, bucket;
1045 
1046 	bucket = DYN_BUCKET(info->hashval, V_curr_dyn_buckets);
1047 	info->version = DYN_BUCKET_VERSION(bucket, ipv4_add);
1048 restart:
1049 	version = DYN_BUCKET_VERSION(bucket, ipv4_del);
1050 	CK_SLIST_FOREACH(s, &V_dyn_ipv4[bucket], entry) {
1051 		DYNSTATE_PROTECT(s);
1052 		if (version != DYN_BUCKET_VERSION(bucket, ipv4_del))
1053 			goto restart;
1054 		if (s->proto != pkt->proto)
1055 			continue;
1056 		if (info->kidx != 0 && s->kidx != info->kidx)
1057 			continue;
1058 		if (s->sport == pkt->src_port && s->dport == pkt->dst_port &&
1059 		    s->src == pkt->src_ip && s->dst == pkt->dst_ip) {
1060 			info->direction = MATCH_FORWARD;
1061 			break;
1062 		}
1063 		if (s->sport == pkt->dst_port && s->dport == pkt->src_port &&
1064 		    s->src == pkt->dst_ip && s->dst == pkt->src_ip) {
1065 			info->direction = MATCH_REVERSE;
1066 			break;
1067 		}
1068 	}
1069 
1070 	if (s != NULL)
1071 		dyn_update_proto_state(s->data, pkt, ulp, pktlen,
1072 		    info->direction);
1073 	return (s);
1074 }
1075 
1076 /*
1077  * Lookup IPv4 state.
1078  * Simplifed version is used to check that matching state doesn't exist.
1079  */
1080 static int
dyn_lookup_ipv4_state_locked(const struct ipfw_flow_id * pkt,const void * ulp,int pktlen,uint32_t bucket,uint16_t kidx)1081 dyn_lookup_ipv4_state_locked(const struct ipfw_flow_id *pkt,
1082     const void *ulp, int pktlen, uint32_t bucket, uint16_t kidx)
1083 {
1084 	struct dyn_ipv4_state *s;
1085 	int dir;
1086 
1087 	dir = MATCH_NONE;
1088 	DYN_BUCKET_ASSERT(bucket);
1089 	CK_SLIST_FOREACH(s, &V_dyn_ipv4[bucket], entry) {
1090 		if (s->proto != pkt->proto ||
1091 		    s->kidx != kidx)
1092 			continue;
1093 		if (s->sport == pkt->src_port &&
1094 		    s->dport == pkt->dst_port &&
1095 		    s->src == pkt->src_ip && s->dst == pkt->dst_ip) {
1096 			dir = MATCH_FORWARD;
1097 			break;
1098 		}
1099 		if (s->sport == pkt->dst_port && s->dport == pkt->src_port &&
1100 		    s->src == pkt->dst_ip && s->dst == pkt->src_ip) {
1101 			dir = MATCH_REVERSE;
1102 			break;
1103 		}
1104 	}
1105 	if (s != NULL)
1106 		dyn_update_proto_state(s->data, pkt, ulp, pktlen, dir);
1107 	return (s != NULL);
1108 }
1109 
1110 struct dyn_ipv4_state *
dyn_lookup_ipv4_parent(const struct ipfw_flow_id * pkt,const void * rule,uint32_t ruleid,uint16_t rulenum,uint32_t hashval)1111 dyn_lookup_ipv4_parent(const struct ipfw_flow_id *pkt, const void *rule,
1112     uint32_t ruleid, uint16_t rulenum, uint32_t hashval)
1113 {
1114 	struct dyn_ipv4_state *s;
1115 	uint32_t version, bucket;
1116 
1117 	bucket = DYN_BUCKET(hashval, V_curr_dyn_buckets);
1118 restart:
1119 	version = DYN_BUCKET_VERSION(bucket, ipv4_parent_del);
1120 	CK_SLIST_FOREACH(s, &V_dyn_ipv4_parent[bucket], entry) {
1121 		DYNSTATE_PROTECT(s);
1122 		if (version != DYN_BUCKET_VERSION(bucket, ipv4_parent_del))
1123 			goto restart;
1124 		/*
1125 		 * NOTE: we do not need to check kidx, because parent rule
1126 		 * can not create states with different kidx.
1127 		 * And parent rule always created for forward direction.
1128 		 */
1129 		if (s->limit->parent == rule &&
1130 		    s->limit->ruleid == ruleid &&
1131 		    s->limit->rulenum == rulenum &&
1132 		    s->proto == pkt->proto &&
1133 		    s->sport == pkt->src_port &&
1134 		    s->dport == pkt->dst_port &&
1135 		    s->src == pkt->src_ip && s->dst == pkt->dst_ip) {
1136 			if (s->limit->expire != time_uptime +
1137 			    V_dyn_short_lifetime)
1138 				ck_pr_store_32(&s->limit->expire,
1139 				    time_uptime + V_dyn_short_lifetime);
1140 			break;
1141 		}
1142 	}
1143 	return (s);
1144 }
1145 
1146 static struct dyn_ipv4_state *
dyn_lookup_ipv4_parent_locked(const struct ipfw_flow_id * pkt,const void * rule,uint32_t ruleid,uint16_t rulenum,uint32_t bucket)1147 dyn_lookup_ipv4_parent_locked(const struct ipfw_flow_id *pkt,
1148     const void *rule, uint32_t ruleid, uint16_t rulenum, uint32_t bucket)
1149 {
1150 	struct dyn_ipv4_state *s;
1151 
1152 	DYN_BUCKET_ASSERT(bucket);
1153 	CK_SLIST_FOREACH(s, &V_dyn_ipv4_parent[bucket], entry) {
1154 		if (s->limit->parent == rule &&
1155 		    s->limit->ruleid == ruleid &&
1156 		    s->limit->rulenum == rulenum &&
1157 		    s->proto == pkt->proto &&
1158 		    s->sport == pkt->src_port &&
1159 		    s->dport == pkt->dst_port &&
1160 		    s->src == pkt->src_ip && s->dst == pkt->dst_ip)
1161 			break;
1162 	}
1163 	return (s);
1164 }
1165 
1166 
1167 #ifdef INET6
1168 static uint32_t
dyn_getscopeid(const struct ip_fw_args * args)1169 dyn_getscopeid(const struct ip_fw_args *args)
1170 {
1171 
1172 	/*
1173 	 * If source or destination address is an scopeid address, we need
1174 	 * determine the scope zone id to resolve address scope ambiguity.
1175 	 */
1176 	if (IN6_IS_ADDR_LINKLOCAL(&args->f_id.src_ip6) ||
1177 	    IN6_IS_ADDR_LINKLOCAL(&args->f_id.dst_ip6)) {
1178 		MPASS(args->oif != NULL ||
1179 		    args->m->m_pkthdr.rcvif != NULL);
1180 		return (in6_getscopezone(args->oif != NULL ? args->oif:
1181 		    args->m->m_pkthdr.rcvif, IPV6_ADDR_SCOPE_LINKLOCAL));
1182 	}
1183 	return (0);
1184 }
1185 
1186 /*
1187  * Lookup IPv6 state.
1188  * Must be called in critical section.
1189  */
1190 static struct dyn_ipv6_state *
dyn_lookup_ipv6_state(const struct ipfw_flow_id * pkt,uint32_t zoneid,const void * ulp,struct ipfw_dyn_info * info,int pktlen)1191 dyn_lookup_ipv6_state(const struct ipfw_flow_id *pkt, uint32_t zoneid,
1192     const void *ulp, struct ipfw_dyn_info *info, int pktlen)
1193 {
1194 	struct dyn_ipv6_state *s;
1195 	uint32_t version, bucket;
1196 
1197 	bucket = DYN_BUCKET(info->hashval, V_curr_dyn_buckets);
1198 	info->version = DYN_BUCKET_VERSION(bucket, ipv6_add);
1199 restart:
1200 	version = DYN_BUCKET_VERSION(bucket, ipv6_del);
1201 	CK_SLIST_FOREACH(s, &V_dyn_ipv6[bucket], entry) {
1202 		DYNSTATE_PROTECT(s);
1203 		if (version != DYN_BUCKET_VERSION(bucket, ipv6_del))
1204 			goto restart;
1205 		if (s->proto != pkt->proto || s->zoneid != zoneid)
1206 			continue;
1207 		if (info->kidx != 0 && s->kidx != info->kidx)
1208 			continue;
1209 		if (s->sport == pkt->src_port && s->dport == pkt->dst_port &&
1210 		    IN6_ARE_ADDR_EQUAL(&s->src, &pkt->src_ip6) &&
1211 		    IN6_ARE_ADDR_EQUAL(&s->dst, &pkt->dst_ip6)) {
1212 			info->direction = MATCH_FORWARD;
1213 			break;
1214 		}
1215 		if (s->sport == pkt->dst_port && s->dport == pkt->src_port &&
1216 		    IN6_ARE_ADDR_EQUAL(&s->src, &pkt->dst_ip6) &&
1217 		    IN6_ARE_ADDR_EQUAL(&s->dst, &pkt->src_ip6)) {
1218 			info->direction = MATCH_REVERSE;
1219 			break;
1220 		}
1221 	}
1222 	if (s != NULL)
1223 		dyn_update_proto_state(s->data, pkt, ulp, pktlen,
1224 		    info->direction);
1225 	return (s);
1226 }
1227 
1228 /*
1229  * Lookup IPv6 state.
1230  * Simplifed version is used to check that matching state doesn't exist.
1231  */
1232 static int
dyn_lookup_ipv6_state_locked(const struct ipfw_flow_id * pkt,uint32_t zoneid,const void * ulp,int pktlen,uint32_t bucket,uint16_t kidx)1233 dyn_lookup_ipv6_state_locked(const struct ipfw_flow_id *pkt, uint32_t zoneid,
1234     const void *ulp, int pktlen, uint32_t bucket, uint16_t kidx)
1235 {
1236 	struct dyn_ipv6_state *s;
1237 	int dir;
1238 
1239 	dir = MATCH_NONE;
1240 	DYN_BUCKET_ASSERT(bucket);
1241 	CK_SLIST_FOREACH(s, &V_dyn_ipv6[bucket], entry) {
1242 		if (s->proto != pkt->proto || s->kidx != kidx ||
1243 		    s->zoneid != zoneid)
1244 			continue;
1245 		if (s->sport == pkt->src_port && s->dport == pkt->dst_port &&
1246 		    IN6_ARE_ADDR_EQUAL(&s->src, &pkt->src_ip6) &&
1247 		    IN6_ARE_ADDR_EQUAL(&s->dst, &pkt->dst_ip6)) {
1248 			dir = MATCH_FORWARD;
1249 			break;
1250 		}
1251 		if (s->sport == pkt->dst_port && s->dport == pkt->src_port &&
1252 		    IN6_ARE_ADDR_EQUAL(&s->src, &pkt->dst_ip6) &&
1253 		    IN6_ARE_ADDR_EQUAL(&s->dst, &pkt->src_ip6)) {
1254 			dir = MATCH_REVERSE;
1255 			break;
1256 		}
1257 	}
1258 	if (s != NULL)
1259 		dyn_update_proto_state(s->data, pkt, ulp, pktlen, dir);
1260 	return (s != NULL);
1261 }
1262 
1263 static struct dyn_ipv6_state *
dyn_lookup_ipv6_parent(const struct ipfw_flow_id * pkt,uint32_t zoneid,const void * rule,uint32_t ruleid,uint16_t rulenum,uint32_t hashval)1264 dyn_lookup_ipv6_parent(const struct ipfw_flow_id *pkt, uint32_t zoneid,
1265     const void *rule, uint32_t ruleid, uint16_t rulenum, uint32_t hashval)
1266 {
1267 	struct dyn_ipv6_state *s;
1268 	uint32_t version, bucket;
1269 
1270 	bucket = DYN_BUCKET(hashval, V_curr_dyn_buckets);
1271 restart:
1272 	version = DYN_BUCKET_VERSION(bucket, ipv6_parent_del);
1273 	CK_SLIST_FOREACH(s, &V_dyn_ipv6_parent[bucket], entry) {
1274 		DYNSTATE_PROTECT(s);
1275 		if (version != DYN_BUCKET_VERSION(bucket, ipv6_parent_del))
1276 			goto restart;
1277 		/*
1278 		 * NOTE: we do not need to check kidx, because parent rule
1279 		 * can not create states with different kidx.
1280 		 * Also parent rule always created for forward direction.
1281 		 */
1282 		if (s->limit->parent == rule &&
1283 		    s->limit->ruleid == ruleid &&
1284 		    s->limit->rulenum == rulenum &&
1285 		    s->proto == pkt->proto &&
1286 		    s->sport == pkt->src_port &&
1287 		    s->dport == pkt->dst_port && s->zoneid == zoneid &&
1288 		    IN6_ARE_ADDR_EQUAL(&s->src, &pkt->src_ip6) &&
1289 		    IN6_ARE_ADDR_EQUAL(&s->dst, &pkt->dst_ip6)) {
1290 			if (s->limit->expire != time_uptime +
1291 			    V_dyn_short_lifetime)
1292 				ck_pr_store_32(&s->limit->expire,
1293 				    time_uptime + V_dyn_short_lifetime);
1294 			break;
1295 		}
1296 	}
1297 	return (s);
1298 }
1299 
1300 static struct dyn_ipv6_state *
dyn_lookup_ipv6_parent_locked(const struct ipfw_flow_id * pkt,uint32_t zoneid,const void * rule,uint32_t ruleid,uint16_t rulenum,uint32_t bucket)1301 dyn_lookup_ipv6_parent_locked(const struct ipfw_flow_id *pkt, uint32_t zoneid,
1302     const void *rule, uint32_t ruleid, uint16_t rulenum, uint32_t bucket)
1303 {
1304 	struct dyn_ipv6_state *s;
1305 
1306 	DYN_BUCKET_ASSERT(bucket);
1307 	CK_SLIST_FOREACH(s, &V_dyn_ipv6_parent[bucket], entry) {
1308 		if (s->limit->parent == rule &&
1309 		    s->limit->ruleid == ruleid &&
1310 		    s->limit->rulenum == rulenum &&
1311 		    s->proto == pkt->proto &&
1312 		    s->sport == pkt->src_port &&
1313 		    s->dport == pkt->dst_port && s->zoneid == zoneid &&
1314 		    IN6_ARE_ADDR_EQUAL(&s->src, &pkt->src_ip6) &&
1315 		    IN6_ARE_ADDR_EQUAL(&s->dst, &pkt->dst_ip6))
1316 			break;
1317 	}
1318 	return (s);
1319 }
1320 
1321 #endif /* INET6 */
1322 
1323 /*
1324  * Lookup dynamic state.
1325  *  pkt - filled by ipfw_chk() ipfw_flow_id;
1326  *  ulp - determined by ipfw_chk() upper level protocol header;
1327  *  dyn_info - info about matched state to return back;
1328  * Returns pointer to state's parent rule and dyn_info. If there is
1329  * no state, NULL is returned.
1330  * On match ipfw_dyn_lookup() updates state's counters.
1331  */
1332 struct ip_fw *
ipfw_dyn_lookup_state(const struct ip_fw_args * args,const void * ulp,int pktlen,const ipfw_insn * cmd,struct ipfw_dyn_info * info)1333 ipfw_dyn_lookup_state(const struct ip_fw_args *args, const void *ulp,
1334     int pktlen, const ipfw_insn *cmd, struct ipfw_dyn_info *info)
1335 {
1336 	struct dyn_data *data;
1337 	struct ip_fw *rule;
1338 
1339 	IPFW_RLOCK_ASSERT(&V_layer3_chain);
1340 
1341 	data = NULL;
1342 	rule = NULL;
1343 	info->kidx = cmd->arg1;
1344 	info->direction = MATCH_NONE;
1345 	info->hashval = hash_packet(&args->f_id);
1346 
1347 	DYNSTATE_CRITICAL_ENTER();
1348 	if (IS_IP4_FLOW_ID(&args->f_id)) {
1349 		struct dyn_ipv4_state *s;
1350 
1351 		s = dyn_lookup_ipv4_state(&args->f_id, ulp, info, pktlen);
1352 		if (s != NULL) {
1353 			/*
1354 			 * Dynamic states are created using the same 5-tuple,
1355 			 * so it is assumed, that parent rule for O_LIMIT
1356 			 * state has the same address family.
1357 			 */
1358 			data = s->data;
1359 			if (s->type == O_LIMIT) {
1360 				s = data->parent;
1361 				rule = s->limit->parent;
1362 			} else
1363 				rule = data->parent;
1364 		}
1365 	}
1366 #ifdef INET6
1367 	else if (IS_IP6_FLOW_ID(&args->f_id)) {
1368 		struct dyn_ipv6_state *s;
1369 
1370 		s = dyn_lookup_ipv6_state(&args->f_id, dyn_getscopeid(args),
1371 		    ulp, info, pktlen);
1372 		if (s != NULL) {
1373 			data = s->data;
1374 			if (s->type == O_LIMIT) {
1375 				s = data->parent;
1376 				rule = s->limit->parent;
1377 			} else
1378 				rule = data->parent;
1379 		}
1380 	}
1381 #endif
1382 	if (data != NULL) {
1383 		/*
1384 		 * If cached chain id is the same, we can avoid rule index
1385 		 * lookup. Otherwise do lookup and update chain_id and f_pos.
1386 		 * It is safe even if there is concurrent thread that want
1387 		 * update the same state, because chain->id can be changed
1388 		 * only under IPFW_WLOCK().
1389 		 */
1390 		if (data->chain_id != V_layer3_chain.id) {
1391 			data->f_pos = ipfw_find_rule(&V_layer3_chain,
1392 			    data->rulenum, data->ruleid);
1393 			/*
1394 			 * Check that found state has not orphaned.
1395 			 * When chain->id being changed the parent
1396 			 * rule can be deleted. If found rule doesn't
1397 			 * match the parent pointer, consider this
1398 			 * result as MATCH_NONE and return NULL.
1399 			 *
1400 			 * This will lead to creation of new similar state
1401 			 * that will be added into head of this bucket.
1402 			 * And the state that we currently have matched
1403 			 * should be deleted by dyn_expire_states().
1404 			 *
1405 			 * In case when dyn_keep_states is enabled, return
1406 			 * pointer to deleted rule and f_pos value
1407 			 * corresponding to penultimate rule.
1408 			 * When we have enabled V_dyn_keep_states, states
1409 			 * that become orphaned will get the DYN_REFERENCED
1410 			 * flag and rule will keep around. So we can return
1411 			 * it. But since it is not in the rules map, we need
1412 			 * return such f_pos value, so after the state
1413 			 * handling if the search will continue, the next rule
1414 			 * will be the last one - the default rule.
1415 			 */
1416 			if (V_layer3_chain.map[data->f_pos] == rule) {
1417 				data->chain_id = V_layer3_chain.id;
1418 				info->f_pos = data->f_pos;
1419 			} else if (V_dyn_keep_states != 0) {
1420 				/*
1421 				 * The original rule pointer is still usable.
1422 				 * So, we return it, but f_pos need to be
1423 				 * changed to point to the penultimate rule.
1424 				 */
1425 				MPASS(V_layer3_chain.n_rules > 1);
1426 				data->chain_id = V_layer3_chain.id;
1427 				data->f_pos = V_layer3_chain.n_rules - 2;
1428 				info->f_pos = data->f_pos;
1429 			} else {
1430 				rule = NULL;
1431 				info->direction = MATCH_NONE;
1432 				DYN_DEBUG("rule %p  [%u, %u] is considered "
1433 				    "invalid in data %p", rule, data->ruleid,
1434 				    data->rulenum, data);
1435 				/* info->f_pos doesn't matter here. */
1436 			}
1437 		} else
1438 			info->f_pos = data->f_pos;
1439 	}
1440 	DYNSTATE_CRITICAL_EXIT();
1441 #if 0
1442 	/*
1443 	 * Return MATCH_NONE if parent rule is in disabled set.
1444 	 * This will lead to creation of new similar state that
1445 	 * will be added into head of this bucket.
1446 	 *
1447 	 * XXXAE: we need to be able update state's set when parent
1448 	 *	  rule set is changed.
1449 	 */
1450 	if (rule != NULL && (V_set_disable & (1 << rule->set))) {
1451 		rule = NULL;
1452 		info->direction = MATCH_NONE;
1453 	}
1454 #endif
1455 	return (rule);
1456 }
1457 
1458 static struct dyn_parent *
dyn_alloc_parent(void * parent,uint32_t ruleid,uint16_t rulenum,uint32_t hashval)1459 dyn_alloc_parent(void *parent, uint32_t ruleid, uint16_t rulenum,
1460     uint32_t hashval)
1461 {
1462 	struct dyn_parent *limit;
1463 
1464 	limit = uma_zalloc(V_dyn_parent_zone, M_NOWAIT | M_ZERO);
1465 	if (limit == NULL) {
1466 		if (last_log != time_uptime) {
1467 			last_log = time_uptime;
1468 			log(LOG_DEBUG,
1469 			    "ipfw: Cannot allocate parent dynamic state, "
1470 			    "consider increasing "
1471 			    "net.inet.ip.fw.dyn_parent_max\n");
1472 		}
1473 		return (NULL);
1474 	}
1475 
1476 	limit->parent = parent;
1477 	limit->ruleid = ruleid;
1478 	limit->rulenum = rulenum;
1479 	limit->hashval = hashval;
1480 	limit->expire = time_uptime + V_dyn_short_lifetime;
1481 	return (limit);
1482 }
1483 
1484 static struct dyn_data *
dyn_alloc_dyndata(void * parent,uint32_t ruleid,uint16_t rulenum,const struct ipfw_flow_id * pkt,const void * ulp,int pktlen,uint32_t hashval,uint16_t fibnum)1485 dyn_alloc_dyndata(void *parent, uint32_t ruleid, uint16_t rulenum,
1486     const struct ipfw_flow_id *pkt, const void *ulp, int pktlen,
1487     uint32_t hashval, uint16_t fibnum)
1488 {
1489 	struct dyn_data *data;
1490 
1491 	data = uma_zalloc(V_dyn_data_zone, M_NOWAIT | M_ZERO);
1492 	if (data == NULL) {
1493 		if (last_log != time_uptime) {
1494 			last_log = time_uptime;
1495 			log(LOG_DEBUG,
1496 			    "ipfw: Cannot allocate dynamic state, "
1497 			    "consider increasing net.inet.ip.fw.dyn_max\n");
1498 		}
1499 		return (NULL);
1500 	}
1501 
1502 	data->parent = parent;
1503 	data->ruleid = ruleid;
1504 	data->rulenum = rulenum;
1505 	data->fibnum = fibnum;
1506 	data->hashval = hashval;
1507 	data->expire = time_uptime + V_dyn_syn_lifetime;
1508 	dyn_update_proto_state(data, pkt, ulp, pktlen, MATCH_FORWARD);
1509 	return (data);
1510 }
1511 
1512 static struct dyn_ipv4_state *
dyn_alloc_ipv4_state(const struct ipfw_flow_id * pkt,uint16_t kidx,uint8_t type)1513 dyn_alloc_ipv4_state(const struct ipfw_flow_id *pkt, uint16_t kidx,
1514     uint8_t type)
1515 {
1516 	struct dyn_ipv4_state *s;
1517 
1518 	s = uma_zalloc(V_dyn_ipv4_zone, M_NOWAIT | M_ZERO);
1519 	if (s == NULL)
1520 		return (NULL);
1521 
1522 	s->type = type;
1523 	s->kidx = kidx;
1524 	s->proto = pkt->proto;
1525 	s->sport = pkt->src_port;
1526 	s->dport = pkt->dst_port;
1527 	s->src = pkt->src_ip;
1528 	s->dst = pkt->dst_ip;
1529 	return (s);
1530 }
1531 
1532 /*
1533  * Add IPv4 parent state.
1534  * Returns pointer to parent state. When it is not NULL we are in
1535  * critical section and pointer protected by hazard pointer.
1536  * When some error occurs, it returns NULL and exit from critical section
1537  * is not needed.
1538  */
1539 static struct dyn_ipv4_state *
dyn_add_ipv4_parent(void * rule,uint32_t ruleid,uint16_t rulenum,const struct ipfw_flow_id * pkt,uint32_t hashval,uint32_t version,uint16_t kidx)1540 dyn_add_ipv4_parent(void *rule, uint32_t ruleid, uint16_t rulenum,
1541     const struct ipfw_flow_id *pkt, uint32_t hashval, uint32_t version,
1542     uint16_t kidx)
1543 {
1544 	struct dyn_ipv4_state *s;
1545 	struct dyn_parent *limit;
1546 	uint32_t bucket;
1547 
1548 	bucket = DYN_BUCKET(hashval, V_curr_dyn_buckets);
1549 	DYN_BUCKET_LOCK(bucket);
1550 	if (version != DYN_BUCKET_VERSION(bucket, ipv4_parent_add)) {
1551 		/*
1552 		 * Bucket version has been changed since last lookup,
1553 		 * do lookup again to be sure that state does not exist.
1554 		 */
1555 		s = dyn_lookup_ipv4_parent_locked(pkt, rule, ruleid,
1556 		    rulenum, bucket);
1557 		if (s != NULL) {
1558 			/*
1559 			 * Simultaneous thread has already created this
1560 			 * state. Just return it.
1561 			 */
1562 			DYNSTATE_CRITICAL_ENTER();
1563 			DYNSTATE_PROTECT(s);
1564 			DYN_BUCKET_UNLOCK(bucket);
1565 			return (s);
1566 		}
1567 	}
1568 
1569 	limit = dyn_alloc_parent(rule, ruleid, rulenum, hashval);
1570 	if (limit == NULL) {
1571 		DYN_BUCKET_UNLOCK(bucket);
1572 		return (NULL);
1573 	}
1574 
1575 	s = dyn_alloc_ipv4_state(pkt, kidx, O_LIMIT_PARENT);
1576 	if (s == NULL) {
1577 		DYN_BUCKET_UNLOCK(bucket);
1578 		uma_zfree(V_dyn_parent_zone, limit);
1579 		return (NULL);
1580 	}
1581 
1582 	s->limit = limit;
1583 	CK_SLIST_INSERT_HEAD(&V_dyn_ipv4_parent[bucket], s, entry);
1584 	DYN_COUNT_INC(dyn_parent_count);
1585 	DYN_BUCKET_VERSION_BUMP(bucket, ipv4_parent_add);
1586 	DYNSTATE_CRITICAL_ENTER();
1587 	DYNSTATE_PROTECT(s);
1588 	DYN_BUCKET_UNLOCK(bucket);
1589 	return (s);
1590 }
1591 
1592 static int
dyn_add_ipv4_state(void * parent,uint32_t ruleid,uint16_t rulenum,const struct ipfw_flow_id * pkt,const void * ulp,int pktlen,uint32_t hashval,struct ipfw_dyn_info * info,uint16_t fibnum,uint16_t kidx,uint8_t type)1593 dyn_add_ipv4_state(void *parent, uint32_t ruleid, uint16_t rulenum,
1594     const struct ipfw_flow_id *pkt, const void *ulp, int pktlen,
1595     uint32_t hashval, struct ipfw_dyn_info *info, uint16_t fibnum,
1596     uint16_t kidx, uint8_t type)
1597 {
1598 	struct dyn_ipv4_state *s;
1599 	void *data;
1600 	uint32_t bucket;
1601 
1602 	bucket = DYN_BUCKET(hashval, V_curr_dyn_buckets);
1603 	DYN_BUCKET_LOCK(bucket);
1604 	if (info->direction == MATCH_UNKNOWN ||
1605 	    info->kidx != kidx ||
1606 	    info->hashval != hashval ||
1607 	    info->version != DYN_BUCKET_VERSION(bucket, ipv4_add)) {
1608 		/*
1609 		 * Bucket version has been changed since last lookup,
1610 		 * do lookup again to be sure that state does not exist.
1611 		 */
1612 		if (dyn_lookup_ipv4_state_locked(pkt, ulp, pktlen,
1613 		    bucket, kidx) != 0) {
1614 			DYN_BUCKET_UNLOCK(bucket);
1615 			return (EEXIST);
1616 		}
1617 	}
1618 
1619 	data = dyn_alloc_dyndata(parent, ruleid, rulenum, pkt, ulp,
1620 	    pktlen, hashval, fibnum);
1621 	if (data == NULL) {
1622 		DYN_BUCKET_UNLOCK(bucket);
1623 		return (ENOMEM);
1624 	}
1625 
1626 	s = dyn_alloc_ipv4_state(pkt, kidx, type);
1627 	if (s == NULL) {
1628 		DYN_BUCKET_UNLOCK(bucket);
1629 		uma_zfree(V_dyn_data_zone, data);
1630 		return (ENOMEM);
1631 	}
1632 
1633 	s->data = data;
1634 	CK_SLIST_INSERT_HEAD(&V_dyn_ipv4[bucket], s, entry);
1635 	DYN_COUNT_INC(dyn_count);
1636 	DYN_BUCKET_VERSION_BUMP(bucket, ipv4_add);
1637 	DYN_BUCKET_UNLOCK(bucket);
1638 	return (0);
1639 }
1640 
1641 #ifdef INET6
1642 static struct dyn_ipv6_state *
dyn_alloc_ipv6_state(const struct ipfw_flow_id * pkt,uint32_t zoneid,uint16_t kidx,uint8_t type)1643 dyn_alloc_ipv6_state(const struct ipfw_flow_id *pkt, uint32_t zoneid,
1644     uint16_t kidx, uint8_t type)
1645 {
1646 	struct dyn_ipv6_state *s;
1647 
1648 	s = uma_zalloc(V_dyn_ipv6_zone, M_NOWAIT | M_ZERO);
1649 	if (s == NULL)
1650 		return (NULL);
1651 
1652 	s->type = type;
1653 	s->kidx = kidx;
1654 	s->zoneid = zoneid;
1655 	s->proto = pkt->proto;
1656 	s->sport = pkt->src_port;
1657 	s->dport = pkt->dst_port;
1658 	s->src = pkt->src_ip6;
1659 	s->dst = pkt->dst_ip6;
1660 	return (s);
1661 }
1662 
1663 /*
1664  * Add IPv6 parent state.
1665  * Returns pointer to parent state. When it is not NULL we are in
1666  * critical section and pointer protected by hazard pointer.
1667  * When some error occurs, it return NULL and exit from critical section
1668  * is not needed.
1669  */
1670 static struct dyn_ipv6_state *
dyn_add_ipv6_parent(void * rule,uint32_t ruleid,uint16_t rulenum,const struct ipfw_flow_id * pkt,uint32_t zoneid,uint32_t hashval,uint32_t version,uint16_t kidx)1671 dyn_add_ipv6_parent(void *rule, uint32_t ruleid, uint16_t rulenum,
1672     const struct ipfw_flow_id *pkt, uint32_t zoneid, uint32_t hashval,
1673     uint32_t version, uint16_t kidx)
1674 {
1675 	struct dyn_ipv6_state *s;
1676 	struct dyn_parent *limit;
1677 	uint32_t bucket;
1678 
1679 	bucket = DYN_BUCKET(hashval, V_curr_dyn_buckets);
1680 	DYN_BUCKET_LOCK(bucket);
1681 	if (version != DYN_BUCKET_VERSION(bucket, ipv6_parent_add)) {
1682 		/*
1683 		 * Bucket version has been changed since last lookup,
1684 		 * do lookup again to be sure that state does not exist.
1685 		 */
1686 		s = dyn_lookup_ipv6_parent_locked(pkt, zoneid, rule, ruleid,
1687 		    rulenum, bucket);
1688 		if (s != NULL) {
1689 			/*
1690 			 * Simultaneous thread has already created this
1691 			 * state. Just return it.
1692 			 */
1693 			DYNSTATE_CRITICAL_ENTER();
1694 			DYNSTATE_PROTECT(s);
1695 			DYN_BUCKET_UNLOCK(bucket);
1696 			return (s);
1697 		}
1698 	}
1699 
1700 	limit = dyn_alloc_parent(rule, ruleid, rulenum, hashval);
1701 	if (limit == NULL) {
1702 		DYN_BUCKET_UNLOCK(bucket);
1703 		return (NULL);
1704 	}
1705 
1706 	s = dyn_alloc_ipv6_state(pkt, zoneid, kidx, O_LIMIT_PARENT);
1707 	if (s == NULL) {
1708 		DYN_BUCKET_UNLOCK(bucket);
1709 		uma_zfree(V_dyn_parent_zone, limit);
1710 		return (NULL);
1711 	}
1712 
1713 	s->limit = limit;
1714 	CK_SLIST_INSERT_HEAD(&V_dyn_ipv6_parent[bucket], s, entry);
1715 	DYN_COUNT_INC(dyn_parent_count);
1716 	DYN_BUCKET_VERSION_BUMP(bucket, ipv6_parent_add);
1717 	DYNSTATE_CRITICAL_ENTER();
1718 	DYNSTATE_PROTECT(s);
1719 	DYN_BUCKET_UNLOCK(bucket);
1720 	return (s);
1721 }
1722 
1723 static int
dyn_add_ipv6_state(void * parent,uint32_t ruleid,uint16_t rulenum,const struct ipfw_flow_id * pkt,uint32_t zoneid,const void * ulp,int pktlen,uint32_t hashval,struct ipfw_dyn_info * info,uint16_t fibnum,uint16_t kidx,uint8_t type)1724 dyn_add_ipv6_state(void *parent, uint32_t ruleid, uint16_t rulenum,
1725     const struct ipfw_flow_id *pkt, uint32_t zoneid, const void *ulp,
1726     int pktlen, uint32_t hashval, struct ipfw_dyn_info *info,
1727     uint16_t fibnum, uint16_t kidx, uint8_t type)
1728 {
1729 	struct dyn_ipv6_state *s;
1730 	struct dyn_data *data;
1731 	uint32_t bucket;
1732 
1733 	bucket = DYN_BUCKET(hashval, V_curr_dyn_buckets);
1734 	DYN_BUCKET_LOCK(bucket);
1735 	if (info->direction == MATCH_UNKNOWN ||
1736 	    info->kidx != kidx ||
1737 	    info->hashval != hashval ||
1738 	    info->version != DYN_BUCKET_VERSION(bucket, ipv6_add)) {
1739 		/*
1740 		 * Bucket version has been changed since last lookup,
1741 		 * do lookup again to be sure that state does not exist.
1742 		 */
1743 		if (dyn_lookup_ipv6_state_locked(pkt, zoneid, ulp, pktlen,
1744 		    bucket, kidx) != 0) {
1745 			DYN_BUCKET_UNLOCK(bucket);
1746 			return (EEXIST);
1747 		}
1748 	}
1749 
1750 	data = dyn_alloc_dyndata(parent, ruleid, rulenum, pkt, ulp,
1751 	    pktlen, hashval, fibnum);
1752 	if (data == NULL) {
1753 		DYN_BUCKET_UNLOCK(bucket);
1754 		return (ENOMEM);
1755 	}
1756 
1757 	s = dyn_alloc_ipv6_state(pkt, zoneid, kidx, type);
1758 	if (s == NULL) {
1759 		DYN_BUCKET_UNLOCK(bucket);
1760 		uma_zfree(V_dyn_data_zone, data);
1761 		return (ENOMEM);
1762 	}
1763 
1764 	s->data = data;
1765 	CK_SLIST_INSERT_HEAD(&V_dyn_ipv6[bucket], s, entry);
1766 	DYN_COUNT_INC(dyn_count);
1767 	DYN_BUCKET_VERSION_BUMP(bucket, ipv6_add);
1768 	DYN_BUCKET_UNLOCK(bucket);
1769 	return (0);
1770 }
1771 #endif /* INET6 */
1772 
1773 static void *
dyn_get_parent_state(const struct ipfw_flow_id * pkt,uint32_t zoneid,struct ip_fw * rule,uint32_t hashval,uint32_t limit,uint16_t kidx)1774 dyn_get_parent_state(const struct ipfw_flow_id *pkt, uint32_t zoneid,
1775     struct ip_fw *rule, uint32_t hashval, uint32_t limit, uint16_t kidx)
1776 {
1777 	char sbuf[24];
1778 	struct dyn_parent *p;
1779 	void *ret;
1780 	uint32_t bucket, version;
1781 
1782 	p = NULL;
1783 	ret = NULL;
1784 	bucket = DYN_BUCKET(hashval, V_curr_dyn_buckets);
1785 	DYNSTATE_CRITICAL_ENTER();
1786 	if (IS_IP4_FLOW_ID(pkt)) {
1787 		struct dyn_ipv4_state *s;
1788 
1789 		version = DYN_BUCKET_VERSION(bucket, ipv4_parent_add);
1790 		s = dyn_lookup_ipv4_parent(pkt, rule, rule->id,
1791 		    rule->rulenum, bucket);
1792 		if (s == NULL) {
1793 			/*
1794 			 * Exit from critical section because dyn_add_parent()
1795 			 * will acquire bucket lock.
1796 			 */
1797 			DYNSTATE_CRITICAL_EXIT();
1798 
1799 			s = dyn_add_ipv4_parent(rule, rule->id,
1800 			    rule->rulenum, pkt, hashval, version, kidx);
1801 			if (s == NULL)
1802 				return (NULL);
1803 			/* Now we are in critical section again. */
1804 		}
1805 		ret = s;
1806 		p = s->limit;
1807 	}
1808 #ifdef INET6
1809 	else if (IS_IP6_FLOW_ID(pkt)) {
1810 		struct dyn_ipv6_state *s;
1811 
1812 		version = DYN_BUCKET_VERSION(bucket, ipv6_parent_add);
1813 		s = dyn_lookup_ipv6_parent(pkt, zoneid, rule, rule->id,
1814 		    rule->rulenum, bucket);
1815 		if (s == NULL) {
1816 			/*
1817 			 * Exit from critical section because dyn_add_parent()
1818 			 * can acquire bucket mutex.
1819 			 */
1820 			DYNSTATE_CRITICAL_EXIT();
1821 
1822 			s = dyn_add_ipv6_parent(rule, rule->id,
1823 			    rule->rulenum, pkt, zoneid, hashval, version,
1824 			    kidx);
1825 			if (s == NULL)
1826 				return (NULL);
1827 			/* Now we are in critical section again. */
1828 		}
1829 		ret = s;
1830 		p = s->limit;
1831 	}
1832 #endif
1833 	else {
1834 		DYNSTATE_CRITICAL_EXIT();
1835 		return (NULL);
1836 	}
1837 
1838 	/* Check the limit */
1839 	if (DPARENT_COUNT(p) >= limit) {
1840 		DYNSTATE_CRITICAL_EXIT();
1841 		if (V_fw_verbose && last_log != time_uptime) {
1842 			last_log = time_uptime;
1843 			snprintf(sbuf, sizeof(sbuf), "%u drop session",
1844 			    rule->rulenum);
1845 			print_dyn_rule_flags(pkt, O_LIMIT,
1846 			    LOG_SECURITY | LOG_DEBUG, sbuf,
1847 			    "too many entries");
1848 		}
1849 		return (NULL);
1850 	}
1851 
1852 	/* Take new session into account. */
1853 	DPARENT_COUNT_INC(p);
1854 	/*
1855 	 * We must exit from critical section because the following code
1856 	 * can acquire bucket mutex.
1857 	 * We rely on the the 'count' field. The state will not expire
1858 	 * until it has some child states, i.e. 'count' field is not zero.
1859 	 * Return state pointer, it will be used by child states as parent.
1860 	 */
1861 	DYNSTATE_CRITICAL_EXIT();
1862 	return (ret);
1863 }
1864 
1865 static int
dyn_install_state(const struct ipfw_flow_id * pkt,uint32_t zoneid,uint16_t fibnum,const void * ulp,int pktlen,struct ip_fw * rule,struct ipfw_dyn_info * info,uint32_t limit,uint16_t limit_mask,uint16_t kidx,uint8_t type)1866 dyn_install_state(const struct ipfw_flow_id *pkt, uint32_t zoneid,
1867     uint16_t fibnum, const void *ulp, int pktlen, struct ip_fw *rule,
1868     struct ipfw_dyn_info *info, uint32_t limit, uint16_t limit_mask,
1869     uint16_t kidx, uint8_t type)
1870 {
1871 	struct ipfw_flow_id id;
1872 	uint32_t hashval, parent_hashval, ruleid, rulenum;
1873 	int ret;
1874 
1875 	MPASS(type == O_LIMIT || type == O_KEEP_STATE);
1876 
1877 	ruleid = rule->id;
1878 	rulenum = rule->rulenum;
1879 	if (type == O_LIMIT) {
1880 		/* Create masked flow id and calculate bucket */
1881 		id.addr_type = pkt->addr_type;
1882 		id.proto = pkt->proto;
1883 		id.fib = fibnum; /* unused */
1884 		id.src_port = (limit_mask & DYN_SRC_PORT) ?
1885 		    pkt->src_port: 0;
1886 		id.dst_port = (limit_mask & DYN_DST_PORT) ?
1887 		    pkt->dst_port: 0;
1888 		if (IS_IP4_FLOW_ID(pkt)) {
1889 			id.src_ip = (limit_mask & DYN_SRC_ADDR) ?
1890 			    pkt->src_ip: 0;
1891 			id.dst_ip = (limit_mask & DYN_DST_ADDR) ?
1892 			    pkt->dst_ip: 0;
1893 		}
1894 #ifdef INET6
1895 		else if (IS_IP6_FLOW_ID(pkt)) {
1896 			if (limit_mask & DYN_SRC_ADDR)
1897 				id.src_ip6 = pkt->src_ip6;
1898 			else
1899 				memset(&id.src_ip6, 0, sizeof(id.src_ip6));
1900 			if (limit_mask & DYN_DST_ADDR)
1901 				id.dst_ip6 = pkt->dst_ip6;
1902 			else
1903 				memset(&id.dst_ip6, 0, sizeof(id.dst_ip6));
1904 		}
1905 #endif
1906 		else
1907 			return (EAFNOSUPPORT);
1908 
1909 		parent_hashval = hash_parent(&id, rule);
1910 		rule = dyn_get_parent_state(&id, zoneid, rule, parent_hashval,
1911 		    limit, kidx);
1912 		if (rule == NULL) {
1913 #if 0
1914 			if (V_fw_verbose && last_log != time_uptime) {
1915 				last_log = time_uptime;
1916 				snprintf(sbuf, sizeof(sbuf),
1917 				    "%u drop session", rule->rulenum);
1918 			print_dyn_rule_flags(pkt, O_LIMIT,
1919 			    LOG_SECURITY | LOG_DEBUG, sbuf,
1920 			    "too many entries");
1921 			}
1922 #endif
1923 			return (EACCES);
1924 		}
1925 		/*
1926 		 * Limit is not reached, create new state.
1927 		 * Now rule points to parent state.
1928 		 */
1929 	}
1930 
1931 	hashval = hash_packet(pkt);
1932 	if (IS_IP4_FLOW_ID(pkt))
1933 		ret = dyn_add_ipv4_state(rule, ruleid, rulenum, pkt,
1934 		    ulp, pktlen, hashval, info, fibnum, kidx, type);
1935 #ifdef INET6
1936 	else if (IS_IP6_FLOW_ID(pkt))
1937 		ret = dyn_add_ipv6_state(rule, ruleid, rulenum, pkt,
1938 		    zoneid, ulp, pktlen, hashval, info, fibnum, kidx, type);
1939 #endif /* INET6 */
1940 	else
1941 		ret = EAFNOSUPPORT;
1942 
1943 	if (type == O_LIMIT) {
1944 		if (ret != 0) {
1945 			/*
1946 			 * We failed to create child state for O_LIMIT
1947 			 * opcode. Since we already counted it in the parent,
1948 			 * we must revert counter back. The 'rule' points to
1949 			 * parent state, use it to get dyn_parent.
1950 			 *
1951 			 * XXXAE: it should be safe to use 'rule' pointer
1952 			 * without extra lookup, parent state is referenced
1953 			 * and should not be freed.
1954 			 */
1955 			if (IS_IP4_FLOW_ID(&id))
1956 				DPARENT_COUNT_DEC(
1957 				    ((struct dyn_ipv4_state *)rule)->limit);
1958 #ifdef INET6
1959 			else if (IS_IP6_FLOW_ID(&id))
1960 				DPARENT_COUNT_DEC(
1961 				    ((struct dyn_ipv6_state *)rule)->limit);
1962 #endif
1963 		}
1964 	}
1965 	/*
1966 	 * EEXIST means that simultaneous thread has created this
1967 	 * state. Consider this as success.
1968 	 *
1969 	 * XXXAE: should we invalidate 'info' content here?
1970 	 */
1971 	if (ret == EEXIST)
1972 		return (0);
1973 	return (ret);
1974 }
1975 
1976 /*
1977  * Install dynamic state.
1978  *  chain - ipfw's instance;
1979  *  rule - the parent rule that installs the state;
1980  *  cmd - opcode that installs the state;
1981  *  args - ipfw arguments;
1982  *  ulp - upper level protocol header;
1983  *  pktlen - packet length;
1984  *  info - dynamic state lookup info;
1985  *  tablearg - tablearg id.
1986  *
1987  * Returns non-zero value (failure) if state is not installed because
1988  * of errors or because session limitations are enforced.
1989  */
1990 int
ipfw_dyn_install_state(struct ip_fw_chain * chain,struct ip_fw * rule,const ipfw_insn_limit * cmd,const struct ip_fw_args * args,const void * ulp,int pktlen,struct ipfw_dyn_info * info,uint32_t tablearg)1991 ipfw_dyn_install_state(struct ip_fw_chain *chain, struct ip_fw *rule,
1992     const ipfw_insn_limit *cmd, const struct ip_fw_args *args,
1993     const void *ulp, int pktlen, struct ipfw_dyn_info *info,
1994     uint32_t tablearg)
1995 {
1996 	uint32_t limit;
1997 	uint16_t limit_mask;
1998 
1999 	if (cmd->o.opcode == O_LIMIT) {
2000 		limit = IP_FW_ARG_TABLEARG(chain, cmd->conn_limit, limit);
2001 		limit_mask = cmd->limit_mask;
2002 	} else {
2003 		limit = 0;
2004 		limit_mask = 0;
2005 	}
2006 	return (dyn_install_state(&args->f_id,
2007 #ifdef INET6
2008 	    IS_IP6_FLOW_ID(&args->f_id) ? dyn_getscopeid(args):
2009 #endif
2010 	    0, M_GETFIB(args->m), ulp, pktlen, rule, info, limit,
2011 	    limit_mask, cmd->o.arg1, cmd->o.opcode));
2012 }
2013 
2014 /*
2015  * Free safe to remove state entries from expired lists.
2016  */
2017 static void
dyn_free_states(struct ip_fw_chain * chain)2018 dyn_free_states(struct ip_fw_chain *chain)
2019 {
2020 	struct dyn_ipv4_state *s4, *s4n;
2021 #ifdef INET6
2022 	struct dyn_ipv6_state *s6, *s6n;
2023 #endif
2024 	int cached_count, i;
2025 
2026 	/*
2027 	 * We keep pointers to objects that are in use on each CPU
2028 	 * in the per-cpu dyn_hp pointer. When object is going to be
2029 	 * removed, first of it is unlinked from the corresponding
2030 	 * list. This leads to changing of dyn_bucket_xxx_delver version.
2031 	 * Unlinked objects is placed into corresponding dyn_expired_xxx
2032 	 * list. Reader that is going to dereference object pointer checks
2033 	 * dyn_bucket_xxx_delver version before and after storing pointer
2034 	 * into dyn_hp. If version is the same, the object is protected
2035 	 * from freeing and it is safe to dereference. Othervise reader
2036 	 * tries to iterate list again from the beginning, but this object
2037 	 * now unlinked and thus will not be accessible.
2038 	 *
2039 	 * Copy dyn_hp pointers for each CPU into dyn_hp_cache array.
2040 	 * It does not matter that some pointer can be changed in
2041 	 * time while we are copying. We need to check, that objects
2042 	 * removed in the previous pass are not in use. And if dyn_hp
2043 	 * pointer does not contain it in the time when we are copying,
2044 	 * it will not appear there, because it is already unlinked.
2045 	 * And for new pointers we will not free objects that will be
2046 	 * unlinked in this pass.
2047 	 */
2048 	cached_count = 0;
2049 	CPU_FOREACH(i) {
2050 		dyn_hp_cache[cached_count] = DYNSTATE_GET(i);
2051 		if (dyn_hp_cache[cached_count] != NULL)
2052 			cached_count++;
2053 	}
2054 
2055 	/*
2056 	 * Free expired states that are safe to free.
2057 	 * Check each entry from previous pass in the dyn_expired_xxx
2058 	 * list, if pointer to the object is in the dyn_hp_cache array,
2059 	 * keep it until next pass. Otherwise it is safe to free the
2060 	 * object.
2061 	 *
2062 	 * XXXAE: optimize this to use SLIST_REMOVE_AFTER.
2063 	 */
2064 #define	DYN_FREE_STATES(s, next, name)		do {			\
2065 	s = SLIST_FIRST(&V_dyn_expired_ ## name);			\
2066 	while (s != NULL) {						\
2067 		next = SLIST_NEXT(s, expired);				\
2068 		for (i = 0; i < cached_count; i++)			\
2069 			if (dyn_hp_cache[i] == s)			\
2070 				break;					\
2071 		if (i == cached_count) {				\
2072 			if (s->type == O_LIMIT_PARENT &&		\
2073 			    s->limit->count != 0) {			\
2074 				s = next;				\
2075 				continue;				\
2076 			}						\
2077 			SLIST_REMOVE(&V_dyn_expired_ ## name,		\
2078 			    s, dyn_ ## name ## _state, expired);	\
2079 			if (s->type == O_LIMIT_PARENT)			\
2080 				uma_zfree(V_dyn_parent_zone, s->limit);	\
2081 			else						\
2082 				uma_zfree(V_dyn_data_zone, s->data);	\
2083 			uma_zfree(V_dyn_ ## name ## _zone, s);		\
2084 		}							\
2085 		s = next;						\
2086 	}								\
2087 } while (0)
2088 
2089 	/*
2090 	 * Protect access to expired lists with DYN_EXPIRED_LOCK.
2091 	 * Userland can invoke ipfw_expire_dyn_states() to delete
2092 	 * specific states, this will lead to modification of expired
2093 	 * lists.
2094 	 *
2095 	 * XXXAE: do we need DYN_EXPIRED_LOCK? We can just use
2096 	 *	  IPFW_UH_WLOCK to protect access to these lists.
2097 	 */
2098 	DYN_EXPIRED_LOCK();
2099 	DYN_FREE_STATES(s4, s4n, ipv4);
2100 #ifdef INET6
2101 	DYN_FREE_STATES(s6, s6n, ipv6);
2102 #endif
2103 	DYN_EXPIRED_UNLOCK();
2104 #undef DYN_FREE_STATES
2105 }
2106 
2107 /*
2108  * Returns:
2109  * 0 when state is not matched by specified range;
2110  * 1 when state is matched by specified range;
2111  * 2 when state is matched by specified range and requested deletion of
2112  *   dynamic states.
2113  */
2114 static int
dyn_match_range(uint16_t rulenum,uint8_t set,const ipfw_range_tlv * rt)2115 dyn_match_range(uint16_t rulenum, uint8_t set, const ipfw_range_tlv *rt)
2116 {
2117 
2118 	MPASS(rt != NULL);
2119 	/* flush all states */
2120 	if (rt->flags & IPFW_RCFLAG_ALL) {
2121 		if (rt->flags & IPFW_RCFLAG_DYNAMIC)
2122 			return (2); /* forced */
2123 		return (1);
2124 	}
2125 	if ((rt->flags & IPFW_RCFLAG_SET) != 0 && set != rt->set)
2126 		return (0);
2127 	if ((rt->flags & IPFW_RCFLAG_RANGE) != 0 &&
2128 	    (rulenum < rt->start_rule || rulenum > rt->end_rule))
2129 		return (0);
2130 	if (rt->flags & IPFW_RCFLAG_DYNAMIC)
2131 		return (2);
2132 	return (1);
2133 }
2134 
2135 static void
dyn_acquire_rule(struct ip_fw_chain * ch,struct dyn_data * data,struct ip_fw * rule,uint16_t kidx)2136 dyn_acquire_rule(struct ip_fw_chain *ch, struct dyn_data *data,
2137     struct ip_fw *rule, uint16_t kidx)
2138 {
2139 	struct dyn_state_obj *obj;
2140 
2141 	/*
2142 	 * Do not acquire reference twice.
2143 	 * This can happen when rule deletion executed for
2144 	 * the same range, but different ruleset id.
2145 	 */
2146 	if (data->flags & DYN_REFERENCED)
2147 		return;
2148 
2149 	IPFW_UH_WLOCK_ASSERT(ch);
2150 	MPASS(kidx != 0);
2151 
2152 	data->flags |= DYN_REFERENCED;
2153 	/* Reference the named object */
2154 	obj = SRV_OBJECT(ch, kidx);
2155 	obj->no.refcnt++;
2156 	MPASS(obj->no.etlv == IPFW_TLV_STATE_NAME);
2157 
2158 	/* Reference the parent rule */
2159 	rule->refcnt++;
2160 }
2161 
2162 static void
dyn_release_rule(struct ip_fw_chain * ch,struct dyn_data * data,struct ip_fw * rule,uint16_t kidx)2163 dyn_release_rule(struct ip_fw_chain *ch, struct dyn_data *data,
2164     struct ip_fw *rule, uint16_t kidx)
2165 {
2166 	struct dyn_state_obj *obj;
2167 
2168 	IPFW_UH_WLOCK_ASSERT(ch);
2169 	MPASS(kidx != 0);
2170 
2171 	obj = SRV_OBJECT(ch, kidx);
2172 	if (obj->no.refcnt == 1)
2173 		dyn_destroy(ch, &obj->no);
2174 	else
2175 		obj->no.refcnt--;
2176 
2177 	if (--rule->refcnt == 1)
2178 		ipfw_free_rule(rule);
2179 }
2180 
2181 /*
2182  * We do not keep O_LIMIT_PARENT states when V_dyn_keep_states is enabled.
2183  * O_LIMIT state is created when new connection is going to be established
2184  * and there is no matching state. So, since the old parent rule was deleted
2185  * we can't create new states with old parent, and thus we can not account
2186  * new connections with already established connections, and can not do
2187  * proper limiting.
2188  */
2189 static int
dyn_match_ipv4_state(struct ip_fw_chain * ch,struct dyn_ipv4_state * s,const ipfw_range_tlv * rt)2190 dyn_match_ipv4_state(struct ip_fw_chain *ch, struct dyn_ipv4_state *s,
2191     const ipfw_range_tlv *rt)
2192 {
2193 	struct ip_fw *rule;
2194 	int ret;
2195 
2196 	if (s->type == O_LIMIT_PARENT) {
2197 		rule = s->limit->parent;
2198 		return (dyn_match_range(s->limit->rulenum, rule->set, rt));
2199 	}
2200 
2201 	rule = s->data->parent;
2202 	if (s->type == O_LIMIT)
2203 		rule = ((struct dyn_ipv4_state *)rule)->limit->parent;
2204 
2205 	ret = dyn_match_range(s->data->rulenum, rule->set, rt);
2206 	if (ret == 0 || V_dyn_keep_states == 0 || ret > 1)
2207 		return (ret);
2208 
2209 	dyn_acquire_rule(ch, s->data, rule, s->kidx);
2210 	return (0);
2211 }
2212 
2213 #ifdef INET6
2214 static int
dyn_match_ipv6_state(struct ip_fw_chain * ch,struct dyn_ipv6_state * s,const ipfw_range_tlv * rt)2215 dyn_match_ipv6_state(struct ip_fw_chain *ch, struct dyn_ipv6_state *s,
2216     const ipfw_range_tlv *rt)
2217 {
2218 	struct ip_fw *rule;
2219 	int ret;
2220 
2221 	if (s->type == O_LIMIT_PARENT) {
2222 		rule = s->limit->parent;
2223 		return (dyn_match_range(s->limit->rulenum, rule->set, rt));
2224 	}
2225 
2226 	rule = s->data->parent;
2227 	if (s->type == O_LIMIT)
2228 		rule = ((struct dyn_ipv6_state *)rule)->limit->parent;
2229 
2230 	ret = dyn_match_range(s->data->rulenum, rule->set, rt);
2231 	if (ret == 0 || V_dyn_keep_states == 0 || ret > 1)
2232 		return (ret);
2233 
2234 	dyn_acquire_rule(ch, s->data, rule, s->kidx);
2235 	return (0);
2236 }
2237 #endif
2238 
2239 /*
2240  * Unlink expired entries from states lists.
2241  * @rt can be used to specify the range of states for deletion.
2242  */
2243 static void
dyn_expire_states(struct ip_fw_chain * ch,ipfw_range_tlv * rt)2244 dyn_expire_states(struct ip_fw_chain *ch, ipfw_range_tlv *rt)
2245 {
2246 	struct dyn_ipv4_slist expired_ipv4;
2247 #ifdef INET6
2248 	struct dyn_ipv6_slist expired_ipv6;
2249 	struct dyn_ipv6_state *s6, *s6n, *s6p;
2250 #endif
2251 	struct dyn_ipv4_state *s4, *s4n, *s4p;
2252 	void *rule;
2253 	int bucket, removed, length, max_length;
2254 
2255 	IPFW_UH_WLOCK_ASSERT(ch);
2256 
2257 	/*
2258 	 * Unlink expired states from each bucket.
2259 	 * With acquired bucket lock iterate entries of each lists:
2260 	 * ipv4, ipv4_parent, ipv6, and ipv6_parent. Check expired time
2261 	 * and unlink entry from the list, link entry into temporary
2262 	 * expired_xxx lists then bump "del" bucket version.
2263 	 *
2264 	 * When an entry is removed, corresponding states counter is
2265 	 * decremented. If entry has O_LIMIT type, parent's reference
2266 	 * counter is decremented.
2267 	 *
2268 	 * NOTE: this function can be called from userspace context
2269 	 * when user deletes rules. In this case all matched states
2270 	 * will be forcedly unlinked. O_LIMIT_PARENT states will be kept
2271 	 * in the expired lists until reference counter become zero.
2272 	 */
2273 #define	DYN_UNLINK_STATES(s, prev, next, exp, af, name, extra)	do {	\
2274 	length = 0;							\
2275 	removed = 0;							\
2276 	prev = NULL;							\
2277 	s = CK_SLIST_FIRST(&V_dyn_ ## name [bucket]);			\
2278 	while (s != NULL) {						\
2279 		next = CK_SLIST_NEXT(s, entry);				\
2280 		if ((TIME_LEQ((s)->exp, time_uptime) && extra) ||	\
2281 		    (rt != NULL &&					\
2282 		     dyn_match_ ## af ## _state(ch, s, rt))) {		\
2283 			if (prev != NULL)				\
2284 				CK_SLIST_REMOVE_AFTER(prev, entry);	\
2285 			else						\
2286 				CK_SLIST_REMOVE_HEAD(			\
2287 				    &V_dyn_ ## name [bucket], entry);	\
2288 			removed++;					\
2289 			SLIST_INSERT_HEAD(&expired_ ## af, s, expired);	\
2290 			if (s->type == O_LIMIT_PARENT)			\
2291 				DYN_COUNT_DEC(dyn_parent_count);	\
2292 			else {						\
2293 				DYN_COUNT_DEC(dyn_count);		\
2294 				if (s->data->flags & DYN_REFERENCED) {	\
2295 					rule = s->data->parent;		\
2296 					if (s->type == O_LIMIT)		\
2297 						rule = ((__typeof(s))	\
2298 						    rule)->limit->parent;\
2299 					dyn_release_rule(ch, s->data,	\
2300 					    rule, s->kidx);		\
2301 				}					\
2302 				if (s->type == O_LIMIT)	{		\
2303 					s = s->data->parent;		\
2304 					DPARENT_COUNT_DEC(s->limit);	\
2305 				}					\
2306 			}						\
2307 		} else {						\
2308 			prev = s;					\
2309 			length++;					\
2310 		}							\
2311 		s = next;						\
2312 	}								\
2313 	if (removed != 0)						\
2314 		DYN_BUCKET_VERSION_BUMP(bucket, name ## _del);		\
2315 	if (length > max_length)				\
2316 		max_length = length;				\
2317 } while (0)
2318 
2319 	SLIST_INIT(&expired_ipv4);
2320 #ifdef INET6
2321 	SLIST_INIT(&expired_ipv6);
2322 #endif
2323 	max_length = 0;
2324 	for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
2325 		DYN_BUCKET_LOCK(bucket);
2326 		DYN_UNLINK_STATES(s4, s4p, s4n, data->expire, ipv4, ipv4, 1);
2327 		DYN_UNLINK_STATES(s4, s4p, s4n, limit->expire, ipv4,
2328 		    ipv4_parent, (s4->limit->count == 0));
2329 #ifdef INET6
2330 		DYN_UNLINK_STATES(s6, s6p, s6n, data->expire, ipv6, ipv6, 1);
2331 		DYN_UNLINK_STATES(s6, s6p, s6n, limit->expire, ipv6,
2332 		    ipv6_parent, (s6->limit->count == 0));
2333 #endif
2334 		DYN_BUCKET_UNLOCK(bucket);
2335 	}
2336 	/* Update curr_max_length for statistics. */
2337 	V_curr_max_length = max_length;
2338 	/*
2339 	 * Concatenate temporary lists with global expired lists.
2340 	 */
2341 	DYN_EXPIRED_LOCK();
2342 	SLIST_CONCAT(&V_dyn_expired_ipv4, &expired_ipv4,
2343 	    dyn_ipv4_state, expired);
2344 #ifdef INET6
2345 	SLIST_CONCAT(&V_dyn_expired_ipv6, &expired_ipv6,
2346 	    dyn_ipv6_state, expired);
2347 #endif
2348 	DYN_EXPIRED_UNLOCK();
2349 #undef DYN_UNLINK_STATES
2350 #undef DYN_UNREF_STATES
2351 }
2352 
2353 static struct mbuf *
dyn_mgethdr(int len,uint16_t fibnum)2354 dyn_mgethdr(int len, uint16_t fibnum)
2355 {
2356 	struct mbuf *m;
2357 
2358 	m = m_gethdr(M_NOWAIT, MT_DATA);
2359 	if (m == NULL)
2360 		return (NULL);
2361 #ifdef MAC
2362 	mac_netinet_firewall_send(m);
2363 #endif
2364 	M_SETFIB(m, fibnum);
2365 	m->m_data += max_linkhdr;
2366 	m->m_flags |= M_SKIP_FIREWALL;
2367 	m->m_len = m->m_pkthdr.len = len;
2368 	bzero(m->m_data, len);
2369 	return (m);
2370 }
2371 
2372 static void
dyn_make_keepalive_ipv4(struct mbuf * m,in_addr_t src,in_addr_t dst,uint32_t seq,uint32_t ack,uint16_t sport,uint16_t dport)2373 dyn_make_keepalive_ipv4(struct mbuf *m, in_addr_t src, in_addr_t dst,
2374     uint32_t seq, uint32_t ack, uint16_t sport, uint16_t dport)
2375 {
2376 	struct tcphdr *tcp;
2377 	struct ip *ip;
2378 
2379 	ip = mtod(m, struct ip *);
2380 	ip->ip_v = 4;
2381 	ip->ip_hl = sizeof(*ip) >> 2;
2382 	ip->ip_tos = IPTOS_LOWDELAY;
2383 	ip->ip_len = htons(m->m_len);
2384 	ip->ip_off |= htons(IP_DF);
2385 	ip->ip_ttl = V_ip_defttl;
2386 	ip->ip_p = IPPROTO_TCP;
2387 	ip->ip_src.s_addr = htonl(src);
2388 	ip->ip_dst.s_addr = htonl(dst);
2389 
2390 	tcp = mtodo(m, sizeof(struct ip));
2391 	tcp->th_sport = htons(sport);
2392 	tcp->th_dport = htons(dport);
2393 	tcp->th_off = sizeof(struct tcphdr) >> 2;
2394 	tcp->th_seq = htonl(seq);
2395 	tcp->th_ack = htonl(ack);
2396 	tcp->th_flags = TH_ACK;
2397 	tcp->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
2398 	    htons(sizeof(struct tcphdr) + IPPROTO_TCP));
2399 
2400 	m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2401 	m->m_pkthdr.csum_flags = CSUM_TCP;
2402 }
2403 
2404 static void
dyn_enqueue_keepalive_ipv4(struct mbufq * q,const struct dyn_ipv4_state * s)2405 dyn_enqueue_keepalive_ipv4(struct mbufq *q, const struct dyn_ipv4_state *s)
2406 {
2407 	struct mbuf *m;
2408 
2409 	if ((s->data->state & ACK_FWD) == 0 && s->data->ack_fwd > 0) {
2410 		m = dyn_mgethdr(sizeof(struct ip) + sizeof(struct tcphdr),
2411 		    s->data->fibnum);
2412 		if (m != NULL) {
2413 			dyn_make_keepalive_ipv4(m, s->dst, s->src,
2414 			    s->data->ack_fwd - 1, s->data->ack_rev,
2415 			    s->dport, s->sport);
2416 			if (mbufq_enqueue(q, m)) {
2417 				m_freem(m);
2418 				log(LOG_DEBUG, "ipfw: limit for IPv4 "
2419 				    "keepalive queue is reached.\n");
2420 				return;
2421 			}
2422 		}
2423 	}
2424 
2425 	if ((s->data->state & ACK_REV) == 0 && s->data->ack_rev > 0) {
2426 		m = dyn_mgethdr(sizeof(struct ip) + sizeof(struct tcphdr),
2427 		    s->data->fibnum);
2428 		if (m != NULL) {
2429 			dyn_make_keepalive_ipv4(m, s->src, s->dst,
2430 			    s->data->ack_rev - 1, s->data->ack_fwd,
2431 			    s->sport, s->dport);
2432 			if (mbufq_enqueue(q, m)) {
2433 				m_freem(m);
2434 				log(LOG_DEBUG, "ipfw: limit for IPv4 "
2435 				    "keepalive queue is reached.\n");
2436 				return;
2437 			}
2438 		}
2439 	}
2440 }
2441 
2442 /*
2443  * Prepare and send keep-alive packets.
2444  */
2445 static void
dyn_send_keepalive_ipv4(struct ip_fw_chain * chain)2446 dyn_send_keepalive_ipv4(struct ip_fw_chain *chain)
2447 {
2448 	struct mbufq q;
2449 	struct mbuf *m;
2450 	struct dyn_ipv4_state *s;
2451 	uint32_t bucket;
2452 
2453 	mbufq_init(&q, INT_MAX);
2454 	IPFW_UH_RLOCK(chain);
2455 	/*
2456 	 * It is safe to not use hazard pointer and just do lockless
2457 	 * access to the lists, because states entries can not be deleted
2458 	 * while we hold IPFW_UH_RLOCK.
2459 	 */
2460 	for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
2461 		CK_SLIST_FOREACH(s, &V_dyn_ipv4[bucket], entry) {
2462 			/*
2463 			 * Only established TCP connections that will
2464 			 * become expired withing dyn_keepalive_interval.
2465 			 */
2466 			if (s->proto != IPPROTO_TCP ||
2467 			    (s->data->state & BOTH_SYN) != BOTH_SYN ||
2468 			    TIME_LEQ(time_uptime + V_dyn_keepalive_interval,
2469 				s->data->expire))
2470 				continue;
2471 			dyn_enqueue_keepalive_ipv4(&q, s);
2472 		}
2473 	}
2474 	IPFW_UH_RUNLOCK(chain);
2475 	while ((m = mbufq_dequeue(&q)) != NULL)
2476 		ip_output(m, NULL, NULL, 0, NULL, NULL);
2477 }
2478 
2479 #ifdef INET6
2480 static void
dyn_make_keepalive_ipv6(struct mbuf * m,const struct in6_addr * src,const struct in6_addr * dst,uint32_t zoneid,uint32_t seq,uint32_t ack,uint16_t sport,uint16_t dport)2481 dyn_make_keepalive_ipv6(struct mbuf *m, const struct in6_addr *src,
2482     const struct in6_addr *dst, uint32_t zoneid, uint32_t seq, uint32_t ack,
2483     uint16_t sport, uint16_t dport)
2484 {
2485 	struct tcphdr *tcp;
2486 	struct ip6_hdr *ip6;
2487 
2488 	ip6 = mtod(m, struct ip6_hdr *);
2489 	ip6->ip6_vfc |= IPV6_VERSION;
2490 	ip6->ip6_plen = htons(sizeof(struct tcphdr));
2491 	ip6->ip6_nxt = IPPROTO_TCP;
2492 	ip6->ip6_hlim = IPV6_DEFHLIM;
2493 	ip6->ip6_src = *src;
2494 	if (IN6_IS_ADDR_LINKLOCAL(src))
2495 		ip6->ip6_src.s6_addr16[1] = htons(zoneid & 0xffff);
2496 	ip6->ip6_dst = *dst;
2497 	if (IN6_IS_ADDR_LINKLOCAL(dst))
2498 		ip6->ip6_dst.s6_addr16[1] = htons(zoneid & 0xffff);
2499 
2500 	tcp = mtodo(m, sizeof(struct ip6_hdr));
2501 	tcp->th_sport = htons(sport);
2502 	tcp->th_dport = htons(dport);
2503 	tcp->th_off = sizeof(struct tcphdr) >> 2;
2504 	tcp->th_seq = htonl(seq);
2505 	tcp->th_ack = htonl(ack);
2506 	tcp->th_flags = TH_ACK;
2507 	tcp->th_sum = in6_cksum_pseudo(ip6, sizeof(struct tcphdr),
2508 	    IPPROTO_TCP, 0);
2509 
2510 	m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2511 	m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
2512 }
2513 
2514 static void
dyn_enqueue_keepalive_ipv6(struct mbufq * q,const struct dyn_ipv6_state * s)2515 dyn_enqueue_keepalive_ipv6(struct mbufq *q, const struct dyn_ipv6_state *s)
2516 {
2517 	struct mbuf *m;
2518 
2519 	if ((s->data->state & ACK_FWD) == 0 && s->data->ack_fwd > 0) {
2520 		m = dyn_mgethdr(sizeof(struct ip6_hdr) +
2521 		    sizeof(struct tcphdr), s->data->fibnum);
2522 		if (m != NULL) {
2523 			dyn_make_keepalive_ipv6(m, &s->dst, &s->src,
2524 			    s->zoneid, s->data->ack_fwd - 1, s->data->ack_rev,
2525 			    s->dport, s->sport);
2526 			if (mbufq_enqueue(q, m)) {
2527 				m_freem(m);
2528 				log(LOG_DEBUG, "ipfw: limit for IPv6 "
2529 				    "keepalive queue is reached.\n");
2530 				return;
2531 			}
2532 		}
2533 	}
2534 
2535 	if ((s->data->state & ACK_REV) == 0 && s->data->ack_rev > 0) {
2536 		m = dyn_mgethdr(sizeof(struct ip6_hdr) +
2537 		    sizeof(struct tcphdr), s->data->fibnum);
2538 		if (m != NULL) {
2539 			dyn_make_keepalive_ipv6(m, &s->src, &s->dst,
2540 			    s->zoneid, s->data->ack_rev - 1, s->data->ack_fwd,
2541 			    s->sport, s->dport);
2542 			if (mbufq_enqueue(q, m)) {
2543 				m_freem(m);
2544 				log(LOG_DEBUG, "ipfw: limit for IPv6 "
2545 				    "keepalive queue is reached.\n");
2546 				return;
2547 			}
2548 		}
2549 	}
2550 }
2551 
2552 static void
dyn_send_keepalive_ipv6(struct ip_fw_chain * chain)2553 dyn_send_keepalive_ipv6(struct ip_fw_chain *chain)
2554 {
2555 	struct mbufq q;
2556 	struct mbuf *m;
2557 	struct dyn_ipv6_state *s;
2558 	uint32_t bucket;
2559 
2560 	mbufq_init(&q, INT_MAX);
2561 	IPFW_UH_RLOCK(chain);
2562 	/*
2563 	 * It is safe to not use hazard pointer and just do lockless
2564 	 * access to the lists, because states entries can not be deleted
2565 	 * while we hold IPFW_UH_RLOCK.
2566 	 */
2567 	for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
2568 		CK_SLIST_FOREACH(s, &V_dyn_ipv6[bucket], entry) {
2569 			/*
2570 			 * Only established TCP connections that will
2571 			 * become expired withing dyn_keepalive_interval.
2572 			 */
2573 			if (s->proto != IPPROTO_TCP ||
2574 			    (s->data->state & BOTH_SYN) != BOTH_SYN ||
2575 			    TIME_LEQ(time_uptime + V_dyn_keepalive_interval,
2576 				s->data->expire))
2577 				continue;
2578 			dyn_enqueue_keepalive_ipv6(&q, s);
2579 		}
2580 	}
2581 	IPFW_UH_RUNLOCK(chain);
2582 	while ((m = mbufq_dequeue(&q)) != NULL)
2583 		ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
2584 }
2585 #endif /* INET6 */
2586 
2587 static void
dyn_grow_hashtable(struct ip_fw_chain * chain,uint32_t new)2588 dyn_grow_hashtable(struct ip_fw_chain *chain, uint32_t new)
2589 {
2590 #ifdef INET6
2591 	struct dyn_ipv6ck_slist *ipv6, *ipv6_parent;
2592 	uint32_t *ipv6_add, *ipv6_del, *ipv6_parent_add, *ipv6_parent_del;
2593 	struct dyn_ipv6_state *s6;
2594 #endif
2595 	struct dyn_ipv4ck_slist *ipv4, *ipv4_parent;
2596 	uint32_t *ipv4_add, *ipv4_del, *ipv4_parent_add, *ipv4_parent_del;
2597 	struct dyn_ipv4_state *s4;
2598 	struct mtx *bucket_lock;
2599 	void *tmp;
2600 	uint32_t bucket;
2601 
2602 	MPASS(powerof2(new));
2603 	DYN_DEBUG("grow hash size %u -> %u", V_curr_dyn_buckets, new);
2604 	/*
2605 	 * Allocate and initialize new lists.
2606 	 * XXXAE: on memory pressure this can disable callout timer.
2607 	 */
2608 	bucket_lock = malloc(new * sizeof(struct mtx), M_IPFW,
2609 	    M_WAITOK | M_ZERO);
2610 	ipv4 = malloc(new * sizeof(struct dyn_ipv4ck_slist), M_IPFW,
2611 	    M_WAITOK | M_ZERO);
2612 	ipv4_parent = malloc(new * sizeof(struct dyn_ipv4ck_slist), M_IPFW,
2613 	    M_WAITOK | M_ZERO);
2614 	ipv4_add = malloc(new * sizeof(uint32_t), M_IPFW, M_WAITOK | M_ZERO);
2615 	ipv4_del = malloc(new * sizeof(uint32_t), M_IPFW, M_WAITOK | M_ZERO);
2616 	ipv4_parent_add = malloc(new * sizeof(uint32_t), M_IPFW,
2617 	    M_WAITOK | M_ZERO);
2618 	ipv4_parent_del = malloc(new * sizeof(uint32_t), M_IPFW,
2619 	    M_WAITOK | M_ZERO);
2620 #ifdef INET6
2621 	ipv6 = malloc(new * sizeof(struct dyn_ipv6ck_slist), M_IPFW,
2622 	    M_WAITOK | M_ZERO);
2623 	ipv6_parent = malloc(new * sizeof(struct dyn_ipv6ck_slist), M_IPFW,
2624 	    M_WAITOK | M_ZERO);
2625 	ipv6_add = malloc(new * sizeof(uint32_t), M_IPFW, M_WAITOK | M_ZERO);
2626 	ipv6_del = malloc(new * sizeof(uint32_t), M_IPFW, M_WAITOK | M_ZERO);
2627 	ipv6_parent_add = malloc(new * sizeof(uint32_t), M_IPFW,
2628 	    M_WAITOK | M_ZERO);
2629 	ipv6_parent_del = malloc(new * sizeof(uint32_t), M_IPFW,
2630 	    M_WAITOK | M_ZERO);
2631 #endif
2632 	for (bucket = 0; bucket < new; bucket++) {
2633 		DYN_BUCKET_LOCK_INIT(bucket_lock, bucket);
2634 		CK_SLIST_INIT(&ipv4[bucket]);
2635 		CK_SLIST_INIT(&ipv4_parent[bucket]);
2636 #ifdef INET6
2637 		CK_SLIST_INIT(&ipv6[bucket]);
2638 		CK_SLIST_INIT(&ipv6_parent[bucket]);
2639 #endif
2640 	}
2641 
2642 #define DYN_RELINK_STATES(s, hval, i, head, ohead)	do {		\
2643 	while ((s = CK_SLIST_FIRST(&V_dyn_ ## ohead[i])) != NULL) {	\
2644 		CK_SLIST_REMOVE_HEAD(&V_dyn_ ## ohead[i], entry);	\
2645 		CK_SLIST_INSERT_HEAD(&head[DYN_BUCKET(s->hval, new)],	\
2646 		    s, entry);						\
2647 	}								\
2648 } while (0)
2649 	/*
2650 	 * Prevent rules changing from userland.
2651 	 */
2652 	IPFW_UH_WLOCK(chain);
2653 	/*
2654 	 * Hold traffic processing until we finish resize to
2655 	 * prevent access to states lists.
2656 	 */
2657 	IPFW_WLOCK(chain);
2658 	/* Re-link all dynamic states */
2659 	for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
2660 		DYN_RELINK_STATES(s4, data->hashval, bucket, ipv4, ipv4);
2661 		DYN_RELINK_STATES(s4, limit->hashval, bucket, ipv4_parent,
2662 		    ipv4_parent);
2663 #ifdef INET6
2664 		DYN_RELINK_STATES(s6, data->hashval, bucket, ipv6, ipv6);
2665 		DYN_RELINK_STATES(s6, limit->hashval, bucket, ipv6_parent,
2666 		    ipv6_parent);
2667 #endif
2668 	}
2669 
2670 #define	DYN_SWAP_PTR(old, new, tmp)	do {		\
2671 	tmp = old;					\
2672 	old = new;					\
2673 	new = tmp;					\
2674 } while (0)
2675 	/* Swap pointers */
2676 	DYN_SWAP_PTR(V_dyn_bucket_lock, bucket_lock, tmp);
2677 	DYN_SWAP_PTR(V_dyn_ipv4, ipv4, tmp);
2678 	DYN_SWAP_PTR(V_dyn_ipv4_parent, ipv4_parent, tmp);
2679 	DYN_SWAP_PTR(V_dyn_ipv4_add, ipv4_add, tmp);
2680 	DYN_SWAP_PTR(V_dyn_ipv4_parent_add, ipv4_parent_add, tmp);
2681 	DYN_SWAP_PTR(V_dyn_ipv4_del, ipv4_del, tmp);
2682 	DYN_SWAP_PTR(V_dyn_ipv4_parent_del, ipv4_parent_del, tmp);
2683 
2684 #ifdef INET6
2685 	DYN_SWAP_PTR(V_dyn_ipv6, ipv6, tmp);
2686 	DYN_SWAP_PTR(V_dyn_ipv6_parent, ipv6_parent, tmp);
2687 	DYN_SWAP_PTR(V_dyn_ipv6_add, ipv6_add, tmp);
2688 	DYN_SWAP_PTR(V_dyn_ipv6_parent_add, ipv6_parent_add, tmp);
2689 	DYN_SWAP_PTR(V_dyn_ipv6_del, ipv6_del, tmp);
2690 	DYN_SWAP_PTR(V_dyn_ipv6_parent_del, ipv6_parent_del, tmp);
2691 #endif
2692 	bucket = V_curr_dyn_buckets;
2693 	V_curr_dyn_buckets = new;
2694 
2695 	IPFW_WUNLOCK(chain);
2696 	IPFW_UH_WUNLOCK(chain);
2697 
2698 	/* Release old resources */
2699 	while (bucket-- != 0)
2700 		DYN_BUCKET_LOCK_DESTROY(bucket_lock, bucket);
2701 	free(bucket_lock, M_IPFW);
2702 	free(ipv4, M_IPFW);
2703 	free(ipv4_parent, M_IPFW);
2704 	free(ipv4_add, M_IPFW);
2705 	free(ipv4_parent_add, M_IPFW);
2706 	free(ipv4_del, M_IPFW);
2707 	free(ipv4_parent_del, M_IPFW);
2708 #ifdef INET6
2709 	free(ipv6, M_IPFW);
2710 	free(ipv6_parent, M_IPFW);
2711 	free(ipv6_add, M_IPFW);
2712 	free(ipv6_parent_add, M_IPFW);
2713 	free(ipv6_del, M_IPFW);
2714 	free(ipv6_parent_del, M_IPFW);
2715 #endif
2716 }
2717 
2718 /*
2719  * This function is used to perform various maintenance
2720  * on dynamic hash lists. Currently it is called every second.
2721  */
2722 static void
dyn_tick(void * vnetx)2723 dyn_tick(void *vnetx)
2724 {
2725 	uint32_t buckets;
2726 
2727 	CURVNET_SET((struct vnet *)vnetx);
2728 	/*
2729 	 * First free states unlinked in previous passes.
2730 	 */
2731 	dyn_free_states(&V_layer3_chain);
2732 	/*
2733 	 * Now unlink others expired states.
2734 	 * We use IPFW_UH_WLOCK to avoid concurrent call of
2735 	 * dyn_expire_states(). It is the only function that does
2736 	 * deletion of state entries from states lists.
2737 	 */
2738 	IPFW_UH_WLOCK(&V_layer3_chain);
2739 	dyn_expire_states(&V_layer3_chain, NULL);
2740 	IPFW_UH_WUNLOCK(&V_layer3_chain);
2741 	/*
2742 	 * Send keepalives if they are enabled and the time has come.
2743 	 */
2744 	if (V_dyn_keepalive != 0 &&
2745 	    V_dyn_keepalive_last + V_dyn_keepalive_period <= time_uptime) {
2746 		V_dyn_keepalive_last = time_uptime;
2747 		dyn_send_keepalive_ipv4(&V_layer3_chain);
2748 #ifdef INET6
2749 		dyn_send_keepalive_ipv6(&V_layer3_chain);
2750 #endif
2751 	}
2752 	/*
2753 	 * Check if we need to resize the hash:
2754 	 * if current number of states exceeds number of buckets in hash,
2755 	 * and dyn_buckets_max permits to grow the number of buckets, then
2756 	 * do it. Grow hash size to the minimum power of 2 which is bigger
2757 	 * than current states count.
2758 	 */
2759 	if (V_curr_dyn_buckets < V_dyn_buckets_max &&
2760 	    (V_curr_dyn_buckets < V_dyn_count / 2 || (
2761 	    V_curr_dyn_buckets < V_dyn_count && V_curr_max_length > 8))) {
2762 		buckets = 1 << fls(V_dyn_count);
2763 		if (buckets > V_dyn_buckets_max)
2764 			buckets = V_dyn_buckets_max;
2765 		dyn_grow_hashtable(&V_layer3_chain, buckets);
2766 	}
2767 
2768 	callout_reset_on(&V_dyn_timeout, hz, dyn_tick, vnetx, 0);
2769 	CURVNET_RESTORE();
2770 }
2771 
2772 void
ipfw_expire_dyn_states(struct ip_fw_chain * chain,ipfw_range_tlv * rt)2773 ipfw_expire_dyn_states(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
2774 {
2775 	/*
2776 	 * Do not perform any checks if we currently have no dynamic states
2777 	 */
2778 	if (V_dyn_count == 0)
2779 		return;
2780 
2781 	IPFW_UH_WLOCK_ASSERT(chain);
2782 	dyn_expire_states(chain, rt);
2783 }
2784 
2785 /*
2786  * Pass through all states and reset eaction for orphaned rules.
2787  */
2788 void
ipfw_dyn_reset_eaction(struct ip_fw_chain * ch,uint16_t eaction_id,uint16_t default_id,uint16_t instance_id)2789 ipfw_dyn_reset_eaction(struct ip_fw_chain *ch, uint16_t eaction_id,
2790     uint16_t default_id, uint16_t instance_id)
2791 {
2792 #ifdef INET6
2793 	struct dyn_ipv6_state *s6;
2794 #endif
2795 	struct dyn_ipv4_state *s4;
2796 	struct ip_fw *rule;
2797 	uint32_t bucket;
2798 
2799 #define	DYN_RESET_EACTION(s, h, b)					\
2800 	CK_SLIST_FOREACH(s, &V_dyn_ ## h[b], entry) {			\
2801 		if ((s->data->flags & DYN_REFERENCED) == 0)		\
2802 			continue;					\
2803 		rule = s->data->parent;					\
2804 		if (s->type == O_LIMIT)					\
2805 			rule = ((__typeof(s))rule)->limit->parent;	\
2806 		ipfw_reset_eaction(ch, rule, eaction_id,		\
2807 		    default_id, instance_id);				\
2808 	}
2809 
2810 	IPFW_UH_WLOCK_ASSERT(ch);
2811 	if (V_dyn_count == 0)
2812 		return;
2813 	for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
2814 		DYN_RESET_EACTION(s4, ipv4, bucket);
2815 #ifdef INET6
2816 		DYN_RESET_EACTION(s6, ipv6, bucket);
2817 #endif
2818 	}
2819 }
2820 
2821 /*
2822  * Returns size of dynamic states in legacy format
2823  */
2824 int
ipfw_dyn_len(void)2825 ipfw_dyn_len(void)
2826 {
2827 
2828 	return ((V_dyn_count + V_dyn_parent_count) * sizeof(ipfw_dyn_rule));
2829 }
2830 
2831 /*
2832  * Returns number of dynamic states.
2833  * Marks every named object index used by dynamic states with bit in @bmask.
2834  * Returns number of named objects accounted in bmask via @nocnt.
2835  * Used by dump format v1 (current).
2836  */
2837 uint32_t
ipfw_dyn_get_count(uint32_t * bmask,int * nocnt)2838 ipfw_dyn_get_count(uint32_t *bmask, int *nocnt)
2839 {
2840 #ifdef INET6
2841 	struct dyn_ipv6_state *s6;
2842 #endif
2843 	struct dyn_ipv4_state *s4;
2844 	uint32_t bucket;
2845 
2846 #define	DYN_COUNT_OBJECTS(s, h, b)					\
2847 	CK_SLIST_FOREACH(s, &V_dyn_ ## h[b], entry) {			\
2848 		MPASS(s->kidx != 0);					\
2849 		if (ipfw_mark_object_kidx(bmask, IPFW_TLV_STATE_NAME,	\
2850 		    s->kidx) != 0)					\
2851 			(*nocnt)++;					\
2852 	}
2853 
2854 	IPFW_UH_RLOCK_ASSERT(&V_layer3_chain);
2855 
2856 	/* No need to pass through all the buckets. */
2857 	*nocnt = 0;
2858 	if (V_dyn_count + V_dyn_parent_count == 0)
2859 		return (0);
2860 
2861 	for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
2862 		DYN_COUNT_OBJECTS(s4, ipv4, bucket);
2863 #ifdef INET6
2864 		DYN_COUNT_OBJECTS(s6, ipv6, bucket);
2865 #endif
2866 	}
2867 
2868 	return (V_dyn_count + V_dyn_parent_count);
2869 }
2870 
2871 /*
2872  * Check if rule contains at least one dynamic opcode.
2873  *
2874  * Returns 1 if such opcode is found, 0 otherwise.
2875  */
2876 int
ipfw_is_dyn_rule(struct ip_fw * rule)2877 ipfw_is_dyn_rule(struct ip_fw *rule)
2878 {
2879 	int cmdlen, l;
2880 	ipfw_insn *cmd;
2881 
2882 	l = rule->cmd_len;
2883 	cmd = rule->cmd;
2884 	cmdlen = 0;
2885 	for ( ;	l > 0 ; l -= cmdlen, cmd += cmdlen) {
2886 		cmdlen = F_LEN(cmd);
2887 
2888 		switch (cmd->opcode) {
2889 		case O_LIMIT:
2890 		case O_KEEP_STATE:
2891 		case O_PROBE_STATE:
2892 		case O_CHECK_STATE:
2893 			return (1);
2894 		}
2895 	}
2896 
2897 	return (0);
2898 }
2899 
2900 static void
dyn_export_parent(const struct dyn_parent * p,uint16_t kidx,uint8_t set,ipfw_dyn_rule * dst)2901 dyn_export_parent(const struct dyn_parent *p, uint16_t kidx, uint8_t set,
2902     ipfw_dyn_rule *dst)
2903 {
2904 
2905 	dst->dyn_type = O_LIMIT_PARENT;
2906 	dst->kidx = kidx;
2907 	dst->count = (uint16_t)DPARENT_COUNT(p);
2908 	dst->expire = TIME_LEQ(p->expire, time_uptime) ?  0:
2909 	    p->expire - time_uptime;
2910 
2911 	/* 'rule' is used to pass up the rule number and set */
2912 	memcpy(&dst->rule, &p->rulenum, sizeof(p->rulenum));
2913 
2914 	/* store set number into high word of dst->rule pointer. */
2915 	memcpy((char *)&dst->rule + sizeof(p->rulenum), &set, sizeof(set));
2916 
2917 	/* unused fields */
2918 	dst->pcnt = 0;
2919 	dst->bcnt = 0;
2920 	dst->parent = NULL;
2921 	dst->state = 0;
2922 	dst->ack_fwd = 0;
2923 	dst->ack_rev = 0;
2924 	dst->bucket = p->hashval;
2925 	/*
2926 	 * The legacy userland code will interpret a NULL here as a marker
2927 	 * for the last dynamic rule.
2928 	 */
2929 	dst->next = (ipfw_dyn_rule *)1;
2930 }
2931 
2932 static void
dyn_export_data(const struct dyn_data * data,uint16_t kidx,uint8_t type,uint8_t set,ipfw_dyn_rule * dst)2933 dyn_export_data(const struct dyn_data *data, uint16_t kidx, uint8_t type,
2934     uint8_t set, ipfw_dyn_rule *dst)
2935 {
2936 
2937 	dst->dyn_type = type;
2938 	dst->kidx = kidx;
2939 	dst->pcnt = data->pcnt_fwd + data->pcnt_rev;
2940 	dst->bcnt = data->bcnt_fwd + data->bcnt_rev;
2941 	dst->expire = TIME_LEQ(data->expire, time_uptime) ?  0:
2942 	    data->expire - time_uptime;
2943 
2944 	/* 'rule' is used to pass up the rule number and set */
2945 	memcpy(&dst->rule, &data->rulenum, sizeof(data->rulenum));
2946 
2947 	/* store set number into high word of dst->rule pointer. */
2948 	memcpy((char *)&dst->rule + sizeof(data->rulenum), &set, sizeof(set));
2949 
2950 	dst->state = data->state;
2951 	if (data->flags & DYN_REFERENCED)
2952 		dst->state |= IPFW_DYN_ORPHANED;
2953 
2954 	/* unused fields */
2955 	dst->parent = NULL;
2956 	dst->ack_fwd = data->ack_fwd;
2957 	dst->ack_rev = data->ack_rev;
2958 	dst->count = 0;
2959 	dst->bucket = data->hashval;
2960 	/*
2961 	 * The legacy userland code will interpret a NULL here as a marker
2962 	 * for the last dynamic rule.
2963 	 */
2964 	dst->next = (ipfw_dyn_rule *)1;
2965 }
2966 
2967 static void
dyn_export_ipv4_state(const struct dyn_ipv4_state * s,ipfw_dyn_rule * dst)2968 dyn_export_ipv4_state(const struct dyn_ipv4_state *s, ipfw_dyn_rule *dst)
2969 {
2970 	struct ip_fw *rule;
2971 
2972 	switch (s->type) {
2973 	case O_LIMIT_PARENT:
2974 		rule = s->limit->parent;
2975 		dyn_export_parent(s->limit, s->kidx, rule->set, dst);
2976 		break;
2977 	default:
2978 		rule = s->data->parent;
2979 		if (s->type == O_LIMIT)
2980 			rule = ((struct dyn_ipv4_state *)rule)->limit->parent;
2981 		dyn_export_data(s->data, s->kidx, s->type, rule->set, dst);
2982 	}
2983 
2984 	dst->id.dst_ip = s->dst;
2985 	dst->id.src_ip = s->src;
2986 	dst->id.dst_port = s->dport;
2987 	dst->id.src_port = s->sport;
2988 	dst->id.fib = s->data->fibnum;
2989 	dst->id.proto = s->proto;
2990 	dst->id._flags = 0;
2991 	dst->id.addr_type = 4;
2992 
2993 	memset(&dst->id.dst_ip6, 0, sizeof(dst->id.dst_ip6));
2994 	memset(&dst->id.src_ip6, 0, sizeof(dst->id.src_ip6));
2995 	dst->id.flow_id6 = dst->id.extra = 0;
2996 }
2997 
2998 #ifdef INET6
2999 static void
dyn_export_ipv6_state(const struct dyn_ipv6_state * s,ipfw_dyn_rule * dst)3000 dyn_export_ipv6_state(const struct dyn_ipv6_state *s, ipfw_dyn_rule *dst)
3001 {
3002 	struct ip_fw *rule;
3003 
3004 	switch (s->type) {
3005 	case O_LIMIT_PARENT:
3006 		rule = s->limit->parent;
3007 		dyn_export_parent(s->limit, s->kidx, rule->set, dst);
3008 		break;
3009 	default:
3010 		rule = s->data->parent;
3011 		if (s->type == O_LIMIT)
3012 			rule = ((struct dyn_ipv6_state *)rule)->limit->parent;
3013 		dyn_export_data(s->data, s->kidx, s->type, rule->set, dst);
3014 	}
3015 
3016 	dst->id.src_ip6 = s->src;
3017 	dst->id.dst_ip6 = s->dst;
3018 	dst->id.dst_port = s->dport;
3019 	dst->id.src_port = s->sport;
3020 	dst->id.fib = s->data->fibnum;
3021 	dst->id.proto = s->proto;
3022 	dst->id._flags = 0;
3023 	dst->id.addr_type = 6;
3024 
3025 	dst->id.dst_ip = dst->id.src_ip = 0;
3026 	dst->id.flow_id6 = dst->id.extra = 0;
3027 }
3028 #endif /* INET6 */
3029 
3030 /*
3031  * Fills the buffer given by @sd with dynamic states.
3032  * Used by dump format v1 (current).
3033  *
3034  * Returns 0 on success.
3035  */
3036 int
ipfw_dump_states(struct ip_fw_chain * chain,struct sockopt_data * sd)3037 ipfw_dump_states(struct ip_fw_chain *chain, struct sockopt_data *sd)
3038 {
3039 #ifdef INET6
3040 	struct dyn_ipv6_state *s6;
3041 #endif
3042 	struct dyn_ipv4_state *s4;
3043 	ipfw_obj_dyntlv *dst, *last;
3044 	ipfw_obj_ctlv *ctlv;
3045 	uint32_t bucket;
3046 
3047 	if (V_dyn_count == 0)
3048 		return (0);
3049 
3050 	/*
3051 	 * IPFW_UH_RLOCK garantees that another userland request
3052 	 * and callout thread will not delete entries from states
3053 	 * lists.
3054 	 */
3055 	IPFW_UH_RLOCK_ASSERT(chain);
3056 
3057 	ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
3058 	if (ctlv == NULL)
3059 		return (ENOMEM);
3060 	ctlv->head.type = IPFW_TLV_DYNSTATE_LIST;
3061 	ctlv->objsize = sizeof(ipfw_obj_dyntlv);
3062 	last = NULL;
3063 
3064 #define	DYN_EXPORT_STATES(s, af, h, b)				\
3065 	CK_SLIST_FOREACH(s, &V_dyn_ ## h[b], entry) {			\
3066 		dst = (ipfw_obj_dyntlv *)ipfw_get_sopt_space(sd,	\
3067 		    sizeof(ipfw_obj_dyntlv));				\
3068 		if (dst == NULL)					\
3069 			return (ENOMEM);				\
3070 		dyn_export_ ## af ## _state(s, &dst->state);		\
3071 		dst->head.length = sizeof(ipfw_obj_dyntlv);		\
3072 		dst->head.type = IPFW_TLV_DYN_ENT;			\
3073 		last = dst;						\
3074 	}
3075 
3076 	for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
3077 		DYN_EXPORT_STATES(s4, ipv4, ipv4_parent, bucket);
3078 		DYN_EXPORT_STATES(s4, ipv4, ipv4, bucket);
3079 #ifdef INET6
3080 		DYN_EXPORT_STATES(s6, ipv6, ipv6_parent, bucket);
3081 		DYN_EXPORT_STATES(s6, ipv6, ipv6, bucket);
3082 #endif /* INET6 */
3083 	}
3084 
3085 	/* mark last dynamic rule */
3086 	if (last != NULL)
3087 		last->head.flags = IPFW_DF_LAST; /* XXX: unused */
3088 	return (0);
3089 #undef DYN_EXPORT_STATES
3090 }
3091 
3092 /*
3093  * Fill given buffer with dynamic states (legacy format).
3094  * IPFW_UH_RLOCK has to be held while calling.
3095  */
3096 void
ipfw_get_dynamic(struct ip_fw_chain * chain,char ** pbp,const char * ep)3097 ipfw_get_dynamic(struct ip_fw_chain *chain, char **pbp, const char *ep)
3098 {
3099 #ifdef INET6
3100 	struct dyn_ipv6_state *s6;
3101 #endif
3102 	struct dyn_ipv4_state *s4;
3103 	ipfw_dyn_rule *p, *last = NULL;
3104 	char *bp;
3105 	uint32_t bucket;
3106 
3107 	if (V_dyn_count == 0)
3108 		return;
3109 	bp = *pbp;
3110 
3111 	IPFW_UH_RLOCK_ASSERT(chain);
3112 
3113 #define	DYN_EXPORT_STATES(s, af, head, b)				\
3114 	CK_SLIST_FOREACH(s, &V_dyn_ ## head[b], entry) {		\
3115 		if (bp + sizeof(*p) > ep)				\
3116 			break;						\
3117 		p = (ipfw_dyn_rule *)bp;				\
3118 		dyn_export_ ## af ## _state(s, p);			\
3119 		last = p;						\
3120 		bp += sizeof(*p);					\
3121 	}
3122 
3123 	for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
3124 		DYN_EXPORT_STATES(s4, ipv4, ipv4_parent, bucket);
3125 		DYN_EXPORT_STATES(s4, ipv4, ipv4, bucket);
3126 #ifdef INET6
3127 		DYN_EXPORT_STATES(s6, ipv6, ipv6_parent, bucket);
3128 		DYN_EXPORT_STATES(s6, ipv6, ipv6, bucket);
3129 #endif /* INET6 */
3130 	}
3131 
3132 	if (last != NULL) /* mark last dynamic rule */
3133 		last->next = NULL;
3134 	*pbp = bp;
3135 #undef DYN_EXPORT_STATES
3136 }
3137 
3138 void
ipfw_dyn_init(struct ip_fw_chain * chain)3139 ipfw_dyn_init(struct ip_fw_chain *chain)
3140 {
3141 
3142 #ifdef IPFIREWALL_JENKINSHASH
3143 	V_dyn_hashseed = arc4random();
3144 #endif
3145 	V_dyn_max = 16384;		/* max # of states */
3146 	V_dyn_parent_max = 4096;	/* max # of parent states */
3147 	V_dyn_buckets_max = 8192;	/* must be power of 2 */
3148 
3149 	V_dyn_ack_lifetime = 300;
3150 	V_dyn_syn_lifetime = 20;
3151 	V_dyn_fin_lifetime = 1;
3152 	V_dyn_rst_lifetime = 1;
3153 	V_dyn_udp_lifetime = 10;
3154 	V_dyn_short_lifetime = 5;
3155 
3156 	V_dyn_keepalive_interval = 20;
3157 	V_dyn_keepalive_period = 5;
3158 	V_dyn_keepalive = 1;		/* send keepalives */
3159 	V_dyn_keepalive_last = time_uptime;
3160 
3161 	V_dyn_data_zone = uma_zcreate("IPFW dynamic states data",
3162 	    sizeof(struct dyn_data), NULL, NULL, NULL, NULL,
3163 	    UMA_ALIGN_PTR, 0);
3164 	uma_zone_set_max(V_dyn_data_zone, V_dyn_max);
3165 
3166 	V_dyn_parent_zone = uma_zcreate("IPFW parent dynamic states",
3167 	    sizeof(struct dyn_parent), NULL, NULL, NULL, NULL,
3168 	    UMA_ALIGN_PTR, 0);
3169 	uma_zone_set_max(V_dyn_parent_zone, V_dyn_parent_max);
3170 
3171 	SLIST_INIT(&V_dyn_expired_ipv4);
3172 	V_dyn_ipv4 = NULL;
3173 	V_dyn_ipv4_parent = NULL;
3174 	V_dyn_ipv4_zone = uma_zcreate("IPFW IPv4 dynamic states",
3175 	    sizeof(struct dyn_ipv4_state), NULL, NULL, NULL, NULL,
3176 	    UMA_ALIGN_PTR, 0);
3177 
3178 #ifdef INET6
3179 	SLIST_INIT(&V_dyn_expired_ipv6);
3180 	V_dyn_ipv6 = NULL;
3181 	V_dyn_ipv6_parent = NULL;
3182 	V_dyn_ipv6_zone = uma_zcreate("IPFW IPv6 dynamic states",
3183 	    sizeof(struct dyn_ipv6_state), NULL, NULL, NULL, NULL,
3184 	    UMA_ALIGN_PTR, 0);
3185 #endif
3186 
3187 	/* Initialize buckets. */
3188 	V_curr_dyn_buckets = 0;
3189 	V_dyn_bucket_lock = NULL;
3190 	dyn_grow_hashtable(chain, 256);
3191 
3192 	if (IS_DEFAULT_VNET(curvnet))
3193 		dyn_hp_cache = malloc(mp_ncpus * sizeof(void *), M_IPFW,
3194 		    M_WAITOK | M_ZERO);
3195 
3196 	DYN_EXPIRED_LOCK_INIT();
3197 	callout_init(&V_dyn_timeout, 1);
3198 	callout_reset(&V_dyn_timeout, hz, dyn_tick, curvnet);
3199 	IPFW_ADD_OBJ_REWRITER(IS_DEFAULT_VNET(curvnet), dyn_opcodes);
3200 }
3201 
3202 void
ipfw_dyn_uninit(int pass)3203 ipfw_dyn_uninit(int pass)
3204 {
3205 #ifdef INET6
3206 	struct dyn_ipv6_state *s6;
3207 #endif
3208 	struct dyn_ipv4_state *s4;
3209 	int bucket;
3210 
3211 	if (pass == 0) {
3212 		callout_drain(&V_dyn_timeout);
3213 		return;
3214 	}
3215 	IPFW_DEL_OBJ_REWRITER(IS_DEFAULT_VNET(curvnet), dyn_opcodes);
3216 	DYN_EXPIRED_LOCK_DESTROY();
3217 
3218 #define	DYN_FREE_STATES_FORCED(CK, s, af, name, en)	do {		\
3219 	while ((s = CK ## SLIST_FIRST(&V_dyn_ ## name)) != NULL) {	\
3220 		CK ## SLIST_REMOVE_HEAD(&V_dyn_ ## name, en);	\
3221 		if (s->type == O_LIMIT_PARENT)				\
3222 			uma_zfree(V_dyn_parent_zone, s->limit);		\
3223 		else							\
3224 			uma_zfree(V_dyn_data_zone, s->data);		\
3225 		uma_zfree(V_dyn_ ## af ## _zone, s);			\
3226 	}								\
3227 } while (0)
3228 	for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
3229 		DYN_BUCKET_LOCK_DESTROY(V_dyn_bucket_lock, bucket);
3230 
3231 		DYN_FREE_STATES_FORCED(CK_, s4, ipv4, ipv4[bucket], entry);
3232 		DYN_FREE_STATES_FORCED(CK_, s4, ipv4, ipv4_parent[bucket],
3233 		    entry);
3234 #ifdef INET6
3235 		DYN_FREE_STATES_FORCED(CK_, s6, ipv6, ipv6[bucket], entry);
3236 		DYN_FREE_STATES_FORCED(CK_, s6, ipv6, ipv6_parent[bucket],
3237 		    entry);
3238 #endif /* INET6 */
3239 	}
3240 	DYN_FREE_STATES_FORCED(, s4, ipv4, expired_ipv4, expired);
3241 #ifdef INET6
3242 	DYN_FREE_STATES_FORCED(, s6, ipv6, expired_ipv6, expired);
3243 #endif
3244 #undef DYN_FREE_STATES_FORCED
3245 
3246 	uma_zdestroy(V_dyn_ipv4_zone);
3247 	uma_zdestroy(V_dyn_data_zone);
3248 	uma_zdestroy(V_dyn_parent_zone);
3249 #ifdef INET6
3250 	uma_zdestroy(V_dyn_ipv6_zone);
3251 	free(V_dyn_ipv6, M_IPFW);
3252 	free(V_dyn_ipv6_parent, M_IPFW);
3253 	free(V_dyn_ipv6_add, M_IPFW);
3254 	free(V_dyn_ipv6_parent_add, M_IPFW);
3255 	free(V_dyn_ipv6_del, M_IPFW);
3256 	free(V_dyn_ipv6_parent_del, M_IPFW);
3257 #endif
3258 	free(V_dyn_bucket_lock, M_IPFW);
3259 	free(V_dyn_ipv4, M_IPFW);
3260 	free(V_dyn_ipv4_parent, M_IPFW);
3261 	free(V_dyn_ipv4_add, M_IPFW);
3262 	free(V_dyn_ipv4_parent_add, M_IPFW);
3263 	free(V_dyn_ipv4_del, M_IPFW);
3264 	free(V_dyn_ipv4_parent_del, M_IPFW);
3265 	if (IS_DEFAULT_VNET(curvnet))
3266 		free(dyn_hp_cache, M_IPFW);
3267 }
3268 
3269 
3270