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