Merge commit 'ed30f24e8d07d30aa3e69d1f508f4d7bd2e8ea14' of git://git.linaro.org/landi...
[firefly-linux-kernel-4.4.55.git] / net / ipv4 / netfilter / ipt_ULOG.c
1 /*
2  * netfilter module for userspace packet logging daemons
3  *
4  * (C) 2000-2004 by Harald Welte <laforge@netfilter.org>
5  * (C) 1999-2001 Paul `Rusty' Russell
6  * (C) 2002-2004 Netfilter Core Team <coreteam@netfilter.org>
7  * (C) 2005-2007 Patrick McHardy <kaber@trash.net>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License version 2 as
11  * published by the Free Software Foundation.
12  *
13  * This module accepts two parameters:
14  *
15  * nlbufsiz:
16  *   The parameter specifies how big the buffer for each netlink multicast
17  * group is. e.g. If you say nlbufsiz=8192, up to eight kb of packets will
18  * get accumulated in the kernel until they are sent to userspace. It is
19  * NOT possible to allocate more than 128kB, and it is strongly discouraged,
20  * because atomically allocating 128kB inside the network rx softirq is not
21  * reliable. Please also keep in mind that this buffer size is allocated for
22  * each nlgroup you are using, so the total kernel memory usage increases
23  * by that factor.
24  *
25  * Actually you should use nlbufsiz a bit smaller than PAGE_SIZE, since
26  * nlbufsiz is used with alloc_skb, which adds another
27  * sizeof(struct skb_shared_info).  Use NLMSG_GOODSIZE instead.
28  *
29  * flushtimeout:
30  *   Specify, after how many hundredths of a second the queue should be
31  *   flushed even if it is not full yet.
32  */
33 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
34 #include <linux/module.h>
35 #include <linux/spinlock.h>
36 #include <linux/socket.h>
37 #include <linux/slab.h>
38 #include <linux/skbuff.h>
39 #include <linux/kernel.h>
40 #include <linux/timer.h>
41 #include <net/netlink.h>
42 #include <linux/netdevice.h>
43 #include <linux/mm.h>
44 #include <linux/moduleparam.h>
45 #include <linux/netfilter.h>
46 #include <linux/netfilter/x_tables.h>
47 #include <linux/netfilter_ipv4/ipt_ULOG.h>
48 #include <net/netfilter/nf_log.h>
49 #include <net/netns/generic.h>
50 #include <net/sock.h>
51 #include <linux/bitops.h>
52 #include <asm/unaligned.h>
53
54 MODULE_LICENSE("GPL");
55 MODULE_AUTHOR("Harald Welte <laforge@gnumonks.org>");
56 MODULE_DESCRIPTION("Xtables: packet logging to netlink using ULOG");
57 MODULE_ALIAS_NET_PF_PROTO(PF_NETLINK, NETLINK_NFLOG);
58
59 #define ULOG_NL_EVENT           111             /* Harald's favorite number */
60 #define ULOG_MAXNLGROUPS        32              /* numer of nlgroups */
61
62 static unsigned int nlbufsiz = NLMSG_GOODSIZE;
63 module_param(nlbufsiz, uint, 0400);
64 MODULE_PARM_DESC(nlbufsiz, "netlink buffer size");
65
66 static unsigned int flushtimeout = 10;
67 module_param(flushtimeout, uint, 0600);
68 MODULE_PARM_DESC(flushtimeout, "buffer flush timeout (hundredths of a second)");
69
70 static bool nflog = true;
71 module_param(nflog, bool, 0400);
72 MODULE_PARM_DESC(nflog, "register as internal netfilter logging module");
73
74 /* global data structures */
75
76 typedef struct {
77         unsigned int qlen;              /* number of nlmsgs' in the skb */
78         struct nlmsghdr *lastnlh;       /* netlink header of last msg in skb */
79         struct sk_buff *skb;            /* the pre-allocated skb */
80         struct timer_list timer;        /* the timer function */
81 } ulog_buff_t;
82
83 static int ulog_net_id __read_mostly;
84 struct ulog_net {
85         unsigned int nlgroup[ULOG_MAXNLGROUPS];
86         ulog_buff_t ulog_buffers[ULOG_MAXNLGROUPS];
87         struct sock *nflognl;
88         spinlock_t lock;
89 };
90
91 static struct ulog_net *ulog_pernet(struct net *net)
92 {
93         return net_generic(net, ulog_net_id);
94 }
95
96 /* send one ulog_buff_t to userspace */
97 static void ulog_send(struct ulog_net *ulog, unsigned int nlgroupnum)
98 {
99         ulog_buff_t *ub = &ulog->ulog_buffers[nlgroupnum];
100
101         pr_debug("ulog_send: timer is deleting\n");
102         del_timer(&ub->timer);
103
104         if (!ub->skb) {
105                 pr_debug("ulog_send: nothing to send\n");
106                 return;
107         }
108
109         /* last nlmsg needs NLMSG_DONE */
110         if (ub->qlen > 1)
111                 ub->lastnlh->nlmsg_type = NLMSG_DONE;
112
113         NETLINK_CB(ub->skb).dst_group = nlgroupnum + 1;
114         pr_debug("throwing %d packets to netlink group %u\n",
115                  ub->qlen, nlgroupnum + 1);
116         netlink_broadcast(ulog->nflognl, ub->skb, 0, nlgroupnum + 1,
117                           GFP_ATOMIC);
118
119         ub->qlen = 0;
120         ub->skb = NULL;
121         ub->lastnlh = NULL;
122 }
123
124
125 /* timer function to flush queue in flushtimeout time */
126 static void ulog_timer(unsigned long data)
127 {
128         unsigned int groupnum = *((unsigned int *)data);
129         struct ulog_net *ulog = container_of((void *)data,
130                                              struct ulog_net,
131                                              nlgroup[groupnum]);
132         pr_debug("timer function called, calling ulog_send\n");
133
134         /* lock to protect against somebody modifying our structure
135          * from ipt_ulog_target at the same time */
136         spin_lock_bh(&ulog->lock);
137         ulog_send(ulog, groupnum);
138         spin_unlock_bh(&ulog->lock);
139 }
140
141 static struct sk_buff *ulog_alloc_skb(unsigned int size)
142 {
143         struct sk_buff *skb;
144         unsigned int n;
145
146         /* alloc skb which should be big enough for a whole
147          * multipart message. WARNING: has to be <= 131000
148          * due to slab allocator restrictions */
149
150         n = max(size, nlbufsiz);
151         skb = alloc_skb(n, GFP_ATOMIC | __GFP_NOWARN);
152         if (!skb) {
153                 if (n > size) {
154                         /* try to allocate only as much as we need for
155                          * current packet */
156
157                         skb = alloc_skb(size, GFP_ATOMIC);
158                         if (!skb)
159                                 pr_debug("cannot even allocate %ub\n", size);
160                 }
161         }
162
163         return skb;
164 }
165
166 static void ipt_ulog_packet(struct net *net,
167                             unsigned int hooknum,
168                             const struct sk_buff *skb,
169                             const struct net_device *in,
170                             const struct net_device *out,
171                             const struct ipt_ulog_info *loginfo,
172                             const char *prefix)
173 {
174         ulog_buff_t *ub;
175         ulog_packet_msg_t *pm;
176         size_t size, copy_len;
177         struct nlmsghdr *nlh;
178         struct timeval tv;
179         struct ulog_net *ulog = ulog_pernet(net);
180
181         /* ffs == find first bit set, necessary because userspace
182          * is already shifting groupnumber, but we need unshifted.
183          * ffs() returns [1..32], we need [0..31] */
184         unsigned int groupnum = ffs(loginfo->nl_group) - 1;
185
186         /* calculate the size of the skb needed */
187         if (loginfo->copy_range == 0 || loginfo->copy_range > skb->len)
188                 copy_len = skb->len;
189         else
190                 copy_len = loginfo->copy_range;
191
192         size = nlmsg_total_size(sizeof(*pm) + copy_len);
193
194         ub = &ulog->ulog_buffers[groupnum];
195
196         spin_lock_bh(&ulog->lock);
197
198         if (!ub->skb) {
199                 if (!(ub->skb = ulog_alloc_skb(size)))
200                         goto alloc_failure;
201         } else if (ub->qlen >= loginfo->qthreshold ||
202                    size > skb_tailroom(ub->skb)) {
203                 /* either the queue len is too high or we don't have
204                  * enough room in nlskb left. send it to userspace. */
205
206                 ulog_send(ulog, groupnum);
207
208                 if (!(ub->skb = ulog_alloc_skb(size)))
209                         goto alloc_failure;
210         }
211
212         pr_debug("qlen %d, qthreshold %Zu\n", ub->qlen, loginfo->qthreshold);
213
214         nlh = nlmsg_put(ub->skb, 0, ub->qlen, ULOG_NL_EVENT,
215                         sizeof(*pm)+copy_len, 0);
216         if (!nlh) {
217                 pr_debug("error during nlmsg_put\n");
218                 goto out_unlock;
219         }
220         ub->qlen++;
221
222         pm = nlmsg_data(nlh);
223
224         /* We might not have a timestamp, get one */
225         if (skb->tstamp.tv64 == 0)
226                 __net_timestamp((struct sk_buff *)skb);
227
228         /* copy hook, prefix, timestamp, payload, etc. */
229         pm->data_len = copy_len;
230         tv = ktime_to_timeval(skb->tstamp);
231         put_unaligned(tv.tv_sec, &pm->timestamp_sec);
232         put_unaligned(tv.tv_usec, &pm->timestamp_usec);
233         put_unaligned(skb->mark, &pm->mark);
234         pm->hook = hooknum;
235         if (prefix != NULL) {
236                 strncpy(pm->prefix, prefix, sizeof(pm->prefix) - 1);
237                 pm->prefix[sizeof(pm->prefix) - 1] = '\0';
238         }
239         else if (loginfo->prefix[0] != '\0')
240                 strncpy(pm->prefix, loginfo->prefix, sizeof(pm->prefix));
241         else
242                 *(pm->prefix) = '\0';
243
244         if (in && in->hard_header_len > 0 &&
245             skb->mac_header != skb->network_header &&
246             in->hard_header_len <= ULOG_MAC_LEN) {
247                 memcpy(pm->mac, skb_mac_header(skb), in->hard_header_len);
248                 pm->mac_len = in->hard_header_len;
249         } else
250                 pm->mac_len = 0;
251
252         if (in)
253                 strncpy(pm->indev_name, in->name, sizeof(pm->indev_name));
254         else
255                 pm->indev_name[0] = '\0';
256
257         if (out)
258                 strncpy(pm->outdev_name, out->name, sizeof(pm->outdev_name));
259         else
260                 pm->outdev_name[0] = '\0';
261
262         /* copy_len <= skb->len, so can't fail. */
263         if (skb_copy_bits(skb, 0, pm->payload, copy_len) < 0)
264                 BUG();
265
266         /* check if we are building multi-part messages */
267         if (ub->qlen > 1)
268                 ub->lastnlh->nlmsg_flags |= NLM_F_MULTI;
269
270         ub->lastnlh = nlh;
271
272         /* if timer isn't already running, start it */
273         if (!timer_pending(&ub->timer)) {
274                 ub->timer.expires = jiffies + flushtimeout * HZ / 100;
275                 add_timer(&ub->timer);
276         }
277
278         /* if threshold is reached, send message to userspace */
279         if (ub->qlen >= loginfo->qthreshold) {
280                 if (loginfo->qthreshold > 1)
281                         nlh->nlmsg_type = NLMSG_DONE;
282                 ulog_send(ulog, groupnum);
283         }
284 out_unlock:
285         spin_unlock_bh(&ulog->lock);
286
287         return;
288
289 alloc_failure:
290         pr_debug("Error building netlink message\n");
291         spin_unlock_bh(&ulog->lock);
292 }
293
294 static unsigned int
295 ulog_tg(struct sk_buff *skb, const struct xt_action_param *par)
296 {
297         struct net *net = dev_net(par->in ? par->in : par->out);
298
299         ipt_ulog_packet(net, par->hooknum, skb, par->in, par->out,
300                         par->targinfo, NULL);
301         return XT_CONTINUE;
302 }
303
304 static void ipt_logfn(struct net *net,
305                       u_int8_t pf,
306                       unsigned int hooknum,
307                       const struct sk_buff *skb,
308                       const struct net_device *in,
309                       const struct net_device *out,
310                       const struct nf_loginfo *li,
311                       const char *prefix)
312 {
313         struct ipt_ulog_info loginfo;
314
315         if (!li || li->type != NF_LOG_TYPE_ULOG) {
316                 loginfo.nl_group = ULOG_DEFAULT_NLGROUP;
317                 loginfo.copy_range = 0;
318                 loginfo.qthreshold = ULOG_DEFAULT_QTHRESHOLD;
319                 loginfo.prefix[0] = '\0';
320         } else {
321                 loginfo.nl_group = li->u.ulog.group;
322                 loginfo.copy_range = li->u.ulog.copy_len;
323                 loginfo.qthreshold = li->u.ulog.qthreshold;
324                 strlcpy(loginfo.prefix, prefix, sizeof(loginfo.prefix));
325         }
326
327         ipt_ulog_packet(net, hooknum, skb, in, out, &loginfo, prefix);
328 }
329
330 static int ulog_tg_check(const struct xt_tgchk_param *par)
331 {
332         const struct ipt_ulog_info *loginfo = par->targinfo;
333
334         if (loginfo->prefix[sizeof(loginfo->prefix) - 1] != '\0') {
335                 pr_debug("prefix not null-terminated\n");
336                 return -EINVAL;
337         }
338         if (loginfo->qthreshold > ULOG_MAX_QLEN) {
339                 pr_debug("queue threshold %Zu > MAX_QLEN\n",
340                          loginfo->qthreshold);
341                 return -EINVAL;
342         }
343         return 0;
344 }
345
346 #ifdef CONFIG_COMPAT
347 struct compat_ipt_ulog_info {
348         compat_uint_t   nl_group;
349         compat_size_t   copy_range;
350         compat_size_t   qthreshold;
351         char            prefix[ULOG_PREFIX_LEN];
352 };
353
354 static void ulog_tg_compat_from_user(void *dst, const void *src)
355 {
356         const struct compat_ipt_ulog_info *cl = src;
357         struct ipt_ulog_info l = {
358                 .nl_group       = cl->nl_group,
359                 .copy_range     = cl->copy_range,
360                 .qthreshold     = cl->qthreshold,
361         };
362
363         memcpy(l.prefix, cl->prefix, sizeof(l.prefix));
364         memcpy(dst, &l, sizeof(l));
365 }
366
367 static int ulog_tg_compat_to_user(void __user *dst, const void *src)
368 {
369         const struct ipt_ulog_info *l = src;
370         struct compat_ipt_ulog_info cl = {
371                 .nl_group       = l->nl_group,
372                 .copy_range     = l->copy_range,
373                 .qthreshold     = l->qthreshold,
374         };
375
376         memcpy(cl.prefix, l->prefix, sizeof(cl.prefix));
377         return copy_to_user(dst, &cl, sizeof(cl)) ? -EFAULT : 0;
378 }
379 #endif /* CONFIG_COMPAT */
380
381 static struct xt_target ulog_tg_reg __read_mostly = {
382         .name           = "ULOG",
383         .family         = NFPROTO_IPV4,
384         .target         = ulog_tg,
385         .targetsize     = sizeof(struct ipt_ulog_info),
386         .checkentry     = ulog_tg_check,
387 #ifdef CONFIG_COMPAT
388         .compatsize     = sizeof(struct compat_ipt_ulog_info),
389         .compat_from_user = ulog_tg_compat_from_user,
390         .compat_to_user = ulog_tg_compat_to_user,
391 #endif
392         .me             = THIS_MODULE,
393 };
394
395 static struct nf_logger ipt_ulog_logger __read_mostly = {
396         .name           = "ipt_ULOG",
397         .logfn          = ipt_logfn,
398         .me             = THIS_MODULE,
399 };
400
401 static int __net_init ulog_tg_net_init(struct net *net)
402 {
403         int i;
404         struct ulog_net *ulog = ulog_pernet(net);
405         struct netlink_kernel_cfg cfg = {
406                 .groups = ULOG_MAXNLGROUPS,
407         };
408
409         spin_lock_init(&ulog->lock);
410         /* initialize ulog_buffers */
411         for (i = 0; i < ULOG_MAXNLGROUPS; i++) {
412                 ulog->nlgroup[i] = i;
413                 setup_timer(&ulog->ulog_buffers[i].timer, ulog_timer,
414                             (unsigned long)&ulog->nlgroup[i]);
415         }
416
417         ulog->nflognl = netlink_kernel_create(net, NETLINK_NFLOG, &cfg);
418         if (!ulog->nflognl)
419                 return -ENOMEM;
420
421         if (nflog)
422                 nf_log_set(net, NFPROTO_IPV4, &ipt_ulog_logger);
423
424         return 0;
425 }
426
427 static void __net_exit ulog_tg_net_exit(struct net *net)
428 {
429         ulog_buff_t *ub;
430         int i;
431         struct ulog_net *ulog = ulog_pernet(net);
432
433         if (nflog)
434                 nf_log_unset(net, &ipt_ulog_logger);
435
436         netlink_kernel_release(ulog->nflognl);
437
438         /* remove pending timers and free allocated skb's */
439         for (i = 0; i < ULOG_MAXNLGROUPS; i++) {
440                 ub = &ulog->ulog_buffers[i];
441                 pr_debug("timer is deleting\n");
442                 del_timer(&ub->timer);
443
444                 if (ub->skb) {
445                         kfree_skb(ub->skb);
446                         ub->skb = NULL;
447                 }
448         }
449 }
450
451 static struct pernet_operations ulog_tg_net_ops = {
452         .init = ulog_tg_net_init,
453         .exit = ulog_tg_net_exit,
454         .id   = &ulog_net_id,
455         .size = sizeof(struct ulog_net),
456 };
457
458 static int __init ulog_tg_init(void)
459 {
460         int ret;
461         pr_debug("init module\n");
462
463         if (nlbufsiz > 128*1024) {
464                 pr_warn("Netlink buffer has to be <= 128kB\n");
465                 return -EINVAL;
466         }
467
468         ret = register_pernet_subsys(&ulog_tg_net_ops);
469         if (ret)
470                 goto out_pernet;
471
472         ret = xt_register_target(&ulog_tg_reg);
473         if (ret < 0)
474                 goto out_target;
475
476         if (nflog)
477                 nf_log_register(NFPROTO_IPV4, &ipt_ulog_logger);
478
479         return 0;
480
481 out_target:
482         unregister_pernet_subsys(&ulog_tg_net_ops);
483 out_pernet:
484         return ret;
485 }
486
487 static void __exit ulog_tg_exit(void)
488 {
489         pr_debug("cleanup_module\n");
490         if (nflog)
491                 nf_log_unregister(&ipt_ulog_logger);
492         xt_unregister_target(&ulog_tg_reg);
493         unregister_pernet_subsys(&ulog_tg_net_ops);
494 }
495
496 module_init(ulog_tg_init);
497 module_exit(ulog_tg_exit);