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 * based on ipt_limit.c by:
11 * Jérôme de Vivie <devivie@info.enserb.u-bordeaux.fr>
12 * Hervé Eychenne <eychenne@info.enserb.u-bordeaux.fr>
13 * Rusty Russell <rusty@rustcorp.com.au>
15 * The general idea is to create a hash table for every dstip and have a
16 * seperate limit counter per tuple. This way you can do something like 'limit
17 * the number of syn packets for each of my internal addresses.
19 * Ideally this would just be implemented as a general 'hash' match, which would
20 * allow us to attach any iptables target to it's hash buckets. But this is
21 * not possible in the current iptables architecture. As always, pkttables for
24 #include <linux/module.h>
25 #include <linux/skbuff.h>
26 #include <linux/spinlock.h>
27 #include <linux/random.h>
28 #include <linux/jhash.h>
29 #include <linux/slab.h>
30 #include <linux/vmalloc.h>
31 #include <linux/tcp.h>
32 #include <linux/udp.h>
33 #include <linux/sctp.h>
34 #include <linux/proc_fs.h>
35 #include <linux/seq_file.h>
37 #define ASSERT_READ_LOCK(x)
38 #define ASSERT_WRITE_LOCK(x)
39 #include <linux/netfilter_ipv4/lockhelp.h>
40 #include <linux/netfilter_ipv4/listhelp.h>
42 #include <linux/netfilter_ipv4/ip_tables.h>
43 #include <linux/netfilter_ipv4/ipt_hashlimit.h>
45 /* FIXME: this is just for IP_NF_ASSERRT */
46 #include <linux/netfilter_ipv4/ip_conntrack.h>
48 #define MS2JIFFIES(x) ((x*HZ)/1000)
50 MODULE_LICENSE("GPL");
51 MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>");
52 MODULE_DESCRIPTION("iptables match for limiting per hash-bucket");
54 /* need to declare this at the top */
55 static struct proc_dir_entry *hashlimit_procdir;
56 static struct file_operations dl_file_ops;
63 /* ports have to be consecutive !!! */
69 /* static / read-only parts in the beginning */
70 struct list_head list;
71 struct dsthash_dst dst;
73 /* modified structure members in the end */
74 unsigned long expires; /* precalculated expiry time */
76 unsigned long prev; /* last modification */
78 u_int32_t credit_cap, cost;
82 struct ipt_hashlimit_htable {
83 struct list_head list; /* global list of all htables */
86 struct hashlimit_cfg cfg; /* config */
89 spinlock_t lock; /* lock for list_head */
90 u_int32_t rnd; /* random seed for hash */
91 struct timer_list timer; /* timer for gc */
92 atomic_t count; /* number entries in table */
95 struct proc_dir_entry *pde;
97 struct list_head hash[0]; /* hashtable itself */
100 static DECLARE_RWLOCK(hashlimit_lock); /* protects htables list */
101 static DECLARE_MUTEX(hlimit_mutex); /* additional checkentry protection */
102 static LIST_HEAD(hashlimit_htables);
103 static kmem_cache_t *hashlimit_cachep;
105 static inline int dst_cmp(const struct dsthash_ent *ent, struct dsthash_dst *b)
107 return (ent->dst.dst_ip == b->dst_ip
108 && ent->dst.dst_port == b->dst_port
109 && ent->dst.src_port == b->src_port
110 && ent->dst.src_ip == b->src_ip);
113 static inline u_int32_t
114 hash_dst(const struct ipt_hashlimit_htable *ht, const struct dsthash_dst *dst)
116 return (jhash_3words(dst->dst_ip, (dst->dst_port<<16 & dst->src_port),
117 dst->src_ip, ht->rnd) % ht->cfg.size);
120 static inline struct dsthash_ent *
121 __dsthash_find(const struct ipt_hashlimit_htable *ht, struct dsthash_dst *dst)
123 struct dsthash_ent *ent;
124 u_int32_t hash = hash_dst(ht, dst);
125 ent = LIST_FIND(&ht->hash[hash], dst_cmp, struct dsthash_ent *, dst);
129 /* allocate dsthash_ent, initialize dst, put in htable and lock it */
130 static struct dsthash_ent *
131 __dsthash_alloc_init(struct ipt_hashlimit_htable *ht, struct dsthash_dst *dst)
133 struct dsthash_ent *ent;
135 /* initialize hash with random val at the time we allocate
136 * the first hashtable entry */
138 get_random_bytes(&ht->rnd, 4);
141 atomic_read(&ht->count) >= ht->cfg.max) {
142 /* FIXME: do something. question is what.. */
145 "ipt_hashlimit: max count of %u reached\n",
150 ent = kmem_cache_alloc(hashlimit_cachep, GFP_ATOMIC);
154 "ipt_hashlimit: can't allocate dsthash_ent\n");
158 atomic_inc(&ht->count);
160 ent->dst.dst_ip = dst->dst_ip;
161 ent->dst.dst_port = dst->dst_port;
162 ent->dst.src_ip = dst->src_ip;
163 ent->dst.src_port = dst->src_port;
165 list_add(&ent->list, &ht->hash[hash_dst(ht, dst)]);
171 __dsthash_free(struct ipt_hashlimit_htable *ht, struct dsthash_ent *ent)
173 list_del(&ent->list);
174 kmem_cache_free(hashlimit_cachep, ent);
175 atomic_dec(&ht->count);
177 static void htable_gc(unsigned long htlong);
179 static int htable_create(struct ipt_hashlimit_info *minfo)
183 struct ipt_hashlimit_htable *hinfo;
186 size = minfo->cfg.size;
188 size = (((num_physpages << PAGE_SHIFT) / 16384)
189 / sizeof(struct list_head));
190 if (num_physpages > (1024 * 1024 * 1024 / PAGE_SIZE))
195 /* FIXME: don't use vmalloc() here or anywhere else -HW */
196 hinfo = vmalloc(sizeof(struct ipt_hashlimit_htable)
197 + (sizeof(struct list_head) * size));
199 printk(KERN_ERR "ipt_hashlimit: Unable to create hashtable\n");
202 minfo->hinfo = hinfo;
204 /* copy match config into hashtable config */
205 memcpy(&hinfo->cfg, &minfo->cfg, sizeof(hinfo->cfg));
206 hinfo->cfg.size = size;
208 hinfo->cfg.max = 8 * hinfo->cfg.size;
209 else if (hinfo->cfg.max < hinfo->cfg.size)
210 hinfo->cfg.max = hinfo->cfg.size;
212 for (i = 0; i < hinfo->cfg.size; i++)
213 INIT_LIST_HEAD(&hinfo->hash[i]);
215 atomic_set(&hinfo->count, 0);
216 atomic_set(&hinfo->use, 1);
218 spin_lock_init(&hinfo->lock);
219 hinfo->pde = create_proc_entry(minfo->name, 0, hashlimit_procdir);
224 hinfo->pde->proc_fops = &dl_file_ops;
225 hinfo->pde->data = hinfo;
227 init_timer(&hinfo->timer);
228 hinfo->timer.expires = jiffies + MS2JIFFIES(hinfo->cfg.gc_interval);
229 hinfo->timer.data = (unsigned long )hinfo;
230 hinfo->timer.function = htable_gc;
231 add_timer(&hinfo->timer);
233 WRITE_LOCK(&hashlimit_lock);
234 list_add(&hinfo->list, &hashlimit_htables);
235 WRITE_UNLOCK(&hashlimit_lock);
240 static int select_all(struct ipt_hashlimit_htable *ht, struct dsthash_ent *he)
245 static int select_gc(struct ipt_hashlimit_htable *ht, struct dsthash_ent *he)
247 return (jiffies >= he->expires);
250 static void htable_selective_cleanup(struct ipt_hashlimit_htable *ht,
251 int (*select)(struct ipt_hashlimit_htable *ht,
252 struct dsthash_ent *he))
256 IP_NF_ASSERT(ht->cfg.size && ht->cfg.max);
258 /* lock hash table and iterate over it */
259 spin_lock_bh(&ht->lock);
260 for (i = 0; i < ht->cfg.size; i++) {
261 struct dsthash_ent *dh, *n;
262 list_for_each_entry_safe(dh, n, &ht->hash[i], list) {
263 if ((*select)(ht, dh))
264 __dsthash_free(ht, dh);
267 spin_unlock_bh(&ht->lock);
270 /* hash table garbage collector, run by timer */
271 static void htable_gc(unsigned long htlong)
273 struct ipt_hashlimit_htable *ht = (struct ipt_hashlimit_htable *)htlong;
275 htable_selective_cleanup(ht, select_gc);
277 /* re-add the timer accordingly */
278 ht->timer.expires = jiffies + MS2JIFFIES(ht->cfg.gc_interval);
279 add_timer(&ht->timer);
282 static void htable_destroy(struct ipt_hashlimit_htable *hinfo)
284 /* remove timer, if it is pending */
285 if (timer_pending(&hinfo->timer))
286 del_timer(&hinfo->timer);
288 /* remove proc entry */
289 remove_proc_entry(hinfo->pde->name, hashlimit_procdir);
291 htable_selective_cleanup(hinfo, select_all);
295 static struct ipt_hashlimit_htable *htable_find_get(char *name)
297 struct ipt_hashlimit_htable *hinfo;
299 READ_LOCK(&hashlimit_lock);
300 list_for_each_entry(hinfo, &hashlimit_htables, list) {
301 if (!strcmp(name, hinfo->pde->name)) {
302 atomic_inc(&hinfo->use);
303 READ_UNLOCK(&hashlimit_lock);
307 READ_UNLOCK(&hashlimit_lock);
312 static void htable_put(struct ipt_hashlimit_htable *hinfo)
314 if (atomic_dec_and_test(&hinfo->use)) {
315 WRITE_LOCK(&hashlimit_lock);
316 list_del(&hinfo->list);
317 WRITE_UNLOCK(&hashlimit_lock);
318 htable_destroy(hinfo);
323 /* The algorithm used is the Simple Token Bucket Filter (TBF)
324 * see net/sched/sch_tbf.c in the linux source tree
327 /* Rusty: This is my (non-mathematically-inclined) understanding of
328 this algorithm. The `average rate' in jiffies becomes your initial
329 amount of credit `credit' and the most credit you can ever have
330 `credit_cap'. The `peak rate' becomes the cost of passing the
333 `prev' tracks the last packet hit: you gain one credit per jiffy.
334 If you get credit balance more than this, the extra credit is
335 discarded. Every time the match passes, you lose `cost' credits;
336 if you don't have that many, the test fails.
338 See Alexey's formal explanation in net/sched/sch_tbf.c.
340 To get the maximum range, we multiply by this factor (ie. you get N
341 credits per jiffy). We want to allow a rate as low as 1 per day
342 (slowest userspace tool allows), which means
343 CREDITS_PER_JIFFY*HZ*60*60*24 < 2^32 ie.
345 #define MAX_CPJ (0xFFFFFFFF / (HZ*60*60*24))
347 /* Repeated shift and or gives us all 1s, final shift and add 1 gives
348 * us the power of 2 below the theoretical max, so GCC simply does a
350 #define _POW2_BELOW2(x) ((x)|((x)>>1))
351 #define _POW2_BELOW4(x) (_POW2_BELOW2(x)|_POW2_BELOW2((x)>>2))
352 #define _POW2_BELOW8(x) (_POW2_BELOW4(x)|_POW2_BELOW4((x)>>4))
353 #define _POW2_BELOW16(x) (_POW2_BELOW8(x)|_POW2_BELOW8((x)>>8))
354 #define _POW2_BELOW32(x) (_POW2_BELOW16(x)|_POW2_BELOW16((x)>>16))
355 #define POW2_BELOW32(x) ((_POW2_BELOW32(x)>>1) + 1)
357 #define CREDITS_PER_JIFFY POW2_BELOW32(MAX_CPJ)
359 /* Precision saver. */
360 static inline u_int32_t
361 user2credits(u_int32_t user)
363 /* If multiplying would overflow... */
364 if (user > 0xFFFFFFFF / (HZ*CREDITS_PER_JIFFY))
366 return (user / IPT_HASHLIMIT_SCALE) * HZ * CREDITS_PER_JIFFY;
368 return (user * HZ * CREDITS_PER_JIFFY) / IPT_HASHLIMIT_SCALE;
371 static inline void rateinfo_recalc(struct dsthash_ent *dh, unsigned long now)
373 dh->rateinfo.credit += (now - xchg(&dh->rateinfo.prev, now))
375 if (dh->rateinfo.credit > dh->rateinfo.credit_cap)
376 dh->rateinfo.credit = dh->rateinfo.credit_cap;
379 static inline int get_ports(const struct sk_buff *skb, int offset,
385 sctp_sctphdr_t sctph;
388 /* Must not be a fragment. */
392 /* Must be big enough to read ports (both UDP and TCP have
393 them at the start). */
394 ptr_u = skb_header_pointer(skb, skb->nh.iph->ihl*4, 8, &hdr_u);
398 switch (skb->nh.iph->protocol) {
400 ports[0] = ptr_u->th.source;
401 ports[1] = ptr_u->th.dest;
404 ports[0] = ptr_u->uh.source;
405 ports[1] = ptr_u->uh.dest;
408 ports[0] = ptr_u->sctph.source;
409 ports[1] = ptr_u->sctph.dest;
412 /* all other protocols don't supprot per-port hash
414 ports[0] = ports[1] = 0;
423 hashlimit_match(const struct sk_buff *skb,
424 const struct net_device *in,
425 const struct net_device *out,
426 const void *matchinfo,
430 struct ipt_hashlimit_info *r =
431 ((struct ipt_hashlimit_info *)matchinfo)->u.master;
432 struct ipt_hashlimit_htable *hinfo = r->hinfo;
433 unsigned long now = jiffies;
434 struct dsthash_ent *dh;
435 struct dsthash_dst dst;
437 /* build 'dst' according to hinfo->cfg and current packet */
438 memset(&dst, 0, sizeof(dst));
439 if (hinfo->cfg.mode & IPT_HASHLIMIT_HASH_DIP)
440 dst.dst_ip = skb->nh.iph->daddr;
441 if (hinfo->cfg.mode & IPT_HASHLIMIT_HASH_SIP)
442 dst.src_ip = skb->nh.iph->saddr;
443 if (hinfo->cfg.mode & IPT_HASHLIMIT_HASH_DPT
444 ||hinfo->cfg.mode & IPT_HASHLIMIT_HASH_SPT) {
446 if (get_ports(skb, offset, ports)) {
447 /* We've been asked to examine this packet, and we
448 can't. Hence, no choice but to drop. */
452 if (hinfo->cfg.mode & IPT_HASHLIMIT_HASH_SPT)
453 dst.src_port = ports[0];
454 if (hinfo->cfg.mode & IPT_HASHLIMIT_HASH_DPT)
455 dst.dst_port = ports[1];
458 spin_lock_bh(&hinfo->lock);
459 dh = __dsthash_find(hinfo, &dst);
461 dh = __dsthash_alloc_init(hinfo, &dst);
464 /* enomem... don't match == DROP */
466 printk(KERN_ERR "%s: ENOMEM\n", __FUNCTION__);
467 spin_unlock_bh(&hinfo->lock);
471 dh->expires = jiffies + MS2JIFFIES(hinfo->cfg.expire);
473 dh->rateinfo.prev = jiffies;
474 dh->rateinfo.credit = user2credits(hinfo->cfg.avg *
476 dh->rateinfo.credit_cap = user2credits(hinfo->cfg.avg *
478 dh->rateinfo.cost = user2credits(hinfo->cfg.avg);
480 spin_unlock_bh(&hinfo->lock);
484 /* update expiration timeout */
485 dh->expires = now + MS2JIFFIES(hinfo->cfg.expire);
487 rateinfo_recalc(dh, now);
488 if (dh->rateinfo.credit >= dh->rateinfo.cost) {
489 /* We're underlimit. */
490 dh->rateinfo.credit -= dh->rateinfo.cost;
491 spin_unlock_bh(&hinfo->lock);
495 spin_unlock_bh(&hinfo->lock);
497 /* default case: we're overlimit, thus don't match */
502 hashlimit_checkentry(const char *tablename,
503 const struct ipt_ip *ip,
505 unsigned int matchsize,
506 unsigned int hook_mask)
508 struct ipt_hashlimit_info *r = matchinfo;
510 if (matchsize != IPT_ALIGN(sizeof(struct ipt_hashlimit_info)))
513 /* Check for overflow. */
514 if (r->cfg.burst == 0
515 || user2credits(r->cfg.avg * r->cfg.burst) <
516 user2credits(r->cfg.avg)) {
517 printk(KERN_ERR "ipt_hashlimit: Overflow, try lower: %u/%u\n",
518 r->cfg.avg, r->cfg.burst);
523 || r->cfg.mode > (IPT_HASHLIMIT_HASH_DPT
524 |IPT_HASHLIMIT_HASH_DIP
525 |IPT_HASHLIMIT_HASH_SIP
526 |IPT_HASHLIMIT_HASH_SPT))
529 if (!r->cfg.gc_interval)
535 /* This is the best we've got: We cannot release and re-grab lock,
536 * since checkentry() is called before ip_tables.c grabs ipt_mutex.
537 * We also cannot grab the hashtable spinlock, since htable_create will
538 * call vmalloc, and that can sleep. And we cannot just re-search
539 * the list of htable's in htable_create(), since then we would
540 * create duplicate proc files. -HW */
542 r->hinfo = htable_find_get(r->name);
543 if (!r->hinfo && (htable_create(r) != 0)) {
549 /* Ugly hack: For SMP, we only want to use one set */
556 hashlimit_destroy(void *matchinfo, unsigned int matchsize)
558 struct ipt_hashlimit_info *r = (struct ipt_hashlimit_info *) matchinfo;
560 htable_put(r->hinfo);
563 static struct ipt_match ipt_hashlimit = {
565 .match = hashlimit_match,
566 .checkentry = hashlimit_checkentry,
567 .destroy = hashlimit_destroy,
573 static void *dl_seq_start(struct seq_file *s, loff_t *pos)
575 struct proc_dir_entry *pde = s->private;
576 struct ipt_hashlimit_htable *htable = pde->data;
577 unsigned int *bucket;
579 spin_lock_bh(&htable->lock);
580 if (*pos >= htable->cfg.size)
583 bucket = kmalloc(sizeof(unsigned int), GFP_ATOMIC);
585 return ERR_PTR(-ENOMEM);
591 static void *dl_seq_next(struct seq_file *s, void *v, loff_t *pos)
593 struct proc_dir_entry *pde = s->private;
594 struct ipt_hashlimit_htable *htable = pde->data;
595 unsigned int *bucket = (unsigned int *)v;
598 if (*pos >= htable->cfg.size) {
605 static void dl_seq_stop(struct seq_file *s, void *v)
607 struct proc_dir_entry *pde = s->private;
608 struct ipt_hashlimit_htable *htable = pde->data;
609 unsigned int *bucket = (unsigned int *)v;
613 spin_unlock_bh(&htable->lock);
616 static inline int dl_seq_real_show(struct dsthash_ent *ent, struct seq_file *s)
618 /* recalculate to show accurate numbers */
619 rateinfo_recalc(ent, jiffies);
621 return seq_printf(s, "%ld %u.%u.%u.%u:%u->%u.%u.%u.%u:%u %u %u %u\n",
622 (ent->expires - jiffies)/HZ,
623 NIPQUAD(ent->dst.src_ip), ntohs(ent->dst.src_port),
624 NIPQUAD(ent->dst.dst_ip), ntohs(ent->dst.dst_port),
625 ent->rateinfo.credit, ent->rateinfo.credit_cap,
629 static int dl_seq_show(struct seq_file *s, void *v)
631 struct proc_dir_entry *pde = s->private;
632 struct ipt_hashlimit_htable *htable = pde->data;
633 unsigned int *bucket = (unsigned int *)v;
635 if (LIST_FIND_W(&htable->hash[*bucket], dl_seq_real_show,
636 struct dsthash_ent *, s)) {
637 /* buffer was filled and unable to print that tuple */
643 static struct seq_operations dl_seq_ops = {
644 .start = dl_seq_start,
650 static int dl_proc_open(struct inode *inode, struct file *file)
652 int ret = seq_open(file, &dl_seq_ops);
655 struct seq_file *sf = file->private_data;
656 sf->private = PDE(inode);
661 static struct file_operations dl_file_ops = {
662 .owner = THIS_MODULE,
663 .open = dl_proc_open,
666 .release = seq_release
669 static int init_or_fini(int fini)
676 if (ipt_register_match(&ipt_hashlimit)) {
678 goto cleanup_nothing;
681 hashlimit_cachep = kmem_cache_create("ipt_hashlimit",
682 sizeof(struct dsthash_ent), 0,
684 if (!hashlimit_cachep) {
685 printk(KERN_ERR "Unable to create ipt_hashlimit slab cache\n");
687 goto cleanup_unreg_match;
690 hashlimit_procdir = proc_mkdir("ipt_hashlimit", proc_net);
691 if (!hashlimit_procdir) {
692 printk(KERN_ERR "Unable to create proc dir entry\n");
694 goto cleanup_free_slab;
700 remove_proc_entry("ipt_hashlimit", proc_net);
702 kmem_cache_destroy(hashlimit_cachep);
704 ipt_unregister_match(&ipt_hashlimit);
710 static int __init init(void)
712 return init_or_fini(0);
715 static void __exit fini(void)