1/*
2 * This is a module which is used for logging packets to userspace via
3 * nfetlink.
4 *
5 * (C) 2005 by Harald Welte <laforge@netfilter.org>
6 *
7 * Based on the old ipv4-only ipt_ULOG.c:
8 * (C) 2000-2004 by Harald Welte <laforge@netfilter.org>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License version 2 as
12 * published by the Free Software Foundation.
13 */
14#include <linux/module.h>
15#include <linux/skbuff.h>
16#include <linux/init.h>
17#include <linux/ip.h>
18#include <linux/ipv6.h>
19#include <linux/netdevice.h>
20#include <linux/netfilter.h>
21#include <linux/netlink.h>
22#include <linux/netfilter/nfnetlink.h>
23#include <linux/netfilter/nfnetlink_log.h>
24#include <linux/spinlock.h>
25#include <linux/sysctl.h>
26#include <linux/proc_fs.h>
27#include <linux/security.h>
28#include <linux/list.h>
29#include <linux/jhash.h>
30#include <linux/random.h>
31#include <net/sock.h>
32
33#include <asm/atomic.h>
34
35#ifdef CONFIG_BRIDGE_NETFILTER
36#include "../bridge/br_private.h"
37#endif
38
39#define NFULNL_NLBUFSIZ_DEFAULT	NLMSG_GOODSIZE
40#define NFULNL_TIMEOUT_DEFAULT 	100	/* every second */
41#define NFULNL_QTHRESH_DEFAULT 	100	/* 100 packets */
42
43#define PRINTR(x, args...)	do { if (net_ratelimit()) \
44				     printk(x, ## args); } while (0);
45
46#define UDEBUG(x, ...)
47
48struct nfulnl_instance {
49	struct hlist_node hlist;	/* global list of instances */
50	spinlock_t lock;
51	atomic_t use;			/* use count */
52
53	unsigned int qlen;		/* number of nlmsgs in skb */
54	struct sk_buff *skb;		/* pre-allocatd skb */
55	struct nlmsghdr *lastnlh;	/* netlink header of last msg in skb */
56	struct timer_list timer;
57	int peer_pid;			/* PID of the peer process */
58
59	/* configurable parameters */
60	unsigned int flushtimeout;	/* timeout until queue flush */
61	unsigned int nlbufsiz;		/* netlink buffer allocation size */
62	unsigned int qthreshold;	/* threshold of the queue */
63	u_int32_t copy_range;
64	u_int32_t seq;			/* instance-local sequential counter */
65	u_int16_t group_num;		/* number of this queue */
66	u_int16_t flags;
67	u_int8_t copy_mode;
68};
69
70static DEFINE_RWLOCK(instances_lock);
71static atomic_t global_seq;
72
73#define INSTANCE_BUCKETS	16
74static struct hlist_head instance_table[INSTANCE_BUCKETS];
75static unsigned int hash_init;
76
77static inline u_int8_t instance_hashfn(u_int16_t group_num)
78{
79	return ((group_num & 0xff) % INSTANCE_BUCKETS);
80}
81
82static struct nfulnl_instance *
83__instance_lookup(u_int16_t group_num)
84{
85	struct hlist_head *head;
86	struct hlist_node *pos;
87	struct nfulnl_instance *inst;
88
89	UDEBUG("entering (group_num=%u)\n", group_num);
90
91	head = &instance_table[instance_hashfn(group_num)];
92	hlist_for_each_entry(inst, pos, head, hlist) {
93		if (inst->group_num == group_num)
94			return inst;
95	}
96	return NULL;
97}
98
99static inline void
100instance_get(struct nfulnl_instance *inst)
101{
102	atomic_inc(&inst->use);
103}
104
105static struct nfulnl_instance *
106instance_lookup_get(u_int16_t group_num)
107{
108	struct nfulnl_instance *inst;
109
110	read_lock_bh(&instances_lock);
111	inst = __instance_lookup(group_num);
112	if (inst)
113		instance_get(inst);
114	read_unlock_bh(&instances_lock);
115
116	return inst;
117}
118
119static void
120instance_put(struct nfulnl_instance *inst)
121{
122	if (inst && atomic_dec_and_test(&inst->use)) {
123		UDEBUG("kfree(inst=%p)\n", inst);
124		kfree(inst);
125		module_put(THIS_MODULE);
126	}
127}
128
129static void nfulnl_timer(unsigned long data);
130
131static struct nfulnl_instance *
132instance_create(u_int16_t group_num, int pid)
133{
134	struct nfulnl_instance *inst;
135
136	UDEBUG("entering (group_num=%u, pid=%d)\n", group_num,
137		pid);
138
139	write_lock_bh(&instances_lock);
140	if (__instance_lookup(group_num)) {
141		inst = NULL;
142		UDEBUG("aborting, instance already exists\n");
143		goto out_unlock;
144	}
145
146	inst = kzalloc(sizeof(*inst), GFP_ATOMIC);
147	if (!inst)
148		goto out_unlock;
149
150	INIT_HLIST_NODE(&inst->hlist);
151	spin_lock_init(&inst->lock);
152	/* needs to be two, since we _put() after creation */
153	atomic_set(&inst->use, 2);
154
155	setup_timer(&inst->timer, nfulnl_timer, (unsigned long)inst);
156
157	inst->peer_pid = pid;
158	inst->group_num = group_num;
159
160	inst->qthreshold 	= NFULNL_QTHRESH_DEFAULT;
161	inst->flushtimeout 	= NFULNL_TIMEOUT_DEFAULT;
162	inst->nlbufsiz 		= NFULNL_NLBUFSIZ_DEFAULT;
163	inst->copy_mode 	= NFULNL_COPY_PACKET;
164	inst->copy_range 	= 0xffff;
165
166	if (!try_module_get(THIS_MODULE))
167		goto out_free;
168
169	hlist_add_head(&inst->hlist,
170		       &instance_table[instance_hashfn(group_num)]);
171
172	UDEBUG("newly added node: %p, next=%p\n", &inst->hlist,
173		inst->hlist.next);
174
175	write_unlock_bh(&instances_lock);
176
177	return inst;
178
179out_free:
180	instance_put(inst);
181out_unlock:
182	write_unlock_bh(&instances_lock);
183	return NULL;
184}
185
186static int __nfulnl_send(struct nfulnl_instance *inst);
187
188static void
189__instance_destroy(struct nfulnl_instance *inst)
190{
191	/* first pull it out of the global list */
192	UDEBUG("removing instance %p (queuenum=%u) from hash\n",
193		inst, inst->group_num);
194
195	hlist_del(&inst->hlist);
196
197	/* then flush all pending packets from skb */
198
199	spin_lock_bh(&inst->lock);
200	if (inst->skb) {
201		/* timer "holds" one reference (we have one more) */
202		if (del_timer(&inst->timer))
203			instance_put(inst);
204		if (inst->qlen)
205			__nfulnl_send(inst);
206		if (inst->skb) {
207			kfree_skb(inst->skb);
208			inst->skb = NULL;
209		}
210	}
211	spin_unlock_bh(&inst->lock);
212
213	/* and finally put the refcount */
214	instance_put(inst);
215}
216
217static inline void
218instance_destroy(struct nfulnl_instance *inst)
219{
220	write_lock_bh(&instances_lock);
221	__instance_destroy(inst);
222	write_unlock_bh(&instances_lock);
223}
224
225static int
226nfulnl_set_mode(struct nfulnl_instance *inst, u_int8_t mode,
227		  unsigned int range)
228{
229	int status = 0;
230
231	spin_lock_bh(&inst->lock);
232
233	switch (mode) {
234	case NFULNL_COPY_NONE:
235	case NFULNL_COPY_META:
236		inst->copy_mode = mode;
237		inst->copy_range = 0;
238		break;
239
240	case NFULNL_COPY_PACKET:
241		inst->copy_mode = mode;
242		/* we're using struct nfattr which has 16bit nfa_len */
243		if (range > 0xffff)
244			inst->copy_range = 0xffff;
245		else
246			inst->copy_range = range;
247		break;
248
249	default:
250		status = -EINVAL;
251		break;
252	}
253
254	spin_unlock_bh(&inst->lock);
255
256	return status;
257}
258
259static int
260nfulnl_set_nlbufsiz(struct nfulnl_instance *inst, u_int32_t nlbufsiz)
261{
262	int status;
263
264	spin_lock_bh(&inst->lock);
265	if (nlbufsiz < NFULNL_NLBUFSIZ_DEFAULT)
266		status = -ERANGE;
267	else if (nlbufsiz > 131072)
268		status = -ERANGE;
269	else {
270		inst->nlbufsiz = nlbufsiz;
271		status = 0;
272	}
273	spin_unlock_bh(&inst->lock);
274
275	return status;
276}
277
278static int
279nfulnl_set_timeout(struct nfulnl_instance *inst, u_int32_t timeout)
280{
281	spin_lock_bh(&inst->lock);
282	inst->flushtimeout = timeout;
283	spin_unlock_bh(&inst->lock);
284
285	return 0;
286}
287
288static int
289nfulnl_set_qthresh(struct nfulnl_instance *inst, u_int32_t qthresh)
290{
291	spin_lock_bh(&inst->lock);
292	inst->qthreshold = qthresh;
293	spin_unlock_bh(&inst->lock);
294
295	return 0;
296}
297
298static int
299nfulnl_set_flags(struct nfulnl_instance *inst, u_int16_t flags)
300{
301	spin_lock_bh(&inst->lock);
302	inst->flags = flags;
303	spin_unlock_bh(&inst->lock);
304
305	return 0;
306}
307
308static struct sk_buff *nfulnl_alloc_skb(unsigned int inst_size,
309					unsigned int pkt_size)
310{
311	struct sk_buff *skb;
312	unsigned int n;
313
314	UDEBUG("entered (%u, %u)\n", inst_size, pkt_size);
315
316	/* alloc skb which should be big enough for a whole multipart
317	 * message.  WARNING: has to be <= 128k due to slab restrictions */
318
319	n = max(inst_size, pkt_size);
320	skb = alloc_skb(n, GFP_ATOMIC);
321	if (!skb) {
322		PRINTR("nfnetlink_log: can't alloc whole buffer (%u bytes)\n",
323			inst_size);
324
325		if (n > pkt_size) {
326			/* try to allocate only as much as we need for current
327			 * packet */
328
329			skb = alloc_skb(pkt_size, GFP_ATOMIC);
330			if (!skb)
331				PRINTR("nfnetlink_log: can't even alloc %u "
332				       "bytes\n", pkt_size);
333		}
334	}
335
336	return skb;
337}
338
339static int
340__nfulnl_send(struct nfulnl_instance *inst)
341{
342	int status;
343
344	if (inst->qlen > 1)
345		inst->lastnlh->nlmsg_type = NLMSG_DONE;
346
347	status = nfnetlink_unicast(inst->skb, inst->peer_pid, MSG_DONTWAIT);
348	if (status < 0) {
349		UDEBUG("netlink_unicast() failed\n");
350	}
351
352	inst->qlen = 0;
353	inst->skb = NULL;
354	inst->lastnlh = NULL;
355
356	return status;
357}
358
359static void nfulnl_timer(unsigned long data)
360{
361	struct nfulnl_instance *inst = (struct nfulnl_instance *)data;
362
363	UDEBUG("timer function called, flushing buffer\n");
364
365	spin_lock_bh(&inst->lock);
366	if (inst->skb)
367		__nfulnl_send(inst);
368	spin_unlock_bh(&inst->lock);
369	instance_put(inst);
370}
371
372/* This is an inline function, we don't really care about a long
373 * list of arguments */
374static inline int
375__build_packet_message(struct nfulnl_instance *inst,
376			const struct sk_buff *skb,
377			unsigned int data_len,
378			unsigned int pf,
379			unsigned int hooknum,
380			const struct net_device *indev,
381			const struct net_device *outdev,
382			const struct nf_loginfo *li,
383			const char *prefix, unsigned int plen)
384{
385	struct nfulnl_msg_packet_hdr pmsg;
386	struct nlmsghdr *nlh;
387	struct nfgenmsg *nfmsg;
388	__be32 tmp_uint;
389	sk_buff_data_t old_tail = inst->skb->tail;
390
391	UDEBUG("entered\n");
392
393	nlh = NLMSG_PUT(inst->skb, 0, 0,
394			NFNL_SUBSYS_ULOG << 8 | NFULNL_MSG_PACKET,
395			sizeof(struct nfgenmsg));
396	nfmsg = NLMSG_DATA(nlh);
397	nfmsg->nfgen_family = pf;
398	nfmsg->version = NFNETLINK_V0;
399	nfmsg->res_id = htons(inst->group_num);
400
401	pmsg.hw_protocol	= skb->protocol;
402	pmsg.hook		= hooknum;
403
404	NFA_PUT(inst->skb, NFULA_PACKET_HDR, sizeof(pmsg), &pmsg);
405
406	if (prefix)
407		NFA_PUT(inst->skb, NFULA_PREFIX, plen, prefix);
408
409	if (indev) {
410		tmp_uint = htonl(indev->ifindex);
411#ifndef CONFIG_BRIDGE_NETFILTER
412		NFA_PUT(inst->skb, NFULA_IFINDEX_INDEV, sizeof(tmp_uint),
413			&tmp_uint);
414#else
415		if (pf == PF_BRIDGE) {
416			/* Case 1: outdev is physical input device, we need to
417			 * look for bridge group (when called from
418			 * netfilter_bridge) */
419			NFA_PUT(inst->skb, NFULA_IFINDEX_PHYSINDEV,
420				sizeof(tmp_uint), &tmp_uint);
421			/* this is the bridge group "brX" */
422			tmp_uint = htonl(indev->br_port->br->dev->ifindex);
423			NFA_PUT(inst->skb, NFULA_IFINDEX_INDEV,
424				sizeof(tmp_uint), &tmp_uint);
425		} else {
426			/* Case 2: indev is bridge group, we need to look for
427			 * physical device (when called from ipv4) */
428			NFA_PUT(inst->skb, NFULA_IFINDEX_INDEV,
429				sizeof(tmp_uint), &tmp_uint);
430			if (skb->nf_bridge && skb->nf_bridge->physindev) {
431				tmp_uint =
432				    htonl(skb->nf_bridge->physindev->ifindex);
433				NFA_PUT(inst->skb, NFULA_IFINDEX_PHYSINDEV,
434					sizeof(tmp_uint), &tmp_uint);
435			}
436		}
437#endif
438	}
439
440	if (outdev) {
441		tmp_uint = htonl(outdev->ifindex);
442#ifndef CONFIG_BRIDGE_NETFILTER
443		NFA_PUT(inst->skb, NFULA_IFINDEX_OUTDEV, sizeof(tmp_uint),
444			&tmp_uint);
445#else
446		if (pf == PF_BRIDGE) {
447			/* Case 1: outdev is physical output device, we need to
448			 * look for bridge group (when called from
449			 * netfilter_bridge) */
450			NFA_PUT(inst->skb, NFULA_IFINDEX_PHYSOUTDEV,
451				sizeof(tmp_uint), &tmp_uint);
452			/* this is the bridge group "brX" */
453			tmp_uint = htonl(outdev->br_port->br->dev->ifindex);
454			NFA_PUT(inst->skb, NFULA_IFINDEX_OUTDEV,
455				sizeof(tmp_uint), &tmp_uint);
456		} else {
457			/* Case 2: indev is a bridge group, we need to look
458			 * for physical device (when called from ipv4) */
459			NFA_PUT(inst->skb, NFULA_IFINDEX_OUTDEV,
460				sizeof(tmp_uint), &tmp_uint);
461			if (skb->nf_bridge && skb->nf_bridge->physoutdev) {
462				tmp_uint =
463				    htonl(skb->nf_bridge->physoutdev->ifindex);
464				NFA_PUT(inst->skb, NFULA_IFINDEX_PHYSOUTDEV,
465					sizeof(tmp_uint), &tmp_uint);
466			}
467		}
468#endif
469	}
470
471	if (skb->mark) {
472		tmp_uint = htonl(skb->mark);
473		NFA_PUT(inst->skb, NFULA_MARK, sizeof(tmp_uint), &tmp_uint);
474	}
475
476	if (indev && skb->dev && skb->dev->hard_header_parse) {
477		struct nfulnl_msg_packet_hw phw;
478		int len = skb->dev->hard_header_parse((struct sk_buff *)skb,
479						    phw.hw_addr);
480		phw.hw_addrlen = htons(len);
481		NFA_PUT(inst->skb, NFULA_HWADDR, sizeof(phw), &phw);
482	}
483
484	if (skb->tstamp.tv64) {
485		struct nfulnl_msg_packet_timestamp ts;
486		struct timeval tv = ktime_to_timeval(skb->tstamp);
487		ts.sec = cpu_to_be64(tv.tv_sec);
488		ts.usec = cpu_to_be64(tv.tv_usec);
489
490		NFA_PUT(inst->skb, NFULA_TIMESTAMP, sizeof(ts), &ts);
491	}
492
493	/* UID */
494	if (skb->sk) {
495		read_lock_bh(&skb->sk->sk_callback_lock);
496		if (skb->sk->sk_socket && skb->sk->sk_socket->file) {
497			__be32 uid = htonl(skb->sk->sk_socket->file->f_uid);
498			/* need to unlock here since NFA_PUT may goto */
499			read_unlock_bh(&skb->sk->sk_callback_lock);
500			NFA_PUT(inst->skb, NFULA_UID, sizeof(uid), &uid);
501		} else
502			read_unlock_bh(&skb->sk->sk_callback_lock);
503	}
504
505	/* local sequence number */
506	if (inst->flags & NFULNL_CFG_F_SEQ) {
507		tmp_uint = htonl(inst->seq++);
508		NFA_PUT(inst->skb, NFULA_SEQ, sizeof(tmp_uint), &tmp_uint);
509	}
510	/* global sequence number */
511	if (inst->flags & NFULNL_CFG_F_SEQ_GLOBAL) {
512		tmp_uint = htonl(atomic_inc_return(&global_seq));
513		NFA_PUT(inst->skb, NFULA_SEQ_GLOBAL, sizeof(tmp_uint), &tmp_uint);
514	}
515
516	if (data_len) {
517		struct nfattr *nfa;
518		int size = NFA_LENGTH(data_len);
519
520		if (skb_tailroom(inst->skb) < (int)NFA_SPACE(data_len)) {
521			printk(KERN_WARNING "nfnetlink_log: no tailroom!\n");
522			goto nlmsg_failure;
523		}
524
525		nfa = (struct nfattr *)skb_put(inst->skb, NFA_ALIGN(size));
526		nfa->nfa_type = NFULA_PAYLOAD;
527		nfa->nfa_len = size;
528
529		if (skb_copy_bits(skb, 0, NFA_DATA(nfa), data_len))
530			BUG();
531	}
532
533	nlh->nlmsg_len = inst->skb->tail - old_tail;
534	inst->lastnlh = nlh;
535	return 0;
536
537nlmsg_failure:
538	UDEBUG("nlmsg_failure\n");
539nfattr_failure:
540	PRINTR(KERN_ERR "nfnetlink_log: error creating log nlmsg\n");
541	return -1;
542}
543
544#define RCV_SKB_FAIL(err) do { netlink_ack(skb, nlh, (err)); return; } while (0)
545
546static struct nf_loginfo default_loginfo = {
547	.type =		NF_LOG_TYPE_ULOG,
548	.u = {
549		.ulog = {
550			.copy_len	= 0xffff,
551			.group		= 0,
552			.qthreshold	= 1,
553		},
554	},
555};
556
557/* log handler for internal netfilter logging api */
558static void
559nfulnl_log_packet(unsigned int pf,
560		  unsigned int hooknum,
561		  const struct sk_buff *skb,
562		  const struct net_device *in,
563		  const struct net_device *out,
564		  const struct nf_loginfo *li_user,
565		  const char *prefix)
566{
567	unsigned int size, data_len;
568	struct nfulnl_instance *inst;
569	const struct nf_loginfo *li;
570	unsigned int qthreshold;
571	unsigned int plen;
572
573	if (li_user && li_user->type == NF_LOG_TYPE_ULOG)
574		li = li_user;
575	else
576		li = &default_loginfo;
577
578	inst = instance_lookup_get(li->u.ulog.group);
579	if (!inst)
580		return;
581
582	plen = 0;
583	if (prefix)
584		plen = strlen(prefix) + 1;
585
586	/* all macros expand to constant values at compile time */
587	size =    NLMSG_SPACE(sizeof(struct nfgenmsg))
588		+ NFA_SPACE(sizeof(struct nfulnl_msg_packet_hdr))
589		+ NFA_SPACE(sizeof(u_int32_t))	/* ifindex */
590		+ NFA_SPACE(sizeof(u_int32_t))	/* ifindex */
591#ifdef CONFIG_BRIDGE_NETFILTER
592		+ NFA_SPACE(sizeof(u_int32_t))	/* ifindex */
593		+ NFA_SPACE(sizeof(u_int32_t))	/* ifindex */
594#endif
595		+ NFA_SPACE(sizeof(u_int32_t))	/* mark */
596		+ NFA_SPACE(sizeof(u_int32_t))	/* uid */
597		+ NFA_SPACE(plen)		/* prefix */
598		+ NFA_SPACE(sizeof(struct nfulnl_msg_packet_hw))
599		+ NFA_SPACE(sizeof(struct nfulnl_msg_packet_timestamp));
600
601	UDEBUG("initial size=%u\n", size);
602
603	spin_lock_bh(&inst->lock);
604
605	if (inst->flags & NFULNL_CFG_F_SEQ)
606		size += NFA_SPACE(sizeof(u_int32_t));
607	if (inst->flags & NFULNL_CFG_F_SEQ_GLOBAL)
608		size += NFA_SPACE(sizeof(u_int32_t));
609
610	qthreshold = inst->qthreshold;
611	/* per-rule qthreshold overrides per-instance */
612	if (qthreshold > li->u.ulog.qthreshold)
613		qthreshold = li->u.ulog.qthreshold;
614
615	switch (inst->copy_mode) {
616	case NFULNL_COPY_META:
617	case NFULNL_COPY_NONE:
618		data_len = 0;
619		break;
620
621	case NFULNL_COPY_PACKET:
622		if (inst->copy_range == 0
623		    || inst->copy_range > skb->len)
624			data_len = skb->len;
625		else
626			data_len = inst->copy_range;
627
628		size += NFA_SPACE(data_len);
629		UDEBUG("copy_packet, therefore size now %u\n", size);
630		break;
631
632	default:
633		goto unlock_and_release;
634	}
635
636	if (inst->qlen >= qthreshold ||
637	    (inst->skb && size > skb_tailroom(inst->skb))) {
638		/* either the queue len is too high or we don't have
639		 * enough room in the skb left. flush to userspace. */
640		UDEBUG("flushing old skb\n");
641
642		/* timer "holds" one reference (we have another one) */
643		if (del_timer(&inst->timer))
644			instance_put(inst);
645		__nfulnl_send(inst);
646	}
647
648	if (!inst->skb) {
649		inst->skb = nfulnl_alloc_skb(inst->nlbufsiz, size);
650		if (!inst->skb)
651			goto alloc_failure;
652	}
653
654	UDEBUG("qlen %d, qthreshold %d\n", inst->qlen, qthreshold);
655	inst->qlen++;
656
657	__build_packet_message(inst, skb, data_len, pf,
658				hooknum, in, out, li, prefix, plen);
659
660	/* timer_pending always called within inst->lock, so there
661	 * is no chance of a race here */
662	if (!timer_pending(&inst->timer)) {
663		instance_get(inst);
664		inst->timer.expires = jiffies + (inst->flushtimeout*HZ/100);
665		add_timer(&inst->timer);
666	}
667
668unlock_and_release:
669	spin_unlock_bh(&inst->lock);
670	instance_put(inst);
671	return;
672
673alloc_failure:
674	UDEBUG("error allocating skb\n");
675	goto unlock_and_release;
676}
677
678static int
679nfulnl_rcv_nl_event(struct notifier_block *this,
680		   unsigned long event, void *ptr)
681{
682	struct netlink_notify *n = ptr;
683
684	if (event == NETLINK_URELEASE &&
685	    n->protocol == NETLINK_NETFILTER && n->pid) {
686		int i;
687
688		/* destroy all instances for this pid */
689		write_lock_bh(&instances_lock);
690		for  (i = 0; i < INSTANCE_BUCKETS; i++) {
691			struct hlist_node *tmp, *t2;
692			struct nfulnl_instance *inst;
693			struct hlist_head *head = &instance_table[i];
694
695			hlist_for_each_entry_safe(inst, tmp, t2, head, hlist) {
696				UDEBUG("node = %p\n", inst);
697				if (n->pid == inst->peer_pid)
698					__instance_destroy(inst);
699			}
700		}
701		write_unlock_bh(&instances_lock);
702	}
703	return NOTIFY_DONE;
704}
705
706static struct notifier_block nfulnl_rtnl_notifier = {
707	.notifier_call	= nfulnl_rcv_nl_event,
708};
709
710static int
711nfulnl_recv_unsupp(struct sock *ctnl, struct sk_buff *skb,
712		  struct nlmsghdr *nlh, struct nfattr *nfqa[])
713{
714	return -ENOTSUPP;
715}
716
717static struct nf_logger nfulnl_logger = {
718	.name	= "nfnetlink_log",
719	.logfn	= &nfulnl_log_packet,
720	.me	= THIS_MODULE,
721};
722
723static const int nfula_min[NFULA_MAX] = {
724	[NFULA_PACKET_HDR-1]	= sizeof(struct nfulnl_msg_packet_hdr),
725	[NFULA_MARK-1]		= sizeof(u_int32_t),
726	[NFULA_TIMESTAMP-1]	= sizeof(struct nfulnl_msg_packet_timestamp),
727	[NFULA_IFINDEX_INDEV-1]	= sizeof(u_int32_t),
728	[NFULA_IFINDEX_OUTDEV-1]= sizeof(u_int32_t),
729	[NFULA_IFINDEX_PHYSINDEV-1]	= sizeof(u_int32_t),
730	[NFULA_IFINDEX_PHYSOUTDEV-1]	= sizeof(u_int32_t),
731	[NFULA_HWADDR-1]	= sizeof(struct nfulnl_msg_packet_hw),
732	[NFULA_PAYLOAD-1]	= 0,
733	[NFULA_PREFIX-1]	= 0,
734	[NFULA_UID-1]		= sizeof(u_int32_t),
735	[NFULA_SEQ-1]		= sizeof(u_int32_t),
736	[NFULA_SEQ_GLOBAL-1]	= sizeof(u_int32_t),
737};
738
739static const int nfula_cfg_min[NFULA_CFG_MAX] = {
740	[NFULA_CFG_CMD-1]	= sizeof(struct nfulnl_msg_config_cmd),
741	[NFULA_CFG_MODE-1]	= sizeof(struct nfulnl_msg_config_mode),
742	[NFULA_CFG_TIMEOUT-1]	= sizeof(u_int32_t),
743	[NFULA_CFG_QTHRESH-1]	= sizeof(u_int32_t),
744	[NFULA_CFG_NLBUFSIZ-1]	= sizeof(u_int32_t),
745	[NFULA_CFG_FLAGS-1]	= sizeof(u_int16_t),
746};
747
748static int
749nfulnl_recv_config(struct sock *ctnl, struct sk_buff *skb,
750		   struct nlmsghdr *nlh, struct nfattr *nfula[])
751{
752	struct nfgenmsg *nfmsg = NLMSG_DATA(nlh);
753	u_int16_t group_num = ntohs(nfmsg->res_id);
754	struct nfulnl_instance *inst;
755	int ret = 0;
756
757	UDEBUG("entering for msg %u\n", NFNL_MSG_TYPE(nlh->nlmsg_type));
758
759	if (nfattr_bad_size(nfula, NFULA_CFG_MAX, nfula_cfg_min)) {
760		UDEBUG("bad attribute size\n");
761		return -EINVAL;
762	}
763
764	inst = instance_lookup_get(group_num);
765	if (nfula[NFULA_CFG_CMD-1]) {
766		u_int8_t pf = nfmsg->nfgen_family;
767		struct nfulnl_msg_config_cmd *cmd;
768		cmd = NFA_DATA(nfula[NFULA_CFG_CMD-1]);
769		UDEBUG("found CFG_CMD for\n");
770
771		switch (cmd->command) {
772		case NFULNL_CFG_CMD_BIND:
773			if (inst) {
774				ret = -EBUSY;
775				goto out_put;
776			}
777
778			inst = instance_create(group_num,
779					       NETLINK_CB(skb).pid);
780			if (!inst) {
781				ret = -EINVAL;
782				goto out;
783			}
784			break;
785		case NFULNL_CFG_CMD_UNBIND:
786			if (!inst) {
787				ret = -ENODEV;
788				goto out;
789			}
790
791			if (inst->peer_pid != NETLINK_CB(skb).pid) {
792				ret = -EPERM;
793				goto out_put;
794			}
795
796			instance_destroy(inst);
797			goto out;
798		case NFULNL_CFG_CMD_PF_BIND:
799			UDEBUG("registering log handler for pf=%u\n", pf);
800			ret = nf_log_register(pf, &nfulnl_logger);
801			break;
802		case NFULNL_CFG_CMD_PF_UNBIND:
803			UDEBUG("unregistering log handler for pf=%u\n", pf);
804			/* This is a bug and a feature.  We cannot unregister
805			 * other handlers, like nfnetlink_inst can */
806			nf_log_unregister_pf(pf);
807			break;
808		default:
809			ret = -EINVAL;
810			break;
811		}
812
813		if (!inst)
814			goto out;
815	} else {
816		if (!inst) {
817			UDEBUG("no config command, and no instance for "
818				"group=%u pid=%u =>ENOENT\n",
819				group_num, NETLINK_CB(skb).pid);
820			ret = -ENOENT;
821			goto out;
822		}
823
824		if (inst->peer_pid != NETLINK_CB(skb).pid) {
825			UDEBUG("no config command, and wrong pid\n");
826			ret = -EPERM;
827			goto out_put;
828		}
829	}
830
831	if (nfula[NFULA_CFG_MODE-1]) {
832		struct nfulnl_msg_config_mode *params;
833		params = NFA_DATA(nfula[NFULA_CFG_MODE-1]);
834
835		nfulnl_set_mode(inst, params->copy_mode,
836				ntohl(params->copy_range));
837	}
838
839	if (nfula[NFULA_CFG_TIMEOUT-1]) {
840		__be32 timeout =
841			*(__be32 *)NFA_DATA(nfula[NFULA_CFG_TIMEOUT-1]);
842
843		nfulnl_set_timeout(inst, ntohl(timeout));
844	}
845
846	if (nfula[NFULA_CFG_NLBUFSIZ-1]) {
847		__be32 nlbufsiz =
848			*(__be32 *)NFA_DATA(nfula[NFULA_CFG_NLBUFSIZ-1]);
849
850		nfulnl_set_nlbufsiz(inst, ntohl(nlbufsiz));
851	}
852
853	if (nfula[NFULA_CFG_QTHRESH-1]) {
854		__be32 qthresh =
855			*(__be32 *)NFA_DATA(nfula[NFULA_CFG_QTHRESH-1]);
856
857		nfulnl_set_qthresh(inst, ntohl(qthresh));
858	}
859
860	if (nfula[NFULA_CFG_FLAGS-1]) {
861		__be16 flags =
862			*(__be16 *)NFA_DATA(nfula[NFULA_CFG_FLAGS-1]);
863		nfulnl_set_flags(inst, ntohs(flags));
864	}
865
866out_put:
867	instance_put(inst);
868out:
869	return ret;
870}
871
872static struct nfnl_callback nfulnl_cb[NFULNL_MSG_MAX] = {
873	[NFULNL_MSG_PACKET]	= { .call = nfulnl_recv_unsupp,
874				    .attr_count = NFULA_MAX, },
875	[NFULNL_MSG_CONFIG]	= { .call = nfulnl_recv_config,
876				    .attr_count = NFULA_CFG_MAX, },
877};
878
879static struct nfnetlink_subsystem nfulnl_subsys = {
880	.name		= "log",
881	.subsys_id	= NFNL_SUBSYS_ULOG,
882	.cb_count	= NFULNL_MSG_MAX,
883	.cb		= nfulnl_cb,
884};
885
886#ifdef CONFIG_PROC_FS
887struct iter_state {
888	unsigned int bucket;
889};
890
891static struct hlist_node *get_first(struct iter_state *st)
892{
893	if (!st)
894		return NULL;
895
896	for (st->bucket = 0; st->bucket < INSTANCE_BUCKETS; st->bucket++) {
897		if (!hlist_empty(&instance_table[st->bucket]))
898			return instance_table[st->bucket].first;
899	}
900	return NULL;
901}
902
903static struct hlist_node *get_next(struct iter_state *st, struct hlist_node *h)
904{
905	h = h->next;
906	while (!h) {
907		if (++st->bucket >= INSTANCE_BUCKETS)
908			return NULL;
909
910		h = instance_table[st->bucket].first;
911	}
912	return h;
913}
914
915static struct hlist_node *get_idx(struct iter_state *st, loff_t pos)
916{
917	struct hlist_node *head;
918	head = get_first(st);
919
920	if (head)
921		while (pos && (head = get_next(st, head)))
922			pos--;
923	return pos ? NULL : head;
924}
925
926static void *seq_start(struct seq_file *seq, loff_t *pos)
927{
928	read_lock_bh(&instances_lock);
929	return get_idx(seq->private, *pos);
930}
931
932static void *seq_next(struct seq_file *s, void *v, loff_t *pos)
933{
934	(*pos)++;
935	return get_next(s->private, v);
936}
937
938static void seq_stop(struct seq_file *s, void *v)
939{
940	read_unlock_bh(&instances_lock);
941}
942
943static int seq_show(struct seq_file *s, void *v)
944{
945	const struct nfulnl_instance *inst = v;
946
947	return seq_printf(s, "%5d %6d %5d %1d %5d %6d %2d\n",
948			  inst->group_num,
949			  inst->peer_pid, inst->qlen,
950			  inst->copy_mode, inst->copy_range,
951			  inst->flushtimeout, atomic_read(&inst->use));
952}
953
954static struct seq_operations nful_seq_ops = {
955	.start	= seq_start,
956	.next	= seq_next,
957	.stop	= seq_stop,
958	.show	= seq_show,
959};
960
961static int nful_open(struct inode *inode, struct file *file)
962{
963	struct seq_file *seq;
964	struct iter_state *is;
965	int ret;
966
967	is = kzalloc(sizeof(*is), GFP_KERNEL);
968	if (!is)
969		return -ENOMEM;
970	ret = seq_open(file, &nful_seq_ops);
971	if (ret < 0)
972		goto out_free;
973	seq = file->private_data;
974	seq->private = is;
975	return ret;
976out_free:
977	kfree(is);
978	return ret;
979}
980
981static const struct file_operations nful_file_ops = {
982	.owner	 = THIS_MODULE,
983	.open	 = nful_open,
984	.read	 = seq_read,
985	.llseek	 = seq_lseek,
986	.release = seq_release_private,
987};
988
989#endif /* PROC_FS */
990
991static int __init nfnetlink_log_init(void)
992{
993	int i, status = -ENOMEM;
994#ifdef CONFIG_PROC_FS
995	struct proc_dir_entry *proc_nful;
996#endif
997
998	for (i = 0; i < INSTANCE_BUCKETS; i++)
999		INIT_HLIST_HEAD(&instance_table[i]);
1000
1001	/* it's not really all that important to have a random value, so
1002	 * we can do this from the init function, even if there hasn't
1003	 * been that much entropy yet */
1004	get_random_bytes(&hash_init, sizeof(hash_init));
1005
1006	netlink_register_notifier(&nfulnl_rtnl_notifier);
1007	status = nfnetlink_subsys_register(&nfulnl_subsys);
1008	if (status < 0) {
1009		printk(KERN_ERR "log: failed to create netlink socket\n");
1010		goto cleanup_netlink_notifier;
1011	}
1012
1013#ifdef CONFIG_PROC_FS
1014	proc_nful = create_proc_entry("nfnetlink_log", 0440,
1015				      proc_net_netfilter);
1016	if (!proc_nful)
1017		goto cleanup_subsys;
1018	proc_nful->proc_fops = &nful_file_ops;
1019#endif
1020	return status;
1021
1022#ifdef CONFIG_PROC_FS
1023cleanup_subsys:
1024	nfnetlink_subsys_unregister(&nfulnl_subsys);
1025#endif
1026cleanup_netlink_notifier:
1027	netlink_unregister_notifier(&nfulnl_rtnl_notifier);
1028	return status;
1029}
1030
1031static void __exit nfnetlink_log_fini(void)
1032{
1033	nf_log_unregister(&nfulnl_logger);
1034#ifdef CONFIG_PROC_FS
1035	remove_proc_entry("nfnetlink_log", proc_net_netfilter);
1036#endif
1037	nfnetlink_subsys_unregister(&nfulnl_subsys);
1038	netlink_unregister_notifier(&nfulnl_rtnl_notifier);
1039}
1040
1041MODULE_DESCRIPTION("netfilter userspace logging");
1042MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>");
1043MODULE_LICENSE("GPL");
1044MODULE_ALIAS_NFNL_SUBSYS(NFNL_SUBSYS_ULOG);
1045
1046module_init(nfnetlink_log_init);
1047module_exit(nfnetlink_log_fini);
1048