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 &&
424 q->dyn_type != O_LIMIT_PARENT) {
425 if (IS_IP6_FLOW_ID(pkt)) {
426 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
428 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
430 pkt->src_port == q->id.src_port &&
431 pkt->dst_port == q->id.dst_port ) {
435 if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
437 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
439 pkt->src_port == q->id.dst_port &&
440 pkt->dst_port == q->id.src_port ) {
445 if (pkt->src_ip == q->id.src_ip &&
446 pkt->dst_ip == q->id.dst_ip &&
447 pkt->src_port == q->id.src_port &&
448 pkt->dst_port == q->id.dst_port ) {
452 if (pkt->src_ip == q->id.dst_ip &&
453 pkt->dst_ip == q->id.src_ip &&
454 pkt->src_port == q->id.dst_port &&
455 pkt->dst_port == q->id.src_port ) {
466 goto done; /* q = NULL, not found */
468 if ( prev != NULL) { /* found and not in front */
469 prev->next = q->next;
470 q->next = V_ipfw_dyn_v[i];
473 if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
474 u_char flags = pkt->_flags & (TH_FIN|TH_SYN|TH_RST);
476 #define BOTH_SYN (TH_SYN | (TH_SYN << 8))
477 #define BOTH_FIN (TH_FIN | (TH_FIN << 8))
478 q->state |= (dir == MATCH_FORWARD ) ? flags : (flags << 8);
480 case TH_SYN: /* opening */
481 q->expire = time_uptime + V_dyn_syn_lifetime;
484 case BOTH_SYN: /* move to established */
485 case BOTH_SYN | TH_FIN : /* one side tries to close */
486 case BOTH_SYN | (TH_FIN << 8) :
488 #define _SEQ_GE(a,b) ((int)(a) - (int)(b) >= 0)
489 u_int32_t ack = ntohl(tcp->th_ack);
490 if (dir == MATCH_FORWARD) {
491 if (q->ack_fwd == 0 || _SEQ_GE(ack, q->ack_fwd))
493 else { /* ignore out-of-sequence */
497 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
499 else { /* ignore out-of-sequence */
504 q->expire = time_uptime + V_dyn_ack_lifetime;
507 case BOTH_SYN | BOTH_FIN: /* both sides closed */
508 if (V_dyn_fin_lifetime >= V_dyn_keepalive_period)
509 V_dyn_fin_lifetime = V_dyn_keepalive_period - 1;
510 q->expire = time_uptime + V_dyn_fin_lifetime;
516 * reset or some invalid combination, but can also
517 * occur if we use keep-state the wrong way.
519 if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
520 printf("invalid state: 0x%x\n", q->state);
522 if (V_dyn_rst_lifetime >= V_dyn_keepalive_period)
523 V_dyn_rst_lifetime = V_dyn_keepalive_period - 1;
524 q->expire = time_uptime + V_dyn_rst_lifetime;
527 } else if (pkt->proto == IPPROTO_UDP) {
528 q->expire = time_uptime + V_dyn_udp_lifetime;
530 /* other protocols */
531 q->expire = time_uptime + V_dyn_short_lifetime;
535 *match_direction = dir;
540 ipfw_lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
546 q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
549 /* NB: return table locked when q is not NULL */
554 realloc_dynamic_table(void)
556 IPFW_DYN_LOCK_ASSERT();
559 * Try reallocation, make sure we have a power of 2 and do
560 * not allow more than 64k entries. In case of overflow,
564 if (V_dyn_buckets > 65536)
565 V_dyn_buckets = 1024;
566 if ((V_dyn_buckets & (V_dyn_buckets-1)) != 0) { /* not a power of 2 */
567 V_dyn_buckets = V_curr_dyn_buckets; /* reset */
570 V_curr_dyn_buckets = V_dyn_buckets;
571 if (V_ipfw_dyn_v != NULL)
572 free(V_ipfw_dyn_v, M_IPFW);
574 V_ipfw_dyn_v = malloc(V_curr_dyn_buckets * sizeof(ipfw_dyn_rule *),
575 M_IPFW, M_NOWAIT | M_ZERO);
576 if (V_ipfw_dyn_v != NULL || V_curr_dyn_buckets <= 2)
578 V_curr_dyn_buckets /= 2;
583 * Install state of type 'type' for a dynamic session.
584 * The hash table contains two type of rules:
585 * - regular rules (O_KEEP_STATE)
586 * - rules for sessions with limited number of sess per user
587 * (O_LIMIT). When they are created, the parent is
588 * increased by 1, and decreased on delete. In this case,
589 * the third parameter is the parent rule and not the chain.
590 * - "parent" rules for the above (O_LIMIT_PARENT).
592 static ipfw_dyn_rule *
593 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
598 IPFW_DYN_LOCK_ASSERT();
600 if (V_ipfw_dyn_v == NULL ||
601 (V_dyn_count == 0 && V_dyn_buckets != V_curr_dyn_buckets)) {
602 realloc_dynamic_table();
603 if (V_ipfw_dyn_v == NULL)
604 return NULL; /* failed ! */
608 r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
610 printf ("ipfw: sorry cannot allocate state\n");
614 /* increase refcount on parent, and set pointer */
615 if (dyn_type == O_LIMIT) {
616 ipfw_dyn_rule *parent = (ipfw_dyn_rule *)rule;
617 if ( parent->dyn_type != O_LIMIT_PARENT)
618 panic("invalid parent");
625 r->expire = time_uptime + V_dyn_syn_lifetime;
627 r->dyn_type = dyn_type;
628 r->pcnt = r->bcnt = 0;
632 r->next = V_ipfw_dyn_v[i];
638 char src[INET6_ADDRSTRLEN];
639 char dst[INET6_ADDRSTRLEN];
641 char src[INET_ADDRSTRLEN];
642 char dst[INET_ADDRSTRLEN];
646 if (IS_IP6_FLOW_ID(&(r->id))) {
647 ip6_sprintf(src, &r->id.src_ip6);
648 ip6_sprintf(dst, &r->id.dst_ip6);
652 da.s_addr = htonl(r->id.src_ip);
653 inet_ntoa_r(da, src);
654 da.s_addr = htonl(r->id.dst_ip);
655 inet_ntoa_r(da, dst);
657 printf("ipfw: add dyn entry ty %d %s %d -> %s %d, total %d\n",
658 dyn_type, src, r->id.src_port, dst, r->id.dst_port,
665 * lookup dynamic parent rule using pkt and rule as search keys.
666 * If the lookup fails, then install one.
668 static ipfw_dyn_rule *
669 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
674 IPFW_DYN_LOCK_ASSERT();
677 int is_v6 = IS_IP6_FLOW_ID(pkt);
678 i = hash_packet( pkt );
679 for (q = V_ipfw_dyn_v[i] ; q != NULL ; q=q->next)
680 if (q->dyn_type == O_LIMIT_PARENT &&
682 pkt->proto == q->id.proto &&
683 pkt->src_port == q->id.src_port &&
684 pkt->dst_port == q->id.dst_port &&
687 IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
689 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
690 &(q->id.dst_ip6))) ||
692 pkt->src_ip == q->id.src_ip &&
693 pkt->dst_ip == q->id.dst_ip)
696 q->expire = time_uptime + V_dyn_short_lifetime;
697 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
701 return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
705 * Install dynamic state for rule type cmd->o.opcode
707 * Returns 1 (failure) if state is not installed because of errors or because
708 * session limitations are enforced.
711 ipfw_install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
712 struct ip_fw_args *args, uint32_t tablearg)
718 char src[INET6_ADDRSTRLEN + 2], dst[INET6_ADDRSTRLEN + 2];
720 char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
730 if (IS_IP6_FLOW_ID(&(args->f_id))) {
731 ip6_sprintf(src, &args->f_id.src_ip6);
732 ip6_sprintf(dst, &args->f_id.dst_ip6);
736 da.s_addr = htonl(args->f_id.src_ip);
737 inet_ntoa_r(da, src);
738 da.s_addr = htonl(args->f_id.dst_ip);
739 inet_ntoa_r(da, dst);
741 printf("ipfw: %s: type %d %s %u -> %s %u\n",
742 __func__, cmd->o.opcode, src, args->f_id.src_port,
743 dst, args->f_id.dst_port);
748 q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
750 if (q != NULL) { /* should never occur */
752 if (last_log != time_uptime) {
753 last_log = time_uptime;
754 printf("ipfw: %s: entry already present, done\n",
761 if (V_dyn_count >= V_dyn_max)
762 /* Run out of slots, try to remove any expired rule. */
763 remove_dyn_rule(NULL, (ipfw_dyn_rule *)1);
765 if (V_dyn_count >= V_dyn_max) {
766 if (last_log != time_uptime) {
767 last_log = time_uptime;
768 printf("ipfw: %s: Too many dynamic rules\n", __func__);
771 return (1); /* cannot install, notify caller */
774 switch (cmd->o.opcode) {
775 case O_KEEP_STATE: /* bidir rule */
776 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
779 case O_LIMIT: { /* limit number of sessions */
780 struct ipfw_flow_id id;
781 ipfw_dyn_rule *parent;
783 uint16_t limit_mask = cmd->limit_mask;
785 conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ?
786 tablearg : cmd->conn_limit;
789 if (cmd->conn_limit == IP_FW_TABLEARG)
790 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
791 "(tablearg)\n", __func__, conn_limit);
793 printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
794 __func__, conn_limit);
797 id.dst_ip = id.src_ip = id.dst_port = id.src_port = 0;
798 id.proto = args->f_id.proto;
799 id.addr_type = args->f_id.addr_type;
800 id.fib = M_GETFIB(args->m);
802 if (IS_IP6_FLOW_ID (&(args->f_id))) {
803 if (limit_mask & DYN_SRC_ADDR)
804 id.src_ip6 = args->f_id.src_ip6;
805 if (limit_mask & DYN_DST_ADDR)
806 id.dst_ip6 = args->f_id.dst_ip6;
808 if (limit_mask & DYN_SRC_ADDR)
809 id.src_ip = args->f_id.src_ip;
810 if (limit_mask & DYN_DST_ADDR)
811 id.dst_ip = args->f_id.dst_ip;
813 if (limit_mask & DYN_SRC_PORT)
814 id.src_port = args->f_id.src_port;
815 if (limit_mask & DYN_DST_PORT)
816 id.dst_port = args->f_id.dst_port;
817 if ((parent = lookup_dyn_parent(&id, rule)) == NULL) {
818 printf("ipfw: %s: add parent failed\n", __func__);
823 if (parent->count >= conn_limit) {
824 /* See if we can remove some expired rule. */
825 remove_dyn_rule(rule, parent);
826 if (parent->count >= conn_limit) {
827 if (V_fw_verbose && last_log != time_uptime) {
828 last_log = time_uptime;
831 * XXX IPv6 flows are not
834 if (IS_IP6_FLOW_ID(&(args->f_id))) {
835 char ip6buf[INET6_ADDRSTRLEN];
836 snprintf(src, sizeof(src),
837 "[%s]", ip6_sprintf(ip6buf,
838 &args->f_id.src_ip6));
839 snprintf(dst, sizeof(dst),
840 "[%s]", ip6_sprintf(ip6buf,
841 &args->f_id.dst_ip6));
846 htonl(args->f_id.src_ip);
847 inet_ntoa_r(da, src);
849 htonl(args->f_id.dst_ip);
850 inet_ntoa_r(da, dst);
852 log(LOG_SECURITY | LOG_DEBUG,
853 "ipfw: %d %s %s:%u -> %s:%u, %s\n",
854 parent->rule->rulenum,
856 src, (args->f_id.src_port),
857 dst, (args->f_id.dst_port),
864 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
868 printf("ipfw: %s: unknown dynamic rule type %u\n",
869 __func__, cmd->o.opcode);
874 /* XXX just set lifetime */
875 lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
882 * Generate a TCP packet, containing either a RST or a keepalive.
883 * When flags & TH_RST, we are sending a RST packet, because of a
884 * "reset" action matched the packet.
885 * Otherwise we are sending a keepalive, and flags & TH_
886 * The 'replyto' mbuf is the mbuf being replied to, if any, and is required
887 * so that MAC can label the reply appropriately.
890 ipfw_send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
891 u_int32_t ack, int flags)
893 struct mbuf *m = NULL; /* stupid compiler */
895 struct ip *h = NULL; /* stupid compiler */
897 struct ip6_hdr *h6 = NULL;
899 struct tcphdr *th = NULL;
901 MGETHDR(m, M_DONTWAIT, MT_DATA);
905 M_SETFIB(m, id->fib);
908 mac_netinet_firewall_reply(replyto, m);
910 mac_netinet_firewall_send(m);
912 (void)replyto; /* don't warn about unused arg */
915 switch (id->addr_type) {
917 len = sizeof(struct ip) + sizeof(struct tcphdr);
921 len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
929 dir = ((flags & (TH_SYN | TH_RST)) == TH_SYN);
931 m->m_data += max_linkhdr;
932 m->m_flags |= M_SKIP_FIREWALL;
933 m->m_pkthdr.len = m->m_len = len;
934 m->m_pkthdr.rcvif = NULL;
935 bzero(m->m_data, len);
937 switch (id->addr_type) {
939 h = mtod(m, struct ip *);
941 /* prepare for checksum */
942 h->ip_p = IPPROTO_TCP;
943 h->ip_len = htons(sizeof(struct tcphdr));
945 h->ip_src.s_addr = htonl(id->src_ip);
946 h->ip_dst.s_addr = htonl(id->dst_ip);
948 h->ip_src.s_addr = htonl(id->dst_ip);
949 h->ip_dst.s_addr = htonl(id->src_ip);
952 th = (struct tcphdr *)(h + 1);
956 h6 = mtod(m, struct ip6_hdr *);
958 /* prepare for checksum */
959 h6->ip6_nxt = IPPROTO_TCP;
960 h6->ip6_plen = htons(sizeof(struct tcphdr));
962 h6->ip6_src = id->src_ip6;
963 h6->ip6_dst = id->dst_ip6;
965 h6->ip6_src = id->dst_ip6;
966 h6->ip6_dst = id->src_ip6;
969 th = (struct tcphdr *)(h6 + 1);
975 th->th_sport = htons(id->src_port);
976 th->th_dport = htons(id->dst_port);
978 th->th_sport = htons(id->dst_port);
979 th->th_dport = htons(id->src_port);
981 th->th_off = sizeof(struct tcphdr) >> 2;
983 if (flags & TH_RST) {
984 if (flags & TH_ACK) {
985 th->th_seq = htonl(ack);
986 th->th_flags = TH_RST;
990 th->th_ack = htonl(seq);
991 th->th_flags = TH_RST | TH_ACK;
995 * Keepalive - use caller provided sequence numbers
997 th->th_seq = htonl(seq);
998 th->th_ack = htonl(ack);
999 th->th_flags = TH_ACK;
1002 switch (id->addr_type) {
1004 th->th_sum = in_cksum(m, len);
1006 /* finish the ip header */
1008 h->ip_hl = sizeof(*h) >> 2;
1009 h->ip_tos = IPTOS_LOWDELAY;
1011 /* ip_len must be in host format for ip_output */
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;
1032 * This procedure is only used to handle keepalives. It is invoked
1033 * every dyn_keepalive_period
1036 ipfw_tick(void * vnetx)
1038 struct mbuf *m0, *m, *mnext, **mtailp;
1040 struct mbuf *m6, **m6_tailp;
1045 struct vnet *vp = vnetx;
1049 if (V_dyn_keepalive == 0 || V_ipfw_dyn_v == NULL || V_dyn_count == 0)
1053 * We make a chain of packets to go out here -- not deferring
1054 * until after we drop the IPFW dynamic rule lock would result
1055 * in a lock order reversal with the normal packet input -> ipfw
1065 for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
1066 for (q = V_ipfw_dyn_v[i] ; q ; q = q->next ) {
1067 if (q->dyn_type == O_LIMIT_PARENT)
1069 if (q->id.proto != IPPROTO_TCP)
1071 if ( (q->state & BOTH_SYN) != BOTH_SYN)
1073 if (TIME_LEQ(time_uptime + V_dyn_keepalive_interval,
1075 continue; /* too early */
1076 if (TIME_LEQ(q->expire, time_uptime))
1077 continue; /* too late, rule expired */
1079 m = ipfw_send_pkt(NULL, &(q->id), q->ack_rev - 1,
1080 q->ack_fwd, TH_SYN);
1081 mnext = ipfw_send_pkt(NULL, &(q->id), q->ack_fwd - 1,
1084 switch (q->id.addr_type) {
1088 mtailp = &(*mtailp)->m_nextpkt;
1090 if (mnext != NULL) {
1092 mtailp = &(*mtailp)->m_nextpkt;
1099 m6_tailp = &(*m6_tailp)->m_nextpkt;
1101 if (mnext != NULL) {
1103 m6_tailp = &(*m6_tailp)->m_nextpkt;
1113 for (m = mnext = m0; m != NULL; m = mnext) {
1114 mnext = m->m_nextpkt;
1115 m->m_nextpkt = NULL;
1116 ip_output(m, NULL, NULL, 0, NULL, NULL);
1119 for (m = mnext = m6; m != NULL; m = mnext) {
1120 mnext = m->m_nextpkt;
1121 m->m_nextpkt = NULL;
1122 ip6_output(m, NULL, NULL, 0, NULL, NULL, NULL);
1126 callout_reset_on(&V_ipfw_timeout, V_dyn_keepalive_period * hz,
1127 ipfw_tick, vnetx, 0);
1132 ipfw_dyn_attach(void)
1134 ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
1135 sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
1138 IPFW_DYN_LOCK_INIT();
1142 ipfw_dyn_detach(void)
1144 uma_zdestroy(ipfw_dyn_rule_zone);
1145 IPFW_DYN_LOCK_DESTROY();
1151 V_ipfw_dyn_v = NULL;
1152 V_dyn_buckets = 256; /* must be power of 2 */
1153 V_curr_dyn_buckets = 256; /* must be power of 2 */
1155 V_dyn_ack_lifetime = 300;
1156 V_dyn_syn_lifetime = 20;
1157 V_dyn_fin_lifetime = 1;
1158 V_dyn_rst_lifetime = 1;
1159 V_dyn_udp_lifetime = 10;
1160 V_dyn_short_lifetime = 5;
1162 V_dyn_keepalive_interval = 20;
1163 V_dyn_keepalive_period = 5;
1164 V_dyn_keepalive = 1; /* do send keepalives */
1166 V_dyn_max = 4096; /* max # of dynamic rules */
1167 callout_init(&V_ipfw_timeout, CALLOUT_MPSAFE);
1168 callout_reset_on(&V_ipfw_timeout, hz, ipfw_tick, curvnet, 0);
1172 ipfw_dyn_uninit(int pass)
1175 callout_drain(&V_ipfw_timeout);
1177 if (V_ipfw_dyn_v != NULL)
1178 free(V_ipfw_dyn_v, M_IPFW);
1185 return (V_ipfw_dyn_v == NULL) ? 0 :
1186 (V_dyn_count * sizeof(ipfw_dyn_rule));
1190 ipfw_get_dynamic(char **pbp, const char *ep)
1192 ipfw_dyn_rule *p, *last = NULL;
1196 if (V_ipfw_dyn_v == NULL)
1201 for (i = 0 ; i < V_curr_dyn_buckets; i++)
1202 for (p = V_ipfw_dyn_v[i] ; p != NULL; p = p->next) {
1203 if (bp + sizeof *p <= ep) {
1204 ipfw_dyn_rule *dst =
1205 (ipfw_dyn_rule *)bp;
1206 bcopy(p, dst, sizeof *p);
1207 bcopy(&(p->rule->rulenum), &(dst->rule),
1208 sizeof(p->rule->rulenum));
1210 * store set number into high word of
1211 * dst->rule pointer.
1213 bcopy(&(p->rule->set),
1214 (char *)&dst->rule +
1215 sizeof(p->rule->rulenum),
1216 sizeof(p->rule->set));
1218 * store a non-null value in "next".
1219 * The userland code will interpret a
1220 * NULL here as a marker
1221 * for the last dynamic rule.
1223 bcopy(&dst, &dst->next, sizeof(dst));
1226 TIME_LEQ(dst->expire, time_uptime) ?
1227 0 : dst->expire - time_uptime ;
1228 bp += sizeof(ipfw_dyn_rule);
1232 if (last != NULL) /* mark last dynamic rule */
1233 bzero(&last->next, sizeof(last));