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