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>
49 #include <sys/socket.h>
50 #include <sys/sysctl.h>
51 #include <sys/syslog.h>
52 #include <net/ethernet.h> /* for ETHERTYPE_IP */
56 #include <netinet/in.h>
57 #include <netinet/ip.h>
58 #include <netinet/ip_var.h> /* ip_defttl */
59 #include <netinet/ip_fw.h>
60 #include <netinet/ipfw/ip_fw_private.h>
61 #include <netinet/tcp_var.h>
62 #include <netinet/udp.h>
64 #include <netinet/ip6.h> /* IN6_ARE_ADDR_EQUAL */
66 #include <netinet6/in6_var.h>
67 #include <netinet6/ip6_var.h>
70 #include <machine/in_cksum.h> /* XXX for in_cksum */
73 #include <security/mac/mac_framework.h>
77 * Description of dynamic rules.
79 * Dynamic rules are stored in lists accessed through a hash table
80 * (ipfw_dyn_v) whose size is curr_dyn_buckets. This value can
81 * be modified through the sysctl variable dyn_buckets which is
82 * updated when the table becomes empty.
84 * XXX currently there is only one list, ipfw_dyn.
86 * When a packet is received, its address fields are first masked
87 * with the mask defined for the rule, then hashed, then matched
88 * against the entries in the corresponding list.
89 * Dynamic rules can be used for different purposes:
91 * + enforcing limits on the number of sessions;
92 * + in-kernel NAT (not implemented yet)
94 * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
95 * measured in seconds and depending on the flags.
97 * The total number of dynamic rules is stored in dyn_count.
98 * The max number of dynamic rules is dyn_max. When we reach
99 * the maximum number of rules we do not create anymore. This is
100 * done to avoid consuming too much memory, but also too much
101 * time when searching on each packet (ideally, we should try instead
102 * to put a limit on the length of the list on each bucket...).
104 * Each dynamic rule holds a pointer to the parent ipfw rule so
105 * we know what action to perform. Dynamic rules are removed when
106 * the parent rule is deleted. XXX we should make them survive.
108 * There are some limitations with dynamic rules -- we do not
109 * obey the 'randomized match', and we do not do multiple
110 * passes through the firewall. XXX check the latter!!!
114 * Static variables followed by global ones
116 static VNET_DEFINE(ipfw_dyn_rule **, ipfw_dyn_v);
117 static VNET_DEFINE(u_int32_t, dyn_buckets);
118 static VNET_DEFINE(u_int32_t, curr_dyn_buckets);
119 static VNET_DEFINE(struct callout, ipfw_timeout);
120 #define V_ipfw_dyn_v VNET(ipfw_dyn_v)
121 #define V_dyn_buckets VNET(dyn_buckets)
122 #define V_curr_dyn_buckets VNET(curr_dyn_buckets)
123 #define V_ipfw_timeout VNET(ipfw_timeout)
125 static uma_zone_t ipfw_dyn_rule_zone;
127 DEFINE_SPINLOCK(ipfw_dyn_mtx);
129 static struct mtx ipfw_dyn_mtx; /* mutex guarding dynamic rules */
132 #define IPFW_DYN_LOCK_INIT() \
133 mtx_init(&ipfw_dyn_mtx, "IPFW dynamic rules", NULL, MTX_DEF)
134 #define IPFW_DYN_LOCK_DESTROY() mtx_destroy(&ipfw_dyn_mtx)
135 #define IPFW_DYN_LOCK() mtx_lock(&ipfw_dyn_mtx)
136 #define IPFW_DYN_UNLOCK() mtx_unlock(&ipfw_dyn_mtx)
137 #define IPFW_DYN_LOCK_ASSERT() mtx_assert(&ipfw_dyn_mtx, MA_OWNED)
140 ipfw_dyn_unlock(void)
146 * Timeouts for various events in handing dynamic rules.
148 static VNET_DEFINE(u_int32_t, dyn_ack_lifetime);
149 static VNET_DEFINE(u_int32_t, dyn_syn_lifetime);
150 static VNET_DEFINE(u_int32_t, dyn_fin_lifetime);
151 static VNET_DEFINE(u_int32_t, dyn_rst_lifetime);
152 static VNET_DEFINE(u_int32_t, dyn_udp_lifetime);
153 static VNET_DEFINE(u_int32_t, dyn_short_lifetime);
155 #define V_dyn_ack_lifetime VNET(dyn_ack_lifetime)
156 #define V_dyn_syn_lifetime VNET(dyn_syn_lifetime)
157 #define V_dyn_fin_lifetime VNET(dyn_fin_lifetime)
158 #define V_dyn_rst_lifetime VNET(dyn_rst_lifetime)
159 #define V_dyn_udp_lifetime VNET(dyn_udp_lifetime)
160 #define V_dyn_short_lifetime VNET(dyn_short_lifetime)
163 * Keepalives are sent if dyn_keepalive is set. They are sent every
164 * dyn_keepalive_period seconds, in the last dyn_keepalive_interval
165 * seconds of lifetime of a rule.
166 * dyn_rst_lifetime and dyn_fin_lifetime should be strictly lower
167 * than dyn_keepalive_period.
170 static VNET_DEFINE(u_int32_t, dyn_keepalive_interval);
171 static VNET_DEFINE(u_int32_t, dyn_keepalive_period);
172 static VNET_DEFINE(u_int32_t, dyn_keepalive);
174 #define V_dyn_keepalive_interval VNET(dyn_keepalive_interval)
175 #define V_dyn_keepalive_period VNET(dyn_keepalive_period)
176 #define V_dyn_keepalive VNET(dyn_keepalive)
178 static VNET_DEFINE(u_int32_t, dyn_count); /* # of dynamic rules */
179 static VNET_DEFINE(u_int32_t, dyn_max); /* max # of dynamic rules */
181 #define V_dyn_count VNET(dyn_count)
182 #define V_dyn_max VNET(dyn_max)
188 SYSCTL_DECL(_net_inet_ip_fw);
189 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_buckets,
190 CTLFLAG_RW, &VNET_NAME(dyn_buckets), 0,
191 "Number of dyn. buckets");
192 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, curr_dyn_buckets,
193 CTLFLAG_RD, &VNET_NAME(curr_dyn_buckets), 0,
194 "Current Number of dyn. buckets");
195 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_count,
196 CTLFLAG_RD, &VNET_NAME(dyn_count), 0,
197 "Number of dyn. rules");
198 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_max,
199 CTLFLAG_RW, &VNET_NAME(dyn_max), 0,
200 "Max number of dyn. rules");
201 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_ack_lifetime,
202 CTLFLAG_RW, &VNET_NAME(dyn_ack_lifetime), 0,
203 "Lifetime of dyn. rules for acks");
204 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_syn_lifetime,
205 CTLFLAG_RW, &VNET_NAME(dyn_syn_lifetime), 0,
206 "Lifetime of dyn. rules for syn");
207 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_fin_lifetime,
208 CTLFLAG_RW, &VNET_NAME(dyn_fin_lifetime), 0,
209 "Lifetime of dyn. rules for fin");
210 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_rst_lifetime,
211 CTLFLAG_RW, &VNET_NAME(dyn_rst_lifetime), 0,
212 "Lifetime of dyn. rules for rst");
213 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_udp_lifetime,
214 CTLFLAG_RW, &VNET_NAME(dyn_udp_lifetime), 0,
215 "Lifetime of dyn. rules for UDP");
216 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_short_lifetime,
217 CTLFLAG_RW, &VNET_NAME(dyn_short_lifetime), 0,
218 "Lifetime of dyn. rules for other situations");
219 SYSCTL_VNET_UINT(_net_inet_ip_fw, OID_AUTO, dyn_keepalive,
220 CTLFLAG_RW, &VNET_NAME(dyn_keepalive), 0,
221 "Enable keepalives for dyn. rules");
225 #endif /* SYSCTL_NODE */
229 hash_packet6(struct ipfw_flow_id *id)
232 i = (id->dst_ip6.__u6_addr.__u6_addr32[2]) ^
233 (id->dst_ip6.__u6_addr.__u6_addr32[3]) ^
234 (id->src_ip6.__u6_addr.__u6_addr32[2]) ^
235 (id->src_ip6.__u6_addr.__u6_addr32[3]) ^
236 (id->dst_port) ^ (id->src_port);
241 * IMPORTANT: the hash function for dynamic rules must be commutative
242 * in source and destination (ip,port), because rules are bidirectional
243 * and we want to find both in the same bucket.
246 hash_packet(struct ipfw_flow_id *id)
251 if (IS_IP6_FLOW_ID(id))
252 i = hash_packet6(id);
255 i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
256 i &= (V_curr_dyn_buckets - 1);
261 unlink_dyn_rule_print(struct ipfw_flow_id *id)
265 char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN];
267 char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
271 if (IS_IP6_FLOW_ID(id)) {
272 ip6_sprintf(src, &id->src_ip6);
273 ip6_sprintf(dst, &id->dst_ip6);
277 da.s_addr = htonl(id->src_ip);
278 inet_ntoa_r(da, src);
279 da.s_addr = htonl(id->dst_ip);
280 inet_ntoa_r(da, dst);
282 printf("ipfw: unlink entry %s %d -> %s %d, %d left\n",
283 src, id->src_port, dst, id->dst_port, V_dyn_count - 1);
287 * unlink a dynamic rule from a chain. prev is a pointer to
288 * the previous one, q is a pointer to the rule to delete,
289 * head is a pointer to the head of the queue.
290 * Modifies q and potentially also head.
292 #define UNLINK_DYN_RULE(prev, head, q) { \
293 ipfw_dyn_rule *old_q = q; \
295 /* remove a refcount to the parent */ \
296 if (q->dyn_type == O_LIMIT) \
297 q->parent->count--; \
298 DEB(unlink_dyn_rule_print(&q->id);) \
300 prev->next = q = q->next; \
302 head = q = q->next; \
304 uma_zfree(ipfw_dyn_rule_zone, old_q); }
306 #define TIME_LEQ(a,b) ((int)((a)-(b)) <= 0)
309 * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
311 * If keep_me == NULL, rules are deleted even if not expired,
312 * otherwise only expired rules are removed.
314 * The value of the second parameter is also used to point to identify
315 * a rule we absolutely do not want to remove (e.g. because we are
316 * holding a reference to it -- this is the case with O_LIMIT_PARENT
317 * rules). The pointer is only used for comparison, so any non-null
321 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
323 static u_int32_t last_remove = 0;
325 #define FORCE (keep_me == NULL)
327 ipfw_dyn_rule *prev, *q;
328 int i, pass = 0, max_pass = 0;
330 IPFW_DYN_LOCK_ASSERT();
332 if (V_ipfw_dyn_v == NULL || V_dyn_count == 0)
334 /* do not expire more than once per second, it is useless */
335 if (!FORCE && last_remove == time_uptime)
337 last_remove = time_uptime;
340 * because O_LIMIT refer to parent rules, during the first pass only
341 * remove child and mark any pending LIMIT_PARENT, and remove
342 * them in a second pass.
345 for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
346 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q ; ) {
348 * Logic can become complex here, so we split tests.
352 if (rule != NULL && rule != q->rule)
353 goto next; /* not the one we are looking for */
354 if (q->dyn_type == O_LIMIT_PARENT) {
356 * handle parent in the second pass,
357 * record we need one.
362 if (FORCE && q->count != 0 ) {
363 /* XXX should not happen! */
364 printf("ipfw: OUCH! cannot remove rule,"
365 " count %d\n", q->count);
369 !TIME_LEQ( q->expire, time_uptime ))
372 if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
373 UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
381 if (pass++ < max_pass)
386 ipfw_remove_dyn_children(struct ip_fw *rule)
389 remove_dyn_rule(rule, NULL /* force removal */);
394 * Lookup a dynamic rule, locked version.
396 static ipfw_dyn_rule *
397 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
401 * Stateful ipfw extensions.
402 * Lookup into dynamic session queue.
404 #define MATCH_REVERSE 0
405 #define MATCH_FORWARD 1
407 #define MATCH_UNKNOWN 3
408 int i, dir = MATCH_NONE;
409 ipfw_dyn_rule *prev, *q = NULL;
411 IPFW_DYN_LOCK_ASSERT();
413 if (V_ipfw_dyn_v == NULL)
414 goto done; /* not found */
415 i = hash_packet(pkt);
416 for (prev = NULL, q = V_ipfw_dyn_v[i]; q != NULL;) {
417 if (q->dyn_type == O_LIMIT_PARENT && q->count)
419 if (TIME_LEQ(q->expire, time_uptime)) { /* expire entry */
420 UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
423 if (pkt->proto != q->id.proto || q->dyn_type == O_LIMIT_PARENT)
426 if (IS_IP6_FLOW_ID(pkt)) {
427 if (IN6_ARE_ADDR_EQUAL(&pkt->src_ip6, &q->id.src_ip6) &&
428 IN6_ARE_ADDR_EQUAL(&pkt->dst_ip6, &q->id.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, &q->id.dst_ip6) &&
435 IN6_ARE_ADDR_EQUAL(&pkt->dst_ip6, &q->id.src_ip6) &&
436 pkt->src_port == q->id.dst_port &&
437 pkt->dst_port == q->id.src_port) {
442 if (pkt->src_ip == q->id.src_ip &&
443 pkt->dst_ip == q->id.dst_ip &&
444 pkt->src_port == q->id.src_port &&
445 pkt->dst_port == q->id.dst_port) {
449 if (pkt->src_ip == q->id.dst_ip &&
450 pkt->dst_ip == q->id.src_ip &&
451 pkt->src_port == q->id.dst_port &&
452 pkt->dst_port == q->id.src_port) {
462 goto done; /* q = NULL, not found */
464 if (prev != NULL) { /* found and not in front */
465 prev->next = q->next;
466 q->next = V_ipfw_dyn_v[i];
469 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
471 u_char flags = pkt->_flags & (TH_FIN | TH_SYN | TH_RST);
473 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
474 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
475 #define TCP_FLAGS (TH_FLAGS | (TH_FLAGS << 8))
476 #define ACK_FWD 0x10000 /* fwd ack seen */
477 #define ACK_REV 0x20000 /* rev ack seen */
479 q->state |= (dir == MATCH_FORWARD) ? flags : (flags << 8);
480 switch (q->state & TCP_FLAGS) {
481 case TH_SYN: /* opening */
482 q->expire = time_uptime + V_dyn_syn_lifetime;
485 case BOTH_SYN: /* move to established */
486 case BOTH_SYN | TH_FIN: /* one side tries to close */
487 case BOTH_SYN | (TH_FIN << 8):
488 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
492 ack = ntohl(tcp->th_ack);
493 if (dir == MATCH_FORWARD) {
494 if (q->ack_fwd == 0 ||
495 _SEQ_GE(ack, q->ack_fwd)) {
500 if (q->ack_rev == 0 ||
501 _SEQ_GE(ack, q->ack_rev)) {
506 if ((q->state & (ACK_FWD | ACK_REV)) ==
507 (ACK_FWD | ACK_REV)) {
508 q->expire = time_uptime + V_dyn_ack_lifetime;
509 q->state &= ~(ACK_FWD | ACK_REV);
513 case BOTH_SYN | BOTH_FIN: /* both sides closed */
514 if (V_dyn_fin_lifetime >= V_dyn_keepalive_period)
515 V_dyn_fin_lifetime = V_dyn_keepalive_period - 1;
516 q->expire = time_uptime + V_dyn_fin_lifetime;
522 * reset or some invalid combination, but can also
523 * occur if we use keep-state the wrong way.
525 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
526 printf("invalid state: 0x%x\n", q->state);
528 if (V_dyn_rst_lifetime >= V_dyn_keepalive_period)
529 V_dyn_rst_lifetime = V_dyn_keepalive_period - 1;
530 q->expire = time_uptime + V_dyn_rst_lifetime;
533 } else if (pkt->proto == IPPROTO_UDP) {
534 q->expire = time_uptime + V_dyn_udp_lifetime;
536 /* other protocols */
537 q->expire = time_uptime + V_dyn_short_lifetime;
540 if (match_direction != NULL)
541 *match_direction = dir;
546 ipfw_lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
552 q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
555 /* NB: return table locked when q is not NULL */
560 realloc_dynamic_table(void)
562 IPFW_DYN_LOCK_ASSERT();
565 * Try reallocation, make sure we have a power of 2 and do
566 * not allow more than 64k entries. In case of overflow,
570 if (V_dyn_buckets > 65536)
571 V_dyn_buckets = 1024;
572 if ((V_dyn_buckets & (V_dyn_buckets-1)) != 0) { /* not a power of 2 */
573 V_dyn_buckets = V_curr_dyn_buckets; /* reset */
576 V_curr_dyn_buckets = V_dyn_buckets;
577 if (V_ipfw_dyn_v != NULL)
578 free(V_ipfw_dyn_v, M_IPFW);
580 V_ipfw_dyn_v = malloc(V_curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
581 M_IPFW, M_NOWAIT | M_ZERO);
582 if (V_ipfw_dyn_v != NULL || V_curr_dyn_buckets <= 2)
584 V_curr_dyn_buckets /= 2;
589 * Install state of type 'type' for a dynamic session.
590 * The hash table contains two type of rules:
591 * - regular rules (O_KEEP_STATE)
592 * - rules for sessions with limited number of sess per user
593 * (O_LIMIT). When they are created, the parent is
594 * increased by 1, and decreased on delete. In this case,
595 * the third parameter is the parent rule and not the chain.
596 * - "parent" rules for the above (O_LIMIT_PARENT).
598 static ipfw_dyn_rule *
599 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
604 IPFW_DYN_LOCK_ASSERT();
606 if (V_ipfw_dyn_v == NULL ||
607 (V_dyn_count == 0 && V_dyn_buckets != V_curr_dyn_buckets)) {
608 realloc_dynamic_table();
609 if (V_ipfw_dyn_v == NULL)
610 return NULL; /* failed ! */
614 r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
616 printf ("ipfw: sorry cannot allocate state\n");
620 /* increase refcount on parent, and set pointer */
621 if (dyn_type == O_LIMIT) {
622 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
623 if ( parent->dyn_type != O_LIMIT_PARENT)
624 panic("invalid parent");
631 r->expire = time_uptime + V_dyn_syn_lifetime;
633 r->dyn_type = dyn_type;
634 r->pcnt = r->bcnt = 0;
638 r->next = V_ipfw_dyn_v[i];
644 char src[INET6_ADDRSTRLEN];
645 char dst[INET6_ADDRSTRLEN];
647 char src[INET_ADDRSTRLEN];
648 char dst[INET_ADDRSTRLEN];
652 if (IS_IP6_FLOW_ID(&(r->id))) {
653 ip6_sprintf(src, &r->id.src_ip6);
654 ip6_sprintf(dst, &r->id.dst_ip6);
658 da.s_addr = htonl(r->id.src_ip);
659 inet_ntoa_r(da, src);
660 da.s_addr = htonl(r->id.dst_ip);
661 inet_ntoa_r(da, dst);
663 printf("ipfw: add dyn entry ty %d %s %d -> %s %d, total %d\n",
664 dyn_type, src, r->id.src_port, dst, r->id.dst_port,
671 * lookup dynamic parent rule using pkt and rule as search keys.
672 * If the lookup fails, then install one.
674 static ipfw_dyn_rule *
675 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
680 IPFW_DYN_LOCK_ASSERT();
683 int is_v6 = IS_IP6_FLOW_ID(pkt);
684 i = hash_packet( pkt );
685 for (q = V_ipfw_dyn_v[i] ; q != NULL ; q=q->next)
686 if (q->dyn_type == O_LIMIT_PARENT &&
688 pkt->proto == q->id.proto &&
689 pkt->src_port == q->id.src_port &&
690 pkt->dst_port == q->id.dst_port &&
693 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
695 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
696 &(q->id.dst_ip6))) ||
698 pkt->src_ip == q->id.src_ip &&
699 pkt->dst_ip == q->id.dst_ip)
702 q->expire = time_uptime + V_dyn_short_lifetime;
703 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
707 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
711 * Install dynamic state for rule type cmd->o.opcode
713 * Returns 1 (failure) if state is not installed because of errors or because
714 * session limitations are enforced.
717 ipfw_install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
718 struct ip_fw_args *args, uint32_t tablearg)
724 char src[INET6_ADDRSTRLEN + 2], dst[INET6_ADDRSTRLEN + 2];
726 char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
736 if (IS_IP6_FLOW_ID(&(args->f_id))) {
737 ip6_sprintf(src, &args->f_id.src_ip6);
738 ip6_sprintf(dst, &args->f_id.dst_ip6);
742 da.s_addr = htonl(args->f_id.src_ip);
743 inet_ntoa_r(da, src);
744 da.s_addr = htonl(args->f_id.dst_ip);
745 inet_ntoa_r(da, dst);
747 printf("ipfw: %s: type %d %s %u -> %s %u\n",
748 __func__, cmd->o.opcode, src, args->f_id.src_port,
749 dst, args->f_id.dst_port);
754 q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
756 if (q != NULL) { /* should never occur */
758 if (last_log != time_uptime) {
759 last_log = time_uptime;
760 printf("ipfw: %s: entry already present, done\n",
767 if (V_dyn_count >= V_dyn_max)
768 /* Run out of slots, try to remove any expired rule. */
769 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
771 if (V_dyn_count >= V_dyn_max) {
772 if (last_log != time_uptime) {
773 last_log = time_uptime;
774 printf("ipfw: %s: Too many dynamic rules\n", __func__);
777 return (1); /* cannot install, notify caller */
780 switch (cmd->o.opcode) {
781 case O_KEEP_STATE: /* bidir rule */
782 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
785 case O_LIMIT: { /* limit number of sessions */
786 struct ipfw_flow_id id;
787 ipfw_dyn_rule *parent;
789 uint16_t limit_mask = cmd->limit_mask;
791 conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ?
792 tablearg : cmd->conn_limit;
795 if (cmd->conn_limit == IP_FW_TABLEARG)
796 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
797 "(tablearg)\n", __func__, conn_limit);
799 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
800 __func__, conn_limit);
803 id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
804 id.proto = args->f_id.proto;
805 id.addr_type = args->f_id.addr_type;
806 id.fib = M_GETFIB(args->m);
808 if (IS_IP6_FLOW_ID (&(args->f_id))) {
809 if (limit_mask & DYN_SRC_ADDR)
810 id.src_ip6 = args->f_id.src_ip6;
811 if (limit_mask & DYN_DST_ADDR)
812 id.dst_ip6 = args->f_id.dst_ip6;
814 if (limit_mask & DYN_SRC_ADDR)
815 id.src_ip = args->f_id.src_ip;
816 if (limit_mask & DYN_DST_ADDR)
817 id.dst_ip = args->f_id.dst_ip;
819 if (limit_mask & DYN_SRC_PORT)
820 id.src_port = args->f_id.src_port;
821 if (limit_mask & DYN_DST_PORT)
822 id.dst_port = args->f_id.dst_port;
823 if ((parent = lookup_dyn_parent(&id, rule)) == NULL) {
824 printf("ipfw: %s: add parent failed\n", __func__);
829 if (parent->count >= conn_limit) {
830 /* See if we can remove some expired rule. */
831 remove_dyn_rule(rule, parent);
832 if (parent->count >= conn_limit) {
833 if (V_fw_verbose && last_log != time_uptime) {
834 last_log = time_uptime;
837 * XXX IPv6 flows are not
840 if (IS_IP6_FLOW_ID(&(args->f_id))) {
841 char ip6buf[INET6_ADDRSTRLEN];
842 snprintf(src, sizeof(src),
843 "[%s]", ip6_sprintf(ip6buf,
844 &args->f_id.src_ip6));
845 snprintf(dst, sizeof(dst),
846 "[%s]", ip6_sprintf(ip6buf,
847 &args->f_id.dst_ip6));
852 htonl(args->f_id.src_ip);
853 inet_ntoa_r(da, src);
855 htonl(args->f_id.dst_ip);
856 inet_ntoa_r(da, dst);
858 log(LOG_SECURITY | LOG_DEBUG,
859 "ipfw: %d %s %s:%u -> %s:%u, %s\n",
860 parent->rule->rulenum,
862 src, (args->f_id.src_port),
863 dst, (args->f_id.dst_port),
870 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
874 printf("ipfw: %s: unknown dynamic rule type %u\n",
875 __func__, cmd->o.opcode);
880 /* XXX just set lifetime */
881 lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
888 * Generate a TCP packet, containing either a RST or a keepalive.
889 * When flags & TH_RST, we are sending a RST packet, because of a
890 * "reset" action matched the packet.
891 * Otherwise we are sending a keepalive, and flags & TH_
892 * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
893 * so that MAC can label the reply appropriately.
896 ipfw_send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
897 u_int32_t ack, int flags)
904 struct ip *h = NULL; /* stupid compiler */
906 struct ip6_hdr *h6 = NULL;
908 struct tcphdr *th = NULL;
910 MGETHDR(m, M_DONTWAIT, MT_DATA);
914 M_SETFIB(m, id->fib);
917 mac_netinet_firewall_reply(replyto, m);
919 mac_netinet_firewall_send(m);
921 (void)replyto; /* don't warn about unused arg */
924 switch (id->addr_type) {
926 len = sizeof(struct ip) + sizeof(struct tcphdr);
930 len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
938 dir = ((flags & (TH_SYN | TH_RST)) == TH_SYN);
940 m->m_data += max_linkhdr;
941 m->m_flags |= M_SKIP_FIREWALL;
942 m->m_pkthdr.len = m->m_len = len;
943 m->m_pkthdr.rcvif = NULL;
944 bzero(m->m_data, len);
946 switch (id->addr_type) {
948 h = mtod(m, struct ip *);
950 /* prepare for checksum */
951 h->ip_p = IPPROTO_TCP;
952 h->ip_len = htons(sizeof(struct tcphdr));
954 h->ip_src.s_addr = htonl(id->src_ip);
955 h->ip_dst.s_addr = htonl(id->dst_ip);
957 h->ip_src.s_addr = htonl(id->dst_ip);
958 h->ip_dst.s_addr = htonl(id->src_ip);
961 th = (struct tcphdr *)(h + 1);
965 h6 = mtod(m, struct ip6_hdr *);
967 /* prepare for checksum */
968 h6->ip6_nxt = IPPROTO_TCP;
969 h6->ip6_plen = htons(sizeof(struct tcphdr));
971 h6->ip6_src = id->src_ip6;
972 h6->ip6_dst = id->dst_ip6;
974 h6->ip6_src = id->dst_ip6;
975 h6->ip6_dst = id->src_ip6;
978 th = (struct tcphdr *)(h6 + 1);
984 th->th_sport = htons(id->src_port);
985 th->th_dport = htons(id->dst_port);
987 th->th_sport = htons(id->dst_port);
988 th->th_dport = htons(id->src_port);
990 th->th_off = sizeof(struct tcphdr) >> 2;
992 if (flags & TH_RST) {
993 if (flags & TH_ACK) {
994 th->th_seq = htonl(ack);
995 th->th_flags = TH_RST;
999 th->th_ack = htonl(seq);
1000 th->th_flags = TH_RST | TH_ACK;
1004 * Keepalive - use caller provided sequence numbers
1006 th->th_seq = htonl(seq);
1007 th->th_ack = htonl(ack);
1008 th->th_flags = TH_ACK;
1011 switch (id->addr_type) {
1013 th->th_sum = in_cksum(m, len);
1015 /* finish the ip header */
1017 h->ip_hl = sizeof(*h) >> 2;
1018 h->ip_tos = IPTOS_LOWDELAY;
1020 /* ip_len must be in host format for ip_output */
1022 h->ip_ttl = V_ip_defttl;
1027 th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(*h6),
1028 sizeof(struct tcphdr));
1030 /* finish the ip6 header */
1031 h6->ip6_vfc |= IPV6_VERSION;
1032 h6->ip6_hlim = IPV6_DEFHLIM;
1038 #endif /* __FreeBSD__ */
1042 * This procedure is only used to handle keepalives. It is invoked
1043 * every dyn_keepalive_period
1046 ipfw_tick(void * vnetx)
1048 struct mbuf *m0, *m, *mnext, **mtailp;
1050 struct mbuf *m6, **m6_tailp;
1055 struct vnet *vp = vnetx;
1059 if (V_dyn_keepalive == 0 || V_ipfw_dyn_v == NULL || V_dyn_count == 0)
1063 * We make a chain of packets to go out here -- not deferring
1064 * until after we drop the IPFW dynamic rule lock would result
1065 * in a lock order reversal with the normal packet input -> ipfw
1075 for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
1076 for (q = V_ipfw_dyn_v[i] ; q ; q = q->next ) {
1077 if (q->dyn_type == O_LIMIT_PARENT)
1079 if (q->id.proto != IPPROTO_TCP)
1081 if ( (q->state & BOTH_SYN) != BOTH_SYN)
1083 if (TIME_LEQ(time_uptime + V_dyn_keepalive_interval,
1085 continue; /* too early */
1086 if (TIME_LEQ(q->expire, time_uptime))
1087 continue; /* too late, rule expired */
1089 m = (q->state & ACK_REV) ? NULL :
1090 ipfw_send_pkt(NULL, &(q->id), q->ack_rev - 1,
1091 q->ack_fwd, TH_SYN);
1092 mnext = (q->state & ACK_FWD) ? NULL :
1093 ipfw_send_pkt(NULL, &(q->id), q->ack_fwd - 1,
1096 switch (q->id.addr_type) {
1100 mtailp = &(*mtailp)->m_nextpkt;
1102 if (mnext != NULL) {
1104 mtailp = &(*mtailp)->m_nextpkt;
1111 m6_tailp = &(*m6_tailp)->m_nextpkt;
1113 if (mnext != NULL) {
1115 m6_tailp = &(*m6_tailp)->m_nextpkt;
1123 for (m = m0; m != NULL; m = mnext) {
1124 mnext = m->m_nextpkt;
1125 m->m_nextpkt = NULL;
1126 ip_output(m, NULL, NULL, 0, NULL, NULL);
1129 for (m = m6; m != NULL; m = mnext) {
1130 mnext = m->m_nextpkt;
1131 m->m_nextpkt = NULL;
1132 ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
1136 callout_reset(&V_ipfw_timeout, V_dyn_keepalive_period * hz,
1142 ipfw_dyn_attach(void)
1144 ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
1145 sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
1148 IPFW_DYN_LOCK_INIT();
1152 ipfw_dyn_detach(void)
1154 uma_zdestroy(ipfw_dyn_rule_zone);
1155 IPFW_DYN_LOCK_DESTROY();
1161 V_ipfw_dyn_v = NULL;
1162 V_dyn_buckets = 256; /* must be power of 2 */
1163 V_curr_dyn_buckets = 256; /* must be power of 2 */
1165 V_dyn_ack_lifetime = 300;
1166 V_dyn_syn_lifetime = 20;
1167 V_dyn_fin_lifetime = 1;
1168 V_dyn_rst_lifetime = 1;
1169 V_dyn_udp_lifetime = 10;
1170 V_dyn_short_lifetime = 5;
1172 V_dyn_keepalive_interval = 20;
1173 V_dyn_keepalive_period = 5;
1174 V_dyn_keepalive = 1; /* do send keepalives */
1176 V_dyn_max = 4096; /* max # of dynamic rules */
1177 callout_init(&V_ipfw_timeout, CALLOUT_MPSAFE);
1178 callout_reset(&V_ipfw_timeout, hz, ipfw_tick, curvnet);
1182 ipfw_dyn_uninit(int pass)
1185 callout_drain(&V_ipfw_timeout);
1187 if (V_ipfw_dyn_v != NULL)
1188 free(V_ipfw_dyn_v, M_IPFW);
1195 return (V_ipfw_dyn_v == NULL) ? 0 :
1196 (V_dyn_count * sizeof(ipfw_dyn_rule));
1200 ipfw_get_dynamic(char **pbp, const char *ep)
1202 ipfw_dyn_rule *p, *last = NULL;
1206 if (V_ipfw_dyn_v == NULL)
1211 for (i = 0 ; i < V_curr_dyn_buckets; i++)
1212 for (p = V_ipfw_dyn_v[i] ; p != NULL; p = p->next) {
1213 if (bp + sizeof *p <= ep) {
1214 ipfw_dyn_rule *dst =
1215 (ipfw_dyn_rule *)bp;
1216 bcopy(p, dst, sizeof *p);
1217 bcopy(&(p->rule->rulenum), &(dst->rule),
1218 sizeof(p->rule->rulenum));
1220 * store set number into high word of
1221 * dst->rule pointer.
1223 bcopy(&(p->rule->set),
1224 (char *)&dst->rule +
1225 sizeof(p->rule->rulenum),
1226 sizeof(p->rule->set));
1228 * store a non-null value in "next".
1229 * The userland code will interpret a
1230 * NULL here as a marker
1231 * for the last dynamic rule.
1233 bcopy(&dst, &dst->next, sizeof(dst));
1236 TIME_LEQ(dst->expire, time_uptime) ?
1237 0 : dst->expire - time_uptime ;
1238 bp += sizeof(ipfw_dyn_rule);
1242 if (last != NULL) /* mark last dynamic rule */
1243 bzero(&last->next, sizeof(last));