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 DECLARE_RWLOCK(hashlimit_lock); /* protects htables list */
101 static LIST_HEAD(hashlimit_htables);
102 static kmem_cache_t *hashlimit_cachep;
104 static inline int dst_cmp(const struct dsthash_ent *ent, struct dsthash_dst *b)
106 return (ent->dst.dst_ip == b->dst_ip
107 && ent->dst.dst_port == b->dst_port
108 && ent->dst.src_port == b->src_port
109 && ent->dst.src_ip == b->src_ip);
112 static inline u_int32_t
113 hash_dst(const struct ipt_hashlimit_htable *ht, const struct dsthash_dst *dst)
115 return (jhash_3words(dst->dst_ip, (dst->dst_port<<16 & dst->src_port),
116 dst->src_ip, ht->rnd) % ht->cfg.size);
119 static inline struct dsthash_ent *
120 __dsthash_find(const struct ipt_hashlimit_htable *ht, struct dsthash_dst *dst)
122 struct dsthash_ent *ent;
123 u_int32_t hash = hash_dst(ht, dst);
124 ent = LIST_FIND(&ht->hash[hash], dst_cmp, struct dsthash_ent *, dst);
128 /* allocate dsthash_ent, initialize dst, put in htable and lock it */
129 static struct dsthash_ent *
130 __dsthash_alloc_init(struct ipt_hashlimit_htable *ht, struct dsthash_dst *dst)
132 struct dsthash_ent *ent;
134 /* initialize hash with random val at the time we allocate
135 * the first hashtable entry */
137 get_random_bytes(&ht->rnd, 4);
140 atomic_read(&ht->count) >= ht->cfg.max) {
141 /* FIXME: do something. question is what.. */
144 "ipt_hashlimit: max count of %u reached\n",
149 ent = kmem_cache_alloc(hashlimit_cachep, GFP_ATOMIC);
153 "ipt_hashlimit: can't allocate dsthash_ent\n");
157 atomic_inc(&ht->count);
159 ent->dst.dst_ip = dst->dst_ip;
160 ent->dst.dst_port = dst->dst_port;
161 ent->dst.src_ip = dst->src_ip;
162 ent->dst.src_port = dst->src_port;
164 list_add(&ent->list, &ht->hash[hash_dst(ht, dst)]);
170 __dsthash_free(struct ipt_hashlimit_htable *ht, struct dsthash_ent *ent)
172 list_del(&ent->list);
173 kmem_cache_free(hashlimit_cachep, ent);
174 atomic_dec(&ht->count);
176 static void htable_gc(unsigned long htlong);
178 static int htable_create(struct ipt_hashlimit_info *minfo)
182 struct ipt_hashlimit_htable *hinfo;
185 size = minfo->cfg.size;
187 size = (((num_physpages << PAGE_SHIFT) / 16384)
188 / sizeof(struct list_head));
189 if (num_physpages > (1024 * 1024 * 1024 / PAGE_SIZE))
194 /* FIXME: don't use vmalloc() here or anywhere else -HW */
195 hinfo = vmalloc(sizeof(struct ipt_hashlimit_htable)
196 + (sizeof(struct list_head) * size));
198 printk(KERN_ERR "ipt_hashlimit: Unable to create hashtable\n");
201 minfo->hinfo = hinfo;
203 /* copy match config into hashtable config */
204 memcpy(&hinfo->cfg, &minfo->cfg, sizeof(hinfo->cfg));
205 hinfo->cfg.size = size;
207 hinfo->cfg.max = 8 * hinfo->cfg.size;
208 else if (hinfo->cfg.max < hinfo->cfg.size)
209 hinfo->cfg.max = hinfo->cfg.size;
211 for (i = 0; i < hinfo->cfg.size; i++)
212 INIT_LIST_HEAD(&hinfo->hash[i]);
214 atomic_set(&hinfo->count, 0);
215 atomic_set(&hinfo->use, 1);
217 spin_lock_init(&hinfo->lock);
218 hinfo->pde = create_proc_entry(minfo->name, 0, hashlimit_procdir);
223 hinfo->pde->proc_fops = &dl_file_ops;
224 hinfo->pde->data = hinfo;
226 init_timer(&hinfo->timer);
227 hinfo->timer.expires = jiffies + MS2JIFFIES(hinfo->cfg.gc_interval);
228 hinfo->timer.data = (unsigned long )hinfo;
229 hinfo->timer.function = htable_gc;
230 add_timer(&hinfo->timer);
232 WRITE_LOCK(&hashlimit_lock);
233 list_add(&hinfo->list, &hashlimit_htables);
234 WRITE_UNLOCK(&hashlimit_lock);
239 static int select_all(struct ipt_hashlimit_htable *ht, struct dsthash_ent *he)
244 static int select_gc(struct ipt_hashlimit_htable *ht, struct dsthash_ent *he)
246 return (jiffies >= he->expires);
249 static void htable_selective_cleanup(struct ipt_hashlimit_htable *ht,
250 int (*select)(struct ipt_hashlimit_htable *ht,
251 struct dsthash_ent *he))
255 IP_NF_ASSERT(ht->cfg.size && ht->cfg.max);
257 /* lock hash table and iterate over it */
258 spin_lock_bh(&ht->lock);
259 for (i = 0; i < ht->cfg.size; i++) {
260 struct dsthash_ent *dh, *n;
261 list_for_each_entry_safe(dh, n, &ht->hash[i], list) {
262 if ((*select)(ht, dh))
263 __dsthash_free(ht, dh);
266 spin_unlock_bh(&ht->lock);
269 /* hash table garbage collector, run by timer */
270 static void htable_gc(unsigned long htlong)
272 struct ipt_hashlimit_htable *ht = (struct ipt_hashlimit_htable *)htlong;
274 htable_selective_cleanup(ht, select_gc);
276 /* re-add the timer accordingly */
277 ht->timer.expires = jiffies + MS2JIFFIES(ht->cfg.gc_interval);
278 add_timer(&ht->timer);
281 static void htable_destroy(struct ipt_hashlimit_htable *hinfo)
283 /* remove timer, if it is pending */
284 if (timer_pending(&hinfo->timer))
285 del_timer(&hinfo->timer);
287 /* remove proc entry */
288 remove_proc_entry(hinfo->pde->name, hashlimit_procdir);
290 htable_selective_cleanup(hinfo, select_all);
294 static struct ipt_hashlimit_htable *htable_find_get(char *name)
296 struct ipt_hashlimit_htable *hinfo;
298 READ_LOCK(&hashlimit_lock);
299 list_for_each_entry(hinfo, &hashlimit_htables, list) {
300 if (!strcmp(name, hinfo->pde->name)) {
301 atomic_inc(&hinfo->use);
302 READ_UNLOCK(&hashlimit_lock);
306 READ_UNLOCK(&hashlimit_lock);
311 static void htable_put(struct ipt_hashlimit_htable *hinfo)
313 if (atomic_dec_and_test(&hinfo->use)) {
314 WRITE_LOCK(&hashlimit_lock);
315 list_del(&hinfo->list);
316 WRITE_UNLOCK(&hashlimit_lock);
317 htable_destroy(hinfo);
322 /* The algorithm used is the Simple Token Bucket Filter (TBF)
323 * see net/sched/sch_tbf.c in the linux source tree
326 /* Rusty: This is my (non-mathematically-inclined) understanding of
327 this algorithm. The `average rate' in jiffies becomes your initial
328 amount of credit `credit' and the most credit you can ever have
329 `credit_cap'. The `peak rate' becomes the cost of passing the
332 `prev' tracks the last packet hit: you gain one credit per jiffy.
333 If you get credit balance more than this, the extra credit is
334 discarded. Every time the match passes, you lose `cost' credits;
335 if you don't have that many, the test fails.
337 See Alexey's formal explanation in net/sched/sch_tbf.c.
339 To get the maximum range, we multiply by this factor (ie. you get N
340 credits per jiffy). We want to allow a rate as low as 1 per day
341 (slowest userspace tool allows), which means
342 CREDITS_PER_JIFFY*HZ*60*60*24 < 2^32 ie.
344 #define MAX_CPJ (0xFFFFFFFF / (HZ*60*60*24))
346 /* Repeated shift and or gives us all 1s, final shift and add 1 gives
347 * us the power of 2 below the theoretical max, so GCC simply does a
349 #define _POW2_BELOW2(x) ((x)|((x)>>1))
350 #define _POW2_BELOW4(x) (_POW2_BELOW2(x)|_POW2_BELOW2((x)>>2))
351 #define _POW2_BELOW8(x) (_POW2_BELOW4(x)|_POW2_BELOW4((x)>>4))
352 #define _POW2_BELOW16(x) (_POW2_BELOW8(x)|_POW2_BELOW8((x)>>8))
353 #define _POW2_BELOW32(x) (_POW2_BELOW16(x)|_POW2_BELOW16((x)>>16))
354 #define POW2_BELOW32(x) ((_POW2_BELOW32(x)>>1) + 1)
356 #define CREDITS_PER_JIFFY POW2_BELOW32(MAX_CPJ)
358 /* Precision saver. */
359 static inline u_int32_t
360 user2credits(u_int32_t user)
362 /* If multiplying would overflow... */
363 if (user > 0xFFFFFFFF / (HZ*CREDITS_PER_JIFFY))
365 return (user / IPT_HASHLIMIT_SCALE) * HZ * CREDITS_PER_JIFFY;
367 return (user * HZ * CREDITS_PER_JIFFY) / IPT_HASHLIMIT_SCALE;
370 static inline void rateinfo_recalc(struct dsthash_ent *dh, unsigned long now)
372 dh->rateinfo.credit += (now - xchg(&dh->rateinfo.prev, now))
374 if (dh->rateinfo.credit > dh->rateinfo.credit_cap)
375 dh->rateinfo.credit = dh->rateinfo.credit_cap;
378 static inline int get_ports(const struct sk_buff *skb, int offset,
384 sctp_sctphdr_t sctph;
387 /* Must not be a fragment. */
391 /* Must be big enough to read ports (both UDP and TCP have
392 them at the start). */
393 ptr_u = skb_header_pointer(skb, skb->nh.iph->ihl*4, 8, &hdr_u);
397 switch (skb->nh.iph->protocol) {
399 ports[0] = ptr_u->th.source;
400 ports[1] = ptr_u->th.dest;
403 ports[0] = ptr_u->uh.source;
404 ports[1] = ptr_u->uh.dest;
407 ports[0] = ptr_u->sctph.source;
408 ports[1] = ptr_u->sctph.dest;
411 /* all other protocols don't supprot per-port hash
413 ports[0] = ports[1] = 0;
422 hashlimit_match(const struct sk_buff *skb,
423 const struct net_device *in,
424 const struct net_device *out,
425 const void *matchinfo,
429 struct ipt_hashlimit_info *r =
430 ((struct ipt_hashlimit_info *)matchinfo)->u.master;
431 struct ipt_hashlimit_htable *hinfo = r->hinfo;
432 unsigned long now = jiffies;
433 struct dsthash_ent *dh;
434 struct dsthash_dst dst;
436 /* build 'dst' according to hinfo->cfg and current packet */
437 memset(&dst, 0, sizeof(dst));
438 if (hinfo->cfg.mode & IPT_HASHLIMIT_HASH_DIP)
439 dst.dst_ip = skb->nh.iph->daddr;
440 if (hinfo->cfg.mode & IPT_HASHLIMIT_HASH_SIP)
441 dst.src_ip = skb->nh.iph->saddr;
442 if (hinfo->cfg.mode & IPT_HASHLIMIT_HASH_DPT
443 ||hinfo->cfg.mode & IPT_HASHLIMIT_HASH_SPT) {
445 if (get_ports(skb, offset, ports)) {
446 /* We've been asked to examine this packet, and we
447 can't. Hence, no choice but to drop. */
451 if (hinfo->cfg.mode & IPT_HASHLIMIT_HASH_SPT)
452 dst.src_port = ports[0];
453 if (hinfo->cfg.mode & IPT_HASHLIMIT_HASH_DPT)
454 dst.dst_port = ports[1];
457 spin_lock_bh(&hinfo->lock);
458 dh = __dsthash_find(hinfo, &dst);
460 dh = __dsthash_alloc_init(hinfo, &dst);
463 /* enomem... don't match == DROP */
465 printk(KERN_ERR "%s: ENOMEM\n", __FUNCTION__);
466 spin_unlock_bh(&hinfo->lock);
470 dh->expires = jiffies + MS2JIFFIES(hinfo->cfg.expire);
472 dh->rateinfo.prev = jiffies;
473 dh->rateinfo.credit = user2credits(hinfo->cfg.avg *
475 dh->rateinfo.credit_cap = user2credits(hinfo->cfg.avg *
477 dh->rateinfo.cost = user2credits(hinfo->cfg.avg);
479 spin_unlock_bh(&hinfo->lock);
483 /* update expiration timeout */
484 dh->expires = now + MS2JIFFIES(hinfo->cfg.expire);
486 rateinfo_recalc(dh, now);
487 if (dh->rateinfo.credit >= dh->rateinfo.cost) {
488 /* We're underlimit. */
489 dh->rateinfo.credit -= dh->rateinfo.cost;
490 spin_unlock_bh(&hinfo->lock);
494 spin_unlock_bh(&hinfo->lock);
496 /* default case: we're overlimit, thus don't match */
501 hashlimit_checkentry(const char *tablename,
502 const struct ipt_ip *ip,
504 unsigned int matchsize,
505 unsigned int hook_mask)
507 struct ipt_hashlimit_info *r = matchinfo;
509 if (matchsize != IPT_ALIGN(sizeof(struct ipt_hashlimit_info)))
512 /* Check for overflow. */
513 if (r->cfg.burst == 0
514 || user2credits(r->cfg.avg * r->cfg.burst) <
515 user2credits(r->cfg.avg)) {
516 printk(KERN_ERR "ipt_hashlimit: Overflow, try lower: %u/%u\n",
517 r->cfg.avg, r->cfg.burst);
522 || r->cfg.mode > (IPT_HASHLIMIT_HASH_DPT
523 |IPT_HASHLIMIT_HASH_DIP
524 |IPT_HASHLIMIT_HASH_SIP
525 |IPT_HASHLIMIT_HASH_SPT))
528 if (!r->cfg.gc_interval)
534 r->hinfo = htable_find_get(r->name);
535 if (!r->hinfo && (htable_create(r) != 0)) {
539 /* Ugly hack: For SMP, we only want to use one set */
546 hashlimit_destroy(void *matchinfo, unsigned int matchsize)
548 struct ipt_hashlimit_info *r = (struct ipt_hashlimit_info *) matchinfo;
550 htable_put(r->hinfo);
553 static struct ipt_match ipt_hashlimit = {
555 .match = hashlimit_match,
556 .checkentry = hashlimit_checkentry,
557 .destroy = hashlimit_destroy,
563 static void *dl_seq_start(struct seq_file *s, loff_t *pos)
565 struct proc_dir_entry *pde = s->private;
566 struct ipt_hashlimit_htable *htable = pde->data;
567 unsigned int *bucket;
569 spin_lock_bh(&htable->lock);
570 if (*pos >= htable->cfg.size)
573 bucket = kmalloc(sizeof(unsigned int), GFP_KERNEL);
575 return ERR_PTR(-ENOMEM);
581 static void *dl_seq_next(struct seq_file *s, void *v, loff_t *pos)
583 struct proc_dir_entry *pde = s->private;
584 struct ipt_hashlimit_htable *htable = pde->data;
585 unsigned int *bucket = (unsigned int *)v;
588 if (*pos >= htable->cfg.size) {
595 static void dl_seq_stop(struct seq_file *s, void *v)
597 struct proc_dir_entry *pde = s->private;
598 struct ipt_hashlimit_htable *htable = pde->data;
599 unsigned int *bucket = (unsigned int *)v;
603 spin_unlock_bh(&htable->lock);
606 static inline int dl_seq_real_show(struct dsthash_ent *ent, struct seq_file *s)
608 /* recalculate to show accurate numbers */
609 rateinfo_recalc(ent, jiffies);
611 return seq_printf(s, "%ld %u.%u.%u.%u:%u->%u.%u.%u.%u:%u %u %u %u\n",
612 (ent->expires - jiffies)/HZ,
613 NIPQUAD(ent->dst.src_ip), ntohs(ent->dst.src_port),
614 NIPQUAD(ent->dst.dst_ip), ntohs(ent->dst.dst_port),
615 ent->rateinfo.credit, ent->rateinfo.credit_cap,
619 static int dl_seq_show(struct seq_file *s, void *v)
621 struct proc_dir_entry *pde = s->private;
622 struct ipt_hashlimit_htable *htable = pde->data;
623 unsigned int *bucket = (unsigned int *)v;
625 if (LIST_FIND_W(&htable->hash[*bucket], dl_seq_real_show,
626 struct dsthash_ent *, s)) {
627 /* buffer was filled and unable to print that tuple */
633 static struct seq_operations dl_seq_ops = {
634 .start = dl_seq_start,
640 static int dl_proc_open(struct inode *inode, struct file *file)
642 int ret = seq_open(file, &dl_seq_ops);
645 struct seq_file *sf = file->private_data;
646 sf->private = PDE(inode);
651 static struct file_operations dl_file_ops = {
652 .owner = THIS_MODULE,
653 .open = dl_proc_open,
656 .release = seq_release
659 static int init_or_fini(int fini)
666 if (ipt_register_match(&ipt_hashlimit)) {
668 goto cleanup_nothing;
671 /* FIXME: do we really want HWCACHE_ALIGN since our objects are
673 hashlimit_cachep = kmem_cache_create("ipt_hashlimit",
674 sizeof(struct dsthash_ent), 0,
675 SLAB_HWCACHE_ALIGN, NULL, NULL);
676 if (!hashlimit_cachep) {
677 printk(KERN_ERR "Unable to create ipt_hashlimit slab cache\n");
679 goto cleanup_unreg_match;
682 hashlimit_procdir = proc_mkdir("ipt_hashlimit", proc_net);
683 if (!hashlimit_procdir) {
684 printk(KERN_ERR "Unable to create proc dir entry\n");
686 goto cleanup_free_slab;
692 remove_proc_entry("ipt_hashlimit", proc_net);
694 kmem_cache_destroy(hashlimit_cachep);
696 ipt_unregister_match(&ipt_hashlimit);
702 static int __init init(void)
704 return init_or_fini(0);
707 static void __exit fini(void)