GNU Linux-libre 5.10.153-gnu1
[releases.git] / net / netfilter / nfnetlink_log.c
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         sk_buff_data_t old_tail = inst->skb->tail;
456         struct sock *sk;
457         const unsigned char *hwhdrp;
458
459         nlh = nfnl_msg_put(inst->skb, 0, 0,
460                            nfnl_msg_type(NFNL_SUBSYS_ULOG, NFULNL_MSG_PACKET),
461                            0, pf, NFNETLINK_V0, htons(inst->group_num));
462         if (!nlh)
463                 return -1;
464
465         memset(&pmsg, 0, sizeof(pmsg));
466         pmsg.hw_protocol        = skb->protocol;
467         pmsg.hook               = hooknum;
468
469         if (nla_put(inst->skb, NFULA_PACKET_HDR, sizeof(pmsg), &pmsg))
470                 goto nla_put_failure;
471
472         if (prefix &&
473             nla_put(inst->skb, NFULA_PREFIX, plen, prefix))
474                 goto nla_put_failure;
475
476         if (indev) {
477 #if !IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
478                 if (nla_put_be32(inst->skb, NFULA_IFINDEX_INDEV,
479                                  htonl(indev->ifindex)))
480                         goto nla_put_failure;
481 #else
482                 if (pf == PF_BRIDGE) {
483                         /* Case 1: outdev is physical input device, we need to
484                          * look for bridge group (when called from
485                          * netfilter_bridge) */
486                         if (nla_put_be32(inst->skb, NFULA_IFINDEX_PHYSINDEV,
487                                          htonl(indev->ifindex)) ||
488                         /* this is the bridge group "brX" */
489                         /* rcu_read_lock()ed by nf_hook_thresh or
490                          * nf_log_packet.
491                          */
492                             nla_put_be32(inst->skb, NFULA_IFINDEX_INDEV,
493                                          htonl(br_port_get_rcu(indev)->br->dev->ifindex)))
494                                 goto nla_put_failure;
495                 } else {
496                         struct net_device *physindev;
497
498                         /* Case 2: indev is bridge group, we need to look for
499                          * physical device (when called from ipv4) */
500                         if (nla_put_be32(inst->skb, NFULA_IFINDEX_INDEV,
501                                          htonl(indev->ifindex)))
502                                 goto nla_put_failure;
503
504                         physindev = nf_bridge_get_physindev(skb);
505                         if (physindev &&
506                             nla_put_be32(inst->skb, NFULA_IFINDEX_PHYSINDEV,
507                                          htonl(physindev->ifindex)))
508                                 goto nla_put_failure;
509                 }
510 #endif
511         }
512
513         if (outdev) {
514 #if !IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
515                 if (nla_put_be32(inst->skb, NFULA_IFINDEX_OUTDEV,
516                                  htonl(outdev->ifindex)))
517                         goto nla_put_failure;
518 #else
519                 if (pf == PF_BRIDGE) {
520                         /* Case 1: outdev is physical output device, we need to
521                          * look for bridge group (when called from
522                          * netfilter_bridge) */
523                         if (nla_put_be32(inst->skb, NFULA_IFINDEX_PHYSOUTDEV,
524                                          htonl(outdev->ifindex)) ||
525                         /* this is the bridge group "brX" */
526                         /* rcu_read_lock()ed by nf_hook_thresh or
527                          * nf_log_packet.
528                          */
529                             nla_put_be32(inst->skb, NFULA_IFINDEX_OUTDEV,
530                                          htonl(br_port_get_rcu(outdev)->br->dev->ifindex)))
531                                 goto nla_put_failure;
532                 } else {
533                         struct net_device *physoutdev;
534
535                         /* Case 2: indev is a bridge group, we need to look
536                          * for physical device (when called from ipv4) */
537                         if (nla_put_be32(inst->skb, NFULA_IFINDEX_OUTDEV,
538                                          htonl(outdev->ifindex)))
539                                 goto nla_put_failure;
540
541                         physoutdev = nf_bridge_get_physoutdev(skb);
542                         if (physoutdev &&
543                             nla_put_be32(inst->skb, NFULA_IFINDEX_PHYSOUTDEV,
544                                          htonl(physoutdev->ifindex)))
545                                 goto nla_put_failure;
546                 }
547 #endif
548         }
549
550         if (skb->mark &&
551             nla_put_be32(inst->skb, NFULA_MARK, htonl(skb->mark)))
552                 goto nla_put_failure;
553
554         if (indev && skb->dev &&
555             skb_mac_header_was_set(skb) &&
556             skb_mac_header_len(skb) != 0) {
557                 struct nfulnl_msg_packet_hw phw;
558                 int len;
559
560                 memset(&phw, 0, sizeof(phw));
561                 len = dev_parse_header(skb, phw.hw_addr);
562                 if (len > 0) {
563                         phw.hw_addrlen = htons(len);
564                         if (nla_put(inst->skb, NFULA_HWADDR, sizeof(phw), &phw))
565                                 goto nla_put_failure;
566                 }
567         }
568
569         if (indev && skb_mac_header_was_set(skb)) {
570                 if (nla_put_be16(inst->skb, NFULA_HWTYPE, htons(skb->dev->type)) ||
571                     nla_put_be16(inst->skb, NFULA_HWLEN,
572                                  htons(skb->dev->hard_header_len)))
573                         goto nla_put_failure;
574
575                 hwhdrp = skb_mac_header(skb);
576
577                 if (skb->dev->type == ARPHRD_SIT)
578                         hwhdrp -= ETH_HLEN;
579
580                 if (hwhdrp >= skb->head &&
581                     nla_put(inst->skb, NFULA_HWHEADER,
582                             skb->dev->hard_header_len, hwhdrp))
583                         goto nla_put_failure;
584         }
585
586         if (hooknum <= NF_INET_FORWARD && skb->tstamp) {
587                 struct nfulnl_msg_packet_timestamp ts;
588                 struct timespec64 kts = ktime_to_timespec64(skb->tstamp);
589                 ts.sec = cpu_to_be64(kts.tv_sec);
590                 ts.usec = cpu_to_be64(kts.tv_nsec / NSEC_PER_USEC);
591
592                 if (nla_put(inst->skb, NFULA_TIMESTAMP, sizeof(ts), &ts))
593                         goto nla_put_failure;
594         }
595
596         /* UID */
597         sk = skb->sk;
598         if (sk && sk_fullsock(sk)) {
599                 read_lock_bh(&sk->sk_callback_lock);
600                 if (sk->sk_socket && sk->sk_socket->file) {
601                         struct file *file = sk->sk_socket->file;
602                         const struct cred *cred = file->f_cred;
603                         struct user_namespace *user_ns = inst->peer_user_ns;
604                         __be32 uid = htonl(from_kuid_munged(user_ns, cred->fsuid));
605                         __be32 gid = htonl(from_kgid_munged(user_ns, cred->fsgid));
606                         read_unlock_bh(&sk->sk_callback_lock);
607                         if (nla_put_be32(inst->skb, NFULA_UID, uid) ||
608                             nla_put_be32(inst->skb, NFULA_GID, gid))
609                                 goto nla_put_failure;
610                 } else
611                         read_unlock_bh(&sk->sk_callback_lock);
612         }
613
614         /* local sequence number */
615         if ((inst->flags & NFULNL_CFG_F_SEQ) &&
616             nla_put_be32(inst->skb, NFULA_SEQ, htonl(inst->seq++)))
617                 goto nla_put_failure;
618
619         /* global sequence number */
620         if ((inst->flags & NFULNL_CFG_F_SEQ_GLOBAL) &&
621             nla_put_be32(inst->skb, NFULA_SEQ_GLOBAL,
622                          htonl(atomic_inc_return(&log->global_seq))))
623                 goto nla_put_failure;
624
625         if (ct && nfnl_ct->build(inst->skb, ct, ctinfo,
626                                  NFULA_CT, NFULA_CT_INFO) < 0)
627                 goto nla_put_failure;
628
629         if ((pf == NFPROTO_NETDEV || pf == NFPROTO_BRIDGE) &&
630             nfulnl_put_bridge(inst, skb) < 0)
631                 goto nla_put_failure;
632
633         if (data_len) {
634                 struct nlattr *nla;
635                 int size = nla_attr_size(data_len);
636
637                 if (skb_tailroom(inst->skb) < nla_total_size(data_len))
638                         goto nla_put_failure;
639
640                 nla = skb_put(inst->skb, nla_total_size(data_len));
641                 nla->nla_type = NFULA_PAYLOAD;
642                 nla->nla_len = size;
643
644                 if (skb_copy_bits(skb, 0, nla_data(nla), data_len))
645                         BUG();
646         }
647
648         nlh->nlmsg_len = inst->skb->tail - old_tail;
649         return 0;
650
651 nla_put_failure:
652         PRINTR(KERN_ERR "nfnetlink_log: error creating log nlmsg\n");
653         return -1;
654 }
655
656 static const struct nf_loginfo default_loginfo = {
657         .type =         NF_LOG_TYPE_ULOG,
658         .u = {
659                 .ulog = {
660                         .copy_len       = 0xffff,
661                         .group          = 0,
662                         .qthreshold     = 1,
663                 },
664         },
665 };
666
667 /* log handler for internal netfilter logging api */
668 static void
669 nfulnl_log_packet(struct net *net,
670                   u_int8_t pf,
671                   unsigned int hooknum,
672                   const struct sk_buff *skb,
673                   const struct net_device *in,
674                   const struct net_device *out,
675                   const struct nf_loginfo *li_user,
676                   const char *prefix)
677 {
678         size_t size;
679         unsigned int data_len;
680         struct nfulnl_instance *inst;
681         const struct nf_loginfo *li;
682         unsigned int qthreshold;
683         unsigned int plen = 0;
684         struct nfnl_log_net *log = nfnl_log_pernet(net);
685         const struct nfnl_ct_hook *nfnl_ct = NULL;
686         struct nf_conn *ct = NULL;
687         enum ip_conntrack_info ctinfo;
688
689         if (li_user && li_user->type == NF_LOG_TYPE_ULOG)
690                 li = li_user;
691         else
692                 li = &default_loginfo;
693
694         inst = instance_lookup_get(log, li->u.ulog.group);
695         if (!inst)
696                 return;
697
698         if (prefix)
699                 plen = strlen(prefix) + 1;
700
701         /* FIXME: do we want to make the size calculation conditional based on
702          * what is actually present?  way more branches and checks, but more
703          * memory efficient... */
704         size = nlmsg_total_size(sizeof(struct nfgenmsg))
705                 + nla_total_size(sizeof(struct nfulnl_msg_packet_hdr))
706                 + nla_total_size(sizeof(u_int32_t))     /* ifindex */
707                 + nla_total_size(sizeof(u_int32_t))     /* ifindex */
708 #if IS_ENABLED(CONFIG_BRIDGE_NETFILTER)
709                 + nla_total_size(sizeof(u_int32_t))     /* ifindex */
710                 + nla_total_size(sizeof(u_int32_t))     /* ifindex */
711 #endif
712                 + nla_total_size(sizeof(u_int32_t))     /* mark */
713                 + nla_total_size(sizeof(u_int32_t))     /* uid */
714                 + nla_total_size(sizeof(u_int32_t))     /* gid */
715                 + nla_total_size(plen)                  /* prefix */
716                 + nla_total_size(sizeof(struct nfulnl_msg_packet_hw))
717                 + nla_total_size(sizeof(struct nfulnl_msg_packet_timestamp))
718                 + nla_total_size(sizeof(struct nfgenmsg));      /* NLMSG_DONE */
719
720         if (in && skb_mac_header_was_set(skb)) {
721                 size += nla_total_size(skb->dev->hard_header_len)
722                         + nla_total_size(sizeof(u_int16_t))     /* hwtype */
723                         + nla_total_size(sizeof(u_int16_t));    /* hwlen */
724         }
725
726         spin_lock_bh(&inst->lock);
727
728         if (inst->flags & NFULNL_CFG_F_SEQ)
729                 size += nla_total_size(sizeof(u_int32_t));
730         if (inst->flags & NFULNL_CFG_F_SEQ_GLOBAL)
731                 size += nla_total_size(sizeof(u_int32_t));
732         if (inst->flags & NFULNL_CFG_F_CONNTRACK) {
733                 nfnl_ct = rcu_dereference(nfnl_ct_hook);
734                 if (nfnl_ct != NULL) {
735                         ct = nfnl_ct->get_ct(skb, &ctinfo);
736                         if (ct != NULL)
737                                 size += nfnl_ct->build_size(ct);
738                 }
739         }
740         if (pf == NFPROTO_NETDEV || pf == NFPROTO_BRIDGE)
741                 size += nfulnl_get_bridge_size(skb);
742
743         qthreshold = inst->qthreshold;
744         /* per-rule qthreshold overrides per-instance */
745         if (li->u.ulog.qthreshold)
746                 if (qthreshold > li->u.ulog.qthreshold)
747                         qthreshold = li->u.ulog.qthreshold;
748
749
750         switch (inst->copy_mode) {
751         case NFULNL_COPY_META:
752         case NFULNL_COPY_NONE:
753                 data_len = 0;
754                 break;
755
756         case NFULNL_COPY_PACKET:
757                 data_len = inst->copy_range;
758                 if ((li->u.ulog.flags & NF_LOG_F_COPY_LEN) &&
759                     (li->u.ulog.copy_len < data_len))
760                         data_len = li->u.ulog.copy_len;
761
762                 if (data_len > skb->len)
763                         data_len = skb->len;
764
765                 size += nla_total_size(data_len);
766                 break;
767
768         case NFULNL_COPY_DISABLED:
769         default:
770                 goto unlock_and_release;
771         }
772
773         if (inst->skb && size > skb_tailroom(inst->skb)) {
774                 /* either the queue len is too high or we don't have
775                  * enough room in the skb left. flush to userspace. */
776                 __nfulnl_flush(inst);
777         }
778
779         if (!inst->skb) {
780                 inst->skb = nfulnl_alloc_skb(net, inst->peer_portid,
781                                              inst->nlbufsiz, size);
782                 if (!inst->skb)
783                         goto alloc_failure;
784         }
785
786         inst->qlen++;
787
788         __build_packet_message(log, inst, skb, data_len, pf,
789                                 hooknum, in, out, prefix, plen,
790                                 nfnl_ct, ct, ctinfo);
791
792         if (inst->qlen >= qthreshold)
793                 __nfulnl_flush(inst);
794         /* timer_pending always called within inst->lock, so there
795          * is no chance of a race here */
796         else if (!timer_pending(&inst->timer)) {
797                 instance_get(inst);
798                 inst->timer.expires = jiffies + (inst->flushtimeout*HZ/100);
799                 add_timer(&inst->timer);
800         }
801
802 unlock_and_release:
803         spin_unlock_bh(&inst->lock);
804         instance_put(inst);
805         return;
806
807 alloc_failure:
808         /* FIXME: statistics */
809         goto unlock_and_release;
810 }
811
812 static int
813 nfulnl_rcv_nl_event(struct notifier_block *this,
814                    unsigned long event, void *ptr)
815 {
816         struct netlink_notify *n = ptr;
817         struct nfnl_log_net *log = nfnl_log_pernet(n->net);
818
819         if (event == NETLINK_URELEASE && n->protocol == NETLINK_NETFILTER) {
820                 int i;
821
822                 /* destroy all instances for this portid */
823                 spin_lock_bh(&log->instances_lock);
824                 for  (i = 0; i < INSTANCE_BUCKETS; i++) {
825                         struct hlist_node *t2;
826                         struct nfulnl_instance *inst;
827                         struct hlist_head *head = &log->instance_table[i];
828
829                         hlist_for_each_entry_safe(inst, t2, head, hlist) {
830                                 if (n->portid == inst->peer_portid)
831                                         __instance_destroy(inst);
832                         }
833                 }
834                 spin_unlock_bh(&log->instances_lock);
835         }
836         return NOTIFY_DONE;
837 }
838
839 static struct notifier_block nfulnl_rtnl_notifier = {
840         .notifier_call  = nfulnl_rcv_nl_event,
841 };
842
843 static int nfulnl_recv_unsupp(struct net *net, struct sock *ctnl,
844                               struct sk_buff *skb, const struct nlmsghdr *nlh,
845                               const struct nlattr * const nfqa[],
846                               struct netlink_ext_ack *extack)
847 {
848         return -ENOTSUPP;
849 }
850
851 static struct nf_logger nfulnl_logger __read_mostly = {
852         .name   = "nfnetlink_log",
853         .type   = NF_LOG_TYPE_ULOG,
854         .logfn  = nfulnl_log_packet,
855         .me     = THIS_MODULE,
856 };
857
858 static const struct nla_policy nfula_cfg_policy[NFULA_CFG_MAX+1] = {
859         [NFULA_CFG_CMD]         = { .len = sizeof(struct nfulnl_msg_config_cmd) },
860         [NFULA_CFG_MODE]        = { .len = sizeof(struct nfulnl_msg_config_mode) },
861         [NFULA_CFG_TIMEOUT]     = { .type = NLA_U32 },
862         [NFULA_CFG_QTHRESH]     = { .type = NLA_U32 },
863         [NFULA_CFG_NLBUFSIZ]    = { .type = NLA_U32 },
864         [NFULA_CFG_FLAGS]       = { .type = NLA_U16 },
865 };
866
867 static int nfulnl_recv_config(struct net *net, struct sock *ctnl,
868                               struct sk_buff *skb, const struct nlmsghdr *nlh,
869                               const struct nlattr * const nfula[],
870                               struct netlink_ext_ack *extack)
871 {
872         struct nfgenmsg *nfmsg = nlmsg_data(nlh);
873         u_int16_t group_num = ntohs(nfmsg->res_id);
874         struct nfulnl_instance *inst;
875         struct nfulnl_msg_config_cmd *cmd = NULL;
876         struct nfnl_log_net *log = nfnl_log_pernet(net);
877         int ret = 0;
878         u16 flags = 0;
879
880         if (nfula[NFULA_CFG_CMD]) {
881                 u_int8_t pf = nfmsg->nfgen_family;
882                 cmd = nla_data(nfula[NFULA_CFG_CMD]);
883
884                 /* Commands without queue context */
885                 switch (cmd->command) {
886                 case NFULNL_CFG_CMD_PF_BIND:
887                         return nf_log_bind_pf(net, pf, &nfulnl_logger);
888                 case NFULNL_CFG_CMD_PF_UNBIND:
889                         nf_log_unbind_pf(net, pf);
890                         return 0;
891                 }
892         }
893
894         inst = instance_lookup_get(log, group_num);
895         if (inst && inst->peer_portid != NETLINK_CB(skb).portid) {
896                 ret = -EPERM;
897                 goto out_put;
898         }
899
900         /* Check if we support these flags in first place, dependencies should
901          * be there too not to break atomicity.
902          */
903         if (nfula[NFULA_CFG_FLAGS]) {
904                 flags = ntohs(nla_get_be16(nfula[NFULA_CFG_FLAGS]));
905
906                 if ((flags & NFULNL_CFG_F_CONNTRACK) &&
907                     !rcu_access_pointer(nfnl_ct_hook)) {
908 #ifdef CONFIG_MODULES
909                         nfnl_unlock(NFNL_SUBSYS_ULOG);
910                         request_module("ip_conntrack_netlink");
911                         nfnl_lock(NFNL_SUBSYS_ULOG);
912                         if (rcu_access_pointer(nfnl_ct_hook)) {
913                                 ret = -EAGAIN;
914                                 goto out_put;
915                         }
916 #endif
917                         ret = -EOPNOTSUPP;
918                         goto out_put;
919                 }
920         }
921
922         if (cmd != NULL) {
923                 switch (cmd->command) {
924                 case NFULNL_CFG_CMD_BIND:
925                         if (inst) {
926                                 ret = -EBUSY;
927                                 goto out_put;
928                         }
929
930                         inst = instance_create(net, group_num,
931                                                NETLINK_CB(skb).portid,
932                                                sk_user_ns(NETLINK_CB(skb).sk));
933                         if (IS_ERR(inst)) {
934                                 ret = PTR_ERR(inst);
935                                 goto out;
936                         }
937                         break;
938                 case NFULNL_CFG_CMD_UNBIND:
939                         if (!inst) {
940                                 ret = -ENODEV;
941                                 goto out;
942                         }
943
944                         instance_destroy(log, inst);
945                         goto out_put;
946                 default:
947                         ret = -ENOTSUPP;
948                         goto out_put;
949                 }
950         } else if (!inst) {
951                 ret = -ENODEV;
952                 goto out;
953         }
954
955         if (nfula[NFULA_CFG_MODE]) {
956                 struct nfulnl_msg_config_mode *params =
957                         nla_data(nfula[NFULA_CFG_MODE]);
958
959                 nfulnl_set_mode(inst, params->copy_mode,
960                                 ntohl(params->copy_range));
961         }
962
963         if (nfula[NFULA_CFG_TIMEOUT]) {
964                 __be32 timeout = nla_get_be32(nfula[NFULA_CFG_TIMEOUT]);
965
966                 nfulnl_set_timeout(inst, ntohl(timeout));
967         }
968
969         if (nfula[NFULA_CFG_NLBUFSIZ]) {
970                 __be32 nlbufsiz = nla_get_be32(nfula[NFULA_CFG_NLBUFSIZ]);
971
972                 nfulnl_set_nlbufsiz(inst, ntohl(nlbufsiz));
973         }
974
975         if (nfula[NFULA_CFG_QTHRESH]) {
976                 __be32 qthresh = nla_get_be32(nfula[NFULA_CFG_QTHRESH]);
977
978                 nfulnl_set_qthresh(inst, ntohl(qthresh));
979         }
980
981         if (nfula[NFULA_CFG_FLAGS])
982                 nfulnl_set_flags(inst, flags);
983
984 out_put:
985         instance_put(inst);
986 out:
987         return ret;
988 }
989
990 static const struct nfnl_callback nfulnl_cb[NFULNL_MSG_MAX] = {
991         [NFULNL_MSG_PACKET]     = { .call = nfulnl_recv_unsupp,
992                                     .attr_count = NFULA_MAX, },
993         [NFULNL_MSG_CONFIG]     = { .call = nfulnl_recv_config,
994                                     .attr_count = NFULA_CFG_MAX,
995                                     .policy = nfula_cfg_policy },
996 };
997
998 static const struct nfnetlink_subsystem nfulnl_subsys = {
999         .name           = "log",
1000         .subsys_id      = NFNL_SUBSYS_ULOG,
1001         .cb_count       = NFULNL_MSG_MAX,
1002         .cb             = nfulnl_cb,
1003 };
1004
1005 #ifdef CONFIG_PROC_FS
1006 struct iter_state {
1007         struct seq_net_private p;
1008         unsigned int bucket;
1009 };
1010
1011 static struct hlist_node *get_first(struct net *net, struct iter_state *st)
1012 {
1013         struct nfnl_log_net *log;
1014         if (!st)
1015                 return NULL;
1016
1017         log = nfnl_log_pernet(net);
1018
1019         for (st->bucket = 0; st->bucket < INSTANCE_BUCKETS; st->bucket++) {
1020                 struct hlist_head *head = &log->instance_table[st->bucket];
1021
1022                 if (!hlist_empty(head))
1023                         return rcu_dereference_bh(hlist_first_rcu(head));
1024         }
1025         return NULL;
1026 }
1027
1028 static struct hlist_node *get_next(struct net *net, struct iter_state *st,
1029                                    struct hlist_node *h)
1030 {
1031         h = rcu_dereference_bh(hlist_next_rcu(h));
1032         while (!h) {
1033                 struct nfnl_log_net *log;
1034                 struct hlist_head *head;
1035
1036                 if (++st->bucket >= INSTANCE_BUCKETS)
1037                         return NULL;
1038
1039                 log = nfnl_log_pernet(net);
1040                 head = &log->instance_table[st->bucket];
1041                 h = rcu_dereference_bh(hlist_first_rcu(head));
1042         }
1043         return h;
1044 }
1045
1046 static struct hlist_node *get_idx(struct net *net, struct iter_state *st,
1047                                   loff_t pos)
1048 {
1049         struct hlist_node *head;
1050         head = get_first(net, st);
1051
1052         if (head)
1053                 while (pos && (head = get_next(net, st, head)))
1054                         pos--;
1055         return pos ? NULL : head;
1056 }
1057
1058 static void *seq_start(struct seq_file *s, loff_t *pos)
1059         __acquires(rcu_bh)
1060 {
1061         rcu_read_lock_bh();
1062         return get_idx(seq_file_net(s), s->private, *pos);
1063 }
1064
1065 static void *seq_next(struct seq_file *s, void *v, loff_t *pos)
1066 {
1067         (*pos)++;
1068         return get_next(seq_file_net(s), s->private, v);
1069 }
1070
1071 static void seq_stop(struct seq_file *s, void *v)
1072         __releases(rcu_bh)
1073 {
1074         rcu_read_unlock_bh();
1075 }
1076
1077 static int seq_show(struct seq_file *s, void *v)
1078 {
1079         const struct nfulnl_instance *inst = v;
1080
1081         seq_printf(s, "%5u %6u %5u %1u %5u %6u %2u\n",
1082                    inst->group_num,
1083                    inst->peer_portid, inst->qlen,
1084                    inst->copy_mode, inst->copy_range,
1085                    inst->flushtimeout, refcount_read(&inst->use));
1086
1087         return 0;
1088 }
1089
1090 static const struct seq_operations nful_seq_ops = {
1091         .start  = seq_start,
1092         .next   = seq_next,
1093         .stop   = seq_stop,
1094         .show   = seq_show,
1095 };
1096 #endif /* PROC_FS */
1097
1098 static int __net_init nfnl_log_net_init(struct net *net)
1099 {
1100         unsigned int i;
1101         struct nfnl_log_net *log = nfnl_log_pernet(net);
1102 #ifdef CONFIG_PROC_FS
1103         struct proc_dir_entry *proc;
1104         kuid_t root_uid;
1105         kgid_t root_gid;
1106 #endif
1107
1108         for (i = 0; i < INSTANCE_BUCKETS; i++)
1109                 INIT_HLIST_HEAD(&log->instance_table[i]);
1110         spin_lock_init(&log->instances_lock);
1111
1112 #ifdef CONFIG_PROC_FS
1113         proc = proc_create_net("nfnetlink_log", 0440, net->nf.proc_netfilter,
1114                         &nful_seq_ops, sizeof(struct iter_state));
1115         if (!proc)
1116                 return -ENOMEM;
1117
1118         root_uid = make_kuid(net->user_ns, 0);
1119         root_gid = make_kgid(net->user_ns, 0);
1120         if (uid_valid(root_uid) && gid_valid(root_gid))
1121                 proc_set_user(proc, root_uid, root_gid);
1122 #endif
1123         return 0;
1124 }
1125
1126 static void __net_exit nfnl_log_net_exit(struct net *net)
1127 {
1128         struct nfnl_log_net *log = nfnl_log_pernet(net);
1129         unsigned int i;
1130
1131 #ifdef CONFIG_PROC_FS
1132         remove_proc_entry("nfnetlink_log", net->nf.proc_netfilter);
1133 #endif
1134         nf_log_unset(net, &nfulnl_logger);
1135         for (i = 0; i < INSTANCE_BUCKETS; i++)
1136                 WARN_ON_ONCE(!hlist_empty(&log->instance_table[i]));
1137 }
1138
1139 static struct pernet_operations nfnl_log_net_ops = {
1140         .init   = nfnl_log_net_init,
1141         .exit   = nfnl_log_net_exit,
1142         .id     = &nfnl_log_net_id,
1143         .size   = sizeof(struct nfnl_log_net),
1144 };
1145
1146 static int __init nfnetlink_log_init(void)
1147 {
1148         int status;
1149
1150         status = register_pernet_subsys(&nfnl_log_net_ops);
1151         if (status < 0) {
1152                 pr_err("failed to register pernet ops\n");
1153                 goto out;
1154         }
1155
1156         netlink_register_notifier(&nfulnl_rtnl_notifier);
1157         status = nfnetlink_subsys_register(&nfulnl_subsys);
1158         if (status < 0) {
1159                 pr_err("failed to create netlink socket\n");
1160                 goto cleanup_netlink_notifier;
1161         }
1162
1163         status = nf_log_register(NFPROTO_UNSPEC, &nfulnl_logger);
1164         if (status < 0) {
1165                 pr_err("failed to register logger\n");
1166                 goto cleanup_subsys;
1167         }
1168
1169         return status;
1170
1171 cleanup_subsys:
1172         nfnetlink_subsys_unregister(&nfulnl_subsys);
1173 cleanup_netlink_notifier:
1174         netlink_unregister_notifier(&nfulnl_rtnl_notifier);
1175         unregister_pernet_subsys(&nfnl_log_net_ops);
1176 out:
1177         return status;
1178 }
1179
1180 static void __exit nfnetlink_log_fini(void)
1181 {
1182         nfnetlink_subsys_unregister(&nfulnl_subsys);
1183         netlink_unregister_notifier(&nfulnl_rtnl_notifier);
1184         unregister_pernet_subsys(&nfnl_log_net_ops);
1185         nf_log_unregister(&nfulnl_logger);
1186 }
1187
1188 MODULE_DESCRIPTION("netfilter userspace logging");
1189 MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>");
1190 MODULE_LICENSE("GPL");
1191 MODULE_ALIAS_NFNL_SUBSYS(NFNL_SUBSYS_ULOG);
1192 MODULE_ALIAS_NF_LOGGER(AF_INET, 1);
1193 MODULE_ALIAS_NF_LOGGER(AF_INET6, 1);
1194 MODULE_ALIAS_NF_LOGGER(AF_BRIDGE, 1);
1195 MODULE_ALIAS_NF_LOGGER(3, 1); /* NFPROTO_ARP */
1196 MODULE_ALIAS_NF_LOGGER(5, 1); /* NFPROTO_NETDEV */
1197
1198 module_init(nfnetlink_log_init);
1199 module_exit(nfnetlink_log_fini);