netfilter: xt_recent: add an entry reaper
[pandora-kernel.git] / net / netfilter / xt_recent.c
1 /*
2  * Copyright (c) 2006 Patrick McHardy <kaber@trash.net>
3  * Copyright © CC Computer Consultants GmbH, 2007 - 2008
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation.
8  *
9  * This is a replacement of the old ipt_recent module, which carried the
10  * following copyright notice:
11  *
12  * Author: Stephen Frost <sfrost@snowman.net>
13  * Copyright 2002-2003, Stephen Frost, 2.5.x port by laforge@netfilter.org
14  */
15 #include <linux/init.h>
16 #include <linux/ip.h>
17 #include <linux/ipv6.h>
18 #include <linux/module.h>
19 #include <linux/moduleparam.h>
20 #include <linux/proc_fs.h>
21 #include <linux/seq_file.h>
22 #include <linux/string.h>
23 #include <linux/ctype.h>
24 #include <linux/list.h>
25 #include <linux/random.h>
26 #include <linux/jhash.h>
27 #include <linux/bitops.h>
28 #include <linux/skbuff.h>
29 #include <linux/inet.h>
30 #include <net/net_namespace.h>
31 #include <net/netns/generic.h>
32
33 #include <linux/netfilter/x_tables.h>
34 #include <linux/netfilter/xt_recent.h>
35
36 MODULE_AUTHOR("Patrick McHardy <kaber@trash.net>");
37 MODULE_AUTHOR("Jan Engelhardt <jengelh@medozas.de>");
38 MODULE_DESCRIPTION("Xtables: \"recently-seen\" host matching");
39 MODULE_LICENSE("GPL");
40 MODULE_ALIAS("ipt_recent");
41 MODULE_ALIAS("ip6t_recent");
42
43 static unsigned int ip_list_tot = 100;
44 static unsigned int ip_pkt_list_tot = 20;
45 static unsigned int ip_list_hash_size = 0;
46 static unsigned int ip_list_perms = 0644;
47 static unsigned int ip_list_uid = 0;
48 static unsigned int ip_list_gid = 0;
49 module_param(ip_list_tot, uint, 0400);
50 module_param(ip_pkt_list_tot, uint, 0400);
51 module_param(ip_list_hash_size, uint, 0400);
52 module_param(ip_list_perms, uint, 0400);
53 module_param(ip_list_uid, uint, 0400);
54 module_param(ip_list_gid, uint, 0400);
55 MODULE_PARM_DESC(ip_list_tot, "number of IPs to remember per list");
56 MODULE_PARM_DESC(ip_pkt_list_tot, "number of packets per IP address to remember (max. 255)");
57 MODULE_PARM_DESC(ip_list_hash_size, "size of hash table used to look up IPs");
58 MODULE_PARM_DESC(ip_list_perms, "permissions on /proc/net/xt_recent/* files");
59 MODULE_PARM_DESC(ip_list_uid,"owner of /proc/net/xt_recent/* files");
60 MODULE_PARM_DESC(ip_list_gid,"owning group of /proc/net/xt_recent/* files");
61
62 struct recent_entry {
63         struct list_head        list;
64         struct list_head        lru_list;
65         union nf_inet_addr      addr;
66         u_int16_t               family;
67         u_int8_t                ttl;
68         u_int8_t                index;
69         u_int16_t               nstamps;
70         unsigned long           stamps[0];
71 };
72
73 struct recent_table {
74         struct list_head        list;
75         char                    name[XT_RECENT_NAME_LEN];
76         unsigned int            refcnt;
77         unsigned int            entries;
78         struct list_head        lru_list;
79         struct list_head        iphash[0];
80 };
81
82 struct recent_net {
83         struct list_head        tables;
84 #ifdef CONFIG_PROC_FS
85         struct proc_dir_entry   *xt_recent;
86 #endif
87 };
88
89 static int recent_net_id;
90 static inline struct recent_net *recent_pernet(struct net *net)
91 {
92         return net_generic(net, recent_net_id);
93 }
94
95 static DEFINE_SPINLOCK(recent_lock);
96 static DEFINE_MUTEX(recent_mutex);
97
98 #ifdef CONFIG_PROC_FS
99 static const struct file_operations recent_old_fops, recent_mt_fops;
100 #endif
101
102 static u_int32_t hash_rnd __read_mostly;
103 static bool hash_rnd_inited __read_mostly;
104
105 static inline unsigned int recent_entry_hash4(const union nf_inet_addr *addr)
106 {
107         return jhash_1word((__force u32)addr->ip, hash_rnd) &
108                (ip_list_hash_size - 1);
109 }
110
111 static inline unsigned int recent_entry_hash6(const union nf_inet_addr *addr)
112 {
113         return jhash2((u32 *)addr->ip6, ARRAY_SIZE(addr->ip6), hash_rnd) &
114                (ip_list_hash_size - 1);
115 }
116
117 static struct recent_entry *
118 recent_entry_lookup(const struct recent_table *table,
119                     const union nf_inet_addr *addrp, u_int16_t family,
120                     u_int8_t ttl)
121 {
122         struct recent_entry *e;
123         unsigned int h;
124
125         if (family == NFPROTO_IPV4)
126                 h = recent_entry_hash4(addrp);
127         else
128                 h = recent_entry_hash6(addrp);
129
130         list_for_each_entry(e, &table->iphash[h], list)
131                 if (e->family == family &&
132                     memcmp(&e->addr, addrp, sizeof(e->addr)) == 0 &&
133                     (ttl == e->ttl || ttl == 0 || e->ttl == 0))
134                         return e;
135         return NULL;
136 }
137
138 static void recent_entry_remove(struct recent_table *t, struct recent_entry *e)
139 {
140         list_del(&e->list);
141         list_del(&e->lru_list);
142         kfree(e);
143         t->entries--;
144 }
145
146 /*
147  * Drop entries with timestamps older then 'time'.
148  */
149 static void recent_entry_reap(struct recent_table *t, unsigned long time)
150 {
151         struct recent_entry *e;
152
153         /*
154          * The head of the LRU list is always the oldest entry.
155          */
156         e = list_entry(t->lru_list.next, struct recent_entry, lru_list);
157
158         /*
159          * The last time stamp is the most recent.
160          */
161         if (time_after(time, e->stamps[e->index-1]))
162                 recent_entry_remove(t, e);
163 }
164
165 static struct recent_entry *
166 recent_entry_init(struct recent_table *t, const union nf_inet_addr *addr,
167                   u_int16_t family, u_int8_t ttl)
168 {
169         struct recent_entry *e;
170
171         if (t->entries >= ip_list_tot) {
172                 e = list_entry(t->lru_list.next, struct recent_entry, lru_list);
173                 recent_entry_remove(t, e);
174         }
175         e = kmalloc(sizeof(*e) + sizeof(e->stamps[0]) * ip_pkt_list_tot,
176                     GFP_ATOMIC);
177         if (e == NULL)
178                 return NULL;
179         memcpy(&e->addr, addr, sizeof(e->addr));
180         e->ttl       = ttl;
181         e->stamps[0] = jiffies;
182         e->nstamps   = 1;
183         e->index     = 1;
184         e->family    = family;
185         if (family == NFPROTO_IPV4)
186                 list_add_tail(&e->list, &t->iphash[recent_entry_hash4(addr)]);
187         else
188                 list_add_tail(&e->list, &t->iphash[recent_entry_hash6(addr)]);
189         list_add_tail(&e->lru_list, &t->lru_list);
190         t->entries++;
191         return e;
192 }
193
194 static void recent_entry_update(struct recent_table *t, struct recent_entry *e)
195 {
196         e->index %= ip_pkt_list_tot;
197         e->stamps[e->index++] = jiffies;
198         if (e->index > e->nstamps)
199                 e->nstamps = e->index;
200         list_move_tail(&e->lru_list, &t->lru_list);
201 }
202
203 static struct recent_table *recent_table_lookup(struct recent_net *recent_net,
204                                                 const char *name)
205 {
206         struct recent_table *t;
207
208         list_for_each_entry(t, &recent_net->tables, list)
209                 if (!strcmp(t->name, name))
210                         return t;
211         return NULL;
212 }
213
214 static void recent_table_flush(struct recent_table *t)
215 {
216         struct recent_entry *e, *next;
217         unsigned int i;
218
219         for (i = 0; i < ip_list_hash_size; i++)
220                 list_for_each_entry_safe(e, next, &t->iphash[i], list)
221                         recent_entry_remove(t, e);
222 }
223
224 static bool
225 recent_mt(const struct sk_buff *skb, const struct xt_match_param *par)
226 {
227         struct net *net = dev_net(par->in ? par->in : par->out);
228         struct recent_net *recent_net = recent_pernet(net);
229         const struct xt_recent_mtinfo *info = par->matchinfo;
230         struct recent_table *t;
231         struct recent_entry *e;
232         union nf_inet_addr addr = {};
233         u_int8_t ttl;
234         bool ret = info->invert;
235
236         if (par->match->family == NFPROTO_IPV4) {
237                 const struct iphdr *iph = ip_hdr(skb);
238
239                 if (info->side == XT_RECENT_DEST)
240                         addr.ip = iph->daddr;
241                 else
242                         addr.ip = iph->saddr;
243
244                 ttl = iph->ttl;
245         } else {
246                 const struct ipv6hdr *iph = ipv6_hdr(skb);
247
248                 if (info->side == XT_RECENT_DEST)
249                         memcpy(&addr.in6, &iph->daddr, sizeof(addr.in6));
250                 else
251                         memcpy(&addr.in6, &iph->saddr, sizeof(addr.in6));
252
253                 ttl = iph->hop_limit;
254         }
255
256         /* use TTL as seen before forwarding */
257         if (par->out != NULL && skb->sk == NULL)
258                 ttl++;
259
260         spin_lock_bh(&recent_lock);
261         t = recent_table_lookup(recent_net, info->name);
262         e = recent_entry_lookup(t, &addr, par->match->family,
263                                 (info->check_set & XT_RECENT_TTL) ? ttl : 0);
264         if (e == NULL) {
265                 if (!(info->check_set & XT_RECENT_SET))
266                         goto out;
267                 e = recent_entry_init(t, &addr, par->match->family, ttl);
268                 if (e == NULL)
269                         *par->hotdrop = true;
270                 ret = !ret;
271                 goto out;
272         }
273
274         if (info->check_set & XT_RECENT_SET)
275                 ret = !ret;
276         else if (info->check_set & XT_RECENT_REMOVE) {
277                 recent_entry_remove(t, e);
278                 ret = !ret;
279         } else if (info->check_set & (XT_RECENT_CHECK | XT_RECENT_UPDATE)) {
280                 unsigned long time = jiffies - info->seconds * HZ;
281                 unsigned int i, hits = 0;
282
283                 for (i = 0; i < e->nstamps; i++) {
284                         if (info->seconds && time_after(time, e->stamps[i]))
285                                 continue;
286                         if (info->hit_count && ++hits >= info->hit_count) {
287                                 ret = !ret;
288                                 break;
289                         }
290                 }
291
292                 /* info->seconds must be non-zero */
293                 if (info->check_set & XT_RECENT_REAP)
294                         recent_entry_reap(t, time);
295         }
296
297         if (info->check_set & XT_RECENT_SET ||
298             (info->check_set & XT_RECENT_UPDATE && ret)) {
299                 recent_entry_update(t, e);
300                 e->ttl = ttl;
301         }
302 out:
303         spin_unlock_bh(&recent_lock);
304         return ret;
305 }
306
307 static bool recent_mt_check(const struct xt_mtchk_param *par)
308 {
309         struct recent_net *recent_net = recent_pernet(par->net);
310         const struct xt_recent_mtinfo *info = par->matchinfo;
311         struct recent_table *t;
312 #ifdef CONFIG_PROC_FS
313         struct proc_dir_entry *pde;
314 #endif
315         unsigned i;
316         bool ret = false;
317
318         if (unlikely(!hash_rnd_inited)) {
319                 get_random_bytes(&hash_rnd, sizeof(hash_rnd));
320                 hash_rnd_inited = true;
321         }
322         if (hweight8(info->check_set &
323                      (XT_RECENT_SET | XT_RECENT_REMOVE |
324                       XT_RECENT_CHECK | XT_RECENT_UPDATE)) != 1)
325                 return false;
326         if ((info->check_set & (XT_RECENT_SET | XT_RECENT_REMOVE)) &&
327             (info->seconds || info->hit_count ||
328             (info->check_set & XT_RECENT_MODIFIERS)))
329                 return false;
330         if ((info->check_set & XT_RECENT_REAP) && !info->seconds)
331                 return false;
332         if (info->hit_count > ip_pkt_list_tot) {
333                 pr_info(KBUILD_MODNAME ": hitcount (%u) is larger than "
334                         "packets to be remembered (%u)\n",
335                         info->hit_count, ip_pkt_list_tot);
336                 return false;
337         }
338         if (info->name[0] == '\0' ||
339             strnlen(info->name, XT_RECENT_NAME_LEN) == XT_RECENT_NAME_LEN)
340                 return false;
341
342         mutex_lock(&recent_mutex);
343         t = recent_table_lookup(recent_net, info->name);
344         if (t != NULL) {
345                 t->refcnt++;
346                 ret = true;
347                 goto out;
348         }
349
350         t = kzalloc(sizeof(*t) + sizeof(t->iphash[0]) * ip_list_hash_size,
351                     GFP_KERNEL);
352         if (t == NULL)
353                 goto out;
354         t->refcnt = 1;
355         strcpy(t->name, info->name);
356         INIT_LIST_HEAD(&t->lru_list);
357         for (i = 0; i < ip_list_hash_size; i++)
358                 INIT_LIST_HEAD(&t->iphash[i]);
359 #ifdef CONFIG_PROC_FS
360         pde = proc_create_data(t->name, ip_list_perms, recent_net->xt_recent,
361                   &recent_mt_fops, t);
362         if (pde == NULL) {
363                 kfree(t);
364                 goto out;
365         }
366         pde->uid = ip_list_uid;
367         pde->gid = ip_list_gid;
368 #endif
369         spin_lock_bh(&recent_lock);
370         list_add_tail(&t->list, &recent_net->tables);
371         spin_unlock_bh(&recent_lock);
372         ret = true;
373 out:
374         mutex_unlock(&recent_mutex);
375         return ret;
376 }
377
378 static void recent_mt_destroy(const struct xt_mtdtor_param *par)
379 {
380         struct recent_net *recent_net = recent_pernet(par->net);
381         const struct xt_recent_mtinfo *info = par->matchinfo;
382         struct recent_table *t;
383
384         mutex_lock(&recent_mutex);
385         t = recent_table_lookup(recent_net, info->name);
386         if (--t->refcnt == 0) {
387                 spin_lock_bh(&recent_lock);
388                 list_del(&t->list);
389                 spin_unlock_bh(&recent_lock);
390 #ifdef CONFIG_PROC_FS
391                 remove_proc_entry(t->name, recent_net->xt_recent);
392 #endif
393                 recent_table_flush(t);
394                 kfree(t);
395         }
396         mutex_unlock(&recent_mutex);
397 }
398
399 #ifdef CONFIG_PROC_FS
400 struct recent_iter_state {
401         const struct recent_table *table;
402         unsigned int            bucket;
403 };
404
405 static void *recent_seq_start(struct seq_file *seq, loff_t *pos)
406         __acquires(recent_lock)
407 {
408         struct recent_iter_state *st = seq->private;
409         const struct recent_table *t = st->table;
410         struct recent_entry *e;
411         loff_t p = *pos;
412
413         spin_lock_bh(&recent_lock);
414
415         for (st->bucket = 0; st->bucket < ip_list_hash_size; st->bucket++)
416                 list_for_each_entry(e, &t->iphash[st->bucket], list)
417                         if (p-- == 0)
418                                 return e;
419         return NULL;
420 }
421
422 static void *recent_seq_next(struct seq_file *seq, void *v, loff_t *pos)
423 {
424         struct recent_iter_state *st = seq->private;
425         const struct recent_table *t = st->table;
426         const struct recent_entry *e = v;
427         const struct list_head *head = e->list.next;
428
429         while (head == &t->iphash[st->bucket]) {
430                 if (++st->bucket >= ip_list_hash_size)
431                         return NULL;
432                 head = t->iphash[st->bucket].next;
433         }
434         (*pos)++;
435         return list_entry(head, struct recent_entry, list);
436 }
437
438 static void recent_seq_stop(struct seq_file *s, void *v)
439         __releases(recent_lock)
440 {
441         spin_unlock_bh(&recent_lock);
442 }
443
444 static int recent_seq_show(struct seq_file *seq, void *v)
445 {
446         const struct recent_entry *e = v;
447         unsigned int i;
448
449         i = (e->index - 1) % ip_pkt_list_tot;
450         if (e->family == NFPROTO_IPV4)
451                 seq_printf(seq, "src=%pI4 ttl: %u last_seen: %lu oldest_pkt: %u",
452                            &e->addr.ip, e->ttl, e->stamps[i], e->index);
453         else
454                 seq_printf(seq, "src=%pI6 ttl: %u last_seen: %lu oldest_pkt: %u",
455                            &e->addr.in6, e->ttl, e->stamps[i], e->index);
456         for (i = 0; i < e->nstamps; i++)
457                 seq_printf(seq, "%s %lu", i ? "," : "", e->stamps[i]);
458         seq_printf(seq, "\n");
459         return 0;
460 }
461
462 static const struct seq_operations recent_seq_ops = {
463         .start          = recent_seq_start,
464         .next           = recent_seq_next,
465         .stop           = recent_seq_stop,
466         .show           = recent_seq_show,
467 };
468
469 static int recent_seq_open(struct inode *inode, struct file *file)
470 {
471         struct proc_dir_entry *pde = PDE(inode);
472         struct recent_iter_state *st;
473
474         st = __seq_open_private(file, &recent_seq_ops, sizeof(*st));
475         if (st == NULL)
476                 return -ENOMEM;
477
478         st->table    = pde->data;
479         return 0;
480 }
481
482 static ssize_t
483 recent_mt_proc_write(struct file *file, const char __user *input,
484                      size_t size, loff_t *loff)
485 {
486         const struct proc_dir_entry *pde = PDE(file->f_path.dentry->d_inode);
487         struct recent_table *t = pde->data;
488         struct recent_entry *e;
489         char buf[sizeof("+b335:1d35:1e55:dead:c0de:1715:5afe:c0de")];
490         const char *c = buf;
491         union nf_inet_addr addr = {};
492         u_int16_t family;
493         bool add, succ;
494
495         if (size == 0)
496                 return 0;
497         if (size > sizeof(buf))
498                 size = sizeof(buf);
499         if (copy_from_user(buf, input, size) != 0)
500                 return -EFAULT;
501
502         /* Strict protocol! */
503         if (*loff != 0)
504                 return -ESPIPE;
505         switch (*c) {
506         case '/': /* flush table */
507                 spin_lock_bh(&recent_lock);
508                 recent_table_flush(t);
509                 spin_unlock_bh(&recent_lock);
510                 return size;
511         case '-': /* remove address */
512                 add = false;
513                 break;
514         case '+': /* add address */
515                 add = true;
516                 break;
517         default:
518                 printk(KERN_INFO KBUILD_MODNAME ": Need +ip, -ip or /\n");
519                 return -EINVAL;
520         }
521
522         ++c;
523         --size;
524         if (strnchr(c, size, ':') != NULL) {
525                 family = NFPROTO_IPV6;
526                 succ   = in6_pton(c, size, (void *)&addr, '\n', NULL);
527         } else {
528                 family = NFPROTO_IPV4;
529                 succ   = in4_pton(c, size, (void *)&addr, '\n', NULL);
530         }
531
532         if (!succ) {
533                 printk(KERN_INFO KBUILD_MODNAME ": illegal address written "
534                        "to procfs\n");
535                 return -EINVAL;
536         }
537
538         spin_lock_bh(&recent_lock);
539         e = recent_entry_lookup(t, &addr, family, 0);
540         if (e == NULL) {
541                 if (add)
542                         recent_entry_init(t, &addr, family, 0);
543         } else {
544                 if (add)
545                         recent_entry_update(t, e);
546                 else
547                         recent_entry_remove(t, e);
548         }
549         spin_unlock_bh(&recent_lock);
550         /* Note we removed one above */
551         *loff += size + 1;
552         return size + 1;
553 }
554
555 static const struct file_operations recent_mt_fops = {
556         .open    = recent_seq_open,
557         .read    = seq_read,
558         .write   = recent_mt_proc_write,
559         .release = seq_release_private,
560         .owner   = THIS_MODULE,
561 };
562
563 static int __net_init recent_proc_net_init(struct net *net)
564 {
565         struct recent_net *recent_net = recent_pernet(net);
566
567         recent_net->xt_recent = proc_mkdir("xt_recent", net->proc_net);
568         if (!recent_net->xt_recent)
569                 return -ENOMEM;
570         return 0;
571 }
572
573 static void __net_exit recent_proc_net_exit(struct net *net)
574 {
575         proc_net_remove(net, "xt_recent");
576 }
577 #else
578 static inline int recent_proc_net_init(struct net *net)
579 {
580         return 0;
581 }
582
583 static inline void recent_proc_net_exit(struct net *net)
584 {
585 }
586 #endif /* CONFIG_PROC_FS */
587
588 static int __net_init recent_net_init(struct net *net)
589 {
590         struct recent_net *recent_net = recent_pernet(net);
591
592         INIT_LIST_HEAD(&recent_net->tables);
593         return recent_proc_net_init(net);
594 }
595
596 static void __net_exit recent_net_exit(struct net *net)
597 {
598         struct recent_net *recent_net = recent_pernet(net);
599
600         BUG_ON(!list_empty(&recent_net->tables));
601         recent_proc_net_exit(net);
602 }
603
604 static struct pernet_operations recent_net_ops = {
605         .init   = recent_net_init,
606         .exit   = recent_net_exit,
607         .id     = &recent_net_id,
608         .size   = sizeof(struct recent_net),
609 };
610
611 static struct xt_match recent_mt_reg[] __read_mostly = {
612         {
613                 .name       = "recent",
614                 .revision   = 0,
615                 .family     = NFPROTO_IPV4,
616                 .match      = recent_mt,
617                 .matchsize  = sizeof(struct xt_recent_mtinfo),
618                 .checkentry = recent_mt_check,
619                 .destroy    = recent_mt_destroy,
620                 .me         = THIS_MODULE,
621         },
622         {
623                 .name       = "recent",
624                 .revision   = 0,
625                 .family     = NFPROTO_IPV6,
626                 .match      = recent_mt,
627                 .matchsize  = sizeof(struct xt_recent_mtinfo),
628                 .checkentry = recent_mt_check,
629                 .destroy    = recent_mt_destroy,
630                 .me         = THIS_MODULE,
631         },
632 };
633
634 static int __init recent_mt_init(void)
635 {
636         int err;
637
638         if (!ip_list_tot || !ip_pkt_list_tot || ip_pkt_list_tot > 255)
639                 return -EINVAL;
640         ip_list_hash_size = 1 << fls(ip_list_tot);
641
642         err = register_pernet_subsys(&recent_net_ops);
643         if (err)
644                 return err;
645         err = xt_register_matches(recent_mt_reg, ARRAY_SIZE(recent_mt_reg));
646         if (err)
647                 unregister_pernet_subsys(&recent_net_ops);
648         return err;
649 }
650
651 static void __exit recent_mt_exit(void)
652 {
653         xt_unregister_matches(recent_mt_reg, ARRAY_SIZE(recent_mt_reg));
654         unregister_pernet_subsys(&recent_net_ops);
655 }
656
657 module_init(recent_mt_init);
658 module_exit(recent_mt_exit);