2 * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
13 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
33 * Dynamic rule support for ipfw
39 #error IPFIREWALL requires INET.
41 #include "opt_inet6.h"
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/malloc.h>
47 #include <sys/kernel.h>
50 #include <sys/socket.h>
51 #include <sys/sysctl.h>
52 #include <sys/syslog.h>
53 #include <net/ethernet.h> /* for ETHERTYPE_IP */
55 #include <net/if_var.h>
58 #include <netinet/in.h>
59 #include <netinet/ip.h>
60 #include <netinet/ip_var.h> /* ip_defttl */
61 #include <netinet/ip_fw.h>
62 #include <netinet/tcp_var.h>
63 #include <netinet/udp.h>
65 #include <netinet/ip6.h> /* IN6_ARE_ADDR_EQUAL */
67 #include <netinet6/in6_var.h>
68 #include <netinet6/ip6_var.h>
71 #include <netpfil/ipfw/ip_fw_private.h>
73 #include <machine/in_cksum.h> /* XXX for in_cksum */
76 #include <security/mac/mac_framework.h>
80 * Description of dynamic rules.
82 * Dynamic rules are stored in lists accessed through a hash table
83 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
84 * be modified through the sysctl variable dyn_buckets which is
85 * updated when the table becomes empty.
87 * XXX currently there is only one list, ipfw_dyn.
89 * When a packet is received, its address fields are first masked
90 * with the mask defined for the rule, then hashed, then matched
91 * against the entries in the corresponding list.
92 * Dynamic rules can be used for different purposes:
94 * + enforcing limits on the number of sessions;
95 * + in-kernel NAT (not implemented yet)
97 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
98 * measured in seconds and depending on the flags.
100 * The total number of dynamic rules is equal to UMA zone items count.
101 * The max number of dynamic rules is dyn_max. When we reach
102 * the maximum number of rules we do not create anymore. This is
103 * done to avoid consuming too much memory, but also too much
104 * time when searching on each packet (ideally, we should try instead
105 * to put a limit on the length of the list on each bucket...).
107 * Each dynamic rule holds a pointer to the parent ipfw rule so
108 * we know what action to perform. Dynamic rules are removed when
109 * the parent rule is deleted. This can be changed by dyn_keep_states
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 struct ipfw_dyn_bucket {
118 struct mtx mtx; /* Bucket protecting lock */
119 ipfw_dyn_rule *head; /* Pointer to first rule */
123 * Static variables followed by global ones
125 static VNET_DEFINE(struct ipfw_dyn_bucket *, ipfw_dyn_v);
126 static VNET_DEFINE(u_int32_t, dyn_buckets_max);
127 static VNET_DEFINE(u_int32_t, curr_dyn_buckets);
128 static VNET_DEFINE(struct callout, ipfw_timeout);
129 #define V_ipfw_dyn_v VNET(ipfw_dyn_v)
130 #define V_dyn_buckets_max VNET(dyn_buckets_max)
131 #define V_curr_dyn_buckets VNET(curr_dyn_buckets)
132 #define V_ipfw_timeout VNET(ipfw_timeout)
134 static VNET_DEFINE(uma_zone_t, ipfw_dyn_rule_zone);
135 #define V_ipfw_dyn_rule_zone VNET(ipfw_dyn_rule_zone)
137 #define IPFW_BUCK_LOCK_INIT(b) \
138 mtx_init(&(b)->mtx, "IPFW dynamic bucket", NULL, MTX_DEF)
139 #define IPFW_BUCK_LOCK_DESTROY(b) \
140 mtx_destroy(&(b)->mtx)
141 #define IPFW_BUCK_LOCK(i) mtx_lock(&V_ipfw_dyn_v[(i)].mtx)
142 #define IPFW_BUCK_UNLOCK(i) mtx_unlock(&V_ipfw_dyn_v[(i)].mtx)
143 #define IPFW_BUCK_ASSERT(i) mtx_assert(&V_ipfw_dyn_v[(i)].mtx, MA_OWNED)
146 static VNET_DEFINE(int, dyn_keep_states);
147 #define V_dyn_keep_states VNET(dyn_keep_states)
150 * Timeouts for various events in handing dynamic rules.
152 static VNET_DEFINE(u_int32_t, dyn_ack_lifetime);
153 static VNET_DEFINE(u_int32_t, dyn_syn_lifetime);
154 static VNET_DEFINE(u_int32_t, dyn_fin_lifetime);
155 static VNET_DEFINE(u_int32_t, dyn_rst_lifetime);
156 static VNET_DEFINE(u_int32_t, dyn_udp_lifetime);
157 static VNET_DEFINE(u_int32_t, dyn_short_lifetime);
159 #define V_dyn_ack_lifetime VNET(dyn_ack_lifetime)
160 #define V_dyn_syn_lifetime VNET(dyn_syn_lifetime)
161 #define V_dyn_fin_lifetime VNET(dyn_fin_lifetime)
162 #define V_dyn_rst_lifetime VNET(dyn_rst_lifetime)
163 #define V_dyn_udp_lifetime VNET(dyn_udp_lifetime)
164 #define V_dyn_short_lifetime VNET(dyn_short_lifetime)
167 * Keepalives are sent if dyn_keepalive is set. They are sent every
168 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
169 * seconds of lifetime of a rule.
170 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
171 * than dyn_keepalive_period.
174 static VNET_DEFINE(u_int32_t, dyn_keepalive_interval);
175 static VNET_DEFINE(u_int32_t, dyn_keepalive_period);
176 static VNET_DEFINE(u_int32_t, dyn_keepalive);
177 static VNET_DEFINE(time_t, dyn_keepalive_last);
179 #define V_dyn_keepalive_interval VNET(dyn_keepalive_interval)
180 #define V_dyn_keepalive_period VNET(dyn_keepalive_period)
181 #define V_dyn_keepalive VNET(dyn_keepalive)
182 #define V_dyn_keepalive_last VNET(dyn_keepalive_last)
184 static VNET_DEFINE(u_int32_t, dyn_max); /* max # of dynamic rules */
186 #define DYN_COUNT uma_zone_get_cur(V_ipfw_dyn_rule_zone)
187 #define V_dyn_max VNET(dyn_max)
189 /* for userspace, we emulate the uma_zone_counter with ipfw_dyn_count */
190 static int ipfw_dyn_count; /* number of objects */
192 #ifdef USERSPACE /* emulation of UMA object counters for userspace */
193 #define uma_zone_get_cur(x) ipfw_dyn_count
194 #endif /* USERSPACE */
196 static int last_log; /* Log ratelimiting */
198 static void ipfw_dyn_tick(void *vnetx);
199 static void check_dyn_rules(struct ip_fw_chain *, struct ip_fw *,
203 static int sysctl_ipfw_dyn_count(SYSCTL_HANDLER_ARGS);
204 static int sysctl_ipfw_dyn_max(SYSCTL_HANDLER_ARGS);
208 SYSCTL_DECL(_net_inet_ip_fw);
209 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_buckets,
210 CTLFLAG_RW, &VNET_NAME(dyn_buckets_max), 0,
211 "Max number of dyn. buckets");
212 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets,
213 CTLFLAG_RD, &VNET_NAME(curr_dyn_buckets), 0,
214 "Current Number of dyn. buckets");
215 SYSCTL_VNET_PROC(_net_inet_ip_fw, OID_AUTO, dyn_count,
216 CTLTYPE_UINT|CTLFLAG_RD, 0, 0, sysctl_ipfw_dyn_count, "IU",
217 "Number of dyn. rules");
218 SYSCTL_VNET_PROC(_net_inet_ip_fw, OID_AUTO, dyn_max,
219 CTLTYPE_UINT|CTLFLAG_RW, 0, 0, sysctl_ipfw_dyn_max, "IU",
220 "Max number of dyn. rules");
221 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime,
222 CTLFLAG_RW, &VNET_NAME(dyn_ack_lifetime), 0,
223 "Lifetime of dyn. rules for acks");
224 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime,
225 CTLFLAG_RW, &VNET_NAME(dyn_syn_lifetime), 0,
226 "Lifetime of dyn. rules for syn");
227 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
228 CTLFLAG_RW, &VNET_NAME(dyn_fin_lifetime), 0,
229 "Lifetime of dyn. rules for fin");
230 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
231 CTLFLAG_RW, &VNET_NAME(dyn_rst_lifetime), 0,
232 "Lifetime of dyn. rules for rst");
233 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime,
234 CTLFLAG_RW, &VNET_NAME(dyn_udp_lifetime), 0,
235 "Lifetime of dyn. rules for UDP");
236 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime,
237 CTLFLAG_RW, &VNET_NAME(dyn_short_lifetime), 0,
238 "Lifetime of dyn. rules for other situations");
239 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive,
240 CTLFLAG_RW, &VNET_NAME(dyn_keepalive), 0,
241 "Enable keepalives for dyn. rules");
242 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_keep_states,
243 CTLFLAG_RW, &VNET_NAME(dyn_keep_states), 0,
244 "Do not flush dynamic states on rule deletion");
248 #endif /* SYSCTL_NODE */
253 hash_packet6(struct ipfw_flow_id *id)
256 i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
257 (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
258 (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
259 (id->src_ip6.__u6_addr.__u6_addr32[3]) ^
260 (id->dst_port) ^ (id->src_port);
266 * IMPORTANT: the hash function for dynamic rules must be commutative
267 * in source and destination (ip,port), because rules are bidirectional
268 * and we want to find both in the same bucket.
271 hash_packet(struct ipfw_flow_id *id, int buckets)
276 if (IS_IP6_FLOW_ID(id))
277 i = hash_packet6(id);
280 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
286 * Print customizable flow id description via log(9) facility.
289 print_dyn_rule_flags(struct ipfw_flow_id *id, int dyn_type, int log_flags,
290 char *prefix, char *postfix)
294 char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN];
296 char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
300 if (IS_IP6_FLOW_ID(id)) {
301 ip6_sprintf(src, &id->src_ip6);
302 ip6_sprintf(dst, &id->dst_ip6);
306 da.s_addr = htonl(id->src_ip);
307 inet_ntop(AF_INET, &da, src, sizeof(src));
308 da.s_addr = htonl(id->dst_ip);
309 inet_ntop(AF_INET, &da, dst, sizeof(dst));
311 log(log_flags, "ipfw: %s type %d %s %d -> %s %d, %d %s\n",
312 prefix, dyn_type, src, id->src_port, dst,
313 id->dst_port, DYN_COUNT, postfix);
316 #define print_dyn_rule(id, dtype, prefix, postfix) \
317 print_dyn_rule_flags(id, dtype, LOG_DEBUG, prefix, postfix)
319 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
320 #define TIME_LE(a,b) ((int)((a)-(b)) < 0)
323 * Lookup a dynamic rule, locked version.
325 static ipfw_dyn_rule *
326 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int i, int *match_direction,
330 * Stateful ipfw extensions.
331 * Lookup into dynamic session queue.
333 #define MATCH_REVERSE 0
334 #define MATCH_FORWARD 1
336 #define MATCH_UNKNOWN 3
337 int dir = MATCH_NONE;
338 ipfw_dyn_rule *prev, *q = NULL;
342 for (prev = NULL, q = V_ipfw_dyn_v[i].head; q; prev = q, q = q->next) {
343 if (q->dyn_type == O_LIMIT_PARENT && q->count)
346 if (pkt->proto != q->id.proto || q->dyn_type == O_LIMIT_PARENT)
349 if (IS_IP6_FLOW_ID(pkt)) {
350 if (IN6_ARE_ADDR_EQUAL(&pkt->src_ip6, &q->id.src_ip6) &&
351 IN6_ARE_ADDR_EQUAL(&pkt->dst_ip6, &q->id.dst_ip6) &&
352 pkt->src_port == q->id.src_port &&
353 pkt->dst_port == q->id.dst_port) {
357 if (IN6_ARE_ADDR_EQUAL(&pkt->src_ip6, &q->id.dst_ip6) &&
358 IN6_ARE_ADDR_EQUAL(&pkt->dst_ip6, &q->id.src_ip6) &&
359 pkt->src_port == q->id.dst_port &&
360 pkt->dst_port == q->id.src_port) {
365 if (pkt->src_ip == q->id.src_ip &&
366 pkt->dst_ip == q->id.dst_ip &&
367 pkt->src_port == q->id.src_port &&
368 pkt->dst_port == q->id.dst_port) {
372 if (pkt->src_ip == q->id.dst_ip &&
373 pkt->dst_ip == q->id.src_ip &&
374 pkt->src_port == q->id.dst_port &&
375 pkt->dst_port == q->id.src_port) {
382 goto done; /* q = NULL, not found */
384 if (prev != NULL) { /* found and not in front */
385 prev->next = q->next;
386 q->next = V_ipfw_dyn_v[i].head;
387 V_ipfw_dyn_v[i].head = q;
389 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
391 u_char flags = pkt->_flags & (TH_FIN | TH_SYN | TH_RST);
393 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
394 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
395 #define TCP_FLAGS (TH_FLAGS | (TH_FLAGS << 8))
396 #define ACK_FWD 0x10000 /* fwd ack seen */
397 #define ACK_REV 0x20000 /* rev ack seen */
399 q->state |= (dir == MATCH_FORWARD) ? flags : (flags << 8);
400 switch (q->state & TCP_FLAGS) {
401 case TH_SYN: /* opening */
402 q->expire = time_uptime + V_dyn_syn_lifetime;
405 case BOTH_SYN: /* move to established */
406 case BOTH_SYN | TH_FIN: /* one side tries to close */
407 case BOTH_SYN | (TH_FIN << 8):
408 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
412 ack = ntohl(tcp->th_ack);
413 if (dir == MATCH_FORWARD) {
414 if (q->ack_fwd == 0 ||
415 _SEQ_GE(ack, q->ack_fwd)) {
420 if (q->ack_rev == 0 ||
421 _SEQ_GE(ack, q->ack_rev)) {
426 if ((q->state & (ACK_FWD | ACK_REV)) ==
427 (ACK_FWD | ACK_REV)) {
428 q->expire = time_uptime + V_dyn_ack_lifetime;
429 q->state &= ~(ACK_FWD | ACK_REV);
433 case BOTH_SYN | BOTH_FIN: /* both sides closed */
434 if (V_dyn_fin_lifetime >= V_dyn_keepalive_period)
435 V_dyn_fin_lifetime = V_dyn_keepalive_period - 1;
436 q->expire = time_uptime + V_dyn_fin_lifetime;
442 * reset or some invalid combination, but can also
443 * occur if we use keep-state the wrong way.
445 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
446 printf("invalid state: 0x%x\n", q->state);
448 if (V_dyn_rst_lifetime >= V_dyn_keepalive_period)
449 V_dyn_rst_lifetime = V_dyn_keepalive_period - 1;
450 q->expire = time_uptime + V_dyn_rst_lifetime;
453 } else if (pkt->proto == IPPROTO_UDP) {
454 q->expire = time_uptime + V_dyn_udp_lifetime;
456 /* other protocols */
457 q->expire = time_uptime + V_dyn_short_lifetime;
460 if (match_direction != NULL)
461 *match_direction = dir;
466 ipfw_lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
472 i = hash_packet(pkt, V_curr_dyn_buckets);
475 q = lookup_dyn_rule_locked(pkt, i, match_direction, tcp);
478 /* NB: return table locked when q is not NULL */
484 * @p - pointer to dynamic rule
487 ipfw_dyn_unlock(ipfw_dyn_rule *q)
490 IPFW_BUCK_UNLOCK(q->bucket);
494 resize_dynamic_table(struct ip_fw_chain *chain, int nbuckets)
496 int i, k, nbuckets_old;
498 struct ipfw_dyn_bucket *dyn_v, *dyn_v_old;
500 /* Check if given number is power of 2 and less than 64k */
501 if ((nbuckets > 65536) || (!powerof2(nbuckets)))
504 CTR3(KTR_NET, "%s: resize dynamic hash: %d -> %d", __func__,
505 V_curr_dyn_buckets, nbuckets);
507 /* Allocate and initialize new hash */
508 dyn_v = malloc(nbuckets * sizeof(ipfw_dyn_rule), M_IPFW,
511 for (i = 0 ; i < nbuckets; i++)
512 IPFW_BUCK_LOCK_INIT(&dyn_v[i]);
515 * Call upper half lock, as get_map() do to ease
516 * read-only access to dynamic rules hash from sysctl
518 IPFW_UH_WLOCK(chain);
521 * Acquire chain write lock to permit hash access
522 * for main traffic path without additional locks
526 /* Save old values */
527 nbuckets_old = V_curr_dyn_buckets;
528 dyn_v_old = V_ipfw_dyn_v;
530 /* Skip relinking if array is not set up */
531 if (V_ipfw_dyn_v == NULL)
532 V_curr_dyn_buckets = 0;
534 /* Re-link all dynamic states */
535 for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
536 while (V_ipfw_dyn_v[i].head != NULL) {
537 /* Remove from current chain */
538 q = V_ipfw_dyn_v[i].head;
539 V_ipfw_dyn_v[i].head = q->next;
541 /* Get new hash value */
542 k = hash_packet(&q->id, nbuckets);
544 /* Add to the new head */
545 q->next = dyn_v[k].head;
550 /* Update current pointers/buckets values */
551 V_curr_dyn_buckets = nbuckets;
552 V_ipfw_dyn_v = dyn_v;
556 IPFW_UH_WUNLOCK(chain);
558 /* Start periodic callout on initial creation */
559 if (dyn_v_old == NULL) {
560 callout_reset_on(&V_ipfw_timeout, hz, ipfw_dyn_tick, curvnet, 0);
564 /* Destroy all mutexes */
565 for (i = 0 ; i < nbuckets_old ; i++)
566 IPFW_BUCK_LOCK_DESTROY(&dyn_v_old[i]);
569 free(dyn_v_old, M_IPFW);
575 * Install state of type 'type' for a dynamic session.
576 * The hash table contains two type of rules:
577 * - regular rules (O_KEEP_STATE)
578 * - rules for sessions with limited number of sess per user
579 * (O_LIMIT). When they are created, the parent is
580 * increased by 1, and decreased on delete. In this case,
581 * the third parameter is the parent rule and not the chain.
582 * - "parent" rules for the above (O_LIMIT_PARENT).
584 static ipfw_dyn_rule *
585 add_dyn_rule(struct ipfw_flow_id *id, int i, u_int8_t dyn_type, struct ip_fw *rule)
591 r = uma_zalloc(V_ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
593 if (last_log != time_uptime) {
594 last_log = time_uptime;
595 log(LOG_DEBUG, "ipfw: %s: Cannot allocate rule\n",
603 * refcount on parent is already incremented, so
604 * it is safe to use parent unlocked.
606 if (dyn_type == O_LIMIT) {
607 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
608 if ( parent->dyn_type != O_LIMIT_PARENT)
609 panic("invalid parent");
615 r->expire = time_uptime + V_dyn_syn_lifetime;
617 r->dyn_type = dyn_type;
618 IPFW_ZERO_DYN_COUNTER(r);
622 r->next = V_ipfw_dyn_v[i].head;
623 V_ipfw_dyn_v[i].head = r;
624 DEB(print_dyn_rule(id, dyn_type, "add dyn entry", "total");)
629 * lookup dynamic parent rule using pkt and rule as search keys.
630 * If the lookup fails, then install one.
632 static ipfw_dyn_rule *
633 lookup_dyn_parent(struct ipfw_flow_id *pkt, int *pindex, struct ip_fw *rule)
638 is_v6 = IS_IP6_FLOW_ID(pkt);
639 i = hash_packet( pkt, V_curr_dyn_buckets );
642 for (q = V_ipfw_dyn_v[i].head ; q != NULL ; q=q->next)
643 if (q->dyn_type == O_LIMIT_PARENT &&
645 pkt->proto == q->id.proto &&
646 pkt->src_port == q->id.src_port &&
647 pkt->dst_port == q->id.dst_port &&
650 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
652 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
653 &(q->id.dst_ip6))) ||
655 pkt->src_ip == q->id.src_ip &&
656 pkt->dst_ip == q->id.dst_ip)
659 q->expire = time_uptime + V_dyn_short_lifetime;
660 DEB(print_dyn_rule(pkt, q->dyn_type,
661 "lookup_dyn_parent found", "");)
665 /* Add virtual limiting rule */
666 return add_dyn_rule(pkt, i, O_LIMIT_PARENT, rule);
670 * Install dynamic state for rule type cmd->o.opcode
672 * Returns 1 (failure) if state is not installed because of errors or because
673 * session limitations are enforced.
676 ipfw_install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
677 struct ip_fw_args *args, uint32_t tablearg)
682 DEB(print_dyn_rule(&args->f_id, cmd->o.opcode, "install_state", "");)
684 i = hash_packet(&args->f_id, V_curr_dyn_buckets);
688 q = lookup_dyn_rule_locked(&args->f_id, i, NULL, NULL);
690 if (q != NULL) { /* should never occur */
692 if (last_log != time_uptime) {
693 last_log = time_uptime;
694 printf("ipfw: %s: entry already present, done\n",
702 * State limiting is done via uma(9) zone limiting.
703 * Save pointer to newly-installed rule and reject
704 * packet if add_dyn_rule() returned NULL.
705 * Note q is currently set to NULL.
708 switch (cmd->o.opcode) {
709 case O_KEEP_STATE: /* bidir rule */
710 q = add_dyn_rule(&args->f_id, i, O_KEEP_STATE, rule);
713 case O_LIMIT: { /* limit number of sessions */
714 struct ipfw_flow_id id;
715 ipfw_dyn_rule *parent;
717 uint16_t limit_mask = cmd->limit_mask;
720 conn_limit = IP_FW_ARG_TABLEARG(cmd->conn_limit);
723 if (cmd->conn_limit == IP_FW_TABLEARG)
724 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
725 "(tablearg)\n", __func__, conn_limit);
727 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
728 __func__, conn_limit);
731 id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
732 id.proto = args->f_id.proto;
733 id.addr_type = args->f_id.addr_type;
734 id.fib = M_GETFIB(args->m);
736 if (IS_IP6_FLOW_ID (&(args->f_id))) {
737 if (limit_mask & DYN_SRC_ADDR)
738 id.src_ip6 = args->f_id.src_ip6;
739 if (limit_mask & DYN_DST_ADDR)
740 id.dst_ip6 = args->f_id.dst_ip6;
742 if (limit_mask & DYN_SRC_ADDR)
743 id.src_ip = args->f_id.src_ip;
744 if (limit_mask & DYN_DST_ADDR)
745 id.dst_ip = args->f_id.dst_ip;
747 if (limit_mask & DYN_SRC_PORT)
748 id.src_port = args->f_id.src_port;
749 if (limit_mask & DYN_DST_PORT)
750 id.dst_port = args->f_id.dst_port;
753 * We have to release lock for previous bucket to
754 * avoid possible deadlock
758 if ((parent = lookup_dyn_parent(&id, &pindex, rule)) == NULL) {
759 printf("ipfw: %s: add parent failed\n", __func__);
760 IPFW_BUCK_UNLOCK(pindex);
764 if (parent->count >= conn_limit) {
765 if (V_fw_verbose && last_log != time_uptime) {
766 last_log = time_uptime;
768 last_log = time_uptime;
769 snprintf(sbuf, sizeof(sbuf),
771 parent->rule->rulenum);
772 print_dyn_rule_flags(&args->f_id,
774 LOG_SECURITY | LOG_DEBUG,
775 sbuf, "too many entries");
777 IPFW_BUCK_UNLOCK(pindex);
780 /* Increment counter on parent */
782 IPFW_BUCK_UNLOCK(pindex);
785 q = add_dyn_rule(&args->f_id, i, O_LIMIT, (struct ip_fw *)parent);
787 /* Decrement index and notify caller */
789 IPFW_BUCK_LOCK(pindex);
791 IPFW_BUCK_UNLOCK(pindex);
797 printf("ipfw: %s: unknown dynamic rule type %u\n",
798 __func__, cmd->o.opcode);
803 return (1); /* Notify caller about failure */
806 /* XXX just set lifetime */
807 lookup_dyn_rule_locked(&args->f_id, i, NULL, NULL);
814 * Generate a TCP packet, containing either a RST or a keepalive.
815 * When flags & TH_RST, we are sending a RST packet, because of a
816 * "reset" action matched the packet.
817 * Otherwise we are sending a keepalive, and flags & TH_
818 * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
819 * so that MAC can label the reply appropriately.
822 ipfw_send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
823 u_int32_t ack, int flags)
825 struct mbuf *m = NULL; /* stupid compiler */
827 struct ip *h = NULL; /* stupid compiler */
829 struct ip6_hdr *h6 = NULL;
831 struct tcphdr *th = NULL;
833 MGETHDR(m, M_NOWAIT, MT_DATA);
837 M_SETFIB(m, id->fib);
840 mac_netinet_firewall_reply(replyto, m);
842 mac_netinet_firewall_send(m);
844 (void)replyto; /* don't warn about unused arg */
847 switch (id->addr_type) {
849 len = sizeof(struct ip) + sizeof(struct tcphdr);
853 len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
861 dir = ((flags & (TH_SYN | TH_RST)) == TH_SYN);
863 m->m_data += max_linkhdr;
864 m->m_flags |= M_SKIP_FIREWALL;
865 m->m_pkthdr.len = m->m_len = len;
866 m->m_pkthdr.rcvif = NULL;
867 bzero(m->m_data, len);
869 switch (id->addr_type) {
871 h = mtod(m, struct ip *);
873 /* prepare for checksum */
874 h->ip_p = IPPROTO_TCP;
875 h->ip_len = htons(sizeof(struct tcphdr));
877 h->ip_src.s_addr = htonl(id->src_ip);
878 h->ip_dst.s_addr = htonl(id->dst_ip);
880 h->ip_src.s_addr = htonl(id->dst_ip);
881 h->ip_dst.s_addr = htonl(id->src_ip);
884 th = (struct tcphdr *)(h + 1);
888 h6 = mtod(m, struct ip6_hdr *);
890 /* prepare for checksum */
891 h6->ip6_nxt = IPPROTO_TCP;
892 h6->ip6_plen = htons(sizeof(struct tcphdr));
894 h6->ip6_src = id->src_ip6;
895 h6->ip6_dst = id->dst_ip6;
897 h6->ip6_src = id->dst_ip6;
898 h6->ip6_dst = id->src_ip6;
901 th = (struct tcphdr *)(h6 + 1);
907 th->th_sport = htons(id->src_port);
908 th->th_dport = htons(id->dst_port);
910 th->th_sport = htons(id->dst_port);
911 th->th_dport = htons(id->src_port);
913 th->th_off = sizeof(struct tcphdr) >> 2;
915 if (flags & TH_RST) {
916 if (flags & TH_ACK) {
917 th->th_seq = htonl(ack);
918 th->th_flags = TH_RST;
922 th->th_ack = htonl(seq);
923 th->th_flags = TH_RST | TH_ACK;
927 * Keepalive - use caller provided sequence numbers
929 th->th_seq = htonl(seq);
930 th->th_ack = htonl(ack);
931 th->th_flags = TH_ACK;
934 switch (id->addr_type) {
936 th->th_sum = in_cksum(m, len);
938 /* finish the ip header */
940 h->ip_hl = sizeof(*h) >> 2;
941 h->ip_tos = IPTOS_LOWDELAY;
942 h->ip_off = htons(0);
943 h->ip_len = htons(len);
944 h->ip_ttl = V_ip_defttl;
949 th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(*h6),
950 sizeof(struct tcphdr));
952 /* finish the ip6 header */
953 h6->ip6_vfc |= IPV6_VERSION;
954 h6->ip6_hlim = IPV6_DEFHLIM;
963 * Queue keepalive packets for given dynamic rule
965 static struct mbuf **
966 ipfw_dyn_send_ka(struct mbuf **mtailp, ipfw_dyn_rule *q)
968 struct mbuf *m_rev, *m_fwd;
970 m_rev = (q->state & ACK_REV) ? NULL :
971 ipfw_send_pkt(NULL, &(q->id), q->ack_rev - 1, q->ack_fwd, TH_SYN);
972 m_fwd = (q->state & ACK_FWD) ? NULL :
973 ipfw_send_pkt(NULL, &(q->id), q->ack_fwd - 1, q->ack_rev, 0);
977 mtailp = &(*mtailp)->m_nextpkt;
981 mtailp = &(*mtailp)->m_nextpkt;
988 * This procedure is used to perform various maintance
989 * on dynamic hash list. Currently it is called every second.
992 ipfw_dyn_tick(void * vnetx)
994 struct ip_fw_chain *chain;
997 struct vnet *vp = vnetx;
1002 chain = &V_layer3_chain;
1004 /* Run keepalive checks every keepalive_period iff ka is enabled */
1005 if ((V_dyn_keepalive_last + V_dyn_keepalive_period <= time_uptime) &&
1006 (V_dyn_keepalive != 0)) {
1007 V_dyn_keepalive_last = time_uptime;
1011 check_dyn_rules(chain, NULL, RESVD_SET, check_ka, 1);
1013 callout_reset_on(&V_ipfw_timeout, hz, ipfw_dyn_tick, vnetx, 0);
1020 * Walk thru all dynamic states doing generic maintance:
1021 * 1) free expired states
1022 * 2) free all states based on deleted rule / set
1023 * 3) send keepalives for states if needed
1025 * @chain - pointer to current ipfw rules chain
1026 * @rule - delete all states originated by given rule if != NULL
1027 * @set - delete all states originated by any rule in set @set if != RESVD_SET
1028 * @check_ka - perform checking/sending keepalives
1029 * @timer - indicate call from timer routine.
1031 * Timer routine must call this function unlocked to permit
1032 * sending keepalives/resizing table.
1034 * Others has to call function with IPFW_UH_WLOCK held.
1035 * Additionally, function assume that dynamic rule/set is
1036 * ALREADY deleted so no new states can be generated by
1039 * Write lock is needed to ensure that unused parent rules
1040 * are not freed by other instance (see stage 2, 3)
1043 check_dyn_rules(struct ip_fw_chain *chain, struct ip_fw *rule,
1044 int set, int check_ka, int timer)
1046 struct mbuf *m0, *m, *mnext, **mtailp;
1048 int i, dyn_count, new_buckets = 0, max_buckets;
1049 int expired = 0, expired_limits = 0, parents = 0, total = 0;
1050 ipfw_dyn_rule *q, *q_prev, *q_next;
1051 ipfw_dyn_rule *exp_head, **exptailp;
1052 ipfw_dyn_rule *exp_lhead, **expltailp;
1054 KASSERT(V_ipfw_dyn_v != NULL, ("%s: dynamic table not allocated",
1057 /* Avoid possible LOR */
1058 KASSERT(!check_ka || timer, ("%s: keepalive check with lock held",
1062 * Do not perform any checks if we currently have no dynamic states
1067 /* Expired states */
1069 exptailp = &exp_head;
1071 /* Expired limit states */
1073 expltailp = &exp_lhead;
1076 * We make a chain of packets to go out here -- not deferring
1077 * until after we drop the IPFW dynamic rule lock would result
1078 * in a lock order reversal with the normal packet input -> ipfw
1084 /* Protect from hash resizing */
1086 IPFW_UH_WLOCK(chain);
1088 IPFW_UH_WLOCK_ASSERT(chain);
1090 #define NEXT_RULE() { q_prev = q; q = q->next ; continue; }
1092 /* Stage 1: perform requested deletion */
1093 for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
1095 for (q = V_ipfw_dyn_v[i].head, q_prev = q; q ; ) {
1096 /* account every rule */
1099 /* Skip parent rules at all */
1100 if (q->dyn_type == O_LIMIT_PARENT) {
1106 * Remove rules which are:
1108 * 2) created by given rule
1109 * 3) created by any rule in given set
1111 if ((TIME_LEQ(q->expire, time_uptime)) ||
1112 ((rule != NULL) && (q->rule == rule)) ||
1113 ((set != RESVD_SET) && (q->rule->set == set))) {
1114 if (TIME_LE(time_uptime, q->expire) &&
1115 q->dyn_type == O_KEEP_STATE &&
1116 V_dyn_keep_states != 0) {
1118 * Do not delete state if
1119 * it is not expired and
1120 * dyn_keep_states is ON.
1121 * However we need to re-link it
1122 * to any other stable rule
1124 q->rule = chain->default_rule;
1128 /* Unlink q from current list */
1130 if (q == V_ipfw_dyn_v[i].head)
1131 V_ipfw_dyn_v[i].head = q_next;
1133 q_prev->next = q_next;
1137 /* queue q to expire list */
1138 if (q->dyn_type != O_LIMIT) {
1140 exptailp = &(*exptailp)->next;
1141 DEB(print_dyn_rule(&q->id, q->dyn_type,
1142 "unlink entry", "left");
1145 /* Separate list for limit rules */
1147 expltailp = &(*expltailp)->next;
1149 DEB(print_dyn_rule(&q->id, q->dyn_type,
1150 "unlink limit entry", "left");
1160 * Check if we need to send keepalive:
1161 * we need to ensure if is time to do KA,
1162 * this is established TCP session, and
1163 * expire time is within keepalive interval
1165 if ((check_ka != 0) && (q->id.proto == IPPROTO_TCP) &&
1166 ((q->state & BOTH_SYN) == BOTH_SYN) &&
1167 (TIME_LEQ(q->expire, time_uptime +
1168 V_dyn_keepalive_interval)))
1169 mtailp = ipfw_dyn_send_ka(mtailp, q);
1173 IPFW_BUCK_UNLOCK(i);
1176 /* Stage 2: decrement counters from O_LIMIT parents */
1177 if (expired_limits != 0) {
1179 * XXX: Note that deleting set with more than one
1180 * heavily-used LIMIT rules can result in overwhelming
1181 * locking due to lack of per-hash value sorting
1183 * We should probably think about:
1184 * 1) pre-allocating hash of size, say,
1185 * MAX(16, V_curr_dyn_buckets / 1024)
1186 * 2) checking if expired_limits is large enough
1187 * 3) If yes, init hash (or its part), re-link
1188 * current list and start decrementing procedure in
1189 * each bucket separately
1193 * Small optimization: do not unlock bucket until
1194 * we see the next item resides in different bucket
1196 if (exp_lhead != NULL) {
1197 i = exp_lhead->parent->bucket;
1200 for (q = exp_lhead; q != NULL; q = q->next) {
1201 if (i != q->parent->bucket) {
1202 IPFW_BUCK_UNLOCK(i);
1203 i = q->parent->bucket;
1207 /* Decrease parent refcount */
1210 if (exp_lhead != NULL)
1211 IPFW_BUCK_UNLOCK(i);
1215 * We protectet ourselves from unused parent deletion
1216 * (from the timer function) by holding UH write lock.
1219 /* Stage 3: remove unused parent rules */
1220 if ((parents != 0) && (expired != 0)) {
1221 for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
1223 for (q = V_ipfw_dyn_v[i].head, q_prev = q ; q ; ) {
1224 if (q->dyn_type != O_LIMIT_PARENT)
1230 /* Parent rule without consumers */
1232 /* Unlink q from current list */
1234 if (q == V_ipfw_dyn_v[i].head)
1235 V_ipfw_dyn_v[i].head = q_next;
1237 q_prev->next = q_next;
1241 /* Add to expired list */
1243 exptailp = &(*exptailp)->next;
1245 DEB(print_dyn_rule(&q->id, q->dyn_type,
1246 "unlink parent entry", "left");
1253 IPFW_BUCK_UNLOCK(i);
1261 * Check if we need to resize hash:
1262 * if current number of states exceeds number of buckes in hash,
1263 * grow hash size to the minimum power of 2 which is bigger than
1264 * current states count. Limit hash size by 64k.
1266 max_buckets = (V_dyn_buckets_max > 65536) ?
1267 65536 : V_dyn_buckets_max;
1269 dyn_count = DYN_COUNT;
1271 if ((dyn_count > V_curr_dyn_buckets * 2) &&
1272 (dyn_count < max_buckets)) {
1273 new_buckets = V_curr_dyn_buckets;
1274 while (new_buckets < dyn_count) {
1277 if (new_buckets >= max_buckets)
1282 IPFW_UH_WUNLOCK(chain);
1285 /* Finally delete old states ad limits if any */
1286 for (q = exp_head; q != NULL; q = q_next) {
1288 uma_zfree(V_ipfw_dyn_rule_zone, q);
1292 for (q = exp_lhead; q != NULL; q = q_next) {
1294 uma_zfree(V_ipfw_dyn_rule_zone, q);
1299 * The rest code MUST be called from timer routine only
1300 * without holding any locks
1305 /* Send keepalive packets if any */
1306 for (m = m0; m != NULL; m = mnext) {
1307 mnext = m->m_nextpkt;
1308 m->m_nextpkt = NULL;
1309 h = mtod(m, struct ip *);
1311 ip_output(m, NULL, NULL, 0, NULL, NULL);
1314 ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
1318 /* Run table resize without holding any locks */
1319 if (new_buckets != 0)
1320 resize_dynamic_table(chain, new_buckets);
1324 * Deletes all dynamic rules originated by given rule or all rules in
1325 * given set. Specify RESVD_SET to indicate set should not be used.
1326 * @chain - pointer to current ipfw rules chain
1327 * @rule - delete all states originated by given rule if != NULL
1328 * @set - delete all states originated by any rule in set @set if != RESVD_SET
1330 * Function has to be called with IPFW_UH_WLOCK held.
1331 * Additionally, function assume that dynamic rule/set is
1332 * ALREADY deleted so no new states can be generated by
1336 ipfw_expire_dyn_rules(struct ip_fw_chain *chain, struct ip_fw *rule, int set)
1339 check_dyn_rules(chain, rule, set, 0, 0);
1343 ipfw_dyn_init(struct ip_fw_chain *chain)
1346 V_ipfw_dyn_v = NULL;
1347 V_dyn_buckets_max = 256; /* must be power of 2 */
1348 V_curr_dyn_buckets = 256; /* must be power of 2 */
1350 V_dyn_ack_lifetime = 300;
1351 V_dyn_syn_lifetime = 20;
1352 V_dyn_fin_lifetime = 1;
1353 V_dyn_rst_lifetime = 1;
1354 V_dyn_udp_lifetime = 10;
1355 V_dyn_short_lifetime = 5;
1357 V_dyn_keepalive_interval = 20;
1358 V_dyn_keepalive_period = 5;
1359 V_dyn_keepalive = 1; /* do send keepalives */
1360 V_dyn_keepalive_last = time_uptime;
1362 V_dyn_max = 4096; /* max # of dynamic rules */
1364 V_ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
1365 sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
1368 /* Enforce limit on dynamic rules */
1369 uma_zone_set_max(V_ipfw_dyn_rule_zone, V_dyn_max);
1371 callout_init(&V_ipfw_timeout, CALLOUT_MPSAFE);
1374 * This can potentially be done on first dynamic rule
1375 * being added to chain.
1377 resize_dynamic_table(chain, V_curr_dyn_buckets);
1381 ipfw_dyn_uninit(int pass)
1386 callout_drain(&V_ipfw_timeout);
1390 if (V_ipfw_dyn_v != NULL) {
1392 * Skip deleting all dynamic states -
1393 * uma_zdestroy() does this more efficiently;
1396 /* Destroy all mutexes */
1397 for (i = 0 ; i < V_curr_dyn_buckets ; i++)
1398 IPFW_BUCK_LOCK_DESTROY(&V_ipfw_dyn_v[i]);
1399 free(V_ipfw_dyn_v, M_IPFW);
1400 V_ipfw_dyn_v = NULL;
1403 uma_zdestroy(V_ipfw_dyn_rule_zone);
1408 * Get/set maximum number of dynamic states in given VNET instance.
1411 sysctl_ipfw_dyn_max(SYSCTL_HANDLER_ARGS)
1414 unsigned int nstates;
1416 nstates = V_dyn_max;
1418 error = sysctl_handle_int(oidp, &nstates, 0, req);
1419 /* Read operation or some error */
1420 if ((error != 0) || (req->newptr == NULL))
1423 V_dyn_max = nstates;
1424 uma_zone_set_max(V_ipfw_dyn_rule_zone, V_dyn_max);
1430 * Get current number of dynamic states in given VNET instance.
1433 sysctl_ipfw_dyn_count(SYSCTL_HANDLER_ARGS)
1436 unsigned int nstates;
1438 nstates = DYN_COUNT;
1440 error = sysctl_handle_int(oidp, &nstates, 0, req);
1447 * Returns size of dynamic states in legacy format
1453 return (V_ipfw_dyn_v == NULL) ? 0 :
1454 (DYN_COUNT * sizeof(ipfw_dyn_rule));
1458 * Returns number of dynamic states.
1459 * Used by dump format v1 (current).
1462 ipfw_dyn_get_count(void)
1465 return (V_ipfw_dyn_v == NULL) ? 0 : DYN_COUNT;
1469 export_dyn_rule(ipfw_dyn_rule *src, ipfw_dyn_rule *dst)
1472 memcpy(dst, src, sizeof(*src));
1473 memcpy(&(dst->rule), &(src->rule->rulenum), sizeof(src->rule->rulenum));
1475 * store set number into high word of
1476 * dst->rule pointer.
1478 memcpy((char *)&dst->rule + sizeof(src->rule->rulenum),
1479 &(src->rule->set), sizeof(src->rule->set));
1481 * store a non-null value in "next".
1482 * The userland code will interpret a
1483 * NULL here as a marker
1484 * for the last dynamic rule.
1486 memcpy(&dst->next, &dst, sizeof(dst));
1488 TIME_LEQ(dst->expire, time_uptime) ? 0 : dst->expire - time_uptime;
1492 * Fills int buffer given by @sd with dynamic states.
1493 * Used by dump format v1 (current).
1495 * Returns 0 on success.
1498 ipfw_dump_states(struct ip_fw_chain *chain, struct sockopt_data *sd)
1501 ipfw_obj_dyntlv *dst, *last;
1502 ipfw_obj_ctlv *ctlv;
1506 if (V_ipfw_dyn_v == NULL)
1509 IPFW_UH_RLOCK_ASSERT(chain);
1511 ctlv = (ipfw_obj_ctlv *)ipfw_get_sopt_space(sd, sizeof(*ctlv));
1514 sz = sizeof(ipfw_obj_dyntlv);
1515 ctlv->head.type = IPFW_TLV_DYNSTATE_LIST;
1519 for (i = 0 ; i < V_curr_dyn_buckets; i++) {
1521 for (p = V_ipfw_dyn_v[i].head ; p != NULL; p = p->next) {
1522 dst = (ipfw_obj_dyntlv *)ipfw_get_sopt_space(sd, sz);
1524 IPFW_BUCK_UNLOCK(i);
1528 export_dyn_rule(p, &dst->state);
1529 dst->head.length = sz;
1530 dst->head.type = IPFW_TLV_DYN_ENT;
1533 IPFW_BUCK_UNLOCK(i);
1536 if (last != NULL) /* mark last dynamic rule */
1537 last->head.flags = IPFW_DF_LAST;
1543 * Fill given buffer with dynamic states (legacy format).
1544 * IPFW_UH_RLOCK has to be held while calling.
1547 ipfw_get_dynamic(struct ip_fw_chain *chain, char **pbp, const char *ep)
1549 ipfw_dyn_rule *p, *last = NULL;
1553 if (V_ipfw_dyn_v == NULL)
1557 IPFW_UH_RLOCK_ASSERT(chain);
1559 for (i = 0 ; i < V_curr_dyn_buckets; i++) {
1561 for (p = V_ipfw_dyn_v[i].head ; p != NULL; p = p->next) {
1562 if (bp + sizeof *p <= ep) {
1563 ipfw_dyn_rule *dst =
1564 (ipfw_dyn_rule *)bp;
1566 export_dyn_rule(p, dst);
1568 bp += sizeof(ipfw_dyn_rule);
1571 IPFW_BUCK_UNLOCK(i);
1574 if (last != NULL) /* mark last dynamic rule */
1575 bzero(&last->next, sizeof(last));