1/*
2 * netfilter module for userspace packet logging daemons
3 *
4 * (C) 2000-2002 by Harald Welte <laforge@gnumonks.org>
5 *
6 * 2000/09/22 ulog-cprange feature added
7 * 2001/01/04 in-kernel queue as proposed by Sebastian Zander
8 * 						<zander@fokus.gmd.de>
9 * 2001/01/30 per-rule nlgroup conflicts with global queue.
10 *            nlgroup now global (sysctl)
11 * 2001/04/19 ulog-queue reworked, now fixed buffer size specified at
12 * 	      module loadtime -HW
13 * 2002/07/07 remove broken nflog_rcv() function -HW
14 * 2002/08/29 fix shifted/unshifted nlgroup bug -HW
15 * 2002/10/30 fix uninitialized mac_len field - <Anders K. Pedersen>
16 *
17 * Released under the terms of the GPL
18 *
19 * This module accepts two parameters:
20 *
21 * nlbufsiz:
22 *   The parameter specifies how big the buffer for each netlink multicast
23 * group is. e.g. If you say nlbufsiz=8192, up to eight kb of packets will
24 * get accumulated in the kernel until they are sent to userspace. It is
25 * NOT possible to allocate more than 128kB, and it is strongly discouraged,
26 * because atomically allocating 128kB inside the network rx softirq is not
27 * reliable. Please also keep in mind that this buffer size is allocated for
28 * each nlgroup you are using, so the total kernel memory usage increases
29 * by that factor.
30 *
31 * flushtimeout:
32 *   Specify, after how many clock ticks (intel: 100 per second) the queue
33 * should be flushed even if it is not full yet.
34 *
35 * ipt_ULOG.c,v 1.22 2002/10/30 09:07:31 laforge Exp
36 */
37
38#include <linux/module.h>
39#include <linux/version.h>
40#include <linux/config.h>
41#include <linux/spinlock.h>
42#include <linux/socket.h>
43#include <linux/skbuff.h>
44#include <linux/kernel.h>
45#include <linux/timer.h>
46#include <linux/netlink.h>
47#include <linux/netdevice.h>
48#include <linux/mm.h>
49#include <linux/socket.h>
50#include <linux/netfilter_ipv4/ip_tables.h>
51#include <linux/netfilter_ipv4/ipt_ULOG.h>
52#include <linux/netfilter_ipv4/lockhelp.h>
53#include <net/sock.h>
54#include <linux/bitops.h>
55
56MODULE_LICENSE("GPL");
57MODULE_AUTHOR("Harald Welte <laforge@gnumonks.org>");
58MODULE_DESCRIPTION("IP tables userspace logging module");
59
60#define ULOG_NL_EVENT		111		/* Harald's favorite number */
61#define ULOG_MAXNLGROUPS	32		/* numer of nlgroups */
62
63#define DEBUGP(format, args...)
64
65#define PRINTR(format, args...) do { if (net_ratelimit()) printk(format, ## args); } while (0)
66
67static unsigned int nlbufsiz = 4096;
68MODULE_PARM(nlbufsiz, "i");
69MODULE_PARM_DESC(nlbufsiz, "netlink buffer size");
70
71static unsigned int flushtimeout = 10 * HZ;
72MODULE_PARM(flushtimeout, "i");
73MODULE_PARM_DESC(flushtimeout, "buffer flush timeout");
74
75/* global data structures */
76
77typedef struct {
78	unsigned int qlen;		/* number of nlmsgs' in the skb */
79	struct nlmsghdr *lastnlh;	/* netlink header of last msg in skb */
80	struct sk_buff *skb;		/* the pre-allocated skb */
81	struct timer_list timer;	/* the timer function */
82} ulog_buff_t;
83
84static ulog_buff_t ulog_buffers[ULOG_MAXNLGROUPS];	/* array of buffers */
85
86static struct sock *nflognl;	/* our socket */
87static size_t qlen;		/* current length of multipart-nlmsg */
88DECLARE_LOCK(ulog_lock);	/* spinlock */
89
90/* send one ulog_buff_t to userspace */
91static void ulog_send(unsigned int nlgroupnum)
92{
93	ulog_buff_t *ub = &ulog_buffers[nlgroupnum];
94
95	if (timer_pending(&ub->timer)) {
96		DEBUGP("ipt_ULOG: ulog_send: timer was pending, deleting\n");
97		del_timer(&ub->timer);
98	}
99
100	/* last nlmsg needs NLMSG_DONE */
101	if (ub->qlen > 1)
102		ub->lastnlh->nlmsg_type = NLMSG_DONE;
103
104	NETLINK_CB(ub->skb).dst_groups = (1 << nlgroupnum);
105	DEBUGP("ipt_ULOG: throwing %d packets to netlink mask %u\n",
106		ub->qlen, nlgroup);
107	netlink_broadcast(nflognl, ub->skb, 0, (1 << nlgroupnum), GFP_ATOMIC);
108
109	ub->qlen = 0;
110	ub->skb = NULL;
111	ub->lastnlh = NULL;
112
113}
114
115
116/* timer function to flush queue in ULOG_FLUSH_INTERVAL time */
117static void ulog_timer(unsigned long data)
118{
119	DEBUGP("ipt_ULOG: 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	LOCK_BH(&ulog_lock);
124	ulog_send(data);
125	UNLOCK_BH(&ulog_lock);
126}
127
128struct sk_buff *ulog_alloc_skb(unsigned int size)
129{
130	struct sk_buff *skb;
131
132	/* alloc skb which should be big enough for a whole
133	 * multipart message. WARNING: has to be <= 131000
134	 * due to slab allocator restrictions */
135
136	skb = alloc_skb(nlbufsiz, GFP_ATOMIC);
137	if (!skb) {
138		PRINTR("ipt_ULOG: can't alloc whole buffer %ub!\n",
139			nlbufsiz);
140
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			PRINTR("ipt_ULOG: can't even allocate %ub\n", size);
147	}
148
149	return skb;
150}
151
152static unsigned int ipt_ulog_target(struct sk_buff **pskb,
153				    unsigned int hooknum,
154				    const struct net_device *in,
155				    const struct net_device *out,
156				    const void *targinfo, void *userinfo)
157{
158	ulog_buff_t *ub;
159	ulog_packet_msg_t *pm;
160	size_t size, copy_len;
161	struct nlmsghdr *nlh;
162	struct ipt_ulog_info *loginfo = (struct ipt_ulog_info *) targinfo;
163
164	/* ffs == find first bit set, necessary because userspace
165	 * is already shifting groupnumber, but we need unshifted.
166	 * ffs() returns [1..32], we need [0..31] */
167	unsigned int groupnum = ffs(loginfo->nl_group) - 1;
168
169	/* calculate the size of the skb needed */
170	if ((loginfo->copy_range == 0) ||
171	    (loginfo->copy_range > (*pskb)->len)) {
172		copy_len = (*pskb)->len;
173	} else {
174		copy_len = loginfo->copy_range;
175	}
176
177	size = NLMSG_SPACE(sizeof(*pm) + copy_len);
178
179	ub = &ulog_buffers[groupnum];
180
181	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	DEBUGP("ipt_ULOG: qlen %d, qthreshold %d\n", ub->qlen,
198		loginfo->qthreshold);
199
200	/* NLMSG_PUT contains a hidden goto nlmsg_failure !!! */
201	nlh = NLMSG_PUT(ub->skb, 0, ub->qlen, ULOG_NL_EVENT,
202			size - sizeof(*nlh));
203	ub->qlen++;
204
205	pm = NLMSG_DATA(nlh);
206
207	/* copy hook, prefix, timestamp, payload, etc. */
208	pm->data_len = copy_len;
209	pm->timestamp_sec = (*pskb)->stamp.tv_sec;
210	pm->timestamp_usec = (*pskb)->stamp.tv_usec;
211	pm->mark = (*pskb)->nfmark;
212	pm->hook = hooknum;
213	if (loginfo->prefix[0] != '\0')
214		strncpy(pm->prefix, loginfo->prefix, sizeof(pm->prefix));
215	else
216		*(pm->prefix) = '\0';
217
218	if (in && in->hard_header_len > 0
219	    && (*pskb)->mac.raw != (void *) (*pskb)->nh.iph
220	    && in->hard_header_len <= ULOG_MAC_LEN) {
221		memcpy(pm->mac, (*pskb)->mac.raw, in->hard_header_len);
222		pm->mac_len = in->hard_header_len;
223	} else
224		pm->mac_len = 0;
225
226	if (in)
227		strncpy(pm->indev_name, in->name, sizeof(pm->indev_name));
228	else
229		pm->indev_name[0] = '\0';
230
231	if (out)
232		strncpy(pm->outdev_name, out->name, sizeof(pm->outdev_name));
233	else
234		pm->outdev_name[0] = '\0';
235
236	if (copy_len)
237		memcpy(pm->payload, (*pskb)->data, copy_len);
238
239	/* check if we are building multi-part messages */
240	if (ub->qlen > 1) {
241		ub->lastnlh->nlmsg_flags |= NLM_F_MULTI;
242	}
243
244	/* if threshold is reached, send message to userspace */
245	if (qlen >= loginfo->qthreshold) {
246		if (loginfo->qthreshold > 1)
247			nlh->nlmsg_type = NLMSG_DONE;
248	}
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;
255		add_timer(&ub->timer);
256	}
257
258	UNLOCK_BH(&ulog_lock);
259
260	return IPT_CONTINUE;
261
262
263nlmsg_failure:
264	PRINTR("ipt_ULOG: error during NLMSG_PUT\n");
265
266alloc_failure:
267	PRINTR("ipt_ULOG: Error building netlink message\n");
268
269	UNLOCK_BH(&ulog_lock);
270
271	return IPT_CONTINUE;
272}
273
274static int ipt_ulog_checkentry(const char *tablename,
275			       const struct ipt_entry *e,
276			       void *targinfo,
277			       unsigned int targinfosize,
278			       unsigned int hookmask)
279{
280	struct ipt_ulog_info *loginfo = (struct ipt_ulog_info *) targinfo;
281
282	if (targinfosize != IPT_ALIGN(sizeof(struct ipt_ulog_info))) {
283		DEBUGP("ipt_ULOG: targinfosize %u != 0\n", targinfosize);
284		return 0;
285	}
286
287	if (loginfo->prefix[sizeof(loginfo->prefix) - 1] != '\0') {
288		DEBUGP("ipt_ULOG: prefix term %i\n",
289		       loginfo->prefix[sizeof(loginfo->prefix) - 1]);
290		return 0;
291	}
292
293	if (loginfo->qthreshold > ULOG_MAX_QLEN) {
294		DEBUGP("ipt_ULOG: queue threshold %i > MAX_QLEN\n",
295			loginfo->qthreshold);
296		return 0;
297	}
298
299	return 1;
300}
301
302static struct ipt_target ipt_ulog_reg =
303    { {NULL, NULL}, "ULOG", ipt_ulog_target, ipt_ulog_checkentry, NULL,
304THIS_MODULE
305};
306
307static int __init init(void)
308{
309	int i;
310
311	DEBUGP("ipt_ULOG: init module\n");
312
313	if (nlbufsiz >= 128*1024) {
314		printk("Netlink buffer has to be <= 128kB\n");
315		return -EINVAL;
316	}
317
318	/* initialize ulog_buffers */
319	for (i = 0; i < ULOG_MAXNLGROUPS; i++) {
320		memset(&ulog_buffers[i], 0, sizeof(ulog_buff_t));
321		init_timer(&ulog_buffers[i].timer);
322		ulog_buffers[i].timer.function = ulog_timer;
323		ulog_buffers[i].timer.data = i;
324	}
325
326	nflognl = netlink_kernel_create(NETLINK_NFLOG, NULL);
327	if (!nflognl)
328		return -ENOMEM;
329
330	if (ipt_register_target(&ipt_ulog_reg) != 0) {
331		sock_release(nflognl->socket);
332		return -EINVAL;
333	}
334
335	return 0;
336}
337
338static void __exit fini(void)
339{
340	ulog_buff_t *ub;
341	int i;
342
343	DEBUGP("ipt_ULOG: cleanup_module\n");
344
345	ipt_unregister_target(&ipt_ulog_reg);
346	sock_release(nflognl->socket);
347
348	/* remove pending timers and free allocated skb's */
349	for (i = 0; i < ULOG_MAXNLGROUPS; i++) {
350		ub = &ulog_buffers[i];
351		if (timer_pending(&ub->timer)) {
352			DEBUGP("timer was pending, deleting\n");
353			del_timer(&ub->timer);
354		}
355
356		if (ub->skb) {
357			kfree_skb(ub->skb);
358			ub->skb = NULL;
359		}
360	}
361
362}
363
364module_init(init);
365module_exit(fini);
366