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