2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 2017-2018 Yandex LLC
5 * Copyright (c) 2017-2018 Andrey V. Elsukov <ae@FreeBSD.org>
6 * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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.
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
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
34 #include "opt_inet6.h"
37 #error IPFIREWALL requires INET.
40 #include <sys/param.h>
41 #include <sys/systm.h>
44 #include <sys/kernel.h>
47 #include <sys/queue.h>
48 #include <sys/rmlock.h>
50 #include <sys/socket.h>
51 #include <sys/sysctl.h>
52 #include <sys/syslog.h>
53 #include <net/ethernet.h>
55 #include <net/if_var.h>
59 #include <netinet/in.h>
60 #include <netinet/ip.h>
61 #include <netinet/ip_var.h>
62 #include <netinet/ip_fw.h>
63 #include <netinet/tcp_var.h>
64 #include <netinet/udp.h>
66 #include <netinet/ip6.h> /* IN6_ARE_ADDR_EQUAL */
68 #include <netinet6/in6_var.h>
69 #include <netinet6/ip6_var.h>
70 #include <netinet6/scope6_var.h>
73 #include <netpfil/ipfw/ip_fw_private.h>
75 #include <machine/in_cksum.h> /* XXX for in_cksum */
78 #include <security/mac/mac_framework.h>
82 * Description of dynamic states.
84 * Dynamic states are stored in lists accessed through a hash tables
85 * whose size is curr_dyn_buckets. This value can be modified through
86 * the sysctl variable dyn_buckets.
88 * Currently there are four tables: dyn_ipv4, dyn_ipv6, dyn_ipv4_parent,
89 * and dyn_ipv6_parent.
91 * When a packet is received, its address fields hashed, then matched
92 * against the entries in the corresponding list by addr_type.
93 * Dynamic states can be used for different purposes:
95 * + enforcing limits on the number of sessions;
96 * + in-kernel NAT (not implemented yet)
98 * The lifetime of dynamic states is regulated by dyn_*_lifetime,
99 * measured in seconds and depending on the flags.
101 * The total number of dynamic states is equal to UMA zone items count.
102 * The max number of dynamic states is dyn_max. When we reach
103 * the maximum number of rules we do not create anymore. This is
104 * done to avoid consuming too much memory, but also too much
105 * time when searching on each packet (ideally, we should try instead
106 * to put a limit on the length of the list on each bucket...).
108 * Each state holds a pointer to the parent ipfw rule so we know what
109 * action to perform. Dynamic rules are removed when the parent rule is
112 * There are some limitations with dynamic rules -- we do not
113 * obey the 'randomized match', and we do not do multiple
114 * passes through the firewall. XXX check the latter!!!
117 /* By default use jenkins hash function */
118 #define IPFIREWALL_JENKINSHASH
120 #define DYN_COUNTER_INC(d, dir, pktlen) do { \
121 (d)->pcnt_ ## dir++; \
122 (d)->bcnt_ ## dir += pktlen; \
126 void *parent; /* pointer to parent rule */
127 uint32_t chain_id; /* cached ruleset id */
128 uint32_t f_pos; /* cached rule index */
130 uint32_t hashval; /* hash value used for hash resize */
131 uint16_t fibnum; /* fib used to send keepalives */
133 uint8_t set; /* parent rule set number */
134 uint16_t rulenum; /* parent rule number */
135 uint32_t ruleid; /* parent rule id */
137 uint32_t state; /* TCP session state and flags */
138 uint32_t ack_fwd; /* most recent ACKs in forward */
139 uint32_t ack_rev; /* and reverse direction (used */
140 /* to generate keepalives) */
141 uint32_t sync; /* synchronization time */
142 uint32_t expire; /* expire time */
144 uint64_t pcnt_fwd; /* bytes counter in forward */
145 uint64_t bcnt_fwd; /* packets counter in forward */
146 uint64_t pcnt_rev; /* bytes counter in reverse */
147 uint64_t bcnt_rev; /* packets counter in reverse */
150 #define DPARENT_COUNT_DEC(p) do { \
151 MPASS(p->count > 0); \
152 ck_pr_dec_32(&(p)->count); \
154 #define DPARENT_COUNT_INC(p) ck_pr_inc_32(&(p)->count)
155 #define DPARENT_COUNT(p) ck_pr_load_32(&(p)->count)
157 void *parent; /* pointer to parent rule */
158 uint32_t count; /* number of linked states */
160 uint8_t set; /* parent rule set number */
161 uint16_t rulenum; /* parent rule number */
162 uint32_t ruleid; /* parent rule id */
163 uint32_t hashval; /* hash value used for hash resize */
164 uint32_t expire; /* expire time */
167 struct dyn_ipv4_state {
168 uint8_t type; /* State type */
169 uint8_t proto; /* UL Protocol */
170 uint16_t kidx; /* named object index */
171 uint16_t sport, dport; /* ULP source and destination ports */
172 in_addr_t src, dst; /* IPv4 source and destination */
175 struct dyn_data *data;
176 struct dyn_parent *limit;
178 CK_SLIST_ENTRY(dyn_ipv4_state) entry;
179 SLIST_ENTRY(dyn_ipv4_state) expired;
181 CK_SLIST_HEAD(dyn_ipv4ck_slist, dyn_ipv4_state);
182 static VNET_DEFINE(struct dyn_ipv4ck_slist *, dyn_ipv4);
183 static VNET_DEFINE(struct dyn_ipv4ck_slist *, dyn_ipv4_parent);
185 SLIST_HEAD(dyn_ipv4_slist, dyn_ipv4_state);
186 static VNET_DEFINE(struct dyn_ipv4_slist, dyn_expired_ipv4);
187 #define V_dyn_ipv4 VNET(dyn_ipv4)
188 #define V_dyn_ipv4_parent VNET(dyn_ipv4_parent)
189 #define V_dyn_expired_ipv4 VNET(dyn_expired_ipv4)
192 struct dyn_ipv6_state {
193 uint8_t type; /* State type */
194 uint8_t proto; /* UL Protocol */
195 uint16_t kidx; /* named object index */
196 uint16_t sport, dport; /* ULP source and destination ports */
197 struct in6_addr src, dst; /* IPv6 source and destination */
198 uint32_t zoneid; /* IPv6 scope zone id */
200 struct dyn_data *data;
201 struct dyn_parent *limit;
203 CK_SLIST_ENTRY(dyn_ipv6_state) entry;
204 SLIST_ENTRY(dyn_ipv6_state) expired;
206 CK_SLIST_HEAD(dyn_ipv6ck_slist, dyn_ipv6_state);
207 static VNET_DEFINE(struct dyn_ipv6ck_slist *, dyn_ipv6);
208 static VNET_DEFINE(struct dyn_ipv6ck_slist *, dyn_ipv6_parent);
210 SLIST_HEAD(dyn_ipv6_slist, dyn_ipv6_state);
211 static VNET_DEFINE(struct dyn_ipv6_slist, dyn_expired_ipv6);
212 #define V_dyn_ipv6 VNET(dyn_ipv6)
213 #define V_dyn_ipv6_parent VNET(dyn_ipv6_parent)
214 #define V_dyn_expired_ipv6 VNET(dyn_expired_ipv6)
218 * Per-CPU pointer indicates that specified state is currently in use
219 * and must not be reclaimed by expiration callout.
221 static void **dyn_hp_cache;
222 static DPCPU_DEFINE(void *, dyn_hp);
223 #define DYNSTATE_GET(cpu) ck_pr_load_ptr(DPCPU_ID_PTR((cpu), dyn_hp))
224 #define DYNSTATE_PROTECT(v) ck_pr_store_ptr(DPCPU_PTR(dyn_hp), (v))
225 #define DYNSTATE_RELEASE() DYNSTATE_PROTECT(NULL)
226 #define DYNSTATE_CRITICAL_ENTER() critical_enter()
227 #define DYNSTATE_CRITICAL_EXIT() do { \
228 DYNSTATE_RELEASE(); \
233 * We keep two version numbers, one is updated when new entry added to
234 * the list. Second is updated when an entry deleted from the list.
235 * Versions are updated under bucket lock.
237 * Bucket "add" version number is used to know, that in the time between
238 * state lookup (i.e. ipfw_dyn_lookup_state()) and the followed state
239 * creation (i.e. ipfw_dyn_install_state()) another concurrent thread did
240 * not install some state in this bucket. Using this info we can avoid
241 * additional state lookup, because we are sure that we will not install
244 * Also doing the tracking of bucket "del" version during lookup we can
245 * be sure, that state entry was not unlinked and freed in time between
246 * we read the state pointer and protect it with hazard pointer.
248 * An entry unlinked from CK list keeps unchanged until it is freed.
249 * Unlinked entries are linked into expired lists using "expired" field.
253 * dyn_expire_lock is used to protect access to dyn_expired_xxx lists.
254 * dyn_bucket_lock is used to get write access to lists in specific bucket.
255 * Currently one dyn_bucket_lock is used for all ipv4, ipv4_parent, ipv6,
256 * and ipv6_parent lists.
258 static VNET_DEFINE(struct mtx, dyn_expire_lock);
259 static VNET_DEFINE(struct mtx *, dyn_bucket_lock);
260 #define V_dyn_expire_lock VNET(dyn_expire_lock)
261 #define V_dyn_bucket_lock VNET(dyn_bucket_lock)
264 * Bucket's add/delete generation versions.
266 static VNET_DEFINE(uint32_t *, dyn_ipv4_add);
267 static VNET_DEFINE(uint32_t *, dyn_ipv4_del);
268 static VNET_DEFINE(uint32_t *, dyn_ipv4_parent_add);
269 static VNET_DEFINE(uint32_t *, dyn_ipv4_parent_del);
270 #define V_dyn_ipv4_add VNET(dyn_ipv4_add)
271 #define V_dyn_ipv4_del VNET(dyn_ipv4_del)
272 #define V_dyn_ipv4_parent_add VNET(dyn_ipv4_parent_add)
273 #define V_dyn_ipv4_parent_del VNET(dyn_ipv4_parent_del)
276 static VNET_DEFINE(uint32_t *, dyn_ipv6_add);
277 static VNET_DEFINE(uint32_t *, dyn_ipv6_del);
278 static VNET_DEFINE(uint32_t *, dyn_ipv6_parent_add);
279 static VNET_DEFINE(uint32_t *, dyn_ipv6_parent_del);
280 #define V_dyn_ipv6_add VNET(dyn_ipv6_add)
281 #define V_dyn_ipv6_del VNET(dyn_ipv6_del)
282 #define V_dyn_ipv6_parent_add VNET(dyn_ipv6_parent_add)
283 #define V_dyn_ipv6_parent_del VNET(dyn_ipv6_parent_del)
286 #define DYN_BUCKET(h, b) ((h) & (b - 1))
287 #define DYN_BUCKET_VERSION(b, v) ck_pr_load_32(&V_dyn_ ## v[(b)])
288 #define DYN_BUCKET_VERSION_BUMP(b, v) ck_pr_inc_32(&V_dyn_ ## v[(b)])
290 #define DYN_BUCKET_LOCK_INIT(lock, b) \
291 mtx_init(&lock[(b)], "IPFW dynamic bucket", NULL, MTX_DEF)
292 #define DYN_BUCKET_LOCK_DESTROY(lock, b) mtx_destroy(&lock[(b)])
293 #define DYN_BUCKET_LOCK(b) mtx_lock(&V_dyn_bucket_lock[(b)])
294 #define DYN_BUCKET_UNLOCK(b) mtx_unlock(&V_dyn_bucket_lock[(b)])
295 #define DYN_BUCKET_ASSERT(b) mtx_assert(&V_dyn_bucket_lock[(b)], MA_OWNED)
297 #define DYN_EXPIRED_LOCK_INIT() \
298 mtx_init(&V_dyn_expire_lock, "IPFW expired states list", NULL, MTX_DEF)
299 #define DYN_EXPIRED_LOCK_DESTROY() mtx_destroy(&V_dyn_expire_lock)
300 #define DYN_EXPIRED_LOCK() mtx_lock(&V_dyn_expire_lock)
301 #define DYN_EXPIRED_UNLOCK() mtx_unlock(&V_dyn_expire_lock)
303 static VNET_DEFINE(uint32_t, dyn_buckets_max);
304 static VNET_DEFINE(uint32_t, curr_dyn_buckets);
305 static VNET_DEFINE(struct callout, dyn_timeout);
306 #define V_dyn_buckets_max VNET(dyn_buckets_max)
307 #define V_curr_dyn_buckets VNET(curr_dyn_buckets)
308 #define V_dyn_timeout VNET(dyn_timeout)
310 /* Maximum length of states chain in a bucket */
311 static VNET_DEFINE(uint32_t, curr_max_length);
312 #define V_curr_max_length VNET(curr_max_length)
314 static VNET_DEFINE(uma_zone_t, dyn_data_zone);
315 static VNET_DEFINE(uma_zone_t, dyn_parent_zone);
316 static VNET_DEFINE(uma_zone_t, dyn_ipv4_zone);
318 static VNET_DEFINE(uma_zone_t, dyn_ipv6_zone);
319 #define V_dyn_ipv6_zone VNET(dyn_ipv6_zone)
321 #define V_dyn_data_zone VNET(dyn_data_zone)
322 #define V_dyn_parent_zone VNET(dyn_parent_zone)
323 #define V_dyn_ipv4_zone VNET(dyn_ipv4_zone)
326 * Timeouts for various events in handing dynamic rules.
328 static VNET_DEFINE(uint32_t, dyn_ack_lifetime);
329 static VNET_DEFINE(uint32_t, dyn_syn_lifetime);
330 static VNET_DEFINE(uint32_t, dyn_fin_lifetime);
331 static VNET_DEFINE(uint32_t, dyn_rst_lifetime);
332 static VNET_DEFINE(uint32_t, dyn_udp_lifetime);
333 static VNET_DEFINE(uint32_t, dyn_short_lifetime);
335 #define V_dyn_ack_lifetime VNET(dyn_ack_lifetime)
336 #define V_dyn_syn_lifetime VNET(dyn_syn_lifetime)
337 #define V_dyn_fin_lifetime VNET(dyn_fin_lifetime)
338 #define V_dyn_rst_lifetime VNET(dyn_rst_lifetime)
339 #define V_dyn_udp_lifetime VNET(dyn_udp_lifetime)
340 #define V_dyn_short_lifetime VNET(dyn_short_lifetime)
343 * Keepalives are sent if dyn_keepalive is set. They are sent every
344 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
345 * seconds of lifetime of a rule.
346 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
347 * than dyn_keepalive_period.
349 #define DYN_KEEPALIVE_MAXQ 512
350 static VNET_DEFINE(uint32_t, dyn_keepalive_interval);
351 static VNET_DEFINE(uint32_t, dyn_keepalive_period);
352 static VNET_DEFINE(uint32_t, dyn_keepalive);
353 static VNET_DEFINE(time_t, dyn_keepalive_last);
355 #define V_dyn_keepalive_interval VNET(dyn_keepalive_interval)
356 #define V_dyn_keepalive_period VNET(dyn_keepalive_period)
357 #define V_dyn_keepalive VNET(dyn_keepalive)
358 #define V_dyn_keepalive_last VNET(dyn_keepalive_last)
360 static VNET_DEFINE(uint32_t, dyn_max); /* max # of dynamic states */
361 static VNET_DEFINE(uint32_t, dyn_count); /* number of states */
362 static VNET_DEFINE(uint32_t, dyn_parent_max); /* max # of parent states */
363 static VNET_DEFINE(uint32_t, dyn_parent_count); /* number of parent states */
364 #define V_dyn_max VNET(dyn_max)
365 #define V_dyn_count VNET(dyn_count)
366 #define V_dyn_parent_max VNET(dyn_parent_max)
367 #define V_dyn_parent_count VNET(dyn_parent_count)
369 #define DYN_COUNT_DEC(name) do { \
370 MPASS((V_ ## name) > 0); \
371 ck_pr_dec_32(&(V_ ## name)); \
373 #define DYN_COUNT_INC(name) ck_pr_inc_32(&(V_ ## name))
374 #define DYN_COUNT(name) ck_pr_load_32(&(V_ ## name))
376 static time_t last_log; /* Log ratelimiting */
379 * Get/set maximum number of dynamic states in given VNET instance.
382 sysctl_dyn_max(SYSCTL_HANDLER_ARGS)
388 error = sysctl_handle_32(oidp, &nstates, 0, req);
389 /* Read operation or some error */
390 if ((error != 0) || (req->newptr == NULL))
394 uma_zone_set_max(V_dyn_data_zone, V_dyn_max);
399 sysctl_dyn_parent_max(SYSCTL_HANDLER_ARGS)
404 nstates = V_dyn_parent_max;
405 error = sysctl_handle_32(oidp, &nstates, 0, req);
406 /* Read operation or some error */
407 if ((error != 0) || (req->newptr == NULL))
410 V_dyn_parent_max = nstates;
411 uma_zone_set_max(V_dyn_parent_zone, V_dyn_parent_max);
416 sysctl_dyn_buckets(SYSCTL_HANDLER_ARGS)
421 nbuckets = V_dyn_buckets_max;
422 error = sysctl_handle_32(oidp, &nbuckets, 0, req);
423 /* Read operation or some error */
424 if ((error != 0) || (req->newptr == NULL))
428 V_dyn_buckets_max = 1 << fls(nbuckets - 1);
434 SYSCTL_DECL(_net_inet_ip_fw);
436 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_count,
437 CTLFLAG_VNET | CTLFLAG_RD, &VNET_NAME(dyn_count), 0,
438 "Current number of dynamic states.");
439 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_parent_count,
440 CTLFLAG_VNET | CTLFLAG_RD, &VNET_NAME(dyn_parent_count), 0,
441 "Current number of parent states. ");
442 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets,
443 CTLFLAG_VNET | CTLFLAG_RD, &VNET_NAME(curr_dyn_buckets), 0,
444 "Current number of buckets for states hash table.");
445 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, curr_max_length,
446 CTLFLAG_VNET | CTLFLAG_RD, &VNET_NAME(curr_max_length), 0,
447 "Current maximum length of states chains in hash buckets.");
448 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_buckets,
449 CTLFLAG_VNET | CTLTYPE_U32 | CTLFLAG_RW, 0, 0, sysctl_dyn_buckets,
450 "IU", "Max number of buckets for dynamic states hash table.");
451 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_max,
452 CTLFLAG_VNET | CTLTYPE_U32 | CTLFLAG_RW, 0, 0, sysctl_dyn_max,
453 "IU", "Max number of dynamic states.");
454 SYSCTL_PROC(_net_inet_ip_fw, OID_AUTO, dyn_parent_max,
455 CTLFLAG_VNET | CTLTYPE_U32 | CTLFLAG_RW, 0, 0, sysctl_dyn_parent_max,
456 "IU", "Max number of parent dynamic states.");
457 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime,
458 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_ack_lifetime), 0,
459 "Lifetime of dynamic states for TCP ACK.");
460 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime,
461 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_syn_lifetime), 0,
462 "Lifetime of dynamic states for TCP SYN.");
463 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
464 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_fin_lifetime), 0,
465 "Lifetime of dynamic states for TCP FIN.");
466 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
467 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_rst_lifetime), 0,
468 "Lifetime of dynamic states for TCP RST.");
469 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime,
470 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_udp_lifetime), 0,
471 "Lifetime of dynamic states for UDP.");
472 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime,
473 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_short_lifetime), 0,
474 "Lifetime of dynamic states for other situations.");
475 SYSCTL_U32(_net_inet_ip_fw, OID_AUTO, dyn_keepalive,
476 CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(dyn_keepalive), 0,
477 "Enable keepalives for dynamic states.");
479 #ifdef IPFIREWALL_DYNDEBUG
480 #define DYN_DEBUG(fmt, ...) do { \
481 printf("%s: " fmt "\n", __func__, __VA_ARGS__); \
484 #define DYN_DEBUG(fmt, ...)
485 #endif /* !IPFIREWALL_DYNDEBUG */
488 /* Functions to work with IPv6 states */
489 static struct dyn_ipv6_state *dyn_lookup_ipv6_state(
490 const struct ipfw_flow_id *, uint32_t, const void *,
491 struct ipfw_dyn_info *, int);
492 static int dyn_lookup_ipv6_state_locked(const struct ipfw_flow_id *,
493 uint32_t, const void *, int, const void *, uint32_t, uint16_t, uint32_t,
495 static struct dyn_ipv6_state *dyn_alloc_ipv6_state(
496 const struct ipfw_flow_id *, uint32_t, uint16_t, uint8_t);
497 static int dyn_add_ipv6_state(void *, uint32_t, uint16_t, uint8_t,
498 const struct ipfw_flow_id *, uint32_t, const void *, int, uint32_t,
499 struct ipfw_dyn_info *, uint16_t, uint16_t, uint8_t);
500 static void dyn_export_ipv6_state(const struct dyn_ipv6_state *,
503 static uint32_t dyn_getscopeid(const struct ip_fw_args *);
504 static void dyn_make_keepalive_ipv6(struct mbuf *, const struct in6_addr *,
505 const struct in6_addr *, uint32_t, uint32_t, uint32_t, uint16_t,
507 static void dyn_enqueue_keepalive_ipv6(struct mbufq *,
508 const struct dyn_ipv6_state *);
509 static void dyn_send_keepalive_ipv6(struct ip_fw_chain *);
511 static struct dyn_ipv6_state *dyn_lookup_ipv6_parent(
512 const struct ipfw_flow_id *, uint32_t, const void *, uint32_t, uint16_t,
514 static struct dyn_ipv6_state *dyn_lookup_ipv6_parent_locked(
515 const struct ipfw_flow_id *, uint32_t, const void *, uint32_t, uint16_t,
517 static struct dyn_ipv6_state *dyn_add_ipv6_parent(void *, uint32_t, uint16_t,
518 uint8_t, const struct ipfw_flow_id *, uint32_t, uint32_t, uint32_t,
522 /* Functions to work with limit states */
523 static void *dyn_get_parent_state(const struct ipfw_flow_id *, uint32_t,
524 struct ip_fw *, uint32_t, uint32_t, uint16_t);
525 static struct dyn_ipv4_state *dyn_lookup_ipv4_parent(
526 const struct ipfw_flow_id *, const void *, uint32_t, uint16_t, uint32_t);
527 static struct dyn_ipv4_state *dyn_lookup_ipv4_parent_locked(
528 const struct ipfw_flow_id *, const void *, uint32_t, uint16_t, uint32_t);
529 static struct dyn_parent *dyn_alloc_parent(void *, uint32_t, uint16_t,
531 static struct dyn_ipv4_state *dyn_add_ipv4_parent(void *, uint32_t, uint16_t,
532 uint8_t, const struct ipfw_flow_id *, uint32_t, uint32_t, uint16_t);
534 static void dyn_tick(void *);
535 static void dyn_expire_states(struct ip_fw_chain *, ipfw_range_tlv *);
536 static void dyn_free_states(struct ip_fw_chain *);
537 static void dyn_export_parent(const struct dyn_parent *, uint16_t,
539 static void dyn_export_data(const struct dyn_data *, uint16_t, uint8_t,
541 static uint32_t dyn_update_tcp_state(struct dyn_data *,
542 const struct ipfw_flow_id *, const struct tcphdr *, int);
543 static void dyn_update_proto_state(struct dyn_data *,
544 const struct ipfw_flow_id *, const void *, int, int);
546 /* Functions to work with IPv4 states */
547 struct dyn_ipv4_state *dyn_lookup_ipv4_state(const struct ipfw_flow_id *,
548 const void *, struct ipfw_dyn_info *, int);
549 static int dyn_lookup_ipv4_state_locked(const struct ipfw_flow_id *,
550 const void *, int, const void *, uint32_t, uint16_t, uint32_t, uint16_t);
551 static struct dyn_ipv4_state *dyn_alloc_ipv4_state(
552 const struct ipfw_flow_id *, uint16_t, uint8_t);
553 static int dyn_add_ipv4_state(void *, uint32_t, uint16_t, uint8_t,
554 const struct ipfw_flow_id *, const void *, int, uint32_t,
555 struct ipfw_dyn_info *, uint16_t, uint16_t, uint8_t);
556 static void dyn_export_ipv4_state(const struct dyn_ipv4_state *,
560 * Named states support.
562 static char *default_state_name = "default";
563 struct dyn_state_obj {
564 struct named_object no;
568 #define DYN_STATE_OBJ(ch, cmd) \
569 ((struct dyn_state_obj *)SRV_OBJECT(ch, (cmd)->arg1))
571 * Classifier callback.
572 * Return 0 if opcode contains object that should be referenced
576 dyn_classify(ipfw_insn *cmd, uint16_t *puidx, uint8_t *ptype)
579 DYN_DEBUG("opcode %d, arg1 %d", cmd->opcode, cmd->arg1);
580 /* Don't rewrite "check-state any" */
581 if (cmd->arg1 == 0 &&
582 cmd->opcode == O_CHECK_STATE)
591 dyn_update(ipfw_insn *cmd, uint16_t idx)
595 DYN_DEBUG("opcode %d, arg1 %d", cmd->opcode, cmd->arg1);
599 dyn_findbyname(struct ip_fw_chain *ch, struct tid_info *ti,
600 struct named_object **pno)
605 DYN_DEBUG("uidx %d", ti->uidx);
607 if (ti->tlvs == NULL)
609 /* Search ntlv in the buffer provided by user */
610 ntlv = ipfw_find_name_tlv_type(ti->tlvs, ti->tlen, ti->uidx,
611 IPFW_TLV_STATE_NAME);
616 name = default_state_name;
618 * Search named object with corresponding name.
619 * Since states objects are global - ignore the set value
620 * and use zero instead.
622 *pno = ipfw_objhash_lookup_name_type(CHAIN_TO_SRV(ch), 0,
623 IPFW_TLV_STATE_NAME, name);
625 * We always return success here.
626 * The caller will check *pno and mark object as unresolved,
627 * then it will automatically create "default" object.
632 static struct named_object *
633 dyn_findbykidx(struct ip_fw_chain *ch, uint16_t idx)
636 DYN_DEBUG("kidx %d", idx);
637 return (ipfw_objhash_lookup_kidx(CHAIN_TO_SRV(ch), idx));
641 dyn_create(struct ip_fw_chain *ch, struct tid_info *ti,
644 struct namedobj_instance *ni;
645 struct dyn_state_obj *obj;
646 struct named_object *no;
650 DYN_DEBUG("uidx %d", ti->uidx);
652 if (ti->tlvs == NULL)
654 ntlv = ipfw_find_name_tlv_type(ti->tlvs, ti->tlen, ti->uidx,
655 IPFW_TLV_STATE_NAME);
660 name = default_state_name;
662 ni = CHAIN_TO_SRV(ch);
663 obj = malloc(sizeof(*obj), M_IPFW, M_WAITOK | M_ZERO);
664 obj->no.name = obj->name;
665 obj->no.etlv = IPFW_TLV_STATE_NAME;
666 strlcpy(obj->name, name, sizeof(obj->name));
669 no = ipfw_objhash_lookup_name_type(ni, 0,
670 IPFW_TLV_STATE_NAME, name);
673 * Object is already created.
674 * Just return its kidx and bump refcount.
680 DYN_DEBUG("\tfound kidx %d", *pkidx);
683 if (ipfw_objhash_alloc_idx(ni, &obj->no.kidx) != 0) {
684 DYN_DEBUG("\talloc_idx failed for %s", name);
689 ipfw_objhash_add(ni, &obj->no);
690 SRV_OBJECT(ch, obj->no.kidx) = obj;
692 *pkidx = obj->no.kidx;
694 DYN_DEBUG("\tcreated kidx %d", *pkidx);
699 dyn_destroy(struct ip_fw_chain *ch, struct named_object *no)
701 struct dyn_state_obj *obj;
703 IPFW_UH_WLOCK_ASSERT(ch);
705 KASSERT(no->refcnt == 1,
706 ("Destroying object '%s' (type %u, idx %u) with refcnt %u",
707 no->name, no->etlv, no->kidx, no->refcnt));
708 DYN_DEBUG("kidx %d", no->kidx);
709 obj = SRV_OBJECT(ch, no->kidx);
710 SRV_OBJECT(ch, no->kidx) = NULL;
711 ipfw_objhash_del(CHAIN_TO_SRV(ch), no);
712 ipfw_objhash_free_idx(CHAIN_TO_SRV(ch), no->kidx);
717 static struct opcode_obj_rewrite dyn_opcodes[] = {
719 O_KEEP_STATE, IPFW_TLV_STATE_NAME,
720 dyn_classify, dyn_update,
721 dyn_findbyname, dyn_findbykidx,
722 dyn_create, dyn_destroy
725 O_CHECK_STATE, IPFW_TLV_STATE_NAME,
726 dyn_classify, dyn_update,
727 dyn_findbyname, dyn_findbykidx,
728 dyn_create, dyn_destroy
731 O_PROBE_STATE, IPFW_TLV_STATE_NAME,
732 dyn_classify, dyn_update,
733 dyn_findbyname, dyn_findbykidx,
734 dyn_create, dyn_destroy
737 O_LIMIT, IPFW_TLV_STATE_NAME,
738 dyn_classify, dyn_update,
739 dyn_findbyname, dyn_findbykidx,
740 dyn_create, dyn_destroy
745 * IMPORTANT: the hash function for dynamic rules must be commutative
746 * in source and destination (ip,port), because rules are bidirectional
747 * and we want to find both in the same bucket.
749 #ifndef IPFIREWALL_JENKINSHASH
750 static __inline uint32_t
751 hash_packet(const struct ipfw_flow_id *id)
756 if (IS_IP6_FLOW_ID(id))
757 i = ntohl((id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
758 (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
759 (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
760 (id->src_ip6.__u6_addr.__u6_addr32[3]));
763 i = (id->dst_ip) ^ (id->src_ip);
764 i ^= (id->dst_port) ^ (id->src_port);
768 static __inline uint32_t
769 hash_parent(const struct ipfw_flow_id *id, const void *rule)
772 return (hash_packet(id) ^ ((uintptr_t)rule));
775 #else /* IPFIREWALL_JENKINSHASH */
777 static VNET_DEFINE(uint32_t, dyn_hashseed);
778 #define V_dyn_hashseed VNET(dyn_hashseed)
781 addrcmp4(const struct ipfw_flow_id *id)
784 if (id->src_ip < id->dst_ip)
786 if (id->src_ip > id->dst_ip)
788 if (id->src_port <= id->dst_port)
795 addrcmp6(const struct ipfw_flow_id *id)
799 ret = memcmp(&id->src_ip6, &id->dst_ip6, sizeof(struct in6_addr));
804 if (id->src_port <= id->dst_port)
809 static __inline uint32_t
810 hash_packet6(const struct ipfw_flow_id *id)
813 struct in6_addr addr[2];
817 if (addrcmp6(id) == 0) {
818 t6.addr[0] = id->src_ip6;
819 t6.addr[1] = id->dst_ip6;
820 t6.port[0] = id->src_port;
821 t6.port[1] = id->dst_port;
823 t6.addr[0] = id->dst_ip6;
824 t6.addr[1] = id->src_ip6;
825 t6.port[0] = id->dst_port;
826 t6.port[1] = id->src_port;
828 return (jenkins_hash32((const uint32_t *)&t6,
829 sizeof(t6) / sizeof(uint32_t), V_dyn_hashseed));
833 static __inline uint32_t
834 hash_packet(const struct ipfw_flow_id *id)
841 if (IS_IP4_FLOW_ID(id)) {
842 /* All fields are in host byte order */
843 if (addrcmp4(id) == 0) {
844 t4.addr[0] = id->src_ip;
845 t4.addr[1] = id->dst_ip;
846 t4.port[0] = id->src_port;
847 t4.port[1] = id->dst_port;
849 t4.addr[0] = id->dst_ip;
850 t4.addr[1] = id->src_ip;
851 t4.port[0] = id->dst_port;
852 t4.port[1] = id->src_port;
854 return (jenkins_hash32((const uint32_t *)&t4,
855 sizeof(t4) / sizeof(uint32_t), V_dyn_hashseed));
858 if (IS_IP6_FLOW_ID(id))
859 return (hash_packet6(id));
864 static __inline uint32_t
865 hash_parent(const struct ipfw_flow_id *id, const void *rule)
868 return (jenkins_hash32((const uint32_t *)&rule,
869 sizeof(rule) / sizeof(uint32_t), hash_packet(id)));
871 #endif /* IPFIREWALL_JENKINSHASH */
874 * Print customizable flow id description via log(9) facility.
877 print_dyn_rule_flags(const struct ipfw_flow_id *id, int dyn_type,
878 int log_flags, char *prefix, char *postfix)
882 char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN];
884 char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
888 if (IS_IP6_FLOW_ID(id)) {
889 ip6_sprintf(src, &id->src_ip6);
890 ip6_sprintf(dst, &id->dst_ip6);
894 da.s_addr = htonl(id->src_ip);
895 inet_ntop(AF_INET, &da, src, sizeof(src));
896 da.s_addr = htonl(id->dst_ip);
897 inet_ntop(AF_INET, &da, dst, sizeof(dst));
899 log(log_flags, "ipfw: %s type %d %s %d -> %s %d, %d %s\n",
900 prefix, dyn_type, src, id->src_port, dst,
901 id->dst_port, V_dyn_count, postfix);
904 #define print_dyn_rule(id, dtype, prefix, postfix) \
905 print_dyn_rule_flags(id, dtype, LOG_DEBUG, prefix, postfix)
907 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
908 #define TIME_LE(a,b) ((int)((a)-(b)) < 0)
909 #define _SEQ_GE(a,b) ((int)((a)-(b)) >= 0)
910 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
911 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
912 #define TCP_FLAGS (TH_FLAGS | (TH_FLAGS << 8))
913 #define ACK_FWD 0x00010000 /* fwd ack seen */
914 #define ACK_REV 0x00020000 /* rev ack seen */
915 #define ACK_BOTH (ACK_FWD | ACK_REV)
918 dyn_update_tcp_state(struct dyn_data *data, const struct ipfw_flow_id *pkt,
919 const struct tcphdr *tcp, int dir)
921 uint32_t ack, expire;
925 expire = data->expire;
926 old = state = data->state;
927 th_flags = pkt->_flags & (TH_FIN | TH_SYN | TH_RST);
928 state |= (dir == MATCH_FORWARD) ? th_flags: (th_flags << 8);
929 switch (state & TCP_FLAGS) {
930 case TH_SYN: /* opening */
931 expire = time_uptime + V_dyn_syn_lifetime;
934 case BOTH_SYN: /* move to established */
935 case BOTH_SYN | TH_FIN: /* one side tries to close */
936 case BOTH_SYN | (TH_FIN << 8):
939 ack = ntohl(tcp->th_ack);
940 if (dir == MATCH_FORWARD) {
941 if (data->ack_fwd == 0 ||
942 _SEQ_GE(ack, data->ack_fwd)) {
944 if (data->ack_fwd != ack)
945 ck_pr_store_32(&data->ack_fwd, ack);
948 if (data->ack_rev == 0 ||
949 _SEQ_GE(ack, data->ack_rev)) {
951 if (data->ack_rev != ack)
952 ck_pr_store_32(&data->ack_rev, ack);
955 if ((state & ACK_BOTH) == ACK_BOTH) {
957 * Set expire time to V_dyn_ack_lifetime only if
958 * we got ACKs for both directions.
959 * We use XOR here to avoid possible state
960 * overwriting in concurrent thread.
962 expire = time_uptime + V_dyn_ack_lifetime;
963 ck_pr_xor_32(&data->state, ACK_BOTH);
964 } else if ((data->state & ACK_BOTH) != (state & ACK_BOTH))
965 ck_pr_or_32(&data->state, state & ACK_BOTH);
968 case BOTH_SYN | BOTH_FIN: /* both sides closed */
969 if (V_dyn_fin_lifetime >= V_dyn_keepalive_period)
970 V_dyn_fin_lifetime = V_dyn_keepalive_period - 1;
971 expire = time_uptime + V_dyn_fin_lifetime;
975 if (V_dyn_rst_lifetime >= V_dyn_keepalive_period)
976 V_dyn_rst_lifetime = V_dyn_keepalive_period - 1;
977 expire = time_uptime + V_dyn_rst_lifetime;
979 /* Save TCP state if it was changed */
980 if ((state & TCP_FLAGS) != (old & TCP_FLAGS))
981 ck_pr_or_32(&data->state, state & TCP_FLAGS);
986 * Update ULP specific state.
987 * For TCP we keep sequence numbers and flags. For other protocols
988 * currently we update only expire time. Packets and bytes counters
989 * are also updated here.
992 dyn_update_proto_state(struct dyn_data *data, const struct ipfw_flow_id *pkt,
993 const void *ulp, int pktlen, int dir)
997 /* NOTE: we are in critical section here. */
998 switch (pkt->proto) {
1000 case IPPROTO_UDPLITE:
1001 expire = time_uptime + V_dyn_udp_lifetime;
1004 expire = dyn_update_tcp_state(data, pkt, ulp, dir);
1007 expire = time_uptime + V_dyn_short_lifetime;
1010 * Expiration timer has the per-second granularity, no need to update
1011 * it every time when state is matched.
1013 if (data->expire != expire)
1014 ck_pr_store_32(&data->expire, expire);
1016 if (dir == MATCH_FORWARD)
1017 DYN_COUNTER_INC(data, fwd, pktlen);
1019 DYN_COUNTER_INC(data, rev, pktlen);
1023 * Lookup IPv4 state.
1024 * Must be called in critical section.
1026 struct dyn_ipv4_state *
1027 dyn_lookup_ipv4_state(const struct ipfw_flow_id *pkt, const void *ulp,
1028 struct ipfw_dyn_info *info, int pktlen)
1030 struct dyn_ipv4_state *s;
1031 uint32_t version, bucket;
1033 bucket = DYN_BUCKET(info->hashval, V_curr_dyn_buckets);
1034 info->version = DYN_BUCKET_VERSION(bucket, ipv4_add);
1036 version = DYN_BUCKET_VERSION(bucket, ipv4_del);
1037 CK_SLIST_FOREACH(s, &V_dyn_ipv4[bucket], entry) {
1038 DYNSTATE_PROTECT(s);
1039 if (version != DYN_BUCKET_VERSION(bucket, ipv4_del))
1041 if (s->proto != pkt->proto)
1043 if (info->kidx != 0 && s->kidx != info->kidx)
1045 if (s->sport == pkt->src_port && s->dport == pkt->dst_port &&
1046 s->src == pkt->src_ip && s->dst == pkt->dst_ip) {
1047 info->direction = MATCH_FORWARD;
1050 if (s->sport == pkt->dst_port && s->dport == pkt->src_port &&
1051 s->src == pkt->dst_ip && s->dst == pkt->src_ip) {
1052 info->direction = MATCH_REVERSE;
1058 dyn_update_proto_state(s->data, pkt, ulp, pktlen,
1064 * Lookup IPv4 state.
1065 * Simplifed version is used to check that matching state doesn't exist.
1068 dyn_lookup_ipv4_state_locked(const struct ipfw_flow_id *pkt,
1069 const void *ulp, int pktlen, const void *parent, uint32_t ruleid,
1070 uint16_t rulenum, uint32_t bucket, uint16_t kidx)
1072 struct dyn_ipv4_state *s;
1076 DYN_BUCKET_ASSERT(bucket);
1077 CK_SLIST_FOREACH(s, &V_dyn_ipv4[bucket], entry) {
1078 if (s->proto != pkt->proto ||
1082 * XXXAE: Install synchronized state only when there are
1083 * no matching states.
1085 if (pktlen != 0 && (
1086 s->data->parent != parent ||
1087 s->data->ruleid != ruleid ||
1088 s->data->rulenum != rulenum))
1090 if (s->sport == pkt->src_port &&
1091 s->dport == pkt->dst_port &&
1092 s->src == pkt->src_ip && s->dst == pkt->dst_ip) {
1093 dir = MATCH_FORWARD;
1096 if (s->sport == pkt->dst_port && s->dport == pkt->src_port &&
1097 s->src == pkt->dst_ip && s->dst == pkt->src_ip) {
1098 dir = MATCH_REVERSE;
1103 dyn_update_proto_state(s->data, pkt, ulp, pktlen, dir);
1107 struct dyn_ipv4_state *
1108 dyn_lookup_ipv4_parent(const struct ipfw_flow_id *pkt, const void *rule,
1109 uint32_t ruleid, uint16_t rulenum, uint32_t hashval)
1111 struct dyn_ipv4_state *s;
1112 uint32_t version, bucket;
1114 bucket = DYN_BUCKET(hashval, V_curr_dyn_buckets);
1116 version = DYN_BUCKET_VERSION(bucket, ipv4_parent_del);
1117 CK_SLIST_FOREACH(s, &V_dyn_ipv4_parent[bucket], entry) {
1118 DYNSTATE_PROTECT(s);
1119 if (version != DYN_BUCKET_VERSION(bucket, ipv4_parent_del))
1122 * NOTE: we do not need to check kidx, because parent rule
1123 * can not create states with different kidx.
1124 * And parent rule always created for forward direction.
1126 if (s->limit->parent == rule &&
1127 s->limit->ruleid == ruleid &&
1128 s->limit->rulenum == rulenum &&
1129 s->proto == pkt->proto &&
1130 s->sport == pkt->src_port &&
1131 s->dport == pkt->dst_port &&
1132 s->src == pkt->src_ip && s->dst == pkt->dst_ip) {
1133 if (s->limit->expire != time_uptime +
1134 V_dyn_short_lifetime)
1135 ck_pr_store_32(&s->limit->expire,
1136 time_uptime + V_dyn_short_lifetime);
1143 static struct dyn_ipv4_state *
1144 dyn_lookup_ipv4_parent_locked(const struct ipfw_flow_id *pkt,
1145 const void *rule, uint32_t ruleid, uint16_t rulenum, uint32_t bucket)
1147 struct dyn_ipv4_state *s;
1149 DYN_BUCKET_ASSERT(bucket);
1150 CK_SLIST_FOREACH(s, &V_dyn_ipv4_parent[bucket], entry) {
1151 if (s->limit->parent == rule &&
1152 s->limit->ruleid == ruleid &&
1153 s->limit->rulenum == rulenum &&
1154 s->proto == pkt->proto &&
1155 s->sport == pkt->src_port &&
1156 s->dport == pkt->dst_port &&
1157 s->src == pkt->src_ip && s->dst == pkt->dst_ip)
1166 dyn_getscopeid(const struct ip_fw_args *args)
1170 * If source or destination address is an scopeid address, we need
1171 * determine the scope zone id to resolve address scope ambiguity.
1173 if (IN6_IS_ADDR_LINKLOCAL(&args->f_id.src_ip6) ||
1174 IN6_IS_ADDR_LINKLOCAL(&args->f_id.dst_ip6)) {
1175 MPASS(args->oif != NULL ||
1176 args->m->m_pkthdr.rcvif != NULL);
1177 return (in6_getscopezone(args->oif != NULL ? args->oif:
1178 args->m->m_pkthdr.rcvif, IPV6_ADDR_SCOPE_LINKLOCAL));
1184 * Lookup IPv6 state.
1185 * Must be called in critical section.
1187 static struct dyn_ipv6_state *
1188 dyn_lookup_ipv6_state(const struct ipfw_flow_id *pkt, uint32_t zoneid,
1189 const void *ulp, struct ipfw_dyn_info *info, int pktlen)
1191 struct dyn_ipv6_state *s;
1192 uint32_t version, bucket;
1194 bucket = DYN_BUCKET(info->hashval, V_curr_dyn_buckets);
1195 info->version = DYN_BUCKET_VERSION(bucket, ipv6_add);
1197 version = DYN_BUCKET_VERSION(bucket, ipv6_del);
1198 CK_SLIST_FOREACH(s, &V_dyn_ipv6[bucket], entry) {
1199 DYNSTATE_PROTECT(s);
1200 if (version != DYN_BUCKET_VERSION(bucket, ipv6_del))
1202 if (s->proto != pkt->proto || s->zoneid != zoneid)
1204 if (info->kidx != 0 && s->kidx != info->kidx)
1206 if (s->sport == pkt->src_port && s->dport == pkt->dst_port &&
1207 IN6_ARE_ADDR_EQUAL(&s->src, &pkt->src_ip6) &&
1208 IN6_ARE_ADDR_EQUAL(&s->dst, &pkt->dst_ip6)) {
1209 info->direction = MATCH_FORWARD;
1212 if (s->sport == pkt->dst_port && s->dport == pkt->src_port &&
1213 IN6_ARE_ADDR_EQUAL(&s->src, &pkt->dst_ip6) &&
1214 IN6_ARE_ADDR_EQUAL(&s->dst, &pkt->src_ip6)) {
1215 info->direction = MATCH_REVERSE;
1220 dyn_update_proto_state(s->data, pkt, ulp, pktlen,
1226 * Lookup IPv6 state.
1227 * Simplifed version is used to check that matching state doesn't exist.
1230 dyn_lookup_ipv6_state_locked(const struct ipfw_flow_id *pkt, uint32_t zoneid,
1231 const void *ulp, int pktlen, const void *parent, uint32_t ruleid,
1232 uint16_t rulenum, uint32_t bucket, uint16_t kidx)
1234 struct dyn_ipv6_state *s;
1238 DYN_BUCKET_ASSERT(bucket);
1239 CK_SLIST_FOREACH(s, &V_dyn_ipv6[bucket], entry) {
1240 if (s->proto != pkt->proto || s->kidx != kidx ||
1241 s->zoneid != zoneid)
1244 * XXXAE: Install synchronized state only when there are
1245 * no matching states.
1247 if (pktlen != 0 && (
1248 s->data->parent != parent ||
1249 s->data->ruleid != ruleid ||
1250 s->data->rulenum != rulenum))
1252 if (s->sport == pkt->src_port && s->dport == pkt->dst_port &&
1253 IN6_ARE_ADDR_EQUAL(&s->src, &pkt->src_ip6) &&
1254 IN6_ARE_ADDR_EQUAL(&s->dst, &pkt->dst_ip6)) {
1255 dir = MATCH_FORWARD;
1258 if (s->sport == pkt->dst_port && s->dport == pkt->src_port &&
1259 IN6_ARE_ADDR_EQUAL(&s->src, &pkt->dst_ip6) &&
1260 IN6_ARE_ADDR_EQUAL(&s->dst, &pkt->src_ip6)) {
1261 dir = MATCH_REVERSE;
1266 dyn_update_proto_state(s->data, pkt, ulp, pktlen, dir);
1270 static struct dyn_ipv6_state *
1271 dyn_lookup_ipv6_parent(const struct ipfw_flow_id *pkt, uint32_t zoneid,
1272 const void *rule, uint32_t ruleid, uint16_t rulenum, uint32_t hashval)
1274 struct dyn_ipv6_state *s;
1275 uint32_t version, bucket;
1277 bucket = DYN_BUCKET(hashval, V_curr_dyn_buckets);
1279 version = DYN_BUCKET_VERSION(bucket, ipv6_parent_del);
1280 CK_SLIST_FOREACH(s, &V_dyn_ipv6_parent[bucket], entry) {
1281 DYNSTATE_PROTECT(s);
1282 if (version != DYN_BUCKET_VERSION(bucket, ipv6_parent_del))
1285 * NOTE: we do not need to check kidx, because parent rule
1286 * can not create states with different kidx.
1287 * Also parent rule always created for forward direction.
1289 if (s->limit->parent == rule &&
1290 s->limit->ruleid == ruleid &&
1291 s->limit->rulenum == rulenum &&
1292 s->proto == pkt->proto &&
1293 s->sport == pkt->src_port &&
1294 s->dport == pkt->dst_port && s->zoneid == zoneid &&
1295 IN6_ARE_ADDR_EQUAL(&s->src, &pkt->src_ip6) &&
1296 IN6_ARE_ADDR_EQUAL(&s->dst, &pkt->dst_ip6)) {
1297 if (s->limit->expire != time_uptime +
1298 V_dyn_short_lifetime)
1299 ck_pr_store_32(&s->limit->expire,
1300 time_uptime + V_dyn_short_lifetime);
1307 static struct dyn_ipv6_state *
1308 dyn_lookup_ipv6_parent_locked(const struct ipfw_flow_id *pkt, uint32_t zoneid,
1309 const void *rule, uint32_t ruleid, uint16_t rulenum, uint32_t bucket)
1311 struct dyn_ipv6_state *s;
1313 DYN_BUCKET_ASSERT(bucket);
1314 CK_SLIST_FOREACH(s, &V_dyn_ipv6_parent[bucket], entry) {
1315 if (s->limit->parent == rule &&
1316 s->limit->ruleid == ruleid &&
1317 s->limit->rulenum == rulenum &&
1318 s->proto == pkt->proto &&
1319 s->sport == pkt->src_port &&
1320 s->dport == pkt->dst_port && s->zoneid == zoneid &&
1321 IN6_ARE_ADDR_EQUAL(&s->src, &pkt->src_ip6) &&
1322 IN6_ARE_ADDR_EQUAL(&s->dst, &pkt->dst_ip6))
1331 * Lookup dynamic state.
1332 * pkt - filled by ipfw_chk() ipfw_flow_id;
1333 * ulp - determined by ipfw_chk() upper level protocol header;
1334 * dyn_info - info about matched state to return back;
1335 * Returns pointer to state's parent rule and dyn_info. If there is
1336 * no state, NULL is returned.
1337 * On match ipfw_dyn_lookup() updates state's counters.
1340 ipfw_dyn_lookup_state(const struct ip_fw_args *args, const void *ulp,
1341 int pktlen, const ipfw_insn *cmd, struct ipfw_dyn_info *info)
1343 struct dyn_data *data;
1346 IPFW_RLOCK_ASSERT(&V_layer3_chain);
1350 info->kidx = cmd->arg1;
1351 info->direction = MATCH_NONE;
1352 info->hashval = hash_packet(&args->f_id);
1354 DYNSTATE_CRITICAL_ENTER();
1355 if (IS_IP4_FLOW_ID(&args->f_id)) {
1356 struct dyn_ipv4_state *s;
1358 s = dyn_lookup_ipv4_state(&args->f_id, ulp, info, pktlen);
1361 * Dynamic states are created using the same 5-tuple,
1362 * so it is assumed, that parent rule for O_LIMIT
1363 * state has the same address family.
1366 if (s->type == O_LIMIT) {
1368 rule = s->limit->parent;
1370 rule = data->parent;
1374 else if (IS_IP6_FLOW_ID(&args->f_id)) {
1375 struct dyn_ipv6_state *s;
1377 s = dyn_lookup_ipv6_state(&args->f_id, dyn_getscopeid(args),
1381 if (s->type == O_LIMIT) {
1383 rule = s->limit->parent;
1385 rule = data->parent;
1391 * If cached chain id is the same, we can avoid rule index
1392 * lookup. Otherwise do lookup and update chain_id and f_pos.
1393 * It is safe even if there is concurrent thread that want
1394 * update the same state, because chain->id can be changed
1395 * only under IPFW_WLOCK().
1397 if (data->chain_id != V_layer3_chain.id) {
1398 data->f_pos = ipfw_find_rule(&V_layer3_chain,
1399 data->rulenum, data->ruleid);
1401 * Check that found state has not orphaned.
1402 * When chain->id being changed the parent
1403 * rule can be deleted. If found rule doesn't
1404 * match the parent pointer, consider this
1405 * result as MATCH_NONE and return NULL.
1407 * This will lead to creation of new similar state
1408 * that will be added into head of this bucket.
1409 * And the state that we currently have matched
1410 * should be deleted by dyn_expire_states().
1412 if (V_layer3_chain.map[data->f_pos] == rule)
1413 data->chain_id = V_layer3_chain.id;
1416 info->direction = MATCH_NONE;
1417 DYN_DEBUG("rule %p [%u, %u] is considered "
1418 "invalid in data %p", rule, data->ruleid,
1419 data->rulenum, data);
1422 info->f_pos = data->f_pos;
1424 DYNSTATE_CRITICAL_EXIT();
1427 * Return MATCH_NONE if parent rule is in disabled set.
1428 * This will lead to creation of new similar state that
1429 * will be added into head of this bucket.
1431 * XXXAE: we need to be able update state's set when parent
1432 * rule set is changed.
1434 if (rule != NULL && (V_set_disable & (1 << rule->set))) {
1436 info->direction = MATCH_NONE;
1442 static struct dyn_parent *
1443 dyn_alloc_parent(void *parent, uint32_t ruleid, uint16_t rulenum,
1444 uint8_t set, uint32_t hashval)
1446 struct dyn_parent *limit;
1448 limit = uma_zalloc(V_dyn_parent_zone, M_NOWAIT | M_ZERO);
1449 if (limit == NULL) {
1450 if (last_log != time_uptime) {
1451 last_log = time_uptime;
1453 "ipfw: Cannot allocate parent dynamic state, "
1454 "consider increasing "
1455 "net.inet.ip.fw.dyn_parent_max\n");
1460 limit->parent = parent;
1461 limit->ruleid = ruleid;
1462 limit->rulenum = rulenum;
1464 limit->hashval = hashval;
1465 limit->expire = time_uptime + V_dyn_short_lifetime;
1469 static struct dyn_data *
1470 dyn_alloc_dyndata(void *parent, uint32_t ruleid, uint16_t rulenum,
1471 uint8_t set, const struct ipfw_flow_id *pkt, const void *ulp, int pktlen,
1472 uint32_t hashval, uint16_t fibnum)
1474 struct dyn_data *data;
1476 data = uma_zalloc(V_dyn_data_zone, M_NOWAIT | M_ZERO);
1478 if (last_log != time_uptime) {
1479 last_log = time_uptime;
1481 "ipfw: Cannot allocate dynamic state, "
1482 "consider increasing net.inet.ip.fw.dyn_max\n");
1487 data->parent = parent;
1488 data->ruleid = ruleid;
1489 data->rulenum = rulenum;
1491 data->fibnum = fibnum;
1492 data->hashval = hashval;
1493 data->expire = time_uptime + V_dyn_syn_lifetime;
1494 dyn_update_proto_state(data, pkt, ulp, pktlen, MATCH_FORWARD);
1498 static struct dyn_ipv4_state *
1499 dyn_alloc_ipv4_state(const struct ipfw_flow_id *pkt, uint16_t kidx,
1502 struct dyn_ipv4_state *s;
1504 s = uma_zalloc(V_dyn_ipv4_zone, M_NOWAIT | M_ZERO);
1510 s->proto = pkt->proto;
1511 s->sport = pkt->src_port;
1512 s->dport = pkt->dst_port;
1513 s->src = pkt->src_ip;
1514 s->dst = pkt->dst_ip;
1519 * Add IPv4 parent state.
1520 * Returns pointer to parent state. When it is not NULL we are in
1521 * critical section and pointer protected by hazard pointer.
1522 * When some error occurs, it returns NULL and exit from critical section
1525 static struct dyn_ipv4_state *
1526 dyn_add_ipv4_parent(void *rule, uint32_t ruleid, uint16_t rulenum,
1527 uint8_t set, const struct ipfw_flow_id *pkt, uint32_t hashval,
1528 uint32_t version, uint16_t kidx)
1530 struct dyn_ipv4_state *s;
1531 struct dyn_parent *limit;
1534 bucket = DYN_BUCKET(hashval, V_curr_dyn_buckets);
1535 DYN_BUCKET_LOCK(bucket);
1536 if (version != DYN_BUCKET_VERSION(bucket, ipv4_parent_add)) {
1538 * Bucket version has been changed since last lookup,
1539 * do lookup again to be sure that state does not exist.
1541 s = dyn_lookup_ipv4_parent_locked(pkt, rule, ruleid,
1545 * Simultaneous thread has already created this
1546 * state. Just return it.
1548 DYNSTATE_CRITICAL_ENTER();
1549 DYNSTATE_PROTECT(s);
1550 DYN_BUCKET_UNLOCK(bucket);
1555 limit = dyn_alloc_parent(rule, ruleid, rulenum, set, hashval);
1556 if (limit == NULL) {
1557 DYN_BUCKET_UNLOCK(bucket);
1561 s = dyn_alloc_ipv4_state(pkt, kidx, O_LIMIT_PARENT);
1563 DYN_BUCKET_UNLOCK(bucket);
1564 uma_zfree(V_dyn_parent_zone, limit);
1569 CK_SLIST_INSERT_HEAD(&V_dyn_ipv4_parent[bucket], s, entry);
1570 DYN_COUNT_INC(dyn_parent_count);
1571 DYN_BUCKET_VERSION_BUMP(bucket, ipv4_parent_add);
1572 DYNSTATE_CRITICAL_ENTER();
1573 DYNSTATE_PROTECT(s);
1574 DYN_BUCKET_UNLOCK(bucket);
1579 dyn_add_ipv4_state(void *parent, uint32_t ruleid, uint16_t rulenum,
1580 uint8_t set, const struct ipfw_flow_id *pkt, const void *ulp, int pktlen,
1581 uint32_t hashval, struct ipfw_dyn_info *info, uint16_t fibnum,
1582 uint16_t kidx, uint8_t type)
1584 struct dyn_ipv4_state *s;
1588 bucket = DYN_BUCKET(hashval, V_curr_dyn_buckets);
1589 DYN_BUCKET_LOCK(bucket);
1590 if (info->direction == MATCH_UNKNOWN ||
1591 info->kidx != kidx ||
1592 info->hashval != hashval ||
1593 info->version != DYN_BUCKET_VERSION(bucket, ipv4_add)) {
1595 * Bucket version has been changed since last lookup,
1596 * do lookup again to be sure that state does not exist.
1598 if (dyn_lookup_ipv4_state_locked(pkt, ulp, pktlen, parent,
1599 ruleid, rulenum, bucket, kidx) != 0) {
1600 DYN_BUCKET_UNLOCK(bucket);
1605 data = dyn_alloc_dyndata(parent, ruleid, rulenum, set, pkt, ulp,
1606 pktlen, hashval, fibnum);
1608 DYN_BUCKET_UNLOCK(bucket);
1612 s = dyn_alloc_ipv4_state(pkt, kidx, type);
1614 DYN_BUCKET_UNLOCK(bucket);
1615 uma_zfree(V_dyn_data_zone, data);
1620 CK_SLIST_INSERT_HEAD(&V_dyn_ipv4[bucket], s, entry);
1621 DYN_COUNT_INC(dyn_count);
1622 DYN_BUCKET_VERSION_BUMP(bucket, ipv4_add);
1623 DYN_BUCKET_UNLOCK(bucket);
1628 static struct dyn_ipv6_state *
1629 dyn_alloc_ipv6_state(const struct ipfw_flow_id *pkt, uint32_t zoneid,
1630 uint16_t kidx, uint8_t type)
1632 struct dyn_ipv6_state *s;
1634 s = uma_zalloc(V_dyn_ipv6_zone, M_NOWAIT | M_ZERO);
1641 s->proto = pkt->proto;
1642 s->sport = pkt->src_port;
1643 s->dport = pkt->dst_port;
1644 s->src = pkt->src_ip6;
1645 s->dst = pkt->dst_ip6;
1650 * Add IPv6 parent state.
1651 * Returns pointer to parent state. When it is not NULL we are in
1652 * critical section and pointer protected by hazard pointer.
1653 * When some error occurs, it return NULL and exit from critical section
1656 static struct dyn_ipv6_state *
1657 dyn_add_ipv6_parent(void *rule, uint32_t ruleid, uint16_t rulenum,
1658 uint8_t set, const struct ipfw_flow_id *pkt, uint32_t zoneid,
1659 uint32_t hashval, uint32_t version, uint16_t kidx)
1661 struct dyn_ipv6_state *s;
1662 struct dyn_parent *limit;
1665 bucket = DYN_BUCKET(hashval, V_curr_dyn_buckets);
1666 DYN_BUCKET_LOCK(bucket);
1667 if (version != DYN_BUCKET_VERSION(bucket, ipv6_parent_add)) {
1669 * Bucket version has been changed since last lookup,
1670 * do lookup again to be sure that state does not exist.
1672 s = dyn_lookup_ipv6_parent_locked(pkt, zoneid, rule, ruleid,
1676 * Simultaneous thread has already created this
1677 * state. Just return it.
1679 DYNSTATE_CRITICAL_ENTER();
1680 DYNSTATE_PROTECT(s);
1681 DYN_BUCKET_UNLOCK(bucket);
1686 limit = dyn_alloc_parent(rule, ruleid, rulenum, set, hashval);
1687 if (limit == NULL) {
1688 DYN_BUCKET_UNLOCK(bucket);
1692 s = dyn_alloc_ipv6_state(pkt, zoneid, kidx, O_LIMIT_PARENT);
1694 DYN_BUCKET_UNLOCK(bucket);
1695 uma_zfree(V_dyn_parent_zone, limit);
1700 CK_SLIST_INSERT_HEAD(&V_dyn_ipv6_parent[bucket], s, entry);
1701 DYN_COUNT_INC(dyn_parent_count);
1702 DYN_BUCKET_VERSION_BUMP(bucket, ipv6_parent_add);
1703 DYNSTATE_CRITICAL_ENTER();
1704 DYNSTATE_PROTECT(s);
1705 DYN_BUCKET_UNLOCK(bucket);
1710 dyn_add_ipv6_state(void *parent, uint32_t ruleid, uint16_t rulenum,
1711 uint8_t set, const struct ipfw_flow_id *pkt, uint32_t zoneid,
1712 const void *ulp, int pktlen, uint32_t hashval, struct ipfw_dyn_info *info,
1713 uint16_t fibnum, uint16_t kidx, uint8_t type)
1715 struct dyn_ipv6_state *s;
1716 struct dyn_data *data;
1719 bucket = DYN_BUCKET(hashval, V_curr_dyn_buckets);
1720 DYN_BUCKET_LOCK(bucket);
1721 if (info->direction == MATCH_UNKNOWN ||
1722 info->kidx != kidx ||
1723 info->hashval != hashval ||
1724 info->version != DYN_BUCKET_VERSION(bucket, ipv6_add)) {
1726 * Bucket version has been changed since last lookup,
1727 * do lookup again to be sure that state does not exist.
1729 if (dyn_lookup_ipv6_state_locked(pkt, zoneid, ulp, pktlen,
1730 parent, ruleid, rulenum, bucket, kidx) != 0) {
1731 DYN_BUCKET_UNLOCK(bucket);
1736 data = dyn_alloc_dyndata(parent, ruleid, rulenum, set, pkt, ulp,
1737 pktlen, hashval, fibnum);
1739 DYN_BUCKET_UNLOCK(bucket);
1743 s = dyn_alloc_ipv6_state(pkt, zoneid, kidx, type);
1745 DYN_BUCKET_UNLOCK(bucket);
1746 uma_zfree(V_dyn_data_zone, data);
1751 CK_SLIST_INSERT_HEAD(&V_dyn_ipv6[bucket], s, entry);
1752 DYN_COUNT_INC(dyn_count);
1753 DYN_BUCKET_VERSION_BUMP(bucket, ipv6_add);
1754 DYN_BUCKET_UNLOCK(bucket);
1760 dyn_get_parent_state(const struct ipfw_flow_id *pkt, uint32_t zoneid,
1761 struct ip_fw *rule, uint32_t hashval, uint32_t limit, uint16_t kidx)
1764 struct dyn_parent *p;
1766 uint32_t bucket, version;
1770 bucket = DYN_BUCKET(hashval, V_curr_dyn_buckets);
1771 DYNSTATE_CRITICAL_ENTER();
1772 if (IS_IP4_FLOW_ID(pkt)) {
1773 struct dyn_ipv4_state *s;
1775 version = DYN_BUCKET_VERSION(bucket, ipv4_parent_add);
1776 s = dyn_lookup_ipv4_parent(pkt, rule, rule->id,
1777 rule->rulenum, bucket);
1780 * Exit from critical section because dyn_add_parent()
1781 * will acquire bucket lock.
1783 DYNSTATE_CRITICAL_EXIT();
1785 s = dyn_add_ipv4_parent(rule, rule->id,
1786 rule->rulenum, rule->set, pkt, hashval,
1790 /* Now we are in critical section again. */
1796 else if (IS_IP6_FLOW_ID(pkt)) {
1797 struct dyn_ipv6_state *s;
1799 version = DYN_BUCKET_VERSION(bucket, ipv6_parent_add);
1800 s = dyn_lookup_ipv6_parent(pkt, zoneid, rule, rule->id,
1801 rule->rulenum, bucket);
1804 * Exit from critical section because dyn_add_parent()
1805 * can acquire bucket mutex.
1807 DYNSTATE_CRITICAL_EXIT();
1809 s = dyn_add_ipv6_parent(rule, rule->id,
1810 rule->rulenum, rule->set, pkt, zoneid, hashval,
1814 /* Now we are in critical section again. */
1821 DYNSTATE_CRITICAL_EXIT();
1825 /* Check the limit */
1826 if (DPARENT_COUNT(p) >= limit) {
1827 DYNSTATE_CRITICAL_EXIT();
1828 if (V_fw_verbose && last_log != time_uptime) {
1829 last_log = time_uptime;
1830 snprintf(sbuf, sizeof(sbuf), "%u drop session",
1832 print_dyn_rule_flags(pkt, O_LIMIT,
1833 LOG_SECURITY | LOG_DEBUG, sbuf,
1834 "too many entries");
1839 /* Take new session into account. */
1840 DPARENT_COUNT_INC(p);
1842 * We must exit from critical section because the following code
1843 * can acquire bucket mutex.
1844 * We rely on the the 'count' field. The state will not expire
1845 * until it has some child states, i.e. 'count' field is not zero.
1846 * Return state pointer, it will be used by child states as parent.
1848 DYNSTATE_CRITICAL_EXIT();
1853 dyn_install_state(const struct ipfw_flow_id *pkt, uint32_t zoneid,
1854 uint16_t fibnum, const void *ulp, int pktlen, void *rule,
1855 uint32_t ruleid, uint16_t rulenum, uint8_t set,
1856 struct ipfw_dyn_info *info, uint32_t limit, uint16_t limit_mask,
1857 uint16_t kidx, uint8_t type)
1859 struct ipfw_flow_id id;
1860 uint32_t hashval, parent_hashval;
1863 MPASS(type == O_LIMIT || type == O_KEEP_STATE);
1865 if (type == O_LIMIT) {
1866 /* Create masked flow id and calculate bucket */
1867 id.addr_type = pkt->addr_type;
1868 id.proto = pkt->proto;
1869 id.fib = fibnum; /* unused */
1870 id.src_port = (limit_mask & DYN_SRC_PORT) ?
1872 id.dst_port = (limit_mask & DYN_DST_PORT) ?
1874 if (IS_IP4_FLOW_ID(pkt)) {
1875 id.src_ip = (limit_mask & DYN_SRC_ADDR) ?
1877 id.dst_ip = (limit_mask & DYN_DST_ADDR) ?
1881 else if (IS_IP6_FLOW_ID(pkt)) {
1882 if (limit_mask & DYN_SRC_ADDR)
1883 id.src_ip6 = pkt->src_ip6;
1885 memset(&id.src_ip6, 0, sizeof(id.src_ip6));
1886 if (limit_mask & DYN_DST_ADDR)
1887 id.dst_ip6 = pkt->dst_ip6;
1889 memset(&id.dst_ip6, 0, sizeof(id.dst_ip6));
1893 return (EAFNOSUPPORT);
1895 parent_hashval = hash_parent(&id, rule);
1896 rule = dyn_get_parent_state(&id, zoneid, rule, parent_hashval,
1900 if (V_fw_verbose && last_log != time_uptime) {
1901 last_log = time_uptime;
1902 snprintf(sbuf, sizeof(sbuf),
1903 "%u drop session", rule->rulenum);
1904 print_dyn_rule_flags(pkt, O_LIMIT,
1905 LOG_SECURITY | LOG_DEBUG, sbuf,
1906 "too many entries");
1912 * Limit is not reached, create new state.
1913 * Now rule points to parent state.
1917 hashval = hash_packet(pkt);
1918 if (IS_IP4_FLOW_ID(pkt))
1919 ret = dyn_add_ipv4_state(rule, ruleid, rulenum, set, pkt,
1920 ulp, pktlen, hashval, info, fibnum, kidx, type);
1922 else if (IS_IP6_FLOW_ID(pkt))
1923 ret = dyn_add_ipv6_state(rule, ruleid, rulenum, set, pkt,
1924 zoneid, ulp, pktlen, hashval, info, fibnum, kidx, type);
1929 if (type == O_LIMIT) {
1932 * We failed to create child state for O_LIMIT
1933 * opcode. Since we already counted it in the parent,
1934 * we must revert counter back. The 'rule' points to
1935 * parent state, use it to get dyn_parent.
1937 * XXXAE: it should be safe to use 'rule' pointer
1938 * without extra lookup, parent state is referenced
1939 * and should not be freed.
1941 if (IS_IP4_FLOW_ID(&id))
1943 ((struct dyn_ipv4_state *)rule)->limit);
1945 else if (IS_IP6_FLOW_ID(&id))
1947 ((struct dyn_ipv6_state *)rule)->limit);
1952 * EEXIST means that simultaneous thread has created this
1953 * state. Consider this as success.
1955 * XXXAE: should we invalidate 'info' content here?
1963 * Install dynamic state.
1964 * chain - ipfw's instance;
1965 * rule - the parent rule that installs the state;
1966 * cmd - opcode that installs the state;
1967 * args - ipfw arguments;
1968 * ulp - upper level protocol header;
1969 * pktlen - packet length;
1970 * info - dynamic state lookup info;
1971 * tablearg - tablearg id.
1973 * Returns non-zero value (failure) if state is not installed because
1974 * of errors or because session limitations are enforced.
1977 ipfw_dyn_install_state(struct ip_fw_chain *chain, struct ip_fw *rule,
1978 const ipfw_insn_limit *cmd, const struct ip_fw_args *args,
1979 const void *ulp, int pktlen, struct ipfw_dyn_info *info,
1983 uint16_t limit_mask;
1985 if (cmd->o.opcode == O_LIMIT) {
1986 limit = IP_FW_ARG_TABLEARG(chain, cmd->conn_limit, limit);
1987 limit_mask = cmd->limit_mask;
1992 return (dyn_install_state(&args->f_id,
1994 IS_IP6_FLOW_ID(&args->f_id) ? dyn_getscopeid(args):
1996 0, M_GETFIB(args->m), ulp, pktlen, rule, rule->id, rule->rulenum,
1997 rule->set, info, limit, limit_mask, cmd->o.arg1, cmd->o.opcode));
2001 * Free safe to remove state entries from expired lists.
2004 dyn_free_states(struct ip_fw_chain *chain)
2006 struct dyn_ipv4_state *s4, *s4n;
2008 struct dyn_ipv6_state *s6, *s6n;
2010 int cached_count, i;
2013 * We keep pointers to objects that are in use on each CPU
2014 * in the per-cpu dyn_hp pointer. When object is going to be
2015 * removed, first of it is unlinked from the corresponding
2016 * list. This leads to changing of dyn_bucket_xxx_delver version.
2017 * Unlinked objects is placed into corresponding dyn_expired_xxx
2018 * list. Reader that is going to dereference object pointer checks
2019 * dyn_bucket_xxx_delver version before and after storing pointer
2020 * into dyn_hp. If version is the same, the object is protected
2021 * from freeing and it is safe to dereference. Othervise reader
2022 * tries to iterate list again from the beginning, but this object
2023 * now unlinked and thus will not be accessible.
2025 * Copy dyn_hp pointers for each CPU into dyn_hp_cache array.
2026 * It does not matter that some pointer can be changed in
2027 * time while we are copying. We need to check, that objects
2028 * removed in the previous pass are not in use. And if dyn_hp
2029 * pointer does not contain it in the time when we are copying,
2030 * it will not appear there, because it is already unlinked.
2031 * And for new pointers we will not free objects that will be
2032 * unlinked in this pass.
2036 dyn_hp_cache[cached_count] = DYNSTATE_GET(i);
2037 if (dyn_hp_cache[cached_count] != NULL)
2042 * Free expired states that are safe to free.
2043 * Check each entry from previous pass in the dyn_expired_xxx
2044 * list, if pointer to the object is in the dyn_hp_cache array,
2045 * keep it until next pass. Otherwise it is safe to free the
2048 * XXXAE: optimize this to use SLIST_REMOVE_AFTER.
2050 #define DYN_FREE_STATES(s, next, name) do { \
2051 s = SLIST_FIRST(&V_dyn_expired_ ## name); \
2052 while (s != NULL) { \
2053 next = SLIST_NEXT(s, expired); \
2054 for (i = 0; i < cached_count; i++) \
2055 if (dyn_hp_cache[i] == s) \
2057 if (i == cached_count) { \
2058 if (s->type == O_LIMIT_PARENT && \
2059 s->limit->count != 0) { \
2063 SLIST_REMOVE(&V_dyn_expired_ ## name, \
2064 s, dyn_ ## name ## _state, expired); \
2065 if (s->type == O_LIMIT_PARENT) \
2066 uma_zfree(V_dyn_parent_zone, s->limit); \
2068 uma_zfree(V_dyn_data_zone, s->data); \
2069 uma_zfree(V_dyn_ ## name ## _zone, s); \
2076 * Protect access to expired lists with DYN_EXPIRED_LOCK.
2077 * Userland can invoke ipfw_expire_dyn_states() to delete
2078 * specific states, this will lead to modification of expired
2081 * XXXAE: do we need DYN_EXPIRED_LOCK? We can just use
2082 * IPFW_UH_WLOCK to protect access to these lists.
2085 DYN_FREE_STATES(s4, s4n, ipv4);
2087 DYN_FREE_STATES(s6, s6n, ipv6);
2089 DYN_EXPIRED_UNLOCK();
2090 #undef DYN_FREE_STATES
2094 * Returns 1 when state is matched by specified range, otherwise returns 0.
2097 dyn_match_range(uint16_t rulenum, uint8_t set, const ipfw_range_tlv *rt)
2101 /* flush all states */
2102 if (rt->flags & IPFW_RCFLAG_ALL)
2104 if ((rt->flags & IPFW_RCFLAG_SET) != 0 && set != rt->set)
2106 if ((rt->flags & IPFW_RCFLAG_RANGE) != 0 &&
2107 (rulenum < rt->start_rule || rulenum > rt->end_rule))
2113 dyn_match_ipv4_state(struct dyn_ipv4_state *s, const ipfw_range_tlv *rt)
2116 if (s->type == O_LIMIT_PARENT)
2117 return (dyn_match_range(s->limit->rulenum,
2118 s->limit->set, rt));
2120 if (s->type == O_LIMIT)
2121 return (dyn_match_range(s->data->rulenum, s->data->set, rt));
2123 if (dyn_match_range(s->data->rulenum, s->data->set, rt))
2131 dyn_match_ipv6_state(struct dyn_ipv6_state *s, const ipfw_range_tlv *rt)
2134 if (s->type == O_LIMIT_PARENT)
2135 return (dyn_match_range(s->limit->rulenum,
2136 s->limit->set, rt));
2138 if (s->type == O_LIMIT)
2139 return (dyn_match_range(s->data->rulenum, s->data->set, rt));
2141 if (dyn_match_range(s->data->rulenum, s->data->set, rt))
2149 * Unlink expired entries from states lists.
2150 * @rt can be used to specify the range of states for deletion.
2153 dyn_expire_states(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
2155 struct dyn_ipv4_slist expired_ipv4;
2157 struct dyn_ipv6_slist expired_ipv6;
2158 struct dyn_ipv6_state *s6, *s6n, *s6p;
2160 struct dyn_ipv4_state *s4, *s4n, *s4p;
2161 int bucket, removed, length, max_length;
2164 * Unlink expired states from each bucket.
2165 * With acquired bucket lock iterate entries of each lists:
2166 * ipv4, ipv4_parent, ipv6, and ipv6_parent. Check expired time
2167 * and unlink entry from the list, link entry into temporary
2168 * expired_xxx lists then bump "del" bucket version.
2170 * When an entry is removed, corresponding states counter is
2171 * decremented. If entry has O_LIMIT type, parent's reference
2172 * counter is decremented.
2174 * NOTE: this function can be called from userspace context
2175 * when user deletes rules. In this case all matched states
2176 * will be forcedly unlinked. O_LIMIT_PARENT states will be kept
2177 * in the expired lists until reference counter become zero.
2179 #define DYN_UNLINK_STATES(s, prev, next, exp, af, name, extra) do { \
2183 s = CK_SLIST_FIRST(&V_dyn_ ## name [bucket]); \
2184 while (s != NULL) { \
2185 next = CK_SLIST_NEXT(s, entry); \
2186 if ((TIME_LEQ((s)->exp, time_uptime) && extra) || \
2187 (rt != NULL && dyn_match_ ## af ## _state(s, rt))) {\
2189 CK_SLIST_REMOVE_AFTER(prev, entry); \
2191 CK_SLIST_REMOVE_HEAD( \
2192 &V_dyn_ ## name [bucket], entry); \
2194 SLIST_INSERT_HEAD(&expired_ ## af, s, expired); \
2195 if (s->type == O_LIMIT_PARENT) \
2196 DYN_COUNT_DEC(dyn_parent_count); \
2198 DYN_COUNT_DEC(dyn_count); \
2199 if (s->type == O_LIMIT) { \
2200 s = s->data->parent; \
2201 DPARENT_COUNT_DEC(s->limit); \
2211 DYN_BUCKET_VERSION_BUMP(bucket, name ## _del); \
2212 if (length > max_length) \
2213 max_length = length; \
2216 SLIST_INIT(&expired_ipv4);
2218 SLIST_INIT(&expired_ipv6);
2221 for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
2222 DYN_BUCKET_LOCK(bucket);
2223 DYN_UNLINK_STATES(s4, s4p, s4n, data->expire, ipv4, ipv4, 1);
2224 DYN_UNLINK_STATES(s4, s4p, s4n, limit->expire, ipv4,
2225 ipv4_parent, (s4->limit->count == 0));
2227 DYN_UNLINK_STATES(s6, s6p, s6n, data->expire, ipv6, ipv6, 1);
2228 DYN_UNLINK_STATES(s6, s6p, s6n, limit->expire, ipv6,
2229 ipv6_parent, (s6->limit->count == 0));
2231 DYN_BUCKET_UNLOCK(bucket);
2233 /* Update curr_max_length for statistics. */
2234 V_curr_max_length = max_length;
2236 * Concatenate temporary lists with global expired lists.
2239 SLIST_CONCAT(&V_dyn_expired_ipv4, &expired_ipv4,
2240 dyn_ipv4_state, expired);
2242 SLIST_CONCAT(&V_dyn_expired_ipv6, &expired_ipv6,
2243 dyn_ipv6_state, expired);
2245 DYN_EXPIRED_UNLOCK();
2246 #undef DYN_UNLINK_STATES
2247 #undef DYN_UNREF_STATES
2250 static struct mbuf *
2251 dyn_mgethdr(int len, uint16_t fibnum)
2255 m = m_gethdr(M_NOWAIT, MT_DATA);
2259 mac_netinet_firewall_send(m);
2261 M_SETFIB(m, fibnum);
2262 m->m_data += max_linkhdr;
2263 m->m_flags |= M_SKIP_FIREWALL;
2264 m->m_len = m->m_pkthdr.len = len;
2265 bzero(m->m_data, len);
2270 dyn_make_keepalive_ipv4(struct mbuf *m, in_addr_t src, in_addr_t dst,
2271 uint32_t seq, uint32_t ack, uint16_t sport, uint16_t dport)
2276 ip = mtod(m, struct ip *);
2278 ip->ip_hl = sizeof(*ip) >> 2;
2279 ip->ip_tos = IPTOS_LOWDELAY;
2280 ip->ip_len = htons(m->m_len);
2281 ip->ip_off |= htons(IP_DF);
2282 ip->ip_ttl = V_ip_defttl;
2283 ip->ip_p = IPPROTO_TCP;
2284 ip->ip_src.s_addr = htonl(src);
2285 ip->ip_dst.s_addr = htonl(dst);
2287 tcp = mtodo(m, sizeof(struct ip));
2288 tcp->th_sport = htons(sport);
2289 tcp->th_dport = htons(dport);
2290 tcp->th_off = sizeof(struct tcphdr) >> 2;
2291 tcp->th_seq = htonl(seq);
2292 tcp->th_ack = htonl(ack);
2293 tcp->th_flags = TH_ACK;
2294 tcp->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
2295 htons(sizeof(struct tcphdr) + IPPROTO_TCP));
2297 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2298 m->m_pkthdr.csum_flags = CSUM_TCP;
2302 dyn_enqueue_keepalive_ipv4(struct mbufq *q, const struct dyn_ipv4_state *s)
2306 if ((s->data->state & ACK_FWD) == 0 && s->data->ack_fwd > 0) {
2307 m = dyn_mgethdr(sizeof(struct ip) + sizeof(struct tcphdr),
2310 dyn_make_keepalive_ipv4(m, s->dst, s->src,
2311 s->data->ack_fwd - 1, s->data->ack_rev,
2312 s->dport, s->sport);
2313 if (mbufq_enqueue(q, m)) {
2315 log(LOG_DEBUG, "ipfw: limit for IPv4 "
2316 "keepalive queue is reached.\n");
2322 if ((s->data->state & ACK_REV) == 0 && s->data->ack_rev > 0) {
2323 m = dyn_mgethdr(sizeof(struct ip) + sizeof(struct tcphdr),
2326 dyn_make_keepalive_ipv4(m, s->src, s->dst,
2327 s->data->ack_rev - 1, s->data->ack_fwd,
2328 s->sport, s->dport);
2329 if (mbufq_enqueue(q, m)) {
2331 log(LOG_DEBUG, "ipfw: limit for IPv4 "
2332 "keepalive queue is reached.\n");
2340 * Prepare and send keep-alive packets.
2343 dyn_send_keepalive_ipv4(struct ip_fw_chain *chain)
2347 struct dyn_ipv4_state *s;
2350 mbufq_init(&q, DYN_KEEPALIVE_MAXQ);
2351 IPFW_UH_RLOCK(chain);
2353 * It is safe to not use hazard pointer and just do lockless
2354 * access to the lists, because states entries can not be deleted
2355 * while we hold IPFW_UH_RLOCK.
2357 for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
2358 CK_SLIST_FOREACH(s, &V_dyn_ipv4[bucket], entry) {
2360 * Only established TCP connections that will
2361 * become expired withing dyn_keepalive_interval.
2363 if (s->proto != IPPROTO_TCP ||
2364 (s->data->state & BOTH_SYN) != BOTH_SYN ||
2365 TIME_LEQ(time_uptime + V_dyn_keepalive_interval,
2368 dyn_enqueue_keepalive_ipv4(&q, s);
2371 IPFW_UH_RUNLOCK(chain);
2372 while ((m = mbufq_dequeue(&q)) != NULL)
2373 ip_output(m, NULL, NULL, 0, NULL, NULL);
2378 dyn_make_keepalive_ipv6(struct mbuf *m, const struct in6_addr *src,
2379 const struct in6_addr *dst, uint32_t zoneid, uint32_t seq, uint32_t ack,
2380 uint16_t sport, uint16_t dport)
2383 struct ip6_hdr *ip6;
2385 ip6 = mtod(m, struct ip6_hdr *);
2386 ip6->ip6_vfc |= IPV6_VERSION;
2387 ip6->ip6_plen = htons(sizeof(struct tcphdr));
2388 ip6->ip6_nxt = IPPROTO_TCP;
2389 ip6->ip6_hlim = IPV6_DEFHLIM;
2390 ip6->ip6_src = *src;
2391 if (IN6_IS_ADDR_LINKLOCAL(src))
2392 ip6->ip6_src.s6_addr16[1] = htons(zoneid & 0xffff);
2393 ip6->ip6_dst = *dst;
2394 if (IN6_IS_ADDR_LINKLOCAL(dst))
2395 ip6->ip6_dst.s6_addr16[1] = htons(zoneid & 0xffff);
2397 tcp = mtodo(m, sizeof(struct ip6_hdr));
2398 tcp->th_sport = htons(sport);
2399 tcp->th_dport = htons(dport);
2400 tcp->th_off = sizeof(struct tcphdr) >> 2;
2401 tcp->th_seq = htonl(seq);
2402 tcp->th_ack = htonl(ack);
2403 tcp->th_flags = TH_ACK;
2404 tcp->th_sum = in6_cksum_pseudo(ip6, sizeof(struct tcphdr),
2407 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
2408 m->m_pkthdr.csum_flags = CSUM_TCP_IPV6;
2412 dyn_enqueue_keepalive_ipv6(struct mbufq *q, const struct dyn_ipv6_state *s)
2416 if ((s->data->state & ACK_FWD) == 0 && s->data->ack_fwd > 0) {
2417 m = dyn_mgethdr(sizeof(struct ip6_hdr) +
2418 sizeof(struct tcphdr), s->data->fibnum);
2420 dyn_make_keepalive_ipv6(m, &s->dst, &s->src,
2421 s->zoneid, s->data->ack_fwd - 1, s->data->ack_rev,
2422 s->dport, s->sport);
2423 if (mbufq_enqueue(q, m)) {
2425 log(LOG_DEBUG, "ipfw: limit for IPv6 "
2426 "keepalive queue is reached.\n");
2432 if ((s->data->state & ACK_REV) == 0 && s->data->ack_rev > 0) {
2433 m = dyn_mgethdr(sizeof(struct ip6_hdr) +
2434 sizeof(struct tcphdr), s->data->fibnum);
2436 dyn_make_keepalive_ipv6(m, &s->src, &s->dst,
2437 s->zoneid, s->data->ack_rev - 1, s->data->ack_fwd,
2438 s->sport, s->dport);
2439 if (mbufq_enqueue(q, m)) {
2441 log(LOG_DEBUG, "ipfw: limit for IPv6 "
2442 "keepalive queue is reached.\n");
2450 dyn_send_keepalive_ipv6(struct ip_fw_chain *chain)
2454 struct dyn_ipv6_state *s;
2457 mbufq_init(&q, DYN_KEEPALIVE_MAXQ);
2458 IPFW_UH_RLOCK(chain);
2460 * It is safe to not use hazard pointer and just do lockless
2461 * access to the lists, because states entries can not be deleted
2462 * while we hold IPFW_UH_RLOCK.
2464 for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
2465 CK_SLIST_FOREACH(s, &V_dyn_ipv6[bucket], entry) {
2467 * Only established TCP connections that will
2468 * become expired withing dyn_keepalive_interval.
2470 if (s->proto != IPPROTO_TCP ||
2471 (s->data->state & BOTH_SYN) != BOTH_SYN ||
2472 TIME_LEQ(time_uptime + V_dyn_keepalive_interval,
2475 dyn_enqueue_keepalive_ipv6(&q, s);
2478 IPFW_UH_RUNLOCK(chain);
2479 while ((m = mbufq_dequeue(&q)) != NULL)
2480 ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
2485 dyn_grow_hashtable(struct ip_fw_chain *chain, uint32_t new)
2488 struct dyn_ipv6ck_slist *ipv6, *ipv6_parent;
2489 uint32_t *ipv6_add, *ipv6_del, *ipv6_parent_add, *ipv6_parent_del;
2490 struct dyn_ipv6_state *s6;
2492 struct dyn_ipv4ck_slist *ipv4, *ipv4_parent;
2493 uint32_t *ipv4_add, *ipv4_del, *ipv4_parent_add, *ipv4_parent_del;
2494 struct dyn_ipv4_state *s4;
2495 struct mtx *bucket_lock;
2499 MPASS(powerof2(new));
2500 DYN_DEBUG("grow hash size %u -> %u", V_curr_dyn_buckets, new);
2502 * Allocate and initialize new lists.
2503 * XXXAE: on memory pressure this can disable callout timer.
2505 bucket_lock = malloc(new * sizeof(struct mtx), M_IPFW,
2507 ipv4 = malloc(new * sizeof(struct dyn_ipv4ck_slist), M_IPFW,
2509 ipv4_parent = malloc(new * sizeof(struct dyn_ipv4ck_slist), M_IPFW,
2511 ipv4_add = malloc(new * sizeof(uint32_t), M_IPFW, M_WAITOK | M_ZERO);
2512 ipv4_del = malloc(new * sizeof(uint32_t), M_IPFW, M_WAITOK | M_ZERO);
2513 ipv4_parent_add = malloc(new * sizeof(uint32_t), M_IPFW,
2515 ipv4_parent_del = malloc(new * sizeof(uint32_t), M_IPFW,
2518 ipv6 = malloc(new * sizeof(struct dyn_ipv6ck_slist), M_IPFW,
2520 ipv6_parent = malloc(new * sizeof(struct dyn_ipv6ck_slist), M_IPFW,
2522 ipv6_add = malloc(new * sizeof(uint32_t), M_IPFW, M_WAITOK | M_ZERO);
2523 ipv6_del = malloc(new * sizeof(uint32_t), M_IPFW, M_WAITOK | M_ZERO);
2524 ipv6_parent_add = malloc(new * sizeof(uint32_t), M_IPFW,
2526 ipv6_parent_del = malloc(new * sizeof(uint32_t), M_IPFW,
2529 for (bucket = 0; bucket < new; bucket++) {
2530 DYN_BUCKET_LOCK_INIT(bucket_lock, bucket);
2531 CK_SLIST_INIT(&ipv4[bucket]);
2532 CK_SLIST_INIT(&ipv4_parent[bucket]);
2534 CK_SLIST_INIT(&ipv6[bucket]);
2535 CK_SLIST_INIT(&ipv6_parent[bucket]);
2539 #define DYN_RELINK_STATES(s, hval, i, head, ohead) do { \
2540 while ((s = CK_SLIST_FIRST(&V_dyn_ ## ohead[i])) != NULL) { \
2541 CK_SLIST_REMOVE_HEAD(&V_dyn_ ## ohead[i], entry); \
2542 CK_SLIST_INSERT_HEAD(&head[DYN_BUCKET(s->hval, new)], \
2547 * Prevent rules changing from userland.
2549 IPFW_UH_WLOCK(chain);
2551 * Hold traffic processing until we finish resize to
2552 * prevent access to states lists.
2555 /* Re-link all dynamic states */
2556 for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
2557 DYN_RELINK_STATES(s4, data->hashval, bucket, ipv4, ipv4);
2558 DYN_RELINK_STATES(s4, limit->hashval, bucket, ipv4_parent,
2561 DYN_RELINK_STATES(s6, data->hashval, bucket, ipv6, ipv6);
2562 DYN_RELINK_STATES(s6, limit->hashval, bucket, ipv6_parent,
2567 #define DYN_SWAP_PTR(old, new, tmp) do { \
2573 DYN_SWAP_PTR(V_dyn_bucket_lock, bucket_lock, tmp);
2574 DYN_SWAP_PTR(V_dyn_ipv4, ipv4, tmp);
2575 DYN_SWAP_PTR(V_dyn_ipv4_parent, ipv4_parent, tmp);
2576 DYN_SWAP_PTR(V_dyn_ipv4_add, ipv4_add, tmp);
2577 DYN_SWAP_PTR(V_dyn_ipv4_parent_add, ipv4_parent_add, tmp);
2578 DYN_SWAP_PTR(V_dyn_ipv4_del, ipv4_del, tmp);
2579 DYN_SWAP_PTR(V_dyn_ipv4_parent_del, ipv4_parent_del, tmp);
2582 DYN_SWAP_PTR(V_dyn_ipv6, ipv6, tmp);
2583 DYN_SWAP_PTR(V_dyn_ipv6_parent, ipv6_parent, tmp);
2584 DYN_SWAP_PTR(V_dyn_ipv6_add, ipv6_add, tmp);
2585 DYN_SWAP_PTR(V_dyn_ipv6_parent_add, ipv6_parent_add, tmp);
2586 DYN_SWAP_PTR(V_dyn_ipv6_del, ipv6_del, tmp);
2587 DYN_SWAP_PTR(V_dyn_ipv6_parent_del, ipv6_parent_del, tmp);
2589 bucket = V_curr_dyn_buckets;
2590 V_curr_dyn_buckets = new;
2592 IPFW_WUNLOCK(chain);
2593 IPFW_UH_WUNLOCK(chain);
2595 /* Release old resources */
2596 while (bucket-- != 0)
2597 DYN_BUCKET_LOCK_DESTROY(bucket_lock, bucket);
2598 free(bucket_lock, M_IPFW);
2600 free(ipv4_parent, M_IPFW);
2601 free(ipv4_add, M_IPFW);
2602 free(ipv4_parent_add, M_IPFW);
2603 free(ipv4_del, M_IPFW);
2604 free(ipv4_parent_del, M_IPFW);
2607 free(ipv6_parent, M_IPFW);
2608 free(ipv6_add, M_IPFW);
2609 free(ipv6_parent_add, M_IPFW);
2610 free(ipv6_del, M_IPFW);
2611 free(ipv6_parent_del, M_IPFW);
2616 * This function is used to perform various maintenance
2617 * on dynamic hash lists. Currently it is called every second.
2620 dyn_tick(void *vnetx)
2624 CURVNET_SET((struct vnet *)vnetx);
2626 * First free states unlinked in previous passes.
2628 dyn_free_states(&V_layer3_chain);
2630 * Now unlink others expired states.
2631 * We use IPFW_UH_WLOCK to avoid concurrent call of
2632 * dyn_expire_states(). It is the only function that does
2633 * deletion of state entries from states lists.
2635 IPFW_UH_WLOCK(&V_layer3_chain);
2636 dyn_expire_states(&V_layer3_chain, NULL);
2637 IPFW_UH_WUNLOCK(&V_layer3_chain);
2639 * Send keepalives if they are enabled and the time has come.
2641 if (V_dyn_keepalive != 0 &&
2642 V_dyn_keepalive_last + V_dyn_keepalive_period <= time_uptime) {
2643 V_dyn_keepalive_last = time_uptime;
2644 dyn_send_keepalive_ipv4(&V_layer3_chain);
2646 dyn_send_keepalive_ipv6(&V_layer3_chain);
2650 * Check if we need to resize the hash:
2651 * if current number of states exceeds number of buckets in hash,
2652 * and dyn_buckets_max permits to grow the number of buckets, then
2653 * do it. Grow hash size to the minimum power of 2 which is bigger
2654 * than current states count.
2656 if (V_curr_dyn_buckets < V_dyn_buckets_max &&
2657 (V_curr_dyn_buckets < V_dyn_count / 2 || (
2658 V_curr_dyn_buckets < V_dyn_count && V_curr_max_length > 8))) {
2659 buckets = 1 << fls(V_dyn_count);
2660 if (buckets > V_dyn_buckets_max)
2661 buckets = V_dyn_buckets_max;
2662 dyn_grow_hashtable(&V_layer3_chain, buckets);
2665 callout_reset_on(&V_dyn_timeout, hz, dyn_tick, vnetx, 0);
2670 ipfw_expire_dyn_states(struct ip_fw_chain *chain, ipfw_range_tlv *rt)
2673 * Do not perform any checks if we currently have no dynamic states
2675 if (V_dyn_count == 0)
2678 IPFW_UH_WLOCK_ASSERT(chain);
2679 dyn_expire_states(chain, rt);
2683 * Returns size of dynamic states in legacy format
2689 return ((V_dyn_count + V_dyn_parent_count) * sizeof(ipfw_dyn_rule));
2693 * Returns number of dynamic states.
2694 * Used by dump format v1 (current).
2697 ipfw_dyn_get_count(void)
2700 return (V_dyn_count + V_dyn_parent_count);
2704 * Check if rule contains at least one dynamic opcode.
2706 * Returns 1 if such opcode is found, 0 otherwise.
2709 ipfw_is_dyn_rule(struct ip_fw *rule)
2717 for ( ; l > 0 ; l -= cmdlen, cmd += cmdlen) {
2718 cmdlen = F_LEN(cmd);
2720 switch (cmd->opcode) {
2733 dyn_export_parent(const struct dyn_parent *p, uint16_t kidx,
2737 dst->dyn_type = O_LIMIT_PARENT;
2739 dst->count = (uint16_t)DPARENT_COUNT(p);
2740 dst->expire = TIME_LEQ(p->expire, time_uptime) ? 0:
2741 p->expire - time_uptime;
2743 /* 'rule' is used to pass up the rule number and set */
2744 memcpy(&dst->rule, &p->rulenum, sizeof(p->rulenum));
2745 /* store set number into high word of dst->rule pointer. */
2746 memcpy((char *)&dst->rule + sizeof(p->rulenum), &p->set,
2756 dst->bucket = p->hashval;
2758 * The legacy userland code will interpret a NULL here as a marker
2759 * for the last dynamic rule.
2761 dst->next = (ipfw_dyn_rule *)1;
2765 dyn_export_data(const struct dyn_data *data, uint16_t kidx, uint8_t type,
2769 dst->dyn_type = type;
2771 dst->pcnt = data->pcnt_fwd + data->pcnt_rev;
2772 dst->bcnt = data->bcnt_fwd + data->bcnt_rev;
2773 dst->expire = TIME_LEQ(data->expire, time_uptime) ? 0:
2774 data->expire - time_uptime;
2776 /* 'rule' is used to pass up the rule number and set */
2777 memcpy(&dst->rule, &data->rulenum, sizeof(data->rulenum));
2778 /* store set number into high word of dst->rule pointer. */
2779 memcpy((char *)&dst->rule + sizeof(data->rulenum), &data->set,
2784 dst->state = data->state;
2785 dst->ack_fwd = data->ack_fwd;
2786 dst->ack_rev = data->ack_rev;
2788 dst->bucket = data->hashval;
2790 * The legacy userland code will interpret a NULL here as a marker
2791 * for the last dynamic rule.
2793 dst->next = (ipfw_dyn_rule *)1;
2797 dyn_export_ipv4_state(const struct dyn_ipv4_state *s, ipfw_dyn_rule *dst)
2801 case O_LIMIT_PARENT:
2802 dyn_export_parent(s->limit, s->kidx, dst);
2805 dyn_export_data(s->data, s->kidx, s->type, dst);
2808 dst->id.dst_ip = s->dst;
2809 dst->id.src_ip = s->src;
2810 dst->id.dst_port = s->dport;
2811 dst->id.src_port = s->sport;
2812 dst->id.fib = s->data->fibnum;
2813 dst->id.proto = s->proto;
2815 dst->id.addr_type = 4;
2817 memset(&dst->id.dst_ip6, 0, sizeof(dst->id.dst_ip6));
2818 memset(&dst->id.src_ip6, 0, sizeof(dst->id.src_ip6));
2819 dst->id.flow_id6 = dst->id.extra = 0;
2824 dyn_export_ipv6_state(const struct dyn_ipv6_state *s, ipfw_dyn_rule *dst)
2828 case O_LIMIT_PARENT:
2829 dyn_export_parent(s->limit, s->kidx, dst);
2832 dyn_export_data(s->data, s->kidx, s->type, dst);
2835 dst->id.src_ip6 = s->src;
2836 dst->id.dst_ip6 = s->dst;
2837 dst->id.dst_port = s->dport;
2838 dst->id.src_port = s->sport;
2839 dst->id.fib = s->data->fibnum;
2840 dst->id.proto = s->proto;
2842 dst->id.addr_type = 6;
2844 dst->id.dst_ip = dst->id.src_ip = 0;
2845 dst->id.flow_id6 = dst->id.extra = 0;
2850 * Fills the buffer given by @sd with dynamic states.
2851 * Used by dump format v1 (current).
2853 * Returns 0 on success.
2856 ipfw_dump_states(struct ip_fw_chain *chain, struct sockopt_data *sd)
2859 struct dyn_ipv6_state *s6;
2861 struct dyn_ipv4_state *s4;
2862 ipfw_obj_dyntlv *dst, *last;
2863 ipfw_obj_ctlv *ctlv;
2866 if (V_dyn_count == 0)
2870 * IPFW_UH_RLOCK garantees that another userland request
2871 * and callout thread will not delete entries from states
2874 IPFW_UH_RLOCK_ASSERT(chain);
2876 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
2879 ctlv->head.type = IPFW_TLV_DYNSTATE_LIST;
2880 ctlv->objsize = sizeof(ipfw_obj_dyntlv);
2883 #define DYN_EXPORT_STATES(s, af, h, b) \
2884 CK_SLIST_FOREACH(s, &V_dyn_ ## h[b], entry) { \
2885 dst = (ipfw_obj_dyntlv *)ipfw_get_sopt_space(sd, \
2886 sizeof(ipfw_obj_dyntlv)); \
2889 dyn_export_ ## af ## _state(s, &dst->state); \
2890 dst->head.length = sizeof(ipfw_obj_dyntlv); \
2891 dst->head.type = IPFW_TLV_DYN_ENT; \
2895 for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
2896 DYN_EXPORT_STATES(s4, ipv4, ipv4_parent, bucket);
2897 DYN_EXPORT_STATES(s4, ipv4, ipv4, bucket);
2899 DYN_EXPORT_STATES(s6, ipv6, ipv6_parent, bucket);
2900 DYN_EXPORT_STATES(s6, ipv6, ipv6, bucket);
2904 /* mark last dynamic rule */
2906 last->head.flags = IPFW_DF_LAST; /* XXX: unused */
2908 #undef DYN_EXPORT_STATES
2912 * Fill given buffer with dynamic states (legacy format).
2913 * IPFW_UH_RLOCK has to be held while calling.
2916 ipfw_get_dynamic(struct ip_fw_chain *chain, char **pbp, const char *ep)
2919 struct dyn_ipv6_state *s6;
2921 struct dyn_ipv4_state *s4;
2922 ipfw_dyn_rule *p, *last = NULL;
2926 if (V_dyn_count == 0)
2930 IPFW_UH_RLOCK_ASSERT(chain);
2932 #define DYN_EXPORT_STATES(s, af, head, b) \
2933 CK_SLIST_FOREACH(s, &V_dyn_ ## head[b], entry) { \
2934 if (bp + sizeof(*p) > ep) \
2936 p = (ipfw_dyn_rule *)bp; \
2937 dyn_export_ ## af ## _state(s, p); \
2942 for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
2943 DYN_EXPORT_STATES(s4, ipv4, ipv4_parent, bucket);
2944 DYN_EXPORT_STATES(s4, ipv4, ipv4, bucket);
2946 DYN_EXPORT_STATES(s6, ipv6, ipv6_parent, bucket);
2947 DYN_EXPORT_STATES(s6, ipv6, ipv6, bucket);
2951 if (last != NULL) /* mark last dynamic rule */
2954 #undef DYN_EXPORT_STATES
2958 ipfw_dyn_init(struct ip_fw_chain *chain)
2961 #ifdef IPFIREWALL_JENKINSHASH
2962 V_dyn_hashseed = arc4random();
2964 V_dyn_max = 16384; /* max # of states */
2965 V_dyn_parent_max = 4096; /* max # of parent states */
2966 V_dyn_buckets_max = 8192; /* must be power of 2 */
2968 V_dyn_ack_lifetime = 300;
2969 V_dyn_syn_lifetime = 20;
2970 V_dyn_fin_lifetime = 1;
2971 V_dyn_rst_lifetime = 1;
2972 V_dyn_udp_lifetime = 10;
2973 V_dyn_short_lifetime = 5;
2975 V_dyn_keepalive_interval = 20;
2976 V_dyn_keepalive_period = 5;
2977 V_dyn_keepalive = 1; /* send keepalives */
2978 V_dyn_keepalive_last = time_uptime;
2980 V_dyn_data_zone = uma_zcreate("IPFW dynamic states data",
2981 sizeof(struct dyn_data), NULL, NULL, NULL, NULL,
2983 uma_zone_set_max(V_dyn_data_zone, V_dyn_max);
2985 V_dyn_parent_zone = uma_zcreate("IPFW parent dynamic states",
2986 sizeof(struct dyn_parent), NULL, NULL, NULL, NULL,
2988 uma_zone_set_max(V_dyn_parent_zone, V_dyn_parent_max);
2990 SLIST_INIT(&V_dyn_expired_ipv4);
2992 V_dyn_ipv4_parent = NULL;
2993 V_dyn_ipv4_zone = uma_zcreate("IPFW IPv4 dynamic states",
2994 sizeof(struct dyn_ipv4_state), NULL, NULL, NULL, NULL,
2998 SLIST_INIT(&V_dyn_expired_ipv6);
3000 V_dyn_ipv6_parent = NULL;
3001 V_dyn_ipv6_zone = uma_zcreate("IPFW IPv6 dynamic states",
3002 sizeof(struct dyn_ipv6_state), NULL, NULL, NULL, NULL,
3006 /* Initialize buckets. */
3007 V_curr_dyn_buckets = 0;
3008 V_dyn_bucket_lock = NULL;
3009 dyn_grow_hashtable(chain, 256);
3011 if (IS_DEFAULT_VNET(curvnet))
3012 dyn_hp_cache = malloc(mp_ncpus * sizeof(void *), M_IPFW,
3015 DYN_EXPIRED_LOCK_INIT();
3016 callout_init(&V_dyn_timeout, 1);
3017 callout_reset(&V_dyn_timeout, hz, dyn_tick, curvnet);
3018 IPFW_ADD_OBJ_REWRITER(IS_DEFAULT_VNET(curvnet), dyn_opcodes);
3022 ipfw_dyn_uninit(int pass)
3025 struct dyn_ipv6_state *s6;
3027 struct dyn_ipv4_state *s4;
3031 callout_drain(&V_dyn_timeout);
3034 IPFW_DEL_OBJ_REWRITER(IS_DEFAULT_VNET(curvnet), dyn_opcodes);
3035 DYN_EXPIRED_LOCK_DESTROY();
3037 #define DYN_FREE_STATES_FORCED(CK, s, af, name, en) do { \
3038 while ((s = CK ## SLIST_FIRST(&V_dyn_ ## name)) != NULL) { \
3039 CK ## SLIST_REMOVE_HEAD(&V_dyn_ ## name, en); \
3040 if (s->type == O_LIMIT_PARENT) \
3041 uma_zfree(V_dyn_parent_zone, s->limit); \
3043 uma_zfree(V_dyn_data_zone, s->data); \
3044 uma_zfree(V_dyn_ ## af ## _zone, s); \
3047 for (bucket = 0; bucket < V_curr_dyn_buckets; bucket++) {
3048 DYN_BUCKET_LOCK_DESTROY(V_dyn_bucket_lock, bucket);
3050 DYN_FREE_STATES_FORCED(CK_, s4, ipv4, ipv4[bucket], entry);
3051 DYN_FREE_STATES_FORCED(CK_, s4, ipv4, ipv4_parent[bucket],
3054 DYN_FREE_STATES_FORCED(CK_, s6, ipv6, ipv6[bucket], entry);
3055 DYN_FREE_STATES_FORCED(CK_, s6, ipv6, ipv6_parent[bucket],
3059 DYN_FREE_STATES_FORCED(, s4, ipv4, expired_ipv4, expired);
3061 DYN_FREE_STATES_FORCED(, s6, ipv6, expired_ipv6, expired);
3063 #undef DYN_FREE_STATES_FORCED
3065 uma_zdestroy(V_dyn_ipv4_zone);
3066 uma_zdestroy(V_dyn_data_zone);
3067 uma_zdestroy(V_dyn_parent_zone);
3069 uma_zdestroy(V_dyn_ipv6_zone);
3070 free(V_dyn_ipv6, M_IPFW);
3071 free(V_dyn_ipv6_parent, M_IPFW);
3072 free(V_dyn_ipv6_add, M_IPFW);
3073 free(V_dyn_ipv6_parent_add, M_IPFW);
3074 free(V_dyn_ipv6_del, M_IPFW);
3075 free(V_dyn_ipv6_parent_del, M_IPFW);
3077 free(V_dyn_bucket_lock, M_IPFW);
3078 free(V_dyn_ipv4, M_IPFW);
3079 free(V_dyn_ipv4_parent, M_IPFW);
3080 free(V_dyn_ipv4_add, M_IPFW);
3081 free(V_dyn_ipv4_parent_add, M_IPFW);
3082 free(V_dyn_ipv4_del, M_IPFW);
3083 free(V_dyn_ipv4_parent_del, M_IPFW);
3084 if (IS_DEFAULT_VNET(curvnet))
3085 free(dyn_hp_cache, M_IPFW);