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: head/sys/netinet/ipfw/ip_fw_dynamic.c 200601 2009-12-16 10:48:40Z luigi $");
33 * Dynamic rule support for ipfw
36 #if !defined(KLD_MODULE)
38 #include "opt_ipdivert.h"
42 #error IPFIREWALL requires INET.
45 #include "opt_inet6.h"
46 #include "opt_ipsec.h"
48 #include <sys/param.h>
49 #include <sys/systm.h>
50 #include <sys/malloc.h>
52 #include <sys/kernel.h>
54 #include <sys/socket.h>
55 #include <sys/sysctl.h>
56 #include <sys/syslog.h>
57 #include <net/ethernet.h> /* for ETHERTYPE_IP */
61 #include <netinet/in.h>
62 #include <netinet/ip.h>
63 #include <netinet/ip_var.h> /* ip_defttl */
64 #include <netinet/ip_fw.h>
65 #include <netinet/ipfw/ip_fw_private.h>
66 #include <netinet/tcp_var.h>
67 #include <netinet/udp.h>
69 #include <netinet/ip6.h> /* IN6_ARE_ADDR_EQUAL */
71 #include <netinet6/in6_var.h>
72 #include <netinet6/ip6_var.h>
75 #include <machine/in_cksum.h> /* XXX for in_cksum */
78 #include <security/mac/mac_framework.h>
82 * Description of dynamic rules.
84 * Dynamic rules are stored in lists accessed through a hash table
85 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
86 * be modified through the sysctl variable dyn_buckets which is
87 * updated when the table becomes empty.
89 * XXX currently there is only one list, ipfw_dyn.
91 * When a packet is received, its address fields are first masked
92 * with the mask defined for the rule, then hashed, then matched
93 * against the entries in the corresponding list.
94 * Dynamic rules can be used for different purposes:
96 * + enforcing limits on the number of sessions;
97 * + in-kernel NAT (not implemented yet)
99 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
100 * measured in seconds and depending on the flags.
102 * The total number of dynamic rules is stored in dyn_count.
103 * The max number of dynamic rules is dyn_max. When we reach
104 * the maximum number of rules we do not create anymore. This is
105 * done to avoid consuming too much memory, but also too much
106 * time when searching on each packet (ideally, we should try instead
107 * to put a limit on the length of the list on each bucket...).
109 * Each dynamic rule holds a pointer to the parent ipfw rule so
110 * we know what action to perform. Dynamic rules are removed when
111 * the parent rule is deleted. XXX we should make them survive.
113 * There are some limitations with dynamic rules -- we do not
114 * obey the 'randomized match', and we do not do multiple
115 * passes through the firewall. XXX check the latter!!!
119 * Static variables followed by global ones
121 static VNET_DEFINE(ipfw_dyn_rule **, ipfw_dyn_v);
122 static VNET_DEFINE(u_int32_t, dyn_buckets);
123 static VNET_DEFINE(u_int32_t, curr_dyn_buckets);
124 static VNET_DEFINE(struct callout, ipfw_timeout);
125 #define V_ipfw_dyn_v VNET(ipfw_dyn_v)
126 #define V_dyn_buckets VNET(dyn_buckets)
127 #define V_curr_dyn_buckets VNET(curr_dyn_buckets)
128 #define V_ipfw_timeout VNET(ipfw_timeout)
130 static uma_zone_t ipfw_dyn_rule_zone;
131 #if defined( __linux__ ) || defined( _WIN32 )
132 DEFINE_SPINLOCK(ipfw_dyn_mtx);
134 static struct mtx ipfw_dyn_mtx; /* mutex guarding dynamic rules */
137 #define IPFW_DYN_LOCK_INIT() \
138 mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
139 #define IPFW_DYN_LOCK_DESTROY() mtx_destroy(&ipfw_dyn_mtx)
140 #define IPFW_DYN_LOCK() mtx_lock(&ipfw_dyn_mtx)
141 #define IPFW_DYN_UNLOCK() mtx_unlock(&ipfw_dyn_mtx)
142 #define IPFW_DYN_LOCK_ASSERT() mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
145 ipfw_dyn_unlock(void)
151 * Timeouts for various events in handing dynamic rules.
153 static VNET_DEFINE(u_int32_t, dyn_ack_lifetime);
154 static VNET_DEFINE(u_int32_t, dyn_syn_lifetime);
155 static VNET_DEFINE(u_int32_t, dyn_fin_lifetime);
156 static VNET_DEFINE(u_int32_t, dyn_rst_lifetime);
157 static VNET_DEFINE(u_int32_t, dyn_udp_lifetime);
158 static VNET_DEFINE(u_int32_t, dyn_short_lifetime);
160 #define V_dyn_ack_lifetime VNET(dyn_ack_lifetime)
161 #define V_dyn_syn_lifetime VNET(dyn_syn_lifetime)
162 #define V_dyn_fin_lifetime VNET(dyn_fin_lifetime)
163 #define V_dyn_rst_lifetime VNET(dyn_rst_lifetime)
164 #define V_dyn_udp_lifetime VNET(dyn_udp_lifetime)
165 #define V_dyn_short_lifetime VNET(dyn_short_lifetime)
168 * Keepalives are sent if dyn_keepalive is set. They are sent every
169 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
170 * seconds of lifetime of a rule.
171 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
172 * than dyn_keepalive_period.
175 static VNET_DEFINE(u_int32_t, dyn_keepalive_interval);
176 static VNET_DEFINE(u_int32_t, dyn_keepalive_period);
177 static VNET_DEFINE(u_int32_t, dyn_keepalive);
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)
183 static VNET_DEFINE(u_int32_t, dyn_count); /* # of dynamic rules */
184 static VNET_DEFINE(u_int32_t, dyn_max); /* max # of dynamic rules */
186 #define V_dyn_count VNET(dyn_count)
187 #define V_dyn_max VNET(dyn_max)
190 SYSCTL_DECL(_net_inet_ip_fw);
191 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_buckets,
192 CTLFLAG_RW, &VNET_NAME(dyn_buckets), 0,
193 "Number of dyn. buckets");
194 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets,
195 CTLFLAG_RD, &VNET_NAME(curr_dyn_buckets), 0,
196 "Current Number of dyn. buckets");
197 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_count,
198 CTLFLAG_RD, &VNET_NAME(dyn_count), 0,
199 "Number of dyn. rules");
200 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_max,
201 CTLFLAG_RW, &VNET_NAME(dyn_max), 0,
202 "Max number of dyn. rules");
203 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime,
204 CTLFLAG_RW, &VNET_NAME(dyn_ack_lifetime), 0,
205 "Lifetime of dyn. rules for acks");
206 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime,
207 CTLFLAG_RW, &VNET_NAME(dyn_syn_lifetime), 0,
208 "Lifetime of dyn. rules for syn");
209 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
210 CTLFLAG_RW, &VNET_NAME(dyn_fin_lifetime), 0,
211 "Lifetime of dyn. rules for fin");
212 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
213 CTLFLAG_RW, &VNET_NAME(dyn_rst_lifetime), 0,
214 "Lifetime of dyn. rules for rst");
215 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime,
216 CTLFLAG_RW, &VNET_NAME(dyn_udp_lifetime), 0,
217 "Lifetime of dyn. rules for UDP");
218 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime,
219 CTLFLAG_RW, &VNET_NAME(dyn_short_lifetime), 0,
220 "Lifetime of dyn. rules for other situations");
221 SYSCTL_VNET_INT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive,
222 CTLFLAG_RW, &VNET_NAME(dyn_keepalive), 0,
223 "Enable keepalives for dyn. rules");
224 #endif /* SYSCTL_NODE */
228 hash_packet6(struct ipfw_flow_id *id)
231 i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
232 (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
233 (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
234 (id->src_ip6.__u6_addr.__u6_addr32[3]) ^
235 (id->dst_port) ^ (id->src_port);
240 * IMPORTANT: the hash function for dynamic rules must be commutative
241 * in source and destination (ip,port), because rules are bidirectional
242 * and we want to find both in the same bucket.
245 hash_packet(struct ipfw_flow_id *id)
250 if (IS_IP6_FLOW_ID(id))
251 i = hash_packet6(id);
254 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
255 i &= (V_curr_dyn_buckets - 1);
260 unlink_dyn_rule_print(struct ipfw_flow_id *id)
264 char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN];
266 char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
270 if (IS_IP6_FLOW_ID(id)) {
271 ip6_sprintf(src, &id->src_ip6);
272 ip6_sprintf(dst, &id->dst_ip6);
276 da.s_addr = htonl(id->src_ip);
277 inet_ntoa_r(da, src);
278 da.s_addr = htonl(id->dst_ip);
279 inet_ntoa_r(da, dst);
281 printf("ipfw: unlink entry %s %d -> %s %d, %d left\n",
282 src, id->src_port, dst, id->dst_port, V_dyn_count - 1);
286 * unlink a dynamic rule from a chain. prev is a pointer to
287 * the previous one, q is a pointer to the rule to delete,
288 * head is a pointer to the head of the queue.
289 * Modifies q and potentially also head.
291 #define UNLINK_DYN_RULE(prev, head, q) { \
292 ipfw_dyn_rule *old_q = q; \
294 /* remove a refcount to the parent */ \
295 if (q->dyn_type == O_LIMIT) \
296 q->parent->count--; \
297 DEB(unlink_dyn_rule_print(&q->id);) \
299 prev->next = q = q->next; \
301 head = q = q->next; \
303 uma_zfree(ipfw_dyn_rule_zone, old_q); }
305 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
308 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
310 * If keep_me == NULL, rules are deleted even if not expired,
311 * otherwise only expired rules are removed.
313 * The value of the second parameter is also used to point to identify
314 * a rule we absolutely do not want to remove (e.g. because we are
315 * holding a reference to it -- this is the case with O_LIMIT_PARENT
316 * rules). The pointer is only used for comparison, so any non-null
320 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
322 static u_int32_t last_remove = 0;
324 #define FORCE (keep_me == NULL)
326 ipfw_dyn_rule *prev, *q;
327 int i, pass = 0, max_pass = 0;
329 IPFW_DYN_LOCK_ASSERT();
331 if (V_ipfw_dyn_v == NULL || V_dyn_count == 0)
333 /* do not expire more than once per second, it is useless */
334 if (!FORCE && last_remove == time_uptime)
336 last_remove = time_uptime;
339 * because O_LIMIT refer to parent rules, during the first pass only
340 * remove child and mark any pending LIMIT_PARENT, and remove
341 * them in a second pass.
344 for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
345 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q ; ) {
347 * Logic can become complex here, so we split tests.
351 if (rule != NULL && rule != q->rule)
352 goto next; /* not the one we are looking for */
353 if (q->dyn_type == O_LIMIT_PARENT) {
355 * handle parent in the second pass,
356 * record we need one.
361 if (FORCE && q->count != 0 ) {
362 /* XXX should not happen! */
363 printf("ipfw: OUCH! cannot remove rule,"
364 " count %d\n", q->count);
368 !TIME_LEQ( q->expire, time_uptime ))
371 if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
372 UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
380 if (pass++ < max_pass)
385 ipfw_remove_dyn_children(struct ip_fw *rule)
388 remove_dyn_rule(rule, NULL /* force removal */);
393 * lookup a dynamic rule, locked version
395 static ipfw_dyn_rule *
396 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
400 * stateful ipfw extensions.
401 * Lookup into dynamic session queue
403 #define MATCH_REVERSE 0
404 #define MATCH_FORWARD 1
406 #define MATCH_UNKNOWN 3
407 int i, dir = MATCH_NONE;
408 ipfw_dyn_rule *prev, *q=NULL;
410 IPFW_DYN_LOCK_ASSERT();
412 if (V_ipfw_dyn_v == NULL)
413 goto done; /* not found */
414 i = hash_packet( pkt );
415 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q != NULL ; ) {
416 if (q->dyn_type == O_LIMIT_PARENT && q->count)
418 if (TIME_LEQ( q->expire, time_uptime)) { /* expire entry */
419 UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
422 if (pkt->proto == q->id.proto &&
423 q->dyn_type != O_LIMIT_PARENT) {
424 if (IS_IP6_FLOW_ID(pkt)) {
425 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
427 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
429 pkt->src_port == q->id.src_port &&
430 pkt->dst_port == q->id.dst_port ) {
434 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
436 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
438 pkt->src_port == q->id.dst_port &&
439 pkt->dst_port == q->id.src_port ) {
444 if (pkt->src_ip == q->id.src_ip &&
445 pkt->dst_ip == q->id.dst_ip &&
446 pkt->src_port == q->id.src_port &&
447 pkt->dst_port == q->id.dst_port ) {
451 if (pkt->src_ip == q->id.dst_ip &&
452 pkt->dst_ip == q->id.src_ip &&
453 pkt->src_port == q->id.dst_port &&
454 pkt->dst_port == q->id.src_port ) {
465 goto done; /* q = NULL, not found */
467 if ( prev != NULL) { /* found and not in front */
468 prev->next = q->next;
469 q->next = V_ipfw_dyn_v[i];
472 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
473 u_char flags = pkt->flags & (TH_FIN|TH_SYN|TH_RST);
475 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
476 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
477 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
479 case TH_SYN: /* opening */
480 q->expire = time_uptime + V_dyn_syn_lifetime;
483 case BOTH_SYN: /* move to established */
484 case BOTH_SYN | TH_FIN : /* one side tries to close */
485 case BOTH_SYN | (TH_FIN << 8) :
487 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
488 u_int32_t ack = ntohl(tcp->th_ack);
489 if (dir == MATCH_FORWARD) {
490 if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
492 else { /* ignore out-of-sequence */
496 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
498 else { /* ignore out-of-sequence */
503 q->expire = time_uptime + V_dyn_ack_lifetime;
506 case BOTH_SYN | BOTH_FIN: /* both sides closed */
507 if (V_dyn_fin_lifetime >= V_dyn_keepalive_period)
508 V_dyn_fin_lifetime = V_dyn_keepalive_period - 1;
509 q->expire = time_uptime + V_dyn_fin_lifetime;
515 * reset or some invalid combination, but can also
516 * occur if we use keep-state the wrong way.
518 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
519 printf("invalid state: 0x%x\n", q->state);
521 if (V_dyn_rst_lifetime >= V_dyn_keepalive_period)
522 V_dyn_rst_lifetime = V_dyn_keepalive_period - 1;
523 q->expire = time_uptime + V_dyn_rst_lifetime;
526 } else if (pkt->proto == IPPROTO_UDP) {
527 q->expire = time_uptime + V_dyn_udp_lifetime;
529 /* other protocols */
530 q->expire = time_uptime + V_dyn_short_lifetime;
534 *match_direction = dir;
539 ipfw_lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
545 q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
548 /* NB: return table locked when q is not NULL */
553 realloc_dynamic_table(void)
555 IPFW_DYN_LOCK_ASSERT();
558 * Try reallocation, make sure we have a power of 2 and do
559 * not allow more than 64k entries. In case of overflow,
563 if (V_dyn_buckets > 65536)
564 V_dyn_buckets = 1024;
565 if ((V_dyn_buckets & (V_dyn_buckets-1)) != 0) { /* not a power of 2 */
566 V_dyn_buckets = V_curr_dyn_buckets; /* reset */
569 V_curr_dyn_buckets = V_dyn_buckets;
570 if (V_ipfw_dyn_v != NULL)
571 free(V_ipfw_dyn_v, M_IPFW);
573 V_ipfw_dyn_v = malloc(V_curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
574 M_IPFW, M_NOWAIT | M_ZERO);
575 if (V_ipfw_dyn_v != NULL || V_curr_dyn_buckets <= 2)
577 V_curr_dyn_buckets /= 2;
582 * Install state of type 'type' for a dynamic session.
583 * The hash table contains two type of rules:
584 * - regular rules (O_KEEP_STATE)
585 * - rules for sessions with limited number of sess per user
586 * (O_LIMIT). When they are created, the parent is
587 * increased by 1, and decreased on delete. In this case,
588 * the third parameter is the parent rule and not the chain.
589 * - "parent" rules for the above (O_LIMIT_PARENT).
591 static ipfw_dyn_rule *
592 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
597 IPFW_DYN_LOCK_ASSERT();
599 if (V_ipfw_dyn_v == NULL ||
600 (V_dyn_count == 0 && V_dyn_buckets != V_curr_dyn_buckets)) {
601 realloc_dynamic_table();
602 if (V_ipfw_dyn_v == NULL)
603 return NULL; /* failed ! */
607 r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
609 printf ("ipfw: sorry cannot allocate state\n");
613 /* increase refcount on parent, and set pointer */
614 if (dyn_type == O_LIMIT) {
615 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
616 if ( parent->dyn_type != O_LIMIT_PARENT)
617 panic("invalid parent");
624 r->expire = time_uptime + V_dyn_syn_lifetime;
626 r->dyn_type = dyn_type;
627 r->pcnt = r->bcnt = 0;
631 r->next = V_ipfw_dyn_v[i];
637 char src[INET6_ADDRSTRLEN];
638 char dst[INET6_ADDRSTRLEN];
640 char src[INET_ADDRSTRLEN];
641 char dst[INET_ADDRSTRLEN];
645 if (IS_IP6_FLOW_ID(&(r->id))) {
646 ip6_sprintf(src, &r->id.src_ip6);
647 ip6_sprintf(dst, &r->id.dst_ip6);
651 da.s_addr = htonl(r->id.src_ip);
652 inet_ntoa_r(da, src);
653 da.s_addr = htonl(r->id.dst_ip);
654 inet_ntoa_r(da, dst);
656 printf("ipfw: add dyn entry ty %d %s %d -> %s %d, total %d\n",
657 dyn_type, src, r->id.src_port, dst, r->id.dst_port,
664 * lookup dynamic parent rule using pkt and rule as search keys.
665 * If the lookup fails, then install one.
667 static ipfw_dyn_rule *
668 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
673 IPFW_DYN_LOCK_ASSERT();
676 int is_v6 = IS_IP6_FLOW_ID(pkt);
677 i = hash_packet( pkt );
678 for (q = V_ipfw_dyn_v[i] ; q != NULL ; q=q->next)
679 if (q->dyn_type == O_LIMIT_PARENT &&
681 pkt->proto == q->id.proto &&
682 pkt->src_port == q->id.src_port &&
683 pkt->dst_port == q->id.dst_port &&
686 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
688 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
689 &(q->id.dst_ip6))) ||
691 pkt->src_ip == q->id.src_ip &&
692 pkt->dst_ip == q->id.dst_ip)
695 q->expire = time_uptime + V_dyn_short_lifetime;
696 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
700 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
704 * Install dynamic state for rule type cmd->o.opcode
706 * Returns 1 (failure) if state is not installed because of errors or because
707 * session limitations are enforced.
710 ipfw_install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
711 struct ip_fw_args *args, uint32_t tablearg)
717 char src[INET6_ADDRSTRLEN + 2], dst[INET6_ADDRSTRLEN + 2];
719 char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
729 if (IS_IP6_FLOW_ID(&(args->f_id))) {
730 ip6_sprintf(src, &args->f_id.src_ip6);
731 ip6_sprintf(dst, &args->f_id.dst_ip6);
735 da.s_addr = htonl(args->f_id.src_ip);
736 inet_ntoa_r(da, src);
737 da.s_addr = htonl(args->f_id.dst_ip);
738 inet_ntoa_r(da, dst);
740 printf("ipfw: %s: type %d %s %u -> %s %u\n",
741 __func__, cmd->o.opcode, src, args->f_id.src_port,
742 dst, args->f_id.dst_port);
747 q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
749 if (q != NULL) { /* should never occur */
750 if (last_log != time_uptime) {
751 last_log = time_uptime;
752 printf("ipfw: %s: entry already present, done\n",
759 if (V_dyn_count >= V_dyn_max)
760 /* Run out of slots, try to remove any expired rule. */
761 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
763 if (V_dyn_count >= V_dyn_max) {
764 if (last_log != time_uptime) {
765 last_log = time_uptime;
766 printf("ipfw: %s: Too many dynamic rules\n", __func__);
769 return (1); /* cannot install, notify caller */
772 switch (cmd->o.opcode) {
773 case O_KEEP_STATE: /* bidir rule */
774 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
777 case O_LIMIT: { /* limit number of sessions */
778 struct ipfw_flow_id id;
779 ipfw_dyn_rule *parent;
781 uint16_t limit_mask = cmd->limit_mask;
783 conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ?
784 tablearg : cmd->conn_limit;
787 if (cmd->conn_limit == IP_FW_TABLEARG)
788 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
789 "(tablearg)\n", __func__, conn_limit);
791 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
792 __func__, conn_limit);
795 id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
796 id.proto = args->f_id.proto;
797 id.addr_type = args->f_id.addr_type;
798 id.fib = M_GETFIB(args->m);
800 if (IS_IP6_FLOW_ID (&(args->f_id))) {
801 if (limit_mask & DYN_SRC_ADDR)
802 id.src_ip6 = args->f_id.src_ip6;
803 if (limit_mask & DYN_DST_ADDR)
804 id.dst_ip6 = args->f_id.dst_ip6;
806 if (limit_mask & DYN_SRC_ADDR)
807 id.src_ip = args->f_id.src_ip;
808 if (limit_mask & DYN_DST_ADDR)
809 id.dst_ip = args->f_id.dst_ip;
811 if (limit_mask & DYN_SRC_PORT)
812 id.src_port = args->f_id.src_port;
813 if (limit_mask & DYN_DST_PORT)
814 id.dst_port = args->f_id.dst_port;
815 if ((parent = lookup_dyn_parent(&id, rule)) == NULL) {
816 printf("ipfw: %s: add parent failed\n", __func__);
821 if (parent->count >= conn_limit) {
822 /* See if we can remove some expired rule. */
823 remove_dyn_rule(rule, parent);
824 if (parent->count >= conn_limit) {
825 if (V_fw_verbose && last_log != time_uptime) {
826 last_log = time_uptime;
829 * XXX IPv6 flows are not
832 if (IS_IP6_FLOW_ID(&(args->f_id))) {
833 char ip6buf[INET6_ADDRSTRLEN];
834 snprintf(src, sizeof(src),
835 "[%s]", ip6_sprintf(ip6buf,
836 &args->f_id.src_ip6));
837 snprintf(dst, sizeof(dst),
838 "[%s]", ip6_sprintf(ip6buf,
839 &args->f_id.dst_ip6));
844 htonl(args->f_id.src_ip);
845 inet_ntoa_r(da, src);
847 htonl(args->f_id.dst_ip);
848 inet_ntoa_r(da, dst);
850 log(LOG_SECURITY | LOG_DEBUG,
851 "ipfw: %d %s %s:%u -> %s:%u, %s\n",
852 parent->rule->rulenum,
854 src, (args->f_id.src_port),
855 dst, (args->f_id.dst_port),
862 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
866 printf("ipfw: %s: unknown dynamic rule type %u\n",
867 __func__, cmd->o.opcode);
872 /* XXX just set lifetime */
873 lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
880 * Generate a TCP packet, containing either a RST or a keepalive.
881 * When flags & TH_RST, we are sending a RST packet, because of a
882 * "reset" action matched the packet.
883 * Otherwise we are sending a keepalive, and flags & TH_
884 * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
885 * so that MAC can label the reply appropriately.
888 ipfw_send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
889 u_int32_t ack, int flags)
891 #ifdef __linux__ // XXX to be revised
896 struct ip *h = NULL; /* stupid compiler */
898 struct ip6_hdr *h6 = NULL;
900 struct tcphdr *th = NULL;
902 MGETHDR(m, M_DONTWAIT, MT_DATA);
906 M_SETFIB(m, id->fib);
909 mac_netinet_firewall_reply(replyto, m);
911 mac_netinet_firewall_send(m);
913 (void)replyto; /* don't warn about unused arg */
916 switch (id->addr_type) {
918 len = sizeof(struct ip) + sizeof(struct tcphdr);
922 len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
930 dir = ((flags & (TH_SYN | TH_RST)) == TH_SYN);
932 m->m_data += max_linkhdr;
933 m->m_flags |= M_SKIP_FIREWALL;
934 m->m_pkthdr.len = m->m_len = len;
935 m->m_pkthdr.rcvif = NULL;
936 bzero(m->m_data, len);
938 switch (id->addr_type) {
940 h = mtod(m, struct ip *);
942 /* prepare for checksum */
943 h->ip_p = IPPROTO_TCP;
944 h->ip_len = htons(sizeof(struct tcphdr));
946 h->ip_src.s_addr = htonl(id->src_ip);
947 h->ip_dst.s_addr = htonl(id->dst_ip);
949 h->ip_src.s_addr = htonl(id->dst_ip);
950 h->ip_dst.s_addr = htonl(id->src_ip);
953 th = (struct tcphdr *)(h + 1);
957 h6 = mtod(m, struct ip6_hdr *);
959 /* prepare for checksum */
960 h6->ip6_nxt = IPPROTO_TCP;
961 h6->ip6_plen = htons(sizeof(struct tcphdr));
963 h6->ip6_src = id->src_ip6;
964 h6->ip6_dst = id->dst_ip6;
966 h6->ip6_src = id->dst_ip6;
967 h6->ip6_dst = id->src_ip6;
970 th = (struct tcphdr *)(h6 + 1);
976 th->th_sport = htons(id->src_port);
977 th->th_dport = htons(id->dst_port);
979 th->th_sport = htons(id->dst_port);
980 th->th_dport = htons(id->src_port);
982 th->th_off = sizeof(struct tcphdr) >> 2;
984 if (flags & TH_RST) {
985 if (flags & TH_ACK) {
986 th->th_seq = htonl(ack);
987 th->th_flags = TH_RST;
991 th->th_ack = htonl(seq);
992 th->th_flags = TH_RST | TH_ACK;
996 * Keepalive - use caller provided sequence numbers
998 th->th_seq = htonl(seq);
999 th->th_ack = htonl(ack);
1000 th->th_flags = TH_ACK;
1003 switch (id->addr_type) {
1005 th->th_sum = in_cksum(m, len);
1007 /* finish the ip header */
1009 h->ip_hl = sizeof(*h) >> 2;
1010 h->ip_tos = IPTOS_LOWDELAY;
1012 h->ip_len = htons(len);
1013 h->ip_ttl = V_ip_defttl;
1018 th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(*h6),
1019 sizeof(struct tcphdr));
1021 /* finish the ip6 header */
1022 h6->ip6_vfc |= IPV6_VERSION;
1023 h6->ip6_hlim = IPV6_DEFHLIM;
1029 #endif /* !__linux__ */
1033 * This procedure is only used to handle keepalives. It is invoked
1034 * every dyn_keepalive_period
1037 ipfw_tick(void * vnetx)
1039 struct mbuf *m0, *m, *mnext, **mtailp;
1041 struct mbuf *m6, **m6_tailp;
1046 struct vnet *vp = vnetx;
1050 if (V_dyn_keepalive == 0 || V_ipfw_dyn_v == NULL || V_dyn_count == 0)
1054 * We make a chain of packets to go out here -- not deferring
1055 * until after we drop the IPFW dynamic rule lock would result
1056 * in a lock order reversal with the normal packet input -> ipfw
1066 for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
1067 for (q = V_ipfw_dyn_v[i] ; q ; q = q->next ) {
1068 if (q->dyn_type == O_LIMIT_PARENT)
1070 if (q->id.proto != IPPROTO_TCP)
1072 if ( (q->state & BOTH_SYN) != BOTH_SYN)
1074 if (TIME_LEQ(time_uptime + V_dyn_keepalive_interval,
1076 continue; /* too early */
1077 if (TIME_LEQ(q->expire, time_uptime))
1078 continue; /* too late, rule expired */
1080 m = ipfw_send_pkt(NULL, &(q->id), q->ack_rev - 1,
1081 q->ack_fwd, TH_SYN);
1082 mnext = ipfw_send_pkt(NULL, &(q->id), q->ack_fwd - 1,
1085 switch (q->id.addr_type) {
1089 mtailp = &(*mtailp)->m_nextpkt;
1091 if (mnext != NULL) {
1093 mtailp = &(*mtailp)->m_nextpkt;
1100 m6_tailp = &(*m6_tailp)->m_nextpkt;
1102 if (mnext != NULL) {
1104 m6_tailp = &(*m6_tailp)->m_nextpkt;
1114 for (m = mnext = m0; m != NULL; m = mnext) {
1115 mnext = m->m_nextpkt;
1116 m->m_nextpkt = NULL;
1117 ip_output(m, NULL, NULL, 0, NULL, NULL);
1120 for (m = mnext = m6; m != NULL; m = mnext) {
1121 mnext = m->m_nextpkt;
1122 m->m_nextpkt = NULL;
1123 ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
1127 callout_reset(&V_ipfw_timeout, V_dyn_keepalive_period * hz,
1133 ipfw_dyn_attach(void)
1135 ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
1136 sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
1139 IPFW_DYN_LOCK_INIT();
1143 ipfw_dyn_detach(void)
1145 uma_zdestroy(ipfw_dyn_rule_zone);
1146 IPFW_DYN_LOCK_DESTROY();
1152 V_ipfw_dyn_v = NULL;
1153 V_dyn_buckets = 256; /* must be power of 2 */
1154 V_curr_dyn_buckets = 256; /* must be power of 2 */
1156 V_dyn_ack_lifetime = 300;
1157 V_dyn_syn_lifetime = 20;
1158 V_dyn_fin_lifetime = 1;
1159 V_dyn_rst_lifetime = 1;
1160 V_dyn_udp_lifetime = 10;
1161 V_dyn_short_lifetime = 5;
1163 V_dyn_keepalive_interval = 20;
1164 V_dyn_keepalive_period = 5;
1165 V_dyn_keepalive = 1; /* do send keepalives */
1167 V_dyn_max = 4096; /* max # of dynamic rules */
1168 callout_init(&V_ipfw_timeout, CALLOUT_MPSAFE);
1169 callout_reset(&V_ipfw_timeout, hz, ipfw_tick, curvnet);
1173 ipfw_dyn_uninit(int pass)
1176 callout_drain(&V_ipfw_timeout);
1178 if (V_ipfw_dyn_v != NULL)
1179 free(V_ipfw_dyn_v, M_IPFW);
1186 return (V_ipfw_dyn_v == NULL) ? 0 :
1187 (V_dyn_count * sizeof(ipfw_dyn_rule));
1191 ipfw_get_dynamic(char **pbp, const char *ep)
1193 ipfw_dyn_rule *p, *last = NULL;
1197 if (V_ipfw_dyn_v == NULL)
1202 for (i = 0 ; i < V_curr_dyn_buckets; i++)
1203 for (p = V_ipfw_dyn_v[i] ; p != NULL; p = p->next) {
1204 if (bp + sizeof *p <= ep) {
1205 ipfw_dyn_rule *dst =
1206 (ipfw_dyn_rule *)bp;
1207 bcopy(p, dst, sizeof *p);
1208 bcopy(&(p->rule->rulenum), &(dst->rule),
1209 sizeof(p->rule->rulenum));
1211 * store set number into high word of
1212 * dst->rule pointer.
1214 bcopy(&(p->rule->set),
1215 (char *)&dst->rule +
1216 sizeof(p->rule->rulenum),
1217 sizeof(p->rule->set));
1219 * store a non-null value in "next".
1220 * The userland code will interpret a
1221 * NULL here as a marker
1222 * for the last dynamic rule.
1224 bcopy(&dst, &dst->next, sizeof(dst));
1227 TIME_LEQ(dst->expire, time_uptime) ?
1228 0 : dst->expire - time_uptime ;
1229 bp += sizeof(ipfw_dyn_rule);
1233 if (last != NULL) /* mark last dynamic rule */
1234 bzero(&last->next, sizeof(last));