1 /* iptables match extension to limit the number of packets per second
2 * seperately for each hashbucket (sourceip/sourceport/dstip/dstport)
4 * (C) 2003-2004 by Harald Welte <laforge@netfilter.org>
6 * $Id: ipt_hashlimit.c 3244 2004-10-20 16:24:29Z laforge@netfilter.org $
8 * Development of this code was funded by Astaro AG, http://www.astaro.com/
10 #include <linux/module.h>
11 #include <linux/spinlock.h>
12 #include <linux/random.h>
13 #include <linux/jhash.h>
14 #include <linux/slab.h>
15 #include <linux/vmalloc.h>
16 #include <linux/proc_fs.h>
17 #include <linux/seq_file.h>
18 #include <linux/list.h>
19 #include <linux/skbuff.h>
23 #include <linux/ipv6.h>
25 #include <net/net_namespace.h>
27 #include <linux/netfilter/x_tables.h>
28 #include <linux/netfilter_ipv4/ip_tables.h>
29 #include <linux/netfilter_ipv6/ip6_tables.h>
30 #include <linux/netfilter/xt_hashlimit.h>
31 #include <linux/mutex.h>
33 MODULE_LICENSE("GPL");
34 MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>");
35 MODULE_DESCRIPTION("iptables match for limiting per hash-bucket");
36 MODULE_ALIAS("ipt_hashlimit");
37 MODULE_ALIAS("ip6t_hashlimit");
39 /* need to declare this at the top */
40 static struct proc_dir_entry *hashlimit_procdir4;
41 static struct proc_dir_entry *hashlimit_procdir6;
42 static const struct file_operations dl_file_ops;
61 /* static / read-only parts in the beginning */
62 struct hlist_node node;
63 struct dsthash_dst dst;
65 /* modified structure members in the end */
66 unsigned long expires; /* precalculated expiry time */
68 unsigned long prev; /* last modification */
70 u_int32_t credit_cap, cost;
74 struct xt_hashlimit_htable {
75 struct hlist_node node; /* global list of all htables */
79 struct hashlimit_cfg cfg; /* config */
82 spinlock_t lock; /* lock for list_head */
83 u_int32_t rnd; /* random seed for hash */
85 unsigned int count; /* number entries in table */
86 struct timer_list timer; /* timer for gc */
89 struct proc_dir_entry *pde;
91 struct hlist_head hash[0]; /* hashtable itself */
94 static DEFINE_SPINLOCK(hashlimit_lock); /* protects htables list */
95 static DEFINE_MUTEX(hlimit_mutex); /* additional checkentry protection */
96 static HLIST_HEAD(hashlimit_htables);
97 static struct kmem_cache *hashlimit_cachep __read_mostly;
99 static inline bool dst_cmp(const struct dsthash_ent *ent,
100 const struct dsthash_dst *b)
102 return !memcmp(&ent->dst, b, sizeof(ent->dst));
106 hash_dst(const struct xt_hashlimit_htable *ht, const struct dsthash_dst *dst)
108 u_int32_t hash = jhash2((const u32 *)dst,
109 sizeof(*dst)/sizeof(u32),
112 * Instead of returning hash % ht->cfg.size (implying a divide)
113 * we return the high 32 bits of the (hash * ht->cfg.size) that will
114 * give results between [0 and cfg.size-1] and same hash distribution,
115 * but using a multiply, less expensive than a divide
117 return ((u64)hash * ht->cfg.size) >> 32;
120 static struct dsthash_ent *
121 dsthash_find(const struct xt_hashlimit_htable *ht,
122 const struct dsthash_dst *dst)
124 struct dsthash_ent *ent;
125 struct hlist_node *pos;
126 u_int32_t hash = hash_dst(ht, dst);
128 if (!hlist_empty(&ht->hash[hash])) {
129 hlist_for_each_entry(ent, pos, &ht->hash[hash], node)
130 if (dst_cmp(ent, dst))
136 /* allocate dsthash_ent, initialize dst, put in htable and lock it */
137 static struct dsthash_ent *
138 dsthash_alloc_init(struct xt_hashlimit_htable *ht,
139 const struct dsthash_dst *dst)
141 struct dsthash_ent *ent;
143 /* initialize hash with random val at the time we allocate
144 * the first hashtable entry */
145 if (!ht->rnd_initialized) {
146 get_random_bytes(&ht->rnd, 4);
147 ht->rnd_initialized = 1;
150 if (ht->cfg.max && ht->count >= ht->cfg.max) {
151 /* FIXME: do something. question is what.. */
154 "xt_hashlimit: max count of %u reached\n",
159 ent = kmem_cache_alloc(hashlimit_cachep, GFP_ATOMIC);
163 "xt_hashlimit: can't allocate dsthash_ent\n");
166 memcpy(&ent->dst, dst, sizeof(ent->dst));
168 hlist_add_head(&ent->node, &ht->hash[hash_dst(ht, dst)]);
174 dsthash_free(struct xt_hashlimit_htable *ht, struct dsthash_ent *ent)
176 hlist_del(&ent->node);
177 kmem_cache_free(hashlimit_cachep, ent);
180 static void htable_gc(unsigned long htlong);
182 static int htable_create(struct xt_hashlimit_info *minfo, int family)
184 struct xt_hashlimit_htable *hinfo;
189 size = minfo->cfg.size;
191 size = ((num_physpages << PAGE_SHIFT) / 16384) /
192 sizeof(struct list_head);
193 if (num_physpages > (1024 * 1024 * 1024 / PAGE_SIZE))
198 /* FIXME: don't use vmalloc() here or anywhere else -HW */
199 hinfo = vmalloc(sizeof(struct xt_hashlimit_htable) +
200 sizeof(struct list_head) * size);
202 printk(KERN_ERR "xt_hashlimit: unable to create hashtable\n");
205 minfo->hinfo = hinfo;
207 /* copy match config into hashtable config */
208 memcpy(&hinfo->cfg, &minfo->cfg, sizeof(hinfo->cfg));
209 hinfo->cfg.size = size;
211 hinfo->cfg.max = 8 * hinfo->cfg.size;
212 else if (hinfo->cfg.max < hinfo->cfg.size)
213 hinfo->cfg.max = hinfo->cfg.size;
215 for (i = 0; i < hinfo->cfg.size; i++)
216 INIT_HLIST_HEAD(&hinfo->hash[i]);
218 atomic_set(&hinfo->use, 1);
220 hinfo->family = family;
221 hinfo->rnd_initialized = 0;
222 spin_lock_init(&hinfo->lock);
223 hinfo->pde = create_proc_entry(minfo->name, 0,
224 family == AF_INET ? hashlimit_procdir4 :
230 hinfo->pde->proc_fops = &dl_file_ops;
231 hinfo->pde->data = hinfo;
233 setup_timer(&hinfo->timer, htable_gc, (unsigned long )hinfo);
234 hinfo->timer.expires = jiffies + msecs_to_jiffies(hinfo->cfg.gc_interval);
235 add_timer(&hinfo->timer);
237 spin_lock_bh(&hashlimit_lock);
238 hlist_add_head(&hinfo->node, &hashlimit_htables);
239 spin_unlock_bh(&hashlimit_lock);
244 static bool select_all(const struct xt_hashlimit_htable *ht,
245 const struct dsthash_ent *he)
250 static bool select_gc(const struct xt_hashlimit_htable *ht,
251 const struct dsthash_ent *he)
253 return time_after_eq(jiffies, he->expires);
256 static void htable_selective_cleanup(struct xt_hashlimit_htable *ht,
257 bool (*select)(const struct xt_hashlimit_htable *ht,
258 const struct dsthash_ent *he))
262 /* lock hash table and iterate over it */
263 spin_lock_bh(&ht->lock);
264 for (i = 0; i < ht->cfg.size; i++) {
265 struct dsthash_ent *dh;
266 struct hlist_node *pos, *n;
267 hlist_for_each_entry_safe(dh, pos, n, &ht->hash[i], node) {
268 if ((*select)(ht, dh))
269 dsthash_free(ht, dh);
272 spin_unlock_bh(&ht->lock);
275 /* hash table garbage collector, run by timer */
276 static void htable_gc(unsigned long htlong)
278 struct xt_hashlimit_htable *ht = (struct xt_hashlimit_htable *)htlong;
280 htable_selective_cleanup(ht, select_gc);
282 /* re-add the timer accordingly */
283 ht->timer.expires = jiffies + msecs_to_jiffies(ht->cfg.gc_interval);
284 add_timer(&ht->timer);
287 static void htable_destroy(struct xt_hashlimit_htable *hinfo)
289 /* remove timer, if it is pending */
290 if (timer_pending(&hinfo->timer))
291 del_timer(&hinfo->timer);
293 /* remove proc entry */
294 remove_proc_entry(hinfo->pde->name,
295 hinfo->family == AF_INET ? hashlimit_procdir4 :
297 htable_selective_cleanup(hinfo, select_all);
301 static struct xt_hashlimit_htable *htable_find_get(const char *name,
304 struct xt_hashlimit_htable *hinfo;
305 struct hlist_node *pos;
307 spin_lock_bh(&hashlimit_lock);
308 hlist_for_each_entry(hinfo, pos, &hashlimit_htables, node) {
309 if (!strcmp(name, hinfo->pde->name) &&
310 hinfo->family == family) {
311 atomic_inc(&hinfo->use);
312 spin_unlock_bh(&hashlimit_lock);
316 spin_unlock_bh(&hashlimit_lock);
320 static void htable_put(struct xt_hashlimit_htable *hinfo)
322 if (atomic_dec_and_test(&hinfo->use)) {
323 spin_lock_bh(&hashlimit_lock);
324 hlist_del(&hinfo->node);
325 spin_unlock_bh(&hashlimit_lock);
326 htable_destroy(hinfo);
330 /* The algorithm used is the Simple Token Bucket Filter (TBF)
331 * see net/sched/sch_tbf.c in the linux source tree
334 /* Rusty: This is my (non-mathematically-inclined) understanding of
335 this algorithm. The `average rate' in jiffies becomes your initial
336 amount of credit `credit' and the most credit you can ever have
337 `credit_cap'. The `peak rate' becomes the cost of passing the
340 `prev' tracks the last packet hit: you gain one credit per jiffy.
341 If you get credit balance more than this, the extra credit is
342 discarded. Every time the match passes, you lose `cost' credits;
343 if you don't have that many, the test fails.
345 See Alexey's formal explanation in net/sched/sch_tbf.c.
347 To get the maximum range, we multiply by this factor (ie. you get N
348 credits per jiffy). We want to allow a rate as low as 1 per day
349 (slowest userspace tool allows), which means
350 CREDITS_PER_JIFFY*HZ*60*60*24 < 2^32 ie.
352 #define MAX_CPJ (0xFFFFFFFF / (HZ*60*60*24))
354 /* Repeated shift and or gives us all 1s, final shift and add 1 gives
355 * us the power of 2 below the theoretical max, so GCC simply does a
357 #define _POW2_BELOW2(x) ((x)|((x)>>1))
358 #define _POW2_BELOW4(x) (_POW2_BELOW2(x)|_POW2_BELOW2((x)>>2))
359 #define _POW2_BELOW8(x) (_POW2_BELOW4(x)|_POW2_BELOW4((x)>>4))
360 #define _POW2_BELOW16(x) (_POW2_BELOW8(x)|_POW2_BELOW8((x)>>8))
361 #define _POW2_BELOW32(x) (_POW2_BELOW16(x)|_POW2_BELOW16((x)>>16))
362 #define POW2_BELOW32(x) ((_POW2_BELOW32(x)>>1) + 1)
364 #define CREDITS_PER_JIFFY POW2_BELOW32(MAX_CPJ)
366 /* Precision saver. */
367 static inline u_int32_t
368 user2credits(u_int32_t user)
370 /* If multiplying would overflow... */
371 if (user > 0xFFFFFFFF / (HZ*CREDITS_PER_JIFFY))
373 return (user / XT_HASHLIMIT_SCALE) * HZ * CREDITS_PER_JIFFY;
375 return (user * HZ * CREDITS_PER_JIFFY) / XT_HASHLIMIT_SCALE;
378 static inline void rateinfo_recalc(struct dsthash_ent *dh, unsigned long now)
380 dh->rateinfo.credit += (now - dh->rateinfo.prev) * CREDITS_PER_JIFFY;
381 if (dh->rateinfo.credit > dh->rateinfo.credit_cap)
382 dh->rateinfo.credit = dh->rateinfo.credit_cap;
383 dh->rateinfo.prev = now;
387 hashlimit_init_dst(const struct xt_hashlimit_htable *hinfo,
388 struct dsthash_dst *dst,
389 const struct sk_buff *skb, unsigned int protoff)
391 __be16 _ports[2], *ports;
394 memset(dst, 0, sizeof(*dst));
396 switch (hinfo->family) {
398 if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_DIP)
399 dst->addr.ip.dst = ip_hdr(skb)->daddr;
400 if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_SIP)
401 dst->addr.ip.src = ip_hdr(skb)->saddr;
403 if (!(hinfo->cfg.mode &
404 (XT_HASHLIMIT_HASH_DPT | XT_HASHLIMIT_HASH_SPT)))
406 nexthdr = ip_hdr(skb)->protocol;
408 #if defined(CONFIG_IP6_NF_IPTABLES) || defined(CONFIG_IP6_NF_IPTABLES_MODULE)
410 if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_DIP)
411 memcpy(&dst->addr.ip6.dst, &ipv6_hdr(skb)->daddr,
412 sizeof(dst->addr.ip6.dst));
413 if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_SIP)
414 memcpy(&dst->addr.ip6.src, &ipv6_hdr(skb)->saddr,
415 sizeof(dst->addr.ip6.src));
417 if (!(hinfo->cfg.mode &
418 (XT_HASHLIMIT_HASH_DPT | XT_HASHLIMIT_HASH_SPT)))
420 nexthdr = ipv6_hdr(skb)->nexthdr;
421 protoff = ipv6_skip_exthdr(skb, sizeof(struct ipv6hdr), &nexthdr);
422 if ((int)protoff < 0)
434 case IPPROTO_UDPLITE:
437 ports = skb_header_pointer(skb, protoff, sizeof(_ports),
441 _ports[0] = _ports[1] = 0;
447 if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_SPT)
448 dst->src_port = ports[0];
449 if (hinfo->cfg.mode & XT_HASHLIMIT_HASH_DPT)
450 dst->dst_port = ports[1];
455 hashlimit_mt(const struct sk_buff *skb, const struct net_device *in,
456 const struct net_device *out, const struct xt_match *match,
457 const void *matchinfo, int offset, unsigned int protoff,
460 const struct xt_hashlimit_info *r =
461 ((const struct xt_hashlimit_info *)matchinfo)->u.master;
462 struct xt_hashlimit_htable *hinfo = r->hinfo;
463 unsigned long now = jiffies;
464 struct dsthash_ent *dh;
465 struct dsthash_dst dst;
467 if (hashlimit_init_dst(hinfo, &dst, skb, protoff) < 0)
470 spin_lock_bh(&hinfo->lock);
471 dh = dsthash_find(hinfo, &dst);
473 dh = dsthash_alloc_init(hinfo, &dst);
475 spin_unlock_bh(&hinfo->lock);
479 dh->expires = jiffies + msecs_to_jiffies(hinfo->cfg.expire);
480 dh->rateinfo.prev = jiffies;
481 dh->rateinfo.credit = user2credits(hinfo->cfg.avg *
483 dh->rateinfo.credit_cap = user2credits(hinfo->cfg.avg *
485 dh->rateinfo.cost = user2credits(hinfo->cfg.avg);
487 /* update expiration timeout */
488 dh->expires = now + msecs_to_jiffies(hinfo->cfg.expire);
489 rateinfo_recalc(dh, now);
492 if (dh->rateinfo.credit >= dh->rateinfo.cost) {
493 /* We're underlimit. */
494 dh->rateinfo.credit -= dh->rateinfo.cost;
495 spin_unlock_bh(&hinfo->lock);
499 spin_unlock_bh(&hinfo->lock);
501 /* default case: we're overlimit, thus don't match */
510 hashlimit_mt_check(const char *tablename, const void *inf,
511 const struct xt_match *match, void *matchinfo,
512 unsigned int hook_mask)
514 struct xt_hashlimit_info *r = matchinfo;
516 /* Check for overflow. */
517 if (r->cfg.burst == 0 ||
518 user2credits(r->cfg.avg * r->cfg.burst) < user2credits(r->cfg.avg)) {
519 printk(KERN_ERR "xt_hashlimit: overflow, try lower: %u/%u\n",
520 r->cfg.avg, r->cfg.burst);
523 if (r->cfg.mode == 0 ||
524 r->cfg.mode > (XT_HASHLIMIT_HASH_DPT |
525 XT_HASHLIMIT_HASH_DIP |
526 XT_HASHLIMIT_HASH_SIP |
527 XT_HASHLIMIT_HASH_SPT))
529 if (!r->cfg.gc_interval)
533 if (r->name[sizeof(r->name) - 1] != '\0')
536 /* This is the best we've got: We cannot release and re-grab lock,
537 * since checkentry() is called before x_tables.c grabs xt_mutex.
538 * We also cannot grab the hashtable spinlock, since htable_create will
539 * call vmalloc, and that can sleep. And we cannot just re-search
540 * the list of htable's in htable_create(), since then we would
541 * create duplicate proc files. -HW */
542 mutex_lock(&hlimit_mutex);
543 r->hinfo = htable_find_get(r->name, match->family);
544 if (!r->hinfo && htable_create(r, match->family) != 0) {
545 mutex_unlock(&hlimit_mutex);
548 mutex_unlock(&hlimit_mutex);
550 /* Ugly hack: For SMP, we only want to use one set */
556 hashlimit_mt_destroy(const struct xt_match *match, void *matchinfo)
558 const struct xt_hashlimit_info *r = matchinfo;
560 htable_put(r->hinfo);
564 struct compat_xt_hashlimit_info {
566 struct hashlimit_cfg cfg;
568 compat_uptr_t master;
571 static void hashlimit_mt_compat_from_user(void *dst, void *src)
573 int off = offsetof(struct compat_xt_hashlimit_info, hinfo);
575 memcpy(dst, src, off);
576 memset(dst + off, 0, sizeof(struct compat_xt_hashlimit_info) - off);
579 static int hashlimit_mt_compat_to_user(void __user *dst, void *src)
581 int off = offsetof(struct compat_xt_hashlimit_info, hinfo);
583 return copy_to_user(dst, src, off) ? -EFAULT : 0;
587 static struct xt_match hashlimit_mt_reg[] __read_mostly = {
591 .match = hashlimit_mt,
592 .matchsize = sizeof(struct xt_hashlimit_info),
594 .compatsize = sizeof(struct compat_xt_hashlimit_info),
595 .compat_from_user = hashlimit_mt_compat_from_user,
596 .compat_to_user = hashlimit_mt_compat_to_user,
598 .checkentry = hashlimit_mt_check,
599 .destroy = hashlimit_mt_destroy,
605 .match = hashlimit_mt,
606 .matchsize = sizeof(struct xt_hashlimit_info),
608 .compatsize = sizeof(struct compat_xt_hashlimit_info),
609 .compat_from_user = hashlimit_mt_compat_from_user,
610 .compat_to_user = hashlimit_mt_compat_to_user,
612 .checkentry = hashlimit_mt_check,
613 .destroy = hashlimit_mt_destroy,
619 static void *dl_seq_start(struct seq_file *s, loff_t *pos)
621 struct proc_dir_entry *pde = s->private;
622 struct xt_hashlimit_htable *htable = pde->data;
623 unsigned int *bucket;
625 spin_lock_bh(&htable->lock);
626 if (*pos >= htable->cfg.size)
629 bucket = kmalloc(sizeof(unsigned int), GFP_ATOMIC);
631 return ERR_PTR(-ENOMEM);
637 static void *dl_seq_next(struct seq_file *s, void *v, loff_t *pos)
639 struct proc_dir_entry *pde = s->private;
640 struct xt_hashlimit_htable *htable = pde->data;
641 unsigned int *bucket = (unsigned int *)v;
644 if (*pos >= htable->cfg.size) {
651 static void dl_seq_stop(struct seq_file *s, void *v)
653 struct proc_dir_entry *pde = s->private;
654 struct xt_hashlimit_htable *htable = pde->data;
655 unsigned int *bucket = (unsigned int *)v;
658 spin_unlock_bh(&htable->lock);
661 static int dl_seq_real_show(struct dsthash_ent *ent, int family,
664 /* recalculate to show accurate numbers */
665 rateinfo_recalc(ent, jiffies);
669 return seq_printf(s, "%ld %u.%u.%u.%u:%u->"
670 "%u.%u.%u.%u:%u %u %u %u\n",
671 (long)(ent->expires - jiffies)/HZ,
672 NIPQUAD(ent->dst.addr.ip.src),
673 ntohs(ent->dst.src_port),
674 NIPQUAD(ent->dst.addr.ip.dst),
675 ntohs(ent->dst.dst_port),
676 ent->rateinfo.credit, ent->rateinfo.credit_cap,
679 return seq_printf(s, "%ld " NIP6_FMT ":%u->"
680 NIP6_FMT ":%u %u %u %u\n",
681 (long)(ent->expires - jiffies)/HZ,
682 NIP6(*(struct in6_addr *)&ent->dst.addr.ip6.src),
683 ntohs(ent->dst.src_port),
684 NIP6(*(struct in6_addr *)&ent->dst.addr.ip6.dst),
685 ntohs(ent->dst.dst_port),
686 ent->rateinfo.credit, ent->rateinfo.credit_cap,
694 static int dl_seq_show(struct seq_file *s, void *v)
696 struct proc_dir_entry *pde = s->private;
697 struct xt_hashlimit_htable *htable = pde->data;
698 unsigned int *bucket = (unsigned int *)v;
699 struct dsthash_ent *ent;
700 struct hlist_node *pos;
702 if (!hlist_empty(&htable->hash[*bucket])) {
703 hlist_for_each_entry(ent, pos, &htable->hash[*bucket], node)
704 if (dl_seq_real_show(ent, htable->family, s))
710 static const struct seq_operations dl_seq_ops = {
711 .start = dl_seq_start,
717 static int dl_proc_open(struct inode *inode, struct file *file)
719 int ret = seq_open(file, &dl_seq_ops);
722 struct seq_file *sf = file->private_data;
723 sf->private = PDE(inode);
728 static const struct file_operations dl_file_ops = {
729 .owner = THIS_MODULE,
730 .open = dl_proc_open,
733 .release = seq_release
736 static int __init hashlimit_mt_init(void)
740 err = xt_register_matches(hashlimit_mt_reg,
741 ARRAY_SIZE(hashlimit_mt_reg));
746 hashlimit_cachep = kmem_cache_create("xt_hashlimit",
747 sizeof(struct dsthash_ent), 0, 0,
749 if (!hashlimit_cachep) {
750 printk(KERN_ERR "xt_hashlimit: unable to create slab cache\n");
753 hashlimit_procdir4 = proc_mkdir("ipt_hashlimit", init_net.proc_net);
754 if (!hashlimit_procdir4) {
755 printk(KERN_ERR "xt_hashlimit: unable to create proc dir "
759 hashlimit_procdir6 = proc_mkdir("ip6t_hashlimit", init_net.proc_net);
760 if (!hashlimit_procdir6) {
761 printk(KERN_ERR "xt_hashlimit: unable to create proc dir "
767 remove_proc_entry("ipt_hashlimit", init_net.proc_net);
769 kmem_cache_destroy(hashlimit_cachep);
771 xt_unregister_matches(hashlimit_mt_reg, ARRAY_SIZE(hashlimit_mt_reg));
777 static void __exit hashlimit_mt_exit(void)
779 remove_proc_entry("ipt_hashlimit", init_net.proc_net);
780 remove_proc_entry("ip6t_hashlimit", init_net.proc_net);
781 kmem_cache_destroy(hashlimit_cachep);
782 xt_unregister_matches(hashlimit_mt_reg, ARRAY_SIZE(hashlimit_mt_reg));
785 module_init(hashlimit_mt_init);
786 module_exit(hashlimit_mt_exit);