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