xref: /openbmc/linux/net/netfilter/nfnetlink_log.c (revision 842ed298)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * This is a module which is used for logging packets to userspace via
4  * nfetlink.
5  *
6  * (C) 2005 by Harald Welte <laforge@netfilter.org>
7  * (C) 2006-2012 Patrick McHardy <kaber@trash.net>
8  *
9  * Based on the old ipv4-only ipt_ULOG.c:
10  * (C) 2000-2004 by Harald Welte <laforge@netfilter.org>
11  */
12 
13 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14 
15 #include <linux/module.h>
16 #include <linux/skbuff.h>
17 #include <linux/if_arp.h>
18 #include <linux/init.h>
19 #include <linux/ip.h>
20 #include <linux/ipv6.h>
21 #include <linux/netdevice.h>
22 #include <linux/netfilter.h>
23 #include <linux/netfilter_bridge.h>
24 #include <net/netlink.h>
25 #include <linux/netfilter/nfnetlink.h>
26 #include <linux/netfilter/nfnetlink_log.h>
27 #include <linux/netfilter/nf_conntrack_common.h>
28 #include <linux/spinlock.h>
29 #include <linux/sysctl.h>
30 #include <linux/proc_fs.h>
31 #include <linux/security.h>
32 #include <linux/list.h>
33 #include <linux/slab.h>
34 #include <net/sock.h>
35 #include <net/netfilter/nf_log.h>
36 #include <net/netns/generic.h>
37 
38 #include <linux/atomic.h>
39 #include <linux/refcount.h>
40 
41 
42 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
43 #include "../bridge/br_private.h"
44 #endif
45 
46 #define NFULNL_COPY_DISABLED	0xff
47 #define NFULNL_NLBUFSIZ_DEFAULT	NLMSG_GOODSIZE
48 #define NFULNL_TIMEOUT_DEFAULT 	100	/* every second */
49 #define NFULNL_QTHRESH_DEFAULT 	100	/* 100 packets */
50 /* max packet size is limited by 16-bit struct nfattr nfa_len field */
51 #define NFULNL_COPY_RANGE_MAX	(0xFFFF - NLA_HDRLEN)
52 
53 #define PRINTR(x, args...)	do { if (net_ratelimit()) \
54 				     printk(x, ## args); } while (0);
55 
56 struct nfulnl_instance {
57 	struct hlist_node hlist;	/* global list of instances */
58 	spinlock_t lock;
59 	refcount_t use;			/* use count */
60 
61 	unsigned int qlen;		/* number of nlmsgs in skb */
62 	struct sk_buff *skb;		/* pre-allocatd skb */
63 	struct timer_list timer;
64 	struct net *net;
65 	struct user_namespace *peer_user_ns;	/* User namespace of the peer process */
66 	u32 peer_portid;		/* PORTID of the peer process */
67 
68 	/* configurable parameters */
69 	unsigned int flushtimeout;	/* timeout until queue flush */
70 	unsigned int nlbufsiz;		/* netlink buffer allocation size */
71 	unsigned int qthreshold;	/* threshold of the queue */
72 	u_int32_t copy_range;
73 	u_int32_t seq;			/* instance-local sequential counter */
74 	u_int16_t group_num;		/* number of this queue */
75 	u_int16_t flags;
76 	u_int8_t copy_mode;
77 	struct rcu_head rcu;
78 };
79 
80 #define INSTANCE_BUCKETS	16
81 
82 static unsigned int nfnl_log_net_id __read_mostly;
83 
84 struct nfnl_log_net {
85 	spinlock_t instances_lock;
86 	struct hlist_head instance_table[INSTANCE_BUCKETS];
87 	atomic_t global_seq;
88 };
89 
90 static struct nfnl_log_net *nfnl_log_pernet(struct net *net)
91 {
92 	return net_generic(net, nfnl_log_net_id);
93 }
94 
95 static inline u_int8_t instance_hashfn(u_int16_t group_num)
96 {
97 	return ((group_num & 0xff) % INSTANCE_BUCKETS);
98 }
99 
100 static struct nfulnl_instance *
101 __instance_lookup(struct nfnl_log_net *log, u_int16_t group_num)
102 {
103 	struct hlist_head *head;
104 	struct nfulnl_instance *inst;
105 
106 	head = &log->instance_table[instance_hashfn(group_num)];
107 	hlist_for_each_entry_rcu(inst, head, hlist) {
108 		if (inst->group_num == group_num)
109 			return inst;
110 	}
111 	return NULL;
112 }
113 
114 static inline void
115 instance_get(struct nfulnl_instance *inst)
116 {
117 	refcount_inc(&inst->use);
118 }
119 
120 static struct nfulnl_instance *
121 instance_lookup_get(struct nfnl_log_net *log, u_int16_t group_num)
122 {
123 	struct nfulnl_instance *inst;
124 
125 	rcu_read_lock_bh();
126 	inst = __instance_lookup(log, group_num);
127 	if (inst && !refcount_inc_not_zero(&inst->use))
128 		inst = NULL;
129 	rcu_read_unlock_bh();
130 
131 	return inst;
132 }
133 
134 static void nfulnl_instance_free_rcu(struct rcu_head *head)
135 {
136 	struct nfulnl_instance *inst =
137 		container_of(head, struct nfulnl_instance, rcu);
138 
139 	put_net(inst->net);
140 	kfree(inst);
141 	module_put(THIS_MODULE);
142 }
143 
144 static void
145 instance_put(struct nfulnl_instance *inst)
146 {
147 	if (inst && refcount_dec_and_test(&inst->use))
148 		call_rcu(&inst->rcu, nfulnl_instance_free_rcu);
149 }
150 
151 static void nfulnl_timer(struct timer_list *t);
152 
153 static struct nfulnl_instance *
154 instance_create(struct net *net, u_int16_t group_num,
155 		u32 portid, struct user_namespace *user_ns)
156 {
157 	struct nfulnl_instance *inst;
158 	struct nfnl_log_net *log = nfnl_log_pernet(net);
159 	int err;
160 
161 	spin_lock_bh(&log->instances_lock);
162 	if (__instance_lookup(log, group_num)) {
163 		err = -EEXIST;
164 		goto out_unlock;
165 	}
166 
167 	inst = kzalloc(sizeof(*inst), GFP_ATOMIC);
168 	if (!inst) {
169 		err = -ENOMEM;
170 		goto out_unlock;
171 	}
172 
173 	if (!try_module_get(THIS_MODULE)) {
174 		kfree(inst);
175 		err = -EAGAIN;
176 		goto out_unlock;
177 	}
178 
179 	INIT_HLIST_NODE(&inst->hlist);
180 	spin_lock_init(&inst->lock);
181 	/* needs to be two, since we _put() after creation */
182 	refcount_set(&inst->use, 2);
183 
184 	timer_setup(&inst->timer, nfulnl_timer, 0);
185 
186 	inst->net = get_net(net);
187 	inst->peer_user_ns = user_ns;
188 	inst->peer_portid = portid;
189 	inst->group_num = group_num;
190 
191 	inst->qthreshold 	= NFULNL_QTHRESH_DEFAULT;
192 	inst->flushtimeout 	= NFULNL_TIMEOUT_DEFAULT;
193 	inst->nlbufsiz 		= NFULNL_NLBUFSIZ_DEFAULT;
194 	inst->copy_mode 	= NFULNL_COPY_PACKET;
195 	inst->copy_range 	= NFULNL_COPY_RANGE_MAX;
196 
197 	hlist_add_head_rcu(&inst->hlist,
198 		       &log->instance_table[instance_hashfn(group_num)]);
199 
200 
201 	spin_unlock_bh(&log->instances_lock);
202 
203 	return inst;
204 
205 out_unlock:
206 	spin_unlock_bh(&log->instances_lock);
207 	return ERR_PTR(err);
208 }
209 
210 static void __nfulnl_flush(struct nfulnl_instance *inst);
211 
212 /* called with BH disabled */
213 static void
214 __instance_destroy(struct nfulnl_instance *inst)
215 {
216 	/* first pull it out of the global list */
217 	hlist_del_rcu(&inst->hlist);
218 
219 	/* then flush all pending packets from skb */
220 
221 	spin_lock(&inst->lock);
222 
223 	/* lockless readers wont be able to use us */
224 	inst->copy_mode = NFULNL_COPY_DISABLED;
225 
226 	if (inst->skb)
227 		__nfulnl_flush(inst);
228 	spin_unlock(&inst->lock);
229 
230 	/* and finally put the refcount */
231 	instance_put(inst);
232 }
233 
234 static inline void
235 instance_destroy(struct nfnl_log_net *log,
236 		 struct nfulnl_instance *inst)
237 {
238 	spin_lock_bh(&log->instances_lock);
239 	__instance_destroy(inst);
240 	spin_unlock_bh(&log->instances_lock);
241 }
242 
243 static int
244 nfulnl_set_mode(struct nfulnl_instance *inst, u_int8_t mode,
245 		  unsigned int range)
246 {
247 	int status = 0;
248 
249 	spin_lock_bh(&inst->lock);
250 
251 	switch (mode) {
252 	case NFULNL_COPY_NONE:
253 	case NFULNL_COPY_META:
254 		inst->copy_mode = mode;
255 		inst->copy_range = 0;
256 		break;
257 
258 	case NFULNL_COPY_PACKET:
259 		inst->copy_mode = mode;
260 		if (range == 0)
261 			range = NFULNL_COPY_RANGE_MAX;
262 		inst->copy_range = min_t(unsigned int,
263 					 range, NFULNL_COPY_RANGE_MAX);
264 		break;
265 
266 	default:
267 		status = -EINVAL;
268 		break;
269 	}
270 
271 	spin_unlock_bh(&inst->lock);
272 
273 	return status;
274 }
275 
276 static int
277 nfulnl_set_nlbufsiz(struct nfulnl_instance *inst, u_int32_t nlbufsiz)
278 {
279 	int status;
280 
281 	spin_lock_bh(&inst->lock);
282 	if (nlbufsiz < NFULNL_NLBUFSIZ_DEFAULT)
283 		status = -ERANGE;
284 	else if (nlbufsiz > 131072)
285 		status = -ERANGE;
286 	else {
287 		inst->nlbufsiz = nlbufsiz;
288 		status = 0;
289 	}
290 	spin_unlock_bh(&inst->lock);
291 
292 	return status;
293 }
294 
295 static void
296 nfulnl_set_timeout(struct nfulnl_instance *inst, u_int32_t timeout)
297 {
298 	spin_lock_bh(&inst->lock);
299 	inst->flushtimeout = timeout;
300 	spin_unlock_bh(&inst->lock);
301 }
302 
303 static void
304 nfulnl_set_qthresh(struct nfulnl_instance *inst, u_int32_t qthresh)
305 {
306 	spin_lock_bh(&inst->lock);
307 	inst->qthreshold = qthresh;
308 	spin_unlock_bh(&inst->lock);
309 }
310 
311 static int
312 nfulnl_set_flags(struct nfulnl_instance *inst, u_int16_t flags)
313 {
314 	spin_lock_bh(&inst->lock);
315 	inst->flags = flags;
316 	spin_unlock_bh(&inst->lock);
317 
318 	return 0;
319 }
320 
321 static struct sk_buff *
322 nfulnl_alloc_skb(struct net *net, u32 peer_portid, unsigned int inst_size,
323 		 unsigned int pkt_size)
324 {
325 	struct sk_buff *skb;
326 	unsigned int n;
327 
328 	/* alloc skb which should be big enough for a whole multipart
329 	 * message.  WARNING: has to be <= 128k due to slab restrictions */
330 
331 	n = max(inst_size, pkt_size);
332 	skb = alloc_skb(n, GFP_ATOMIC | __GFP_NOWARN);
333 	if (!skb) {
334 		if (n > pkt_size) {
335 			/* try to allocate only as much as we need for current
336 			 * packet */
337 
338 			skb = alloc_skb(pkt_size, GFP_ATOMIC);
339 		}
340 	}
341 
342 	return skb;
343 }
344 
345 static void
346 __nfulnl_send(struct nfulnl_instance *inst)
347 {
348 	if (inst->qlen > 1) {
349 		struct nlmsghdr *nlh = nlmsg_put(inst->skb, 0, 0,
350 						 NLMSG_DONE,
351 						 sizeof(struct nfgenmsg),
352 						 0);
353 		if (WARN_ONCE(!nlh, "bad nlskb size: %u, tailroom %d\n",
354 			      inst->skb->len, skb_tailroom(inst->skb))) {
355 			kfree_skb(inst->skb);
356 			goto out;
357 		}
358 	}
359 	nfnetlink_unicast(inst->skb, inst->net, inst->peer_portid);
360 out:
361 	inst->qlen = 0;
362 	inst->skb = NULL;
363 }
364 
365 static void
366 __nfulnl_flush(struct nfulnl_instance *inst)
367 {
368 	/* timer holds a reference */
369 	if (del_timer(&inst->timer))
370 		instance_put(inst);
371 	if (inst->skb)
372 		__nfulnl_send(inst);
373 }
374 
375 static void
376 nfulnl_timer(struct timer_list *t)
377 {
378 	struct nfulnl_instance *inst = from_timer(inst, t, timer);
379 
380 	spin_lock_bh(&inst->lock);
381 	if (inst->skb)
382 		__nfulnl_send(inst);
383 	spin_unlock_bh(&inst->lock);
384 	instance_put(inst);
385 }
386 
387 static u32 nfulnl_get_bridge_size(const struct sk_buff *skb)
388 {
389 	u32 size = 0;
390 
391 	if (!skb_mac_header_was_set(skb))
392 		return 0;
393 
394 	if (skb_vlan_tag_present(skb)) {
395 		size += nla_total_size(0); /* nested */
396 		size += nla_total_size(sizeof(u16)); /* id */
397 		size += nla_total_size(sizeof(u16)); /* tag */
398 	}
399 
400 	if (skb->network_header > skb->mac_header)
401 		size += nla_total_size(skb->network_header - skb->mac_header);
402 
403 	return size;
404 }
405 
406 static int nfulnl_put_bridge(struct nfulnl_instance *inst, const struct sk_buff *skb)
407 {
408 	if (!skb_mac_header_was_set(skb))
409 		return 0;
410 
411 	if (skb_vlan_tag_present(skb)) {
412 		struct nlattr *nest;
413 
414 		nest = nla_nest_start(inst->skb, NFULA_VLAN);
415 		if (!nest)
416 			goto nla_put_failure;
417 
418 		if (nla_put_be16(inst->skb, NFULA_VLAN_TCI, htons(skb->vlan_tci)) ||
419 		    nla_put_be16(inst->skb, NFULA_VLAN_PROTO, skb->vlan_proto))
420 			goto nla_put_failure;
421 
422 		nla_nest_end(inst->skb, nest);
423 	}
424 
425 	if (skb->mac_header < skb->network_header) {
426 		int len = (int)(skb->network_header - skb->mac_header);
427 
428 		if (nla_put(inst->skb, NFULA_L2HDR, len, skb_mac_header(skb)))
429 			goto nla_put_failure;
430 	}
431 
432 	return 0;
433 
434 nla_put_failure:
435 	return -1;
436 }
437 
438 /* This is an inline function, we don't really care about a long
439  * list of arguments */
440 static inline int
441 __build_packet_message(struct nfnl_log_net *log,
442 			struct nfulnl_instance *inst,
443 			const struct sk_buff *skb,
444 			unsigned int data_len,
445 			u_int8_t pf,
446 			unsigned int hooknum,
447 			const struct net_device *indev,
448 			const struct net_device *outdev,
449 			const char *prefix, unsigned int plen,
450 			const struct nfnl_ct_hook *nfnl_ct,
451 			struct nf_conn *ct, enum ip_conntrack_info ctinfo)
452 {
453 	struct nfulnl_msg_packet_hdr pmsg;
454 	struct nlmsghdr *nlh;
455 	struct nfgenmsg *nfmsg;
456 	sk_buff_data_t old_tail = inst->skb->tail;
457 	struct sock *sk;
458 	const unsigned char *hwhdrp;
459 
460 	nlh = nlmsg_put(inst->skb, 0, 0,
461 			nfnl_msg_type(NFNL_SUBSYS_ULOG, NFULNL_MSG_PACKET),
462 			sizeof(struct nfgenmsg), 0);
463 	if (!nlh)
464 		return -1;
465 	nfmsg = nlmsg_data(nlh);
466 	nfmsg->nfgen_family = pf;
467 	nfmsg->version = NFNETLINK_V0;
468 	nfmsg->res_id = htons(inst->group_num);
469 
470 	memset(&pmsg, 0, sizeof(pmsg));
471 	pmsg.hw_protocol	= skb->protocol;
472 	pmsg.hook		= hooknum;
473 
474 	if (nla_put(inst->skb, NFULA_PACKET_HDR, sizeof(pmsg), &pmsg))
475 		goto nla_put_failure;
476 
477 	if (prefix &&
478 	    nla_put(inst->skb, NFULA_PREFIX, plen, prefix))
479 		goto nla_put_failure;
480 
481 	if (indev) {
482 #if !IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
483 		if (nla_put_be32(inst->skb, NFULA_IFINDEX_INDEV,
484 				 htonl(indev->ifindex)))
485 			goto nla_put_failure;
486 #else
487 		if (pf == PF_BRIDGE) {
488 			/* Case 1: outdev is physical input device, we need to
489 			 * look for bridge group (when called from
490 			 * netfilter_bridge) */
491 			if (nla_put_be32(inst->skb, NFULA_IFINDEX_PHYSINDEV,
492 					 htonl(indev->ifindex)) ||
493 			/* this is the bridge group "brX" */
494 			/* rcu_read_lock()ed by nf_hook_thresh or
495 			 * nf_log_packet.
496 			 */
497 			    nla_put_be32(inst->skb, NFULA_IFINDEX_INDEV,
498 					 htonl(br_port_get_rcu(indev)->br->dev->ifindex)))
499 				goto nla_put_failure;
500 		} else {
501 			struct net_device *physindev;
502 
503 			/* Case 2: indev is bridge group, we need to look for
504 			 * physical device (when called from ipv4) */
505 			if (nla_put_be32(inst->skb, NFULA_IFINDEX_INDEV,
506 					 htonl(indev->ifindex)))
507 				goto nla_put_failure;
508 
509 			physindev = nf_bridge_get_physindev(skb);
510 			if (physindev &&
511 			    nla_put_be32(inst->skb, NFULA_IFINDEX_PHYSINDEV,
512 					 htonl(physindev->ifindex)))
513 				goto nla_put_failure;
514 		}
515 #endif
516 	}
517 
518 	if (outdev) {
519 #if !IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
520 		if (nla_put_be32(inst->skb, NFULA_IFINDEX_OUTDEV,
521 				 htonl(outdev->ifindex)))
522 			goto nla_put_failure;
523 #else
524 		if (pf == PF_BRIDGE) {
525 			/* Case 1: outdev is physical output device, we need to
526 			 * look for bridge group (when called from
527 			 * netfilter_bridge) */
528 			if (nla_put_be32(inst->skb, NFULA_IFINDEX_PHYSOUTDEV,
529 					 htonl(outdev->ifindex)) ||
530 			/* this is the bridge group "brX" */
531 			/* rcu_read_lock()ed by nf_hook_thresh or
532 			 * nf_log_packet.
533 			 */
534 			    nla_put_be32(inst->skb, NFULA_IFINDEX_OUTDEV,
535 					 htonl(br_port_get_rcu(outdev)->br->dev->ifindex)))
536 				goto nla_put_failure;
537 		} else {
538 			struct net_device *physoutdev;
539 
540 			/* Case 2: indev is a bridge group, we need to look
541 			 * for physical device (when called from ipv4) */
542 			if (nla_put_be32(inst->skb, NFULA_IFINDEX_OUTDEV,
543 					 htonl(outdev->ifindex)))
544 				goto nla_put_failure;
545 
546 			physoutdev = nf_bridge_get_physoutdev(skb);
547 			if (physoutdev &&
548 			    nla_put_be32(inst->skb, NFULA_IFINDEX_PHYSOUTDEV,
549 					 htonl(physoutdev->ifindex)))
550 				goto nla_put_failure;
551 		}
552 #endif
553 	}
554 
555 	if (skb->mark &&
556 	    nla_put_be32(inst->skb, NFULA_MARK, htonl(skb->mark)))
557 		goto nla_put_failure;
558 
559 	if (indev && skb->dev &&
560 	    skb->mac_header != skb->network_header) {
561 		struct nfulnl_msg_packet_hw phw;
562 		int len;
563 
564 		memset(&phw, 0, sizeof(phw));
565 		len = dev_parse_header(skb, phw.hw_addr);
566 		if (len > 0) {
567 			phw.hw_addrlen = htons(len);
568 			if (nla_put(inst->skb, NFULA_HWADDR, sizeof(phw), &phw))
569 				goto nla_put_failure;
570 		}
571 	}
572 
573 	if (indev && skb_mac_header_was_set(skb)) {
574 		if (nla_put_be16(inst->skb, NFULA_HWTYPE, htons(skb->dev->type)) ||
575 		    nla_put_be16(inst->skb, NFULA_HWLEN,
576 				 htons(skb->dev->hard_header_len)))
577 			goto nla_put_failure;
578 
579 		hwhdrp = skb_mac_header(skb);
580 
581 		if (skb->dev->type == ARPHRD_SIT)
582 			hwhdrp -= ETH_HLEN;
583 
584 		if (hwhdrp >= skb->head &&
585 		    nla_put(inst->skb, NFULA_HWHEADER,
586 			    skb->dev->hard_header_len, hwhdrp))
587 			goto nla_put_failure;
588 	}
589 
590 	if (hooknum <= NF_INET_FORWARD && skb->tstamp) {
591 		struct nfulnl_msg_packet_timestamp ts;
592 		struct timespec64 kts = ktime_to_timespec64(skb->tstamp);
593 		ts.sec = cpu_to_be64(kts.tv_sec);
594 		ts.usec = cpu_to_be64(kts.tv_nsec / NSEC_PER_USEC);
595 
596 		if (nla_put(inst->skb, NFULA_TIMESTAMP, sizeof(ts), &ts))
597 			goto nla_put_failure;
598 	}
599 
600 	/* UID */
601 	sk = skb->sk;
602 	if (sk && sk_fullsock(sk)) {
603 		read_lock_bh(&sk->sk_callback_lock);
604 		if (sk->sk_socket && sk->sk_socket->file) {
605 			struct file *file = sk->sk_socket->file;
606 			const struct cred *cred = file->f_cred;
607 			struct user_namespace *user_ns = inst->peer_user_ns;
608 			__be32 uid = htonl(from_kuid_munged(user_ns, cred->fsuid));
609 			__be32 gid = htonl(from_kgid_munged(user_ns, cred->fsgid));
610 			read_unlock_bh(&sk->sk_callback_lock);
611 			if (nla_put_be32(inst->skb, NFULA_UID, uid) ||
612 			    nla_put_be32(inst->skb, NFULA_GID, gid))
613 				goto nla_put_failure;
614 		} else
615 			read_unlock_bh(&sk->sk_callback_lock);
616 	}
617 
618 	/* local sequence number */
619 	if ((inst->flags & NFULNL_CFG_F_SEQ) &&
620 	    nla_put_be32(inst->skb, NFULA_SEQ, htonl(inst->seq++)))
621 		goto nla_put_failure;
622 
623 	/* global sequence number */
624 	if ((inst->flags & NFULNL_CFG_F_SEQ_GLOBAL) &&
625 	    nla_put_be32(inst->skb, NFULA_SEQ_GLOBAL,
626 			 htonl(atomic_inc_return(&log->global_seq))))
627 		goto nla_put_failure;
628 
629 	if (ct && nfnl_ct->build(inst->skb, ct, ctinfo,
630 				 NFULA_CT, NFULA_CT_INFO) < 0)
631 		goto nla_put_failure;
632 
633 	if ((pf == NFPROTO_NETDEV || pf == NFPROTO_BRIDGE) &&
634 	    nfulnl_put_bridge(inst, skb) < 0)
635 		goto nla_put_failure;
636 
637 	if (data_len) {
638 		struct nlattr *nla;
639 		int size = nla_attr_size(data_len);
640 
641 		if (skb_tailroom(inst->skb) < nla_total_size(data_len))
642 			goto nla_put_failure;
643 
644 		nla = skb_put(inst->skb, nla_total_size(data_len));
645 		nla->nla_type = NFULA_PAYLOAD;
646 		nla->nla_len = size;
647 
648 		if (skb_copy_bits(skb, 0, nla_data(nla), data_len))
649 			BUG();
650 	}
651 
652 	nlh->nlmsg_len = inst->skb->tail - old_tail;
653 	return 0;
654 
655 nla_put_failure:
656 	PRINTR(KERN_ERR "nfnetlink_log: error creating log nlmsg\n");
657 	return -1;
658 }
659 
660 static const struct nf_loginfo default_loginfo = {
661 	.type =		NF_LOG_TYPE_ULOG,
662 	.u = {
663 		.ulog = {
664 			.copy_len	= 0xffff,
665 			.group		= 0,
666 			.qthreshold	= 1,
667 		},
668 	},
669 };
670 
671 /* log handler for internal netfilter logging api */
672 static void
673 nfulnl_log_packet(struct net *net,
674 		  u_int8_t pf,
675 		  unsigned int hooknum,
676 		  const struct sk_buff *skb,
677 		  const struct net_device *in,
678 		  const struct net_device *out,
679 		  const struct nf_loginfo *li_user,
680 		  const char *prefix)
681 {
682 	size_t size;
683 	unsigned int data_len;
684 	struct nfulnl_instance *inst;
685 	const struct nf_loginfo *li;
686 	unsigned int qthreshold;
687 	unsigned int plen = 0;
688 	struct nfnl_log_net *log = nfnl_log_pernet(net);
689 	const struct nfnl_ct_hook *nfnl_ct = NULL;
690 	struct nf_conn *ct = NULL;
691 	enum ip_conntrack_info ctinfo;
692 
693 	if (li_user && li_user->type == NF_LOG_TYPE_ULOG)
694 		li = li_user;
695 	else
696 		li = &default_loginfo;
697 
698 	inst = instance_lookup_get(log, li->u.ulog.group);
699 	if (!inst)
700 		return;
701 
702 	if (prefix)
703 		plen = strlen(prefix) + 1;
704 
705 	/* FIXME: do we want to make the size calculation conditional based on
706 	 * what is actually present?  way more branches and checks, but more
707 	 * memory efficient... */
708 	size = nlmsg_total_size(sizeof(struct nfgenmsg))
709 		+ nla_total_size(sizeof(struct nfulnl_msg_packet_hdr))
710 		+ nla_total_size(sizeof(u_int32_t))	/* ifindex */
711 		+ nla_total_size(sizeof(u_int32_t))	/* ifindex */
712 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
713 		+ nla_total_size(sizeof(u_int32_t))	/* ifindex */
714 		+ nla_total_size(sizeof(u_int32_t))	/* ifindex */
715 #endif
716 		+ nla_total_size(sizeof(u_int32_t))	/* mark */
717 		+ nla_total_size(sizeof(u_int32_t))	/* uid */
718 		+ nla_total_size(sizeof(u_int32_t))	/* gid */
719 		+ nla_total_size(plen)			/* prefix */
720 		+ nla_total_size(sizeof(struct nfulnl_msg_packet_hw))
721 		+ nla_total_size(sizeof(struct nfulnl_msg_packet_timestamp))
722 		+ nla_total_size(sizeof(struct nfgenmsg));	/* NLMSG_DONE */
723 
724 	if (in && skb_mac_header_was_set(skb)) {
725 		size += nla_total_size(skb->dev->hard_header_len)
726 			+ nla_total_size(sizeof(u_int16_t))	/* hwtype */
727 			+ nla_total_size(sizeof(u_int16_t));	/* hwlen */
728 	}
729 
730 	spin_lock_bh(&inst->lock);
731 
732 	if (inst->flags & NFULNL_CFG_F_SEQ)
733 		size += nla_total_size(sizeof(u_int32_t));
734 	if (inst->flags & NFULNL_CFG_F_SEQ_GLOBAL)
735 		size += nla_total_size(sizeof(u_int32_t));
736 	if (inst->flags & NFULNL_CFG_F_CONNTRACK) {
737 		nfnl_ct = rcu_dereference(nfnl_ct_hook);
738 		if (nfnl_ct != NULL) {
739 			ct = nfnl_ct->get_ct(skb, &ctinfo);
740 			if (ct != NULL)
741 				size += nfnl_ct->build_size(ct);
742 		}
743 	}
744 	if (pf == NFPROTO_NETDEV || pf == NFPROTO_BRIDGE)
745 		size += nfulnl_get_bridge_size(skb);
746 
747 	qthreshold = inst->qthreshold;
748 	/* per-rule qthreshold overrides per-instance */
749 	if (li->u.ulog.qthreshold)
750 		if (qthreshold > li->u.ulog.qthreshold)
751 			qthreshold = li->u.ulog.qthreshold;
752 
753 
754 	switch (inst->copy_mode) {
755 	case NFULNL_COPY_META:
756 	case NFULNL_COPY_NONE:
757 		data_len = 0;
758 		break;
759 
760 	case NFULNL_COPY_PACKET:
761 		data_len = inst->copy_range;
762 		if ((li->u.ulog.flags & NF_LOG_F_COPY_LEN) &&
763 		    (li->u.ulog.copy_len < data_len))
764 			data_len = li->u.ulog.copy_len;
765 
766 		if (data_len > skb->len)
767 			data_len = skb->len;
768 
769 		size += nla_total_size(data_len);
770 		break;
771 
772 	case NFULNL_COPY_DISABLED:
773 	default:
774 		goto unlock_and_release;
775 	}
776 
777 	if (inst->skb && size > skb_tailroom(inst->skb)) {
778 		/* either the queue len is too high or we don't have
779 		 * enough room in the skb left. flush to userspace. */
780 		__nfulnl_flush(inst);
781 	}
782 
783 	if (!inst->skb) {
784 		inst->skb = nfulnl_alloc_skb(net, inst->peer_portid,
785 					     inst->nlbufsiz, size);
786 		if (!inst->skb)
787 			goto alloc_failure;
788 	}
789 
790 	inst->qlen++;
791 
792 	__build_packet_message(log, inst, skb, data_len, pf,
793 				hooknum, in, out, prefix, plen,
794 				nfnl_ct, ct, ctinfo);
795 
796 	if (inst->qlen >= qthreshold)
797 		__nfulnl_flush(inst);
798 	/* timer_pending always called within inst->lock, so there
799 	 * is no chance of a race here */
800 	else if (!timer_pending(&inst->timer)) {
801 		instance_get(inst);
802 		inst->timer.expires = jiffies + (inst->flushtimeout*HZ/100);
803 		add_timer(&inst->timer);
804 	}
805 
806 unlock_and_release:
807 	spin_unlock_bh(&inst->lock);
808 	instance_put(inst);
809 	return;
810 
811 alloc_failure:
812 	/* FIXME: statistics */
813 	goto unlock_and_release;
814 }
815 
816 static int
817 nfulnl_rcv_nl_event(struct notifier_block *this,
818 		   unsigned long event, void *ptr)
819 {
820 	struct netlink_notify *n = ptr;
821 	struct nfnl_log_net *log = nfnl_log_pernet(n->net);
822 
823 	if (event == NETLINK_URELEASE && n->protocol == NETLINK_NETFILTER) {
824 		int i;
825 
826 		/* destroy all instances for this portid */
827 		spin_lock_bh(&log->instances_lock);
828 		for  (i = 0; i < INSTANCE_BUCKETS; i++) {
829 			struct hlist_node *t2;
830 			struct nfulnl_instance *inst;
831 			struct hlist_head *head = &log->instance_table[i];
832 
833 			hlist_for_each_entry_safe(inst, t2, head, hlist) {
834 				if (n->portid == inst->peer_portid)
835 					__instance_destroy(inst);
836 			}
837 		}
838 		spin_unlock_bh(&log->instances_lock);
839 	}
840 	return NOTIFY_DONE;
841 }
842 
843 static struct notifier_block nfulnl_rtnl_notifier = {
844 	.notifier_call	= nfulnl_rcv_nl_event,
845 };
846 
847 static int nfulnl_recv_unsupp(struct net *net, struct sock *ctnl,
848 			      struct sk_buff *skb, const struct nlmsghdr *nlh,
849 			      const struct nlattr * const nfqa[],
850 			      struct netlink_ext_ack *extack)
851 {
852 	return -ENOTSUPP;
853 }
854 
855 static struct nf_logger nfulnl_logger __read_mostly = {
856 	.name	= "nfnetlink_log",
857 	.type	= NF_LOG_TYPE_ULOG,
858 	.logfn	= nfulnl_log_packet,
859 	.me	= THIS_MODULE,
860 };
861 
862 static const struct nla_policy nfula_cfg_policy[NFULA_CFG_MAX+1] = {
863 	[NFULA_CFG_CMD]		= { .len = sizeof(struct nfulnl_msg_config_cmd) },
864 	[NFULA_CFG_MODE]	= { .len = sizeof(struct nfulnl_msg_config_mode) },
865 	[NFULA_CFG_TIMEOUT]	= { .type = NLA_U32 },
866 	[NFULA_CFG_QTHRESH]	= { .type = NLA_U32 },
867 	[NFULA_CFG_NLBUFSIZ]	= { .type = NLA_U32 },
868 	[NFULA_CFG_FLAGS]	= { .type = NLA_U16 },
869 };
870 
871 static int nfulnl_recv_config(struct net *net, struct sock *ctnl,
872 			      struct sk_buff *skb, const struct nlmsghdr *nlh,
873 			      const struct nlattr * const nfula[],
874 			      struct netlink_ext_ack *extack)
875 {
876 	struct nfgenmsg *nfmsg = nlmsg_data(nlh);
877 	u_int16_t group_num = ntohs(nfmsg->res_id);
878 	struct nfulnl_instance *inst;
879 	struct nfulnl_msg_config_cmd *cmd = NULL;
880 	struct nfnl_log_net *log = nfnl_log_pernet(net);
881 	int ret = 0;
882 	u16 flags = 0;
883 
884 	if (nfula[NFULA_CFG_CMD]) {
885 		u_int8_t pf = nfmsg->nfgen_family;
886 		cmd = nla_data(nfula[NFULA_CFG_CMD]);
887 
888 		/* Commands without queue context */
889 		switch (cmd->command) {
890 		case NFULNL_CFG_CMD_PF_BIND:
891 			return nf_log_bind_pf(net, pf, &nfulnl_logger);
892 		case NFULNL_CFG_CMD_PF_UNBIND:
893 			nf_log_unbind_pf(net, pf);
894 			return 0;
895 		}
896 	}
897 
898 	inst = instance_lookup_get(log, group_num);
899 	if (inst && inst->peer_portid != NETLINK_CB(skb).portid) {
900 		ret = -EPERM;
901 		goto out_put;
902 	}
903 
904 	/* Check if we support these flags in first place, dependencies should
905 	 * be there too not to break atomicity.
906 	 */
907 	if (nfula[NFULA_CFG_FLAGS]) {
908 		flags = ntohs(nla_get_be16(nfula[NFULA_CFG_FLAGS]));
909 
910 		if ((flags & NFULNL_CFG_F_CONNTRACK) &&
911 		    !rcu_access_pointer(nfnl_ct_hook)) {
912 #ifdef CONFIG_MODULES
913 			nfnl_unlock(NFNL_SUBSYS_ULOG);
914 			request_module("ip_conntrack_netlink");
915 			nfnl_lock(NFNL_SUBSYS_ULOG);
916 			if (rcu_access_pointer(nfnl_ct_hook)) {
917 				ret = -EAGAIN;
918 				goto out_put;
919 			}
920 #endif
921 			ret = -EOPNOTSUPP;
922 			goto out_put;
923 		}
924 	}
925 
926 	if (cmd != NULL) {
927 		switch (cmd->command) {
928 		case NFULNL_CFG_CMD_BIND:
929 			if (inst) {
930 				ret = -EBUSY;
931 				goto out_put;
932 			}
933 
934 			inst = instance_create(net, group_num,
935 					       NETLINK_CB(skb).portid,
936 					       sk_user_ns(NETLINK_CB(skb).sk));
937 			if (IS_ERR(inst)) {
938 				ret = PTR_ERR(inst);
939 				goto out;
940 			}
941 			break;
942 		case NFULNL_CFG_CMD_UNBIND:
943 			if (!inst) {
944 				ret = -ENODEV;
945 				goto out;
946 			}
947 
948 			instance_destroy(log, inst);
949 			goto out_put;
950 		default:
951 			ret = -ENOTSUPP;
952 			goto out_put;
953 		}
954 	} else if (!inst) {
955 		ret = -ENODEV;
956 		goto out;
957 	}
958 
959 	if (nfula[NFULA_CFG_MODE]) {
960 		struct nfulnl_msg_config_mode *params =
961 			nla_data(nfula[NFULA_CFG_MODE]);
962 
963 		nfulnl_set_mode(inst, params->copy_mode,
964 				ntohl(params->copy_range));
965 	}
966 
967 	if (nfula[NFULA_CFG_TIMEOUT]) {
968 		__be32 timeout = nla_get_be32(nfula[NFULA_CFG_TIMEOUT]);
969 
970 		nfulnl_set_timeout(inst, ntohl(timeout));
971 	}
972 
973 	if (nfula[NFULA_CFG_NLBUFSIZ]) {
974 		__be32 nlbufsiz = nla_get_be32(nfula[NFULA_CFG_NLBUFSIZ]);
975 
976 		nfulnl_set_nlbufsiz(inst, ntohl(nlbufsiz));
977 	}
978 
979 	if (nfula[NFULA_CFG_QTHRESH]) {
980 		__be32 qthresh = nla_get_be32(nfula[NFULA_CFG_QTHRESH]);
981 
982 		nfulnl_set_qthresh(inst, ntohl(qthresh));
983 	}
984 
985 	if (nfula[NFULA_CFG_FLAGS])
986 		nfulnl_set_flags(inst, flags);
987 
988 out_put:
989 	instance_put(inst);
990 out:
991 	return ret;
992 }
993 
994 static const struct nfnl_callback nfulnl_cb[NFULNL_MSG_MAX] = {
995 	[NFULNL_MSG_PACKET]	= { .call = nfulnl_recv_unsupp,
996 				    .attr_count = NFULA_MAX, },
997 	[NFULNL_MSG_CONFIG]	= { .call = nfulnl_recv_config,
998 				    .attr_count = NFULA_CFG_MAX,
999 				    .policy = nfula_cfg_policy },
1000 };
1001 
1002 static const struct nfnetlink_subsystem nfulnl_subsys = {
1003 	.name		= "log",
1004 	.subsys_id	= NFNL_SUBSYS_ULOG,
1005 	.cb_count	= NFULNL_MSG_MAX,
1006 	.cb		= nfulnl_cb,
1007 };
1008 
1009 #ifdef CONFIG_PROC_FS
1010 struct iter_state {
1011 	struct seq_net_private p;
1012 	unsigned int bucket;
1013 };
1014 
1015 static struct hlist_node *get_first(struct net *net, struct iter_state *st)
1016 {
1017 	struct nfnl_log_net *log;
1018 	if (!st)
1019 		return NULL;
1020 
1021 	log = nfnl_log_pernet(net);
1022 
1023 	for (st->bucket = 0; st->bucket < INSTANCE_BUCKETS; st->bucket++) {
1024 		struct hlist_head *head = &log->instance_table[st->bucket];
1025 
1026 		if (!hlist_empty(head))
1027 			return rcu_dereference_bh(hlist_first_rcu(head));
1028 	}
1029 	return NULL;
1030 }
1031 
1032 static struct hlist_node *get_next(struct net *net, struct iter_state *st,
1033 				   struct hlist_node *h)
1034 {
1035 	h = rcu_dereference_bh(hlist_next_rcu(h));
1036 	while (!h) {
1037 		struct nfnl_log_net *log;
1038 		struct hlist_head *head;
1039 
1040 		if (++st->bucket >= INSTANCE_BUCKETS)
1041 			return NULL;
1042 
1043 		log = nfnl_log_pernet(net);
1044 		head = &log->instance_table[st->bucket];
1045 		h = rcu_dereference_bh(hlist_first_rcu(head));
1046 	}
1047 	return h;
1048 }
1049 
1050 static struct hlist_node *get_idx(struct net *net, struct iter_state *st,
1051 				  loff_t pos)
1052 {
1053 	struct hlist_node *head;
1054 	head = get_first(net, st);
1055 
1056 	if (head)
1057 		while (pos && (head = get_next(net, st, head)))
1058 			pos--;
1059 	return pos ? NULL : head;
1060 }
1061 
1062 static void *seq_start(struct seq_file *s, loff_t *pos)
1063 	__acquires(rcu_bh)
1064 {
1065 	rcu_read_lock_bh();
1066 	return get_idx(seq_file_net(s), s->private, *pos);
1067 }
1068 
1069 static void *seq_next(struct seq_file *s, void *v, loff_t *pos)
1070 {
1071 	(*pos)++;
1072 	return get_next(seq_file_net(s), s->private, v);
1073 }
1074 
1075 static void seq_stop(struct seq_file *s, void *v)
1076 	__releases(rcu_bh)
1077 {
1078 	rcu_read_unlock_bh();
1079 }
1080 
1081 static int seq_show(struct seq_file *s, void *v)
1082 {
1083 	const struct nfulnl_instance *inst = v;
1084 
1085 	seq_printf(s, "%5u %6u %5u %1u %5u %6u %2u\n",
1086 		   inst->group_num,
1087 		   inst->peer_portid, inst->qlen,
1088 		   inst->copy_mode, inst->copy_range,
1089 		   inst->flushtimeout, refcount_read(&inst->use));
1090 
1091 	return 0;
1092 }
1093 
1094 static const struct seq_operations nful_seq_ops = {
1095 	.start	= seq_start,
1096 	.next	= seq_next,
1097 	.stop	= seq_stop,
1098 	.show	= seq_show,
1099 };
1100 #endif /* PROC_FS */
1101 
1102 static int __net_init nfnl_log_net_init(struct net *net)
1103 {
1104 	unsigned int i;
1105 	struct nfnl_log_net *log = nfnl_log_pernet(net);
1106 #ifdef CONFIG_PROC_FS
1107 	struct proc_dir_entry *proc;
1108 	kuid_t root_uid;
1109 	kgid_t root_gid;
1110 #endif
1111 
1112 	for (i = 0; i < INSTANCE_BUCKETS; i++)
1113 		INIT_HLIST_HEAD(&log->instance_table[i]);
1114 	spin_lock_init(&log->instances_lock);
1115 
1116 #ifdef CONFIG_PROC_FS
1117 	proc = proc_create_net("nfnetlink_log", 0440, net->nf.proc_netfilter,
1118 			&nful_seq_ops, sizeof(struct iter_state));
1119 	if (!proc)
1120 		return -ENOMEM;
1121 
1122 	root_uid = make_kuid(net->user_ns, 0);
1123 	root_gid = make_kgid(net->user_ns, 0);
1124 	if (uid_valid(root_uid) && gid_valid(root_gid))
1125 		proc_set_user(proc, root_uid, root_gid);
1126 #endif
1127 	return 0;
1128 }
1129 
1130 static void __net_exit nfnl_log_net_exit(struct net *net)
1131 {
1132 	struct nfnl_log_net *log = nfnl_log_pernet(net);
1133 	unsigned int i;
1134 
1135 #ifdef CONFIG_PROC_FS
1136 	remove_proc_entry("nfnetlink_log", net->nf.proc_netfilter);
1137 #endif
1138 	nf_log_unset(net, &nfulnl_logger);
1139 	for (i = 0; i < INSTANCE_BUCKETS; i++)
1140 		WARN_ON_ONCE(!hlist_empty(&log->instance_table[i]));
1141 }
1142 
1143 static struct pernet_operations nfnl_log_net_ops = {
1144 	.init	= nfnl_log_net_init,
1145 	.exit	= nfnl_log_net_exit,
1146 	.id	= &nfnl_log_net_id,
1147 	.size	= sizeof(struct nfnl_log_net),
1148 };
1149 
1150 static int __init nfnetlink_log_init(void)
1151 {
1152 	int status;
1153 
1154 	status = register_pernet_subsys(&nfnl_log_net_ops);
1155 	if (status < 0) {
1156 		pr_err("failed to register pernet ops\n");
1157 		goto out;
1158 	}
1159 
1160 	netlink_register_notifier(&nfulnl_rtnl_notifier);
1161 	status = nfnetlink_subsys_register(&nfulnl_subsys);
1162 	if (status < 0) {
1163 		pr_err("failed to create netlink socket\n");
1164 		goto cleanup_netlink_notifier;
1165 	}
1166 
1167 	status = nf_log_register(NFPROTO_UNSPEC, &nfulnl_logger);
1168 	if (status < 0) {
1169 		pr_err("failed to register logger\n");
1170 		goto cleanup_subsys;
1171 	}
1172 
1173 	return status;
1174 
1175 cleanup_subsys:
1176 	nfnetlink_subsys_unregister(&nfulnl_subsys);
1177 cleanup_netlink_notifier:
1178 	netlink_unregister_notifier(&nfulnl_rtnl_notifier);
1179 	unregister_pernet_subsys(&nfnl_log_net_ops);
1180 out:
1181 	return status;
1182 }
1183 
1184 static void __exit nfnetlink_log_fini(void)
1185 {
1186 	nfnetlink_subsys_unregister(&nfulnl_subsys);
1187 	netlink_unregister_notifier(&nfulnl_rtnl_notifier);
1188 	unregister_pernet_subsys(&nfnl_log_net_ops);
1189 	nf_log_unregister(&nfulnl_logger);
1190 }
1191 
1192 MODULE_DESCRIPTION("netfilter userspace logging");
1193 MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>");
1194 MODULE_LICENSE("GPL");
1195 MODULE_ALIAS_NFNL_SUBSYS(NFNL_SUBSYS_ULOG);
1196 MODULE_ALIAS_NF_LOGGER(AF_INET, 1);
1197 MODULE_ALIAS_NF_LOGGER(AF_INET6, 1);
1198 MODULE_ALIAS_NF_LOGGER(AF_BRIDGE, 1);
1199 MODULE_ALIAS_NF_LOGGER(3, 1); /* NFPROTO_ARP */
1200 MODULE_ALIAS_NF_LOGGER(5, 1); /* NFPROTO_NETDEV */
1201 
1202 module_init(nfnetlink_log_init);
1203 module_exit(nfnetlink_log_fini);
1204