]> CyberLeo.Net >> Repos - FreeBSD/releng/9.0.git/blob - sys/netinet/ipfw/ip_fw_dynamic.c
Copy stable/9 to releng/9.0 as part of the FreeBSD 9.0-RELEASE release
[FreeBSD/releng/9.0.git] / sys / netinet / ipfw / ip_fw_dynamic.c
1 /*-
2  * Copyright (c) 2002 Luigi Rizzo, Universita` di Pisa
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
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.
12  *
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
23  * SUCH DAMAGE.
24  */
25
26 #include <sys/cdefs.h>
27 __FBSDID("$FreeBSD$");
28
29 #define        DEB(x)
30 #define        DDB(x) x
31
32 /*
33  * Dynamic rule support for ipfw
34  */
35
36 #include "opt_ipfw.h"
37 #include "opt_inet.h"
38 #ifndef INET
39 #error IPFIREWALL requires INET.
40 #endif /* INET */
41 #include "opt_inet6.h"
42
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/malloc.h>
46 #include <sys/mbuf.h>
47 #include <sys/kernel.h>
48 #include <sys/lock.h>
49 #include <sys/socket.h>
50 #include <sys/sysctl.h>
51 #include <sys/syslog.h>
52 #include <net/ethernet.h> /* for ETHERTYPE_IP */
53 #include <net/if.h>
54 #include <net/vnet.h>
55
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>
63
64 #include <netinet/ip6.h>        /* IN6_ARE_ADDR_EQUAL */
65 #ifdef INET6
66 #include <netinet6/in6_var.h>
67 #include <netinet6/ip6_var.h>
68 #endif
69
70 #include <machine/in_cksum.h>   /* XXX for in_cksum */
71
72 #ifdef MAC
73 #include <security/mac/mac_framework.h>
74 #endif
75
76 /*
77  * Description of dynamic rules.
78  *
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.
83  *
84  * XXX currently there is only one list, ipfw_dyn.
85  *
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:
90  *  + stateful rules;
91  *  + enforcing limits on the number of sessions;
92  *  + in-kernel NAT (not implemented yet)
93  *
94  * The lifetime of dynamic rules is regulated by dyn_*_lifetime,
95  * measured in seconds and depending on the flags.
96  *
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...).
103  *
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.
107  *
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!!!
111  */
112
113 /*
114  * Static variables followed by global ones
115  */
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)
124
125 static uma_zone_t ipfw_dyn_rule_zone;
126 #ifndef __FreeBSD__
127 DEFINE_SPINLOCK(ipfw_dyn_mtx);
128 #else
129 static struct mtx ipfw_dyn_mtx;         /* mutex guarding dynamic rules */
130 #endif
131
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)
138
139 void
140 ipfw_dyn_unlock(void)
141 {
142         IPFW_DYN_UNLOCK();
143 }
144
145 /*
146  * Timeouts for various events in handing dynamic rules.
147  */
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);
154
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)
161
162 /*
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.
168  */
169
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);
173
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)
177
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 */
180
181 #define V_dyn_count                     VNET(dyn_count)
182 #define V_dyn_max                       VNET(dyn_max)
183
184 #ifdef SYSCTL_NODE
185
186 SYSBEGIN(f2)
187
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");
222
223 SYSEND
224
225 #endif /* SYSCTL_NODE */
226
227
228 static __inline int
229 hash_packet6(struct ipfw_flow_id *id)
230 {
231         u_int32_t i;
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);
237         return i;
238 }
239
240 /*
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.
244  */
245 static __inline int
246 hash_packet(struct ipfw_flow_id *id)
247 {
248         u_int32_t i;
249
250 #ifdef INET6
251         if (IS_IP6_FLOW_ID(id)) 
252                 i = hash_packet6(id);
253         else
254 #endif /* INET6 */
255         i = (id->dst_ip) ^ (id->src_ip) ^ (id->dst_port) ^ (id->src_port);
256         i &= (V_curr_dyn_buckets - 1);
257         return i;
258 }
259
260 static __inline void
261 unlink_dyn_rule_print(struct ipfw_flow_id *id)
262 {
263         struct in_addr da;
264 #ifdef INET6
265         char src[INET6_ADDRSTRLEN], dst[INET6_ADDRSTRLEN];
266 #else
267         char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
268 #endif
269
270 #ifdef INET6
271         if (IS_IP6_FLOW_ID(id)) {
272                 ip6_sprintf(src, &id->src_ip6);
273                 ip6_sprintf(dst, &id->dst_ip6);
274         } else
275 #endif
276         {
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);
281         }
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);
284 }
285
286 /**
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.
291  */
292 #define UNLINK_DYN_RULE(prev, head, q) {                                \
293         ipfw_dyn_rule *old_q = q;                                       \
294                                                                         \
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);)                             \
299         if (prev != NULL)                                               \
300                 prev->next = q = q->next;                               \
301         else                                                            \
302                 head = q = q->next;                                     \
303         V_dyn_count--;                                                  \
304         uma_zfree(ipfw_dyn_rule_zone, old_q); }
305
306 #define TIME_LEQ(a,b)       ((int)((a)-(b)) <= 0)
307
308 /**
309  * Remove dynamic rules pointing to "rule", or all of them if rule == NULL.
310  *
311  * If keep_me == NULL, rules are deleted even if not expired,
312  * otherwise only expired rules are removed.
313  *
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
318  * value will do.
319  */
320 static void
321 remove_dyn_rule(struct ip_fw *rule, ipfw_dyn_rule *keep_me)
322 {
323         static u_int32_t last_remove = 0;
324
325 #define FORCE (keep_me == NULL)
326
327         ipfw_dyn_rule *prev, *q;
328         int i, pass = 0, max_pass = 0;
329
330         IPFW_DYN_LOCK_ASSERT();
331
332         if (V_ipfw_dyn_v == NULL || V_dyn_count == 0)
333                 return;
334         /* do not expire more than once per second, it is useless */
335         if (!FORCE && last_remove == time_uptime)
336                 return;
337         last_remove = time_uptime;
338
339         /*
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.
343          */
344 next_pass:
345         for (i = 0 ; i < V_curr_dyn_buckets ; i++) {
346                 for (prev=NULL, q = V_ipfw_dyn_v[i] ; q ; ) {
347                         /*
348                          * Logic can become complex here, so we split tests.
349                          */
350                         if (q == keep_me)
351                                 goto next;
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) {
355                                 /*
356                                  * handle parent in the second pass,
357                                  * record we need one.
358                                  */
359                                 max_pass = 1;
360                                 if (pass == 0)
361                                         goto next;
362                                 if (FORCE && q->count != 0 ) {
363                                         /* XXX should not happen! */
364                                         printf("ipfw: OUCH! cannot remove rule,"
365                                              " count %d\n", q->count);
366                                 }
367                         } else {
368                                 if (!FORCE &&
369                                     !TIME_LEQ( q->expire, time_uptime ))
370                                         goto next;
371                         }
372              if (q->dyn_type != O_LIMIT_PARENT || !q->count) {
373                      UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
374                      continue;
375              }
376 next:
377                         prev=q;
378                         q=q->next;
379                 }
380         }
381         if (pass++ < max_pass)
382                 goto next_pass;
383 }
384
385 void
386 ipfw_remove_dyn_children(struct ip_fw *rule)
387 {
388         IPFW_DYN_LOCK();
389         remove_dyn_rule(rule, NULL /* force removal */);
390         IPFW_DYN_UNLOCK();
391 }
392
393 /**
394  * lookup a dynamic rule, locked version
395  */
396 static ipfw_dyn_rule *
397 lookup_dyn_rule_locked(struct ipfw_flow_id *pkt, int *match_direction,
398     struct tcphdr *tcp)
399 {
400         /*
401          * stateful ipfw extensions.
402          * Lookup into dynamic session queue
403          */
404 #define MATCH_REVERSE   0
405 #define MATCH_FORWARD   1
406 #define MATCH_NONE      2
407 #define MATCH_UNKNOWN   3
408         int i, dir = MATCH_NONE;
409         ipfw_dyn_rule *prev, *q=NULL;
410
411         IPFW_DYN_LOCK_ASSERT();
412
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)
418                         goto next;
419                 if (TIME_LEQ( q->expire, time_uptime)) { /* expire entry */
420                         UNLINK_DYN_RULE(prev, V_ipfw_dyn_v[i], q);
421                         continue;
422                 }
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),
427                                 &(q->id.src_ip6)) &&
428                             IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
429                                 &(q->id.dst_ip6)) &&
430                             pkt->src_port == q->id.src_port &&
431                             pkt->dst_port == q->id.dst_port ) {
432                                 dir = MATCH_FORWARD;
433                                 break;
434                             }
435                             if (IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
436                                     &(q->id.dst_ip6)) &&
437                                 IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
438                                     &(q->id.src_ip6)) &&
439                                 pkt->src_port == q->id.dst_port &&
440                                 pkt->dst_port == q->id.src_port ) {
441                                     dir = MATCH_REVERSE;
442                                     break;
443                             }
444                         } else {
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 ) {
449                                     dir = MATCH_FORWARD;
450                                     break;
451                             }
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 ) {
456                                     dir = MATCH_REVERSE;
457                                     break;
458                             }
459                         }
460                 }
461 next:
462                 prev = q;
463                 q = q->next;
464         }
465         if (q == NULL)
466                 goto done; /* q = NULL, not found */
467
468         if ( prev != NULL) { /* found and not in front */
469                 prev->next = q->next;
470                 q->next = V_ipfw_dyn_v[i];
471                 V_ipfw_dyn_v[i] = q;
472         }
473         if (pkt->proto == IPPROTO_TCP) { /* update state according to flags */
474                 u_char flags = pkt->_flags & (TH_FIN|TH_SYN|TH_RST);
475
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);
479                 switch (q->state) {
480                 case TH_SYN:                            /* opening */
481                         q->expire = time_uptime + V_dyn_syn_lifetime;
482                         break;
483
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) :
487                         if (tcp) {
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))
492                                     q->ack_fwd = ack;
493                                 else { /* ignore out-of-sequence */
494                                     break;
495                                 }
496                             } else {
497                                 if (q->ack_rev == 0 || _SEQ_GE(ack, q->ack_rev))
498                                     q->ack_rev = ack;
499                                 else { /* ignore out-of-sequence */
500                                     break;
501                                 }
502                             }
503                         }
504                         q->expire = time_uptime + V_dyn_ack_lifetime;
505                         break;
506
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;
511                         break;
512
513                 default:
514 #if 0
515                         /*
516                          * reset or some invalid combination, but can also
517                          * occur if we use keep-state the wrong way.
518                          */
519                         if ( (q->state & ((TH_RST << 8)|TH_RST)) == 0)
520                                 printf("invalid state: 0x%x\n", q->state);
521 #endif
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;
525                         break;
526                 }
527         } else if (pkt->proto == IPPROTO_UDP) {
528                 q->expire = time_uptime + V_dyn_udp_lifetime;
529         } else {
530                 /* other protocols */
531                 q->expire = time_uptime + V_dyn_short_lifetime;
532         }
533 done:
534         if (match_direction)
535                 *match_direction = dir;
536         return q;
537 }
538
539 ipfw_dyn_rule *
540 ipfw_lookup_dyn_rule(struct ipfw_flow_id *pkt, int *match_direction,
541     struct tcphdr *tcp)
542 {
543         ipfw_dyn_rule *q;
544
545         IPFW_DYN_LOCK();
546         q = lookup_dyn_rule_locked(pkt, match_direction, tcp);
547         if (q == NULL)
548                 IPFW_DYN_UNLOCK();
549         /* NB: return table locked when q is not NULL */
550         return q;
551 }
552
553 static void
554 realloc_dynamic_table(void)
555 {
556         IPFW_DYN_LOCK_ASSERT();
557
558         /*
559          * Try reallocation, make sure we have a power of 2 and do
560          * not allow more than 64k entries. In case of overflow,
561          * default to 1024.
562          */
563
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 */
568                 return;
569         }
570         V_curr_dyn_buckets = V_dyn_buckets;
571         if (V_ipfw_dyn_v != NULL)
572                 free(V_ipfw_dyn_v, M_IPFW);
573         for (;;) {
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)
577                         break;
578                 V_curr_dyn_buckets /= 2;
579         }
580 }
581
582 /**
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).
591  */
592 static ipfw_dyn_rule *
593 add_dyn_rule(struct ipfw_flow_id *id, u_int8_t dyn_type, struct ip_fw *rule)
594 {
595         ipfw_dyn_rule *r;
596         int i;
597
598         IPFW_DYN_LOCK_ASSERT();
599
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 ! */
605         }
606         i = hash_packet(id);
607
608         r = uma_zalloc(ipfw_dyn_rule_zone, M_NOWAIT | M_ZERO);
609         if (r == NULL) {
610                 printf ("ipfw: sorry cannot allocate state\n");
611                 return NULL;
612         }
613
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");
619                 parent->count++;
620                 r->parent = parent;
621                 rule = parent->rule;
622         }
623
624         r->id = *id;
625         r->expire = time_uptime + V_dyn_syn_lifetime;
626         r->rule = rule;
627         r->dyn_type = dyn_type;
628         r->pcnt = r->bcnt = 0;
629         r->count = 0;
630
631         r->bucket = i;
632         r->next = V_ipfw_dyn_v[i];
633         V_ipfw_dyn_v[i] = r;
634         V_dyn_count++;
635         DEB({
636                 struct in_addr da;
637 #ifdef INET6
638                 char src[INET6_ADDRSTRLEN];
639                 char dst[INET6_ADDRSTRLEN];
640 #else
641                 char src[INET_ADDRSTRLEN];
642                 char dst[INET_ADDRSTRLEN];
643 #endif
644
645 #ifdef INET6
646                 if (IS_IP6_FLOW_ID(&(r->id))) {
647                         ip6_sprintf(src, &r->id.src_ip6);
648                         ip6_sprintf(dst, &r->id.dst_ip6);
649                 } else
650 #endif
651                 {
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);
656                 }
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,
659                     V_dyn_count);
660         })
661         return r;
662 }
663
664 /**
665  * lookup dynamic parent rule using pkt and rule as search keys.
666  * If the lookup fails, then install one.
667  */
668 static ipfw_dyn_rule *
669 lookup_dyn_parent(struct ipfw_flow_id *pkt, struct ip_fw *rule)
670 {
671         ipfw_dyn_rule *q;
672         int i;
673
674         IPFW_DYN_LOCK_ASSERT();
675
676         if (V_ipfw_dyn_v) {
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 &&
681                             rule== q->rule &&
682                             pkt->proto == q->id.proto &&
683                             pkt->src_port == q->id.src_port &&
684                             pkt->dst_port == q->id.dst_port &&
685                             (
686                                 (is_v6 &&
687                                  IN6_ARE_ADDR_EQUAL(&(pkt->src_ip6),
688                                         &(q->id.src_ip6)) &&
689                                  IN6_ARE_ADDR_EQUAL(&(pkt->dst_ip6),
690                                         &(q->id.dst_ip6))) ||
691                                 (!is_v6 &&
692                                  pkt->src_ip == q->id.src_ip &&
693                                  pkt->dst_ip == q->id.dst_ip)
694                             )
695                         ) {
696                                 q->expire = time_uptime + V_dyn_short_lifetime;
697                                 DEB(printf("ipfw: lookup_dyn_parent found 0x%p\n",q);)
698                                 return q;
699                         }
700         }
701         return add_dyn_rule(pkt, O_LIMIT_PARENT, rule);
702 }
703
704 /**
705  * Install dynamic state for rule type cmd->o.opcode
706  *
707  * Returns 1 (failure) if state is not installed because of errors or because
708  * session limitations are enforced.
709  */
710 int
711 ipfw_install_state(struct ip_fw *rule, ipfw_insn_limit *cmd,
712     struct ip_fw_args *args, uint32_t tablearg)
713 {
714         static int last_log;
715         ipfw_dyn_rule *q;
716         struct in_addr da;
717 #ifdef INET6
718         char src[INET6_ADDRSTRLEN + 2], dst[INET6_ADDRSTRLEN + 2];
719 #else
720         char src[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
721 #endif
722
723         src[0] = '\0';
724         dst[0] = '\0';
725
726         IPFW_DYN_LOCK();
727
728         DEB(
729 #ifdef INET6
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);
733         } else
734 #endif
735         {
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);
740         }
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);
744         src[0] = '\0';
745         dst[0] = '\0';
746         )
747
748         q = lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
749
750         if (q != NULL) {        /* should never occur */
751                 DEB(
752                 if (last_log != time_uptime) {
753                         last_log = time_uptime;
754                         printf("ipfw: %s: entry already present, done\n",
755                             __func__);
756                 })
757                 IPFW_DYN_UNLOCK();
758                 return (0);
759         }
760
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);
764
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__);
769                 }
770                 IPFW_DYN_UNLOCK();
771                 return (1);     /* cannot install, notify caller */
772         }
773
774         switch (cmd->o.opcode) {
775         case O_KEEP_STATE:      /* bidir rule */
776                 add_dyn_rule(&args->f_id, O_KEEP_STATE, rule);
777                 break;
778
779         case O_LIMIT: {         /* limit number of sessions */
780                 struct ipfw_flow_id id;
781                 ipfw_dyn_rule *parent;
782                 uint32_t conn_limit;
783                 uint16_t limit_mask = cmd->limit_mask;
784
785                 conn_limit = (cmd->conn_limit == IP_FW_TABLEARG) ?
786                     tablearg : cmd->conn_limit;
787                   
788                 DEB(
789                 if (cmd->conn_limit == IP_FW_TABLEARG)
790                         printf("ipfw: %s: O_LIMIT rule, conn_limit: %u "
791                             "(tablearg)\n", __func__, conn_limit);
792                 else
793                         printf("ipfw: %s: O_LIMIT rule, conn_limit: %u\n",
794                             __func__, conn_limit);
795                 )
796
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);
801
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;
807                 } else {
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;
812                 }
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__);
819                         IPFW_DYN_UNLOCK();
820                         return (1);
821                 }
822
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;
829 #ifdef INET6
830                                         /*
831                                          * XXX IPv6 flows are not
832                                          * supported yet.
833                                          */
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));
842                                         } else
843 #endif
844                                         {
845                                                 da.s_addr =
846                                                     htonl(args->f_id.src_ip);
847                                                 inet_ntoa_r(da, src);
848                                                 da.s_addr =
849                                                     htonl(args->f_id.dst_ip);
850                                                 inet_ntoa_r(da, dst);
851                                         }
852                                         log(LOG_SECURITY | LOG_DEBUG,
853                                             "ipfw: %d %s %s:%u -> %s:%u, %s\n",
854                                             parent->rule->rulenum,
855                                             "drop session",
856                                             src, (args->f_id.src_port),
857                                             dst, (args->f_id.dst_port),
858                                             "too many entries");
859                                 }
860                                 IPFW_DYN_UNLOCK();
861                                 return (1);
862                         }
863                 }
864                 add_dyn_rule(&args->f_id, O_LIMIT, (struct ip_fw *)parent);
865                 break;
866         }
867         default:
868                 printf("ipfw: %s: unknown dynamic rule type %u\n",
869                     __func__, cmd->o.opcode);
870                 IPFW_DYN_UNLOCK();
871                 return (1);
872         }
873
874         /* XXX just set lifetime */
875         lookup_dyn_rule_locked(&args->f_id, NULL, NULL);
876
877         IPFW_DYN_UNLOCK();
878         return (0);
879 }
880
881 /*
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.
888  */
889 struct mbuf *
890 ipfw_send_pkt(struct mbuf *replyto, struct ipfw_flow_id *id, u_int32_t seq,
891     u_int32_t ack, int flags)
892 {
893         struct mbuf *m = NULL;          /* stupid compiler */
894         int len, dir;
895         struct ip *h = NULL;            /* stupid compiler */
896 #ifdef INET6
897         struct ip6_hdr *h6 = NULL;
898 #endif
899         struct tcphdr *th = NULL;
900
901         MGETHDR(m, M_DONTWAIT, MT_DATA);
902         if (m == NULL)
903                 return (NULL);
904
905         M_SETFIB(m, id->fib);
906 #ifdef MAC
907         if (replyto != NULL)
908                 mac_netinet_firewall_reply(replyto, m);
909         else
910                 mac_netinet_firewall_send(m);
911 #else
912         (void)replyto;          /* don't warn about unused arg */
913 #endif
914
915         switch (id->addr_type) {
916         case 4:
917                 len = sizeof(struct ip) + sizeof(struct tcphdr);
918                 break;
919 #ifdef INET6
920         case 6:
921                 len = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
922                 break;
923 #endif
924         default:
925                 /* XXX: log me?!? */
926                 FREE_PKT(m);
927                 return (NULL);
928         }
929         dir = ((flags & (TH_SYN | TH_RST)) == TH_SYN);
930
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);
936
937         switch (id->addr_type) {
938         case 4:
939                 h = mtod(m, struct ip *);
940
941                 /* prepare for checksum */
942                 h->ip_p = IPPROTO_TCP;
943                 h->ip_len = htons(sizeof(struct tcphdr));
944                 if (dir) {
945                         h->ip_src.s_addr = htonl(id->src_ip);
946                         h->ip_dst.s_addr = htonl(id->dst_ip);
947                 } else {
948                         h->ip_src.s_addr = htonl(id->dst_ip);
949                         h->ip_dst.s_addr = htonl(id->src_ip);
950                 }
951
952                 th = (struct tcphdr *)(h + 1);
953                 break;
954 #ifdef INET6
955         case 6:
956                 h6 = mtod(m, struct ip6_hdr *);
957
958                 /* prepare for checksum */
959                 h6->ip6_nxt = IPPROTO_TCP;
960                 h6->ip6_plen = htons(sizeof(struct tcphdr));
961                 if (dir) {
962                         h6->ip6_src = id->src_ip6;
963                         h6->ip6_dst = id->dst_ip6;
964                 } else {
965                         h6->ip6_src = id->dst_ip6;
966                         h6->ip6_dst = id->src_ip6;
967                 }
968
969                 th = (struct tcphdr *)(h6 + 1);
970                 break;
971 #endif
972         }
973
974         if (dir) {
975                 th->th_sport = htons(id->src_port);
976                 th->th_dport = htons(id->dst_port);
977         } else {
978                 th->th_sport = htons(id->dst_port);
979                 th->th_dport = htons(id->src_port);
980         }
981         th->th_off = sizeof(struct tcphdr) >> 2;
982
983         if (flags & TH_RST) {
984                 if (flags & TH_ACK) {
985                         th->th_seq = htonl(ack);
986                         th->th_flags = TH_RST;
987                 } else {
988                         if (flags & TH_SYN)
989                                 seq++;
990                         th->th_ack = htonl(seq);
991                         th->th_flags = TH_RST | TH_ACK;
992                 }
993         } else {
994                 /*
995                  * Keepalive - use caller provided sequence numbers
996                  */
997                 th->th_seq = htonl(seq);
998                 th->th_ack = htonl(ack);
999                 th->th_flags = TH_ACK;
1000         }
1001
1002         switch (id->addr_type) {
1003         case 4:
1004                 th->th_sum = in_cksum(m, len);
1005
1006                 /* finish the ip header */
1007                 h->ip_v = 4;
1008                 h->ip_hl = sizeof(*h) >> 2;
1009                 h->ip_tos = IPTOS_LOWDELAY;
1010                 h->ip_off = 0;
1011                 /* ip_len must be in host format for ip_output */
1012                 h->ip_len = len;
1013                 h->ip_ttl = V_ip_defttl;
1014                 h->ip_sum = 0;
1015                 break;
1016 #ifdef INET6
1017         case 6:
1018                 th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(*h6),
1019                     sizeof(struct tcphdr));
1020
1021                 /* finish the ip6 header */
1022                 h6->ip6_vfc |= IPV6_VERSION;
1023                 h6->ip6_hlim = IPV6_DEFHLIM;
1024                 break;
1025 #endif
1026         }
1027
1028         return (m);
1029 }
1030
1031 /*
1032  * This procedure is only used to handle keepalives. It is invoked
1033  * every dyn_keepalive_period
1034  */
1035 static void
1036 ipfw_tick(void * vnetx) 
1037 {
1038         struct mbuf *m0, *m, *mnext, **mtailp;
1039 #ifdef INET6
1040         struct mbuf *m6, **m6_tailp;
1041 #endif
1042         int i;
1043         ipfw_dyn_rule *q;
1044 #ifdef VIMAGE
1045         struct vnet *vp = vnetx;
1046 #endif
1047
1048         CURVNET_SET(vp);
1049         if (V_dyn_keepalive == 0 || V_ipfw_dyn_v == NULL || V_dyn_count == 0)
1050                 goto done;
1051
1052         /*
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
1056          * call stack.
1057          */
1058         m0 = NULL;
1059         mtailp = &m0;
1060 #ifdef INET6
1061         m6 = NULL;
1062         m6_tailp = &m6;
1063 #endif
1064         IPFW_DYN_LOCK();
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)
1068                                 continue;
1069                         if (q->id.proto != IPPROTO_TCP)
1070                                 continue;
1071                         if ( (q->state & BOTH_SYN) != BOTH_SYN)
1072                                 continue;
1073                         if (TIME_LEQ(time_uptime + V_dyn_keepalive_interval,
1074                             q->expire))
1075                                 continue;       /* too early */
1076                         if (TIME_LEQ(q->expire, time_uptime))
1077                                 continue;       /* too late, rule expired */
1078
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,
1082                                 q->ack_rev, 0);
1083
1084                         switch (q->id.addr_type) {
1085                         case 4:
1086                                 if (m != NULL) {
1087                                         *mtailp = m;
1088                                         mtailp = &(*mtailp)->m_nextpkt;
1089                                 }
1090                                 if (mnext != NULL) {
1091                                         *mtailp = mnext;
1092                                         mtailp = &(*mtailp)->m_nextpkt;
1093                                 }
1094                                 break;
1095 #ifdef INET6
1096                         case 6:
1097                                 if (m != NULL) {
1098                                         *m6_tailp = m;
1099                                         m6_tailp = &(*m6_tailp)->m_nextpkt;
1100                                 }
1101                                 if (mnext != NULL) {
1102                                         *m6_tailp = mnext;
1103                                         m6_tailp = &(*m6_tailp)->m_nextpkt;
1104                                 }
1105                                 break;
1106 #endif
1107                         }
1108
1109                         m = mnext = NULL;
1110                 }
1111         }
1112         IPFW_DYN_UNLOCK();
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);
1117         }
1118 #ifdef INET6
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);
1123         }
1124 #endif
1125 done:
1126         callout_reset_on(&V_ipfw_timeout, V_dyn_keepalive_period * hz,
1127                       ipfw_tick, vnetx, 0);
1128         CURVNET_RESTORE();
1129 }
1130
1131 void
1132 ipfw_dyn_attach(void)
1133 {
1134         ipfw_dyn_rule_zone = uma_zcreate("IPFW dynamic rule",
1135             sizeof(ipfw_dyn_rule), NULL, NULL, NULL, NULL,
1136             UMA_ALIGN_PTR, 0);
1137
1138         IPFW_DYN_LOCK_INIT();
1139 }
1140
1141 void
1142 ipfw_dyn_detach(void)
1143 {
1144         uma_zdestroy(ipfw_dyn_rule_zone);
1145         IPFW_DYN_LOCK_DESTROY();
1146 }
1147
1148 void
1149 ipfw_dyn_init(void)
1150 {
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 */
1154  
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;
1161
1162         V_dyn_keepalive_interval = 20;
1163         V_dyn_keepalive_period = 5;
1164         V_dyn_keepalive = 1;    /* do send keepalives */
1165         
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);
1169 }
1170
1171 void
1172 ipfw_dyn_uninit(int pass)
1173 {
1174         if (pass == 0)
1175                 callout_drain(&V_ipfw_timeout);
1176         else {
1177                 if (V_ipfw_dyn_v != NULL)
1178                         free(V_ipfw_dyn_v, M_IPFW);
1179         }
1180 }
1181
1182 int
1183 ipfw_dyn_len(void)
1184 {
1185         return (V_ipfw_dyn_v == NULL) ? 0 :
1186                 (V_dyn_count * sizeof(ipfw_dyn_rule));
1187 }
1188
1189 void
1190 ipfw_get_dynamic(char **pbp, const char *ep)
1191 {
1192         ipfw_dyn_rule *p, *last = NULL;
1193         char *bp;
1194         int i;
1195
1196         if (V_ipfw_dyn_v == NULL)
1197                 return;
1198         bp = *pbp;
1199
1200         IPFW_DYN_LOCK();
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));
1209                                 /*
1210                                  * store set number into high word of
1211                                  * dst->rule pointer.
1212                                  */
1213                                 bcopy(&(p->rule->set),
1214                                     (char *)&dst->rule +
1215                                     sizeof(p->rule->rulenum),
1216                                     sizeof(p->rule->set));
1217                                 /*
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.
1222                                  */
1223                                 bcopy(&dst, &dst->next, sizeof(dst));
1224                                 last = dst;
1225                                 dst->expire =
1226                                     TIME_LEQ(dst->expire, time_uptime) ?
1227                                         0 : dst->expire - time_uptime ;
1228                                 bp += sizeof(ipfw_dyn_rule);
1229                         }
1230                 }
1231         IPFW_DYN_UNLOCK();
1232         if (last != NULL) /* mark last dynamic rule */
1233                 bzero(&last->next, sizeof(last));
1234         *pbp = bp;
1235 }
1236 /* end of file */