blob: 17d86eee8bd8be8e18aea4968ca1332527a842bf [file] [log] [blame]
b.liue9582032025-04-17 19:18:16 +08001// SPDX-License-Identifier: GPL-2.0-or-later
2/*
3 * NETLINK Kernel-user communication protocol.
4 *
5 * Authors: Alan Cox <alan@lxorguk.ukuu.org.uk>
6 * Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
7 * Patrick McHardy <kaber@trash.net>
8 *
9 * Tue Jun 26 14:36:48 MEST 2001 Herbert "herp" Rosmanith
10 * added netlink_proto_exit
11 * Tue Jan 22 18:32:44 BRST 2002 Arnaldo C. de Melo <acme@conectiva.com.br>
12 * use nlk_sk, as sk->protinfo is on a diet 8)
13 * Fri Jul 22 19:51:12 MEST 2005 Harald Welte <laforge@gnumonks.org>
14 * - inc module use count of module that owns
15 * the kernel socket in case userspace opens
16 * socket of same protocol
17 * - remove all module support, since netlink is
18 * mandatory if CONFIG_NET=y these days
19 */
20
21#include <linux/module.h>
22
23#include <linux/capability.h>
24#include <linux/kernel.h>
25#include <linux/init.h>
26#include <linux/signal.h>
27#include <linux/sched.h>
28#include <linux/errno.h>
29#include <linux/string.h>
30#include <linux/stat.h>
31#include <linux/socket.h>
32#include <linux/un.h>
33#include <linux/fcntl.h>
34#include <linux/termios.h>
35#include <linux/sockios.h>
36#include <linux/net.h>
37#include <linux/fs.h>
38#include <linux/slab.h>
39#include <linux/uaccess.h>
40#include <linux/skbuff.h>
41#include <linux/netdevice.h>
42#include <linux/rtnetlink.h>
43#include <linux/proc_fs.h>
44#include <linux/seq_file.h>
45#include <linux/notifier.h>
46#include <linux/security.h>
47#include <linux/jhash.h>
48#include <linux/jiffies.h>
49#include <linux/random.h>
50#include <linux/bitops.h>
51#include <linux/mm.h>
52#include <linux/types.h>
53#include <linux/audit.h>
54#include <linux/mutex.h>
55#include <linux/vmalloc.h>
56#include <linux/if_arp.h>
57#include <linux/rhashtable.h>
58#include <asm/cacheflush.h>
59#include <linux/hash.h>
60#include <linux/genetlink.h>
61#include <linux/net_namespace.h>
62#include <linux/nospec.h>
63
64#include <net/net_namespace.h>
65#include <net/netns/generic.h>
66#include <net/sock.h>
67#include <net/scm.h>
68#include <net/netlink.h>
69
70#include "af_netlink.h"
71
72struct listeners {
73 struct rcu_head rcu;
74 unsigned long masks[0];
75};
76
77/* state bits */
78#define NETLINK_S_CONGESTED 0x0
79
80static inline int netlink_is_kernel(struct sock *sk)
81{
82 return nlk_sk(sk)->flags & NETLINK_F_KERNEL_SOCKET;
83}
84
85struct netlink_table *nl_table __read_mostly;
86EXPORT_SYMBOL_GPL(nl_table);
87
88static DECLARE_WAIT_QUEUE_HEAD(nl_table_wait);
89
90static struct lock_class_key nlk_cb_mutex_keys[MAX_LINKS];
91
92static const char *const nlk_cb_mutex_key_strings[MAX_LINKS + 1] = {
93 "nlk_cb_mutex-ROUTE",
94 "nlk_cb_mutex-1",
95 "nlk_cb_mutex-USERSOCK",
96 "nlk_cb_mutex-FIREWALL",
97 "nlk_cb_mutex-SOCK_DIAG",
98 "nlk_cb_mutex-NFLOG",
99 "nlk_cb_mutex-XFRM",
100 "nlk_cb_mutex-SELINUX",
101 "nlk_cb_mutex-ISCSI",
102 "nlk_cb_mutex-AUDIT",
103 "nlk_cb_mutex-FIB_LOOKUP",
104 "nlk_cb_mutex-CONNECTOR",
105 "nlk_cb_mutex-NETFILTER",
106 "nlk_cb_mutex-IP6_FW",
107 "nlk_cb_mutex-DNRTMSG",
108 "nlk_cb_mutex-KOBJECT_UEVENT",
109 "nlk_cb_mutex-GENERIC",
110 "nlk_cb_mutex-17",
111 "nlk_cb_mutex-SCSITRANSPORT",
112 "nlk_cb_mutex-ECRYPTFS",
113 "nlk_cb_mutex-RDMA",
114 "nlk_cb_mutex-CRYPTO",
115 "nlk_cb_mutex-SMC",
116 "nlk_cb_mutex-23",
117 "nlk_cb_mutex-24",
118 "nlk_cb_mutex-25",
119 "nlk_cb_mutex-26",
120 "nlk_cb_mutex-27",
121 "nlk_cb_mutex-28",
122 "nlk_cb_mutex-29",
123 "nlk_cb_mutex-30",
124 "nlk_cb_mutex-31",
125 "nlk_cb_mutex-MAX_LINKS"
126};
127
128static int netlink_dump(struct sock *sk);
129
130/* nl_table locking explained:
131 * Lookup and traversal are protected with an RCU read-side lock. Insertion
132 * and removal are protected with per bucket lock while using RCU list
133 * modification primitives and may run in parallel to RCU protected lookups.
134 * Destruction of the Netlink socket may only occur *after* nl_table_lock has
135 * been acquired * either during or after the socket has been removed from
136 * the list and after an RCU grace period.
137 */
138DEFINE_RWLOCK(nl_table_lock);
139EXPORT_SYMBOL_GPL(nl_table_lock);
140static atomic_t nl_table_users = ATOMIC_INIT(0);
141
142#define nl_deref_protected(X) rcu_dereference_protected(X, lockdep_is_held(&nl_table_lock));
143
144static BLOCKING_NOTIFIER_HEAD(netlink_chain);
145
146
147static const struct rhashtable_params netlink_rhashtable_params;
148
149static inline u32 netlink_group_mask(u32 group)
150{
151 if (group > 32)
152 return 0;
153 return group ? 1 << (group - 1) : 0;
154}
155
156static struct sk_buff *netlink_to_full_skb(const struct sk_buff *skb,
157 gfp_t gfp_mask)
158{
159 unsigned int len = skb->len;
160 struct sk_buff *new;
161
162 new = alloc_skb(len, gfp_mask);
163 if (new == NULL)
164 return NULL;
165
166 NETLINK_CB(new).portid = NETLINK_CB(skb).portid;
167 NETLINK_CB(new).dst_group = NETLINK_CB(skb).dst_group;
168 NETLINK_CB(new).creds = NETLINK_CB(skb).creds;
169
170 skb_put_data(new, skb->data, len);
171 return new;
172}
173
174static unsigned int netlink_tap_net_id;
175
176struct netlink_tap_net {
177 struct list_head netlink_tap_all;
178 struct mutex netlink_tap_lock;
179};
180
181int netlink_add_tap(struct netlink_tap *nt)
182{
183 struct net *net = dev_net(nt->dev);
184 struct netlink_tap_net *nn = net_generic(net, netlink_tap_net_id);
185
186 if (unlikely(nt->dev->type != ARPHRD_NETLINK))
187 return -EINVAL;
188
189 mutex_lock(&nn->netlink_tap_lock);
190 list_add_rcu(&nt->list, &nn->netlink_tap_all);
191 mutex_unlock(&nn->netlink_tap_lock);
192
193 __module_get(nt->module);
194
195 return 0;
196}
197EXPORT_SYMBOL_GPL(netlink_add_tap);
198
199static int __netlink_remove_tap(struct netlink_tap *nt)
200{
201 struct net *net = dev_net(nt->dev);
202 struct netlink_tap_net *nn = net_generic(net, netlink_tap_net_id);
203 bool found = false;
204 struct netlink_tap *tmp;
205
206 mutex_lock(&nn->netlink_tap_lock);
207
208 list_for_each_entry(tmp, &nn->netlink_tap_all, list) {
209 if (nt == tmp) {
210 list_del_rcu(&nt->list);
211 found = true;
212 goto out;
213 }
214 }
215
216 pr_warn("__netlink_remove_tap: %p not found\n", nt);
217out:
218 mutex_unlock(&nn->netlink_tap_lock);
219
220 if (found)
221 module_put(nt->module);
222
223 return found ? 0 : -ENODEV;
224}
225
226int netlink_remove_tap(struct netlink_tap *nt)
227{
228 int ret;
229
230 ret = __netlink_remove_tap(nt);
231 synchronize_net();
232
233 return ret;
234}
235EXPORT_SYMBOL_GPL(netlink_remove_tap);
236
237static __net_init int netlink_tap_init_net(struct net *net)
238{
239 struct netlink_tap_net *nn = net_generic(net, netlink_tap_net_id);
240
241 INIT_LIST_HEAD(&nn->netlink_tap_all);
242 mutex_init(&nn->netlink_tap_lock);
243 return 0;
244}
245
246static struct pernet_operations netlink_tap_net_ops = {
247 .init = netlink_tap_init_net,
248 .id = &netlink_tap_net_id,
249 .size = sizeof(struct netlink_tap_net),
250};
251
252static bool netlink_filter_tap(const struct sk_buff *skb)
253{
254 struct sock *sk = skb->sk;
255
256 /* We take the more conservative approach and
257 * whitelist socket protocols that may pass.
258 */
259 switch (sk->sk_protocol) {
260 case NETLINK_ROUTE:
261 case NETLINK_USERSOCK:
262 case NETLINK_SOCK_DIAG:
263 case NETLINK_NFLOG:
264 case NETLINK_XFRM:
265 case NETLINK_FIB_LOOKUP:
266 case NETLINK_NETFILTER:
267 case NETLINK_GENERIC:
268 return true;
269 }
270
271 return false;
272}
273
274static int __netlink_deliver_tap_skb(struct sk_buff *skb,
275 struct net_device *dev)
276{
277 struct sk_buff *nskb;
278 struct sock *sk = skb->sk;
279 int ret = -ENOMEM;
280
281 if (!net_eq(dev_net(dev), sock_net(sk)))
282 return 0;
283
284 dev_hold(dev);
285
286 if (is_vmalloc_addr(skb->head))
287 nskb = netlink_to_full_skb(skb, GFP_ATOMIC);
288 else
289 nskb = skb_clone(skb, GFP_ATOMIC);
290 if (nskb) {
291 nskb->dev = dev;
292 nskb->protocol = htons((u16) sk->sk_protocol);
293 nskb->pkt_type = netlink_is_kernel(sk) ?
294 PACKET_KERNEL : PACKET_USER;
295 skb_reset_network_header(nskb);
296 ret = dev_queue_xmit(nskb);
297 if (unlikely(ret > 0))
298 ret = net_xmit_errno(ret);
299 }
300
301 dev_put(dev);
302 return ret;
303}
304
305static void __netlink_deliver_tap(struct sk_buff *skb, struct netlink_tap_net *nn)
306{
307 int ret;
308 struct netlink_tap *tmp;
309
310 if (!netlink_filter_tap(skb))
311 return;
312
313 list_for_each_entry_rcu(tmp, &nn->netlink_tap_all, list) {
314 ret = __netlink_deliver_tap_skb(skb, tmp->dev);
315 if (unlikely(ret))
316 break;
317 }
318}
319
320static void netlink_deliver_tap(struct net *net, struct sk_buff *skb)
321{
322 struct netlink_tap_net *nn = net_generic(net, netlink_tap_net_id);
323
324 rcu_read_lock();
325
326 if (unlikely(!list_empty(&nn->netlink_tap_all)))
327 __netlink_deliver_tap(skb, nn);
328
329 rcu_read_unlock();
330}
331
332static void netlink_deliver_tap_kernel(struct sock *dst, struct sock *src,
333 struct sk_buff *skb)
334{
335 if (!(netlink_is_kernel(dst) && netlink_is_kernel(src)))
336 netlink_deliver_tap(sock_net(dst), skb);
337}
338
339static void netlink_overrun(struct sock *sk)
340{
341 struct netlink_sock *nlk = nlk_sk(sk);
342
343 if (!(nlk->flags & NETLINK_F_RECV_NO_ENOBUFS)) {
344 if (!test_and_set_bit(NETLINK_S_CONGESTED,
345 &nlk_sk(sk)->state)) {
346 sk->sk_err = ENOBUFS;
347 sk->sk_error_report(sk);
348 }
349 }
350 atomic_inc(&sk->sk_drops);
351}
352
353static void netlink_rcv_wake(struct sock *sk)
354{
355 struct netlink_sock *nlk = nlk_sk(sk);
356
357 if (skb_queue_empty(&sk->sk_receive_queue))
358 clear_bit(NETLINK_S_CONGESTED, &nlk->state);
359 if (!test_bit(NETLINK_S_CONGESTED, &nlk->state))
360 wake_up_interruptible(&nlk->wait);
361}
362
363static void netlink_skb_destructor(struct sk_buff *skb)
364{
365 if (is_vmalloc_addr(skb->head)) {
366 if (!skb->cloned ||
367 !atomic_dec_return(&(skb_shinfo(skb)->dataref)))
368 vfree_atomic(skb->head);
369
370 skb->head = NULL;
371 }
372 if (skb->sk != NULL)
373 sock_rfree(skb);
374}
375
376static void netlink_skb_set_owner_r(struct sk_buff *skb, struct sock *sk)
377{
378 WARN_ON(skb->sk != NULL);
379 skb->sk = sk;
380 skb->destructor = netlink_skb_destructor;
381 atomic_add(skb->truesize, &sk->sk_rmem_alloc);
382 sk_mem_charge(sk, skb->truesize);
383}
384
385static void netlink_sock_destruct(struct sock *sk)
386{
387 skb_queue_purge(&sk->sk_receive_queue);
388
389 if (!sock_flag(sk, SOCK_DEAD)) {
390 printk(KERN_ERR "Freeing alive netlink socket %p\n", sk);
391 return;
392 }
393
394 WARN_ON(atomic_read(&sk->sk_rmem_alloc));
395 WARN_ON(refcount_read(&sk->sk_wmem_alloc));
396 WARN_ON(nlk_sk(sk)->groups);
397}
398
399/* This lock without WQ_FLAG_EXCLUSIVE is good on UP and it is _very_ bad on
400 * SMP. Look, when several writers sleep and reader wakes them up, all but one
401 * immediately hit write lock and grab all the cpus. Exclusive sleep solves
402 * this, _but_ remember, it adds useless work on UP machines.
403 */
404
405void netlink_table_grab(void)
406 __acquires(nl_table_lock)
407{
408 might_sleep();
409
410 write_lock_irq(&nl_table_lock);
411
412 if (atomic_read(&nl_table_users)) {
413 DECLARE_WAITQUEUE(wait, current);
414
415 add_wait_queue_exclusive(&nl_table_wait, &wait);
416 for (;;) {
417 set_current_state(TASK_UNINTERRUPTIBLE);
418 if (atomic_read(&nl_table_users) == 0)
419 break;
420 write_unlock_irq(&nl_table_lock);
421 schedule();
422 write_lock_irq(&nl_table_lock);
423 }
424
425 __set_current_state(TASK_RUNNING);
426 remove_wait_queue(&nl_table_wait, &wait);
427 }
428}
429
430void netlink_table_ungrab(void)
431 __releases(nl_table_lock)
432{
433 write_unlock_irq(&nl_table_lock);
434 wake_up(&nl_table_wait);
435}
436
437static inline void
438netlink_lock_table(void)
439{
440 unsigned long flags;
441
442 /* read_lock() synchronizes us to netlink_table_grab */
443
444 read_lock_irqsave(&nl_table_lock, flags);
445 atomic_inc(&nl_table_users);
446 read_unlock_irqrestore(&nl_table_lock, flags);
447}
448
449static inline void
450netlink_unlock_table(void)
451{
452 if (atomic_dec_and_test(&nl_table_users))
453 wake_up(&nl_table_wait);
454}
455
456struct netlink_compare_arg
457{
458 possible_net_t pnet;
459 u32 portid;
460};
461
462/* Doing sizeof directly may yield 4 extra bytes on 64-bit. */
463#define netlink_compare_arg_len \
464 (offsetof(struct netlink_compare_arg, portid) + sizeof(u32))
465
466static inline int netlink_compare(struct rhashtable_compare_arg *arg,
467 const void *ptr)
468{
469 const struct netlink_compare_arg *x = arg->key;
470 const struct netlink_sock *nlk = ptr;
471
472 return nlk->portid != x->portid ||
473 !net_eq(sock_net(&nlk->sk), read_pnet(&x->pnet));
474}
475
476static void netlink_compare_arg_init(struct netlink_compare_arg *arg,
477 struct net *net, u32 portid)
478{
479 memset(arg, 0, sizeof(*arg));
480 write_pnet(&arg->pnet, net);
481 arg->portid = portid;
482}
483
484static struct sock *__netlink_lookup(struct netlink_table *table, u32 portid,
485 struct net *net)
486{
487 struct netlink_compare_arg arg;
488
489 netlink_compare_arg_init(&arg, net, portid);
490 return rhashtable_lookup_fast(&table->hash, &arg,
491 netlink_rhashtable_params);
492}
493
494static int __netlink_insert(struct netlink_table *table, struct sock *sk)
495{
496 struct netlink_compare_arg arg;
497
498 netlink_compare_arg_init(&arg, sock_net(sk), nlk_sk(sk)->portid);
499 return rhashtable_lookup_insert_key(&table->hash, &arg,
500 &nlk_sk(sk)->node,
501 netlink_rhashtable_params);
502}
503
504static struct sock *netlink_lookup(struct net *net, int protocol, u32 portid)
505{
506 struct netlink_table *table = &nl_table[protocol];
507 struct sock *sk;
508
509 rcu_read_lock();
510 sk = __netlink_lookup(table, portid, net);
511 if (sk)
512 sock_hold(sk);
513 rcu_read_unlock();
514
515 return sk;
516}
517
518static const struct proto_ops netlink_ops;
519
520static void
521netlink_update_listeners(struct sock *sk)
522{
523 struct netlink_table *tbl = &nl_table[sk->sk_protocol];
524 unsigned long mask;
525 unsigned int i;
526 struct listeners *listeners;
527
528 listeners = nl_deref_protected(tbl->listeners);
529 if (!listeners)
530 return;
531
532 for (i = 0; i < NLGRPLONGS(tbl->groups); i++) {
533 mask = 0;
534 sk_for_each_bound(sk, &tbl->mc_list) {
535 if (i < NLGRPLONGS(nlk_sk(sk)->ngroups))
536 mask |= nlk_sk(sk)->groups[i];
537 }
538 listeners->masks[i] = mask;
539 }
540 /* this function is only called with the netlink table "grabbed", which
541 * makes sure updates are visible before bind or setsockopt return. */
542}
543
544static int netlink_insert(struct sock *sk, u32 portid)
545{
546 struct netlink_table *table = &nl_table[sk->sk_protocol];
547 int err;
548
549 lock_sock(sk);
550
551 err = nlk_sk(sk)->portid == portid ? 0 : -EBUSY;
552 if (nlk_sk(sk)->bound)
553 goto err;
554
555 /* portid can be read locklessly from netlink_getname(). */
556 WRITE_ONCE(nlk_sk(sk)->portid, portid);
557
558 sock_hold(sk);
559
560 err = __netlink_insert(table, sk);
561 if (err) {
562 /* In case the hashtable backend returns with -EBUSY
563 * from here, it must not escape to the caller.
564 */
565 if (unlikely(err == -EBUSY))
566 err = -EOVERFLOW;
567 if (err == -EEXIST)
568 err = -EADDRINUSE;
569 sock_put(sk);
570 goto err;
571 }
572
573 /* We need to ensure that the socket is hashed and visible. */
574 smp_wmb();
575 /* Paired with lockless reads from netlink_bind(),
576 * netlink_connect() and netlink_sendmsg().
577 */
578 WRITE_ONCE(nlk_sk(sk)->bound, portid);
579
580err:
581 release_sock(sk);
582 return err;
583}
584
585static void netlink_remove(struct sock *sk)
586{
587 struct netlink_table *table;
588
589 table = &nl_table[sk->sk_protocol];
590 if (!rhashtable_remove_fast(&table->hash, &nlk_sk(sk)->node,
591 netlink_rhashtable_params)) {
592 WARN_ON(refcount_read(&sk->sk_refcnt) == 1);
593 __sock_put(sk);
594 }
595
596 netlink_table_grab();
597 if (nlk_sk(sk)->subscriptions) {
598 __sk_del_bind_node(sk);
599 netlink_update_listeners(sk);
600 }
601 if (sk->sk_protocol == NETLINK_GENERIC)
602 atomic_inc(&genl_sk_destructing_cnt);
603 netlink_table_ungrab();
604}
605
606static struct proto netlink_proto = {
607 .name = "NETLINK",
608 .owner = THIS_MODULE,
609 .obj_size = sizeof(struct netlink_sock),
610};
611
612static int __netlink_create(struct net *net, struct socket *sock,
613 struct mutex *cb_mutex, int protocol,
614 int kern)
615{
616 struct sock *sk;
617 struct netlink_sock *nlk;
618
619 sock->ops = &netlink_ops;
620
621 sk = sk_alloc(net, PF_NETLINK, GFP_KERNEL, &netlink_proto, kern);
622 if (!sk)
623 return -ENOMEM;
624
625 sock_init_data(sock, sk);
626
627 nlk = nlk_sk(sk);
628 if (cb_mutex) {
629 nlk->cb_mutex = cb_mutex;
630 } else {
631 nlk->cb_mutex = &nlk->cb_def_mutex;
632 mutex_init(nlk->cb_mutex);
633 lockdep_set_class_and_name(nlk->cb_mutex,
634 nlk_cb_mutex_keys + protocol,
635 nlk_cb_mutex_key_strings[protocol]);
636 }
637 init_waitqueue_head(&nlk->wait);
638
639 sk->sk_destruct = netlink_sock_destruct;
640 sk->sk_protocol = protocol;
641 return 0;
642}
643
644static int netlink_create(struct net *net, struct socket *sock, int protocol,
645 int kern)
646{
647 struct module *module = NULL;
648 struct mutex *cb_mutex;
649 struct netlink_sock *nlk;
650 int (*bind)(struct net *net, int group);
651 void (*unbind)(struct net *net, int group);
652 int err = 0;
653
654 sock->state = SS_UNCONNECTED;
655
656 if (sock->type != SOCK_RAW && sock->type != SOCK_DGRAM)
657 return -ESOCKTNOSUPPORT;
658
659 if (protocol < 0 || protocol >= MAX_LINKS)
660 return -EPROTONOSUPPORT;
661 protocol = array_index_nospec(protocol, MAX_LINKS);
662
663 netlink_lock_table();
664#ifdef CONFIG_MODULES
665 if (!nl_table[protocol].registered) {
666 netlink_unlock_table();
667 request_module("net-pf-%d-proto-%d", PF_NETLINK, protocol);
668 netlink_lock_table();
669 }
670#endif
671 if (nl_table[protocol].registered &&
672 try_module_get(nl_table[protocol].module))
673 module = nl_table[protocol].module;
674 else
675 err = -EPROTONOSUPPORT;
676 cb_mutex = nl_table[protocol].cb_mutex;
677 bind = nl_table[protocol].bind;
678 unbind = nl_table[protocol].unbind;
679 netlink_unlock_table();
680
681 if (err < 0)
682 goto out;
683
684 err = __netlink_create(net, sock, cb_mutex, protocol, kern);
685 if (err < 0)
686 goto out_module;
687
688 local_bh_disable();
689 sock_prot_inuse_add(net, &netlink_proto, 1);
690 local_bh_enable();
691
692 nlk = nlk_sk(sock->sk);
693 nlk->module = module;
694 nlk->netlink_bind = bind;
695 nlk->netlink_unbind = unbind;
696out:
697 return err;
698
699out_module:
700 module_put(module);
701 goto out;
702}
703
704static void deferred_put_nlk_sk(struct rcu_head *head)
705{
706 struct netlink_sock *nlk = container_of(head, struct netlink_sock, rcu);
707 struct sock *sk = &nlk->sk;
708
709 kfree(nlk->groups);
710 nlk->groups = NULL;
711
712 if (!refcount_dec_and_test(&sk->sk_refcnt))
713 return;
714
715 sk_free(sk);
716}
717
718static int netlink_release(struct socket *sock)
719{
720 struct sock *sk = sock->sk;
721 struct netlink_sock *nlk;
722
723 if (!sk)
724 return 0;
725
726 netlink_remove(sk);
727 sock_orphan(sk);
728 nlk = nlk_sk(sk);
729
730 /*
731 * OK. Socket is unlinked, any packets that arrive now
732 * will be purged.
733 */
734
735 /* must not acquire netlink_table_lock in any way again before unbind
736 * and notifying genetlink is done as otherwise it might deadlock
737 */
738 if (nlk->netlink_unbind) {
739 int i;
740
741 for (i = 0; i < nlk->ngroups; i++)
742 if (test_bit(i, nlk->groups))
743 nlk->netlink_unbind(sock_net(sk), i + 1);
744 }
745 if (sk->sk_protocol == NETLINK_GENERIC &&
746 atomic_dec_return(&genl_sk_destructing_cnt) == 0)
747 wake_up(&genl_sk_destructing_waitq);
748
749 sock->sk = NULL;
750 wake_up_interruptible_all(&nlk->wait);
751
752 skb_queue_purge(&sk->sk_write_queue);
753
754 if (nlk->portid && nlk->bound) {
755 struct netlink_notify n = {
756 .net = sock_net(sk),
757 .protocol = sk->sk_protocol,
758 .portid = nlk->portid,
759 };
760 blocking_notifier_call_chain(&netlink_chain,
761 NETLINK_URELEASE, &n);
762 }
763
764 /* Terminate any outstanding dump */
765 if (nlk->cb_running) {
766 if (nlk->cb.done)
767 nlk->cb.done(&nlk->cb);
768 module_put(nlk->cb.module);
769 kfree_skb(nlk->cb.skb);
770 }
771
772 module_put(nlk->module);
773
774 if (netlink_is_kernel(sk)) {
775 netlink_table_grab();
776 BUG_ON(nl_table[sk->sk_protocol].registered == 0);
777 if (--nl_table[sk->sk_protocol].registered == 0) {
778 struct listeners *old;
779
780 old = nl_deref_protected(nl_table[sk->sk_protocol].listeners);
781 RCU_INIT_POINTER(nl_table[sk->sk_protocol].listeners, NULL);
782 kfree_rcu(old, rcu);
783 nl_table[sk->sk_protocol].module = NULL;
784 nl_table[sk->sk_protocol].bind = NULL;
785 nl_table[sk->sk_protocol].unbind = NULL;
786 nl_table[sk->sk_protocol].flags = 0;
787 nl_table[sk->sk_protocol].registered = 0;
788 }
789 netlink_table_ungrab();
790 }
791
792 local_bh_disable();
793 sock_prot_inuse_add(sock_net(sk), &netlink_proto, -1);
794 local_bh_enable();
795 call_rcu(&nlk->rcu, deferred_put_nlk_sk);
796 return 0;
797}
798
799static int netlink_autobind(struct socket *sock)
800{
801 struct sock *sk = sock->sk;
802 struct net *net = sock_net(sk);
803 struct netlink_table *table = &nl_table[sk->sk_protocol];
804 s32 portid = task_tgid_vnr(current);
805 int err;
806 s32 rover = -4096;
807 bool ok;
808
809retry:
810 cond_resched();
811 rcu_read_lock();
812 ok = !__netlink_lookup(table, portid, net);
813 rcu_read_unlock();
814 if (!ok) {
815 /* Bind collision, search negative portid values. */
816 if (rover == -4096)
817 /* rover will be in range [S32_MIN, -4097] */
818 rover = S32_MIN + prandom_u32_max(-4096 - S32_MIN);
819 else if (rover >= -4096)
820 rover = -4097;
821 portid = rover--;
822 goto retry;
823 }
824
825 err = netlink_insert(sk, portid);
826 if (err == -EADDRINUSE)
827 goto retry;
828
829 /* If 2 threads race to autobind, that is fine. */
830 if (err == -EBUSY)
831 err = 0;
832
833 return err;
834}
835
836/**
837 * __netlink_ns_capable - General netlink message capability test
838 * @nsp: NETLINK_CB of the socket buffer holding a netlink command from userspace.
839 * @user_ns: The user namespace of the capability to use
840 * @cap: The capability to use
841 *
842 * Test to see if the opener of the socket we received the message
843 * from had when the netlink socket was created and the sender of the
844 * message has has the capability @cap in the user namespace @user_ns.
845 */
846bool __netlink_ns_capable(const struct netlink_skb_parms *nsp,
847 struct user_namespace *user_ns, int cap)
848{
849 return ((nsp->flags & NETLINK_SKB_DST) ||
850 file_ns_capable(nsp->sk->sk_socket->file, user_ns, cap)) &&
851 ns_capable(user_ns, cap);
852}
853EXPORT_SYMBOL(__netlink_ns_capable);
854
855/**
856 * netlink_ns_capable - General netlink message capability test
857 * @skb: socket buffer holding a netlink command from userspace
858 * @user_ns: The user namespace of the capability to use
859 * @cap: The capability to use
860 *
861 * Test to see if the opener of the socket we received the message
862 * from had when the netlink socket was created and the sender of the
863 * message has has the capability @cap in the user namespace @user_ns.
864 */
865bool netlink_ns_capable(const struct sk_buff *skb,
866 struct user_namespace *user_ns, int cap)
867{
868 return __netlink_ns_capable(&NETLINK_CB(skb), user_ns, cap);
869}
870EXPORT_SYMBOL(netlink_ns_capable);
871
872/**
873 * netlink_capable - Netlink global message capability test
874 * @skb: socket buffer holding a netlink command from userspace
875 * @cap: The capability to use
876 *
877 * Test to see if the opener of the socket we received the message
878 * from had when the netlink socket was created and the sender of the
879 * message has has the capability @cap in all user namespaces.
880 */
881bool netlink_capable(const struct sk_buff *skb, int cap)
882{
883 return netlink_ns_capable(skb, &init_user_ns, cap);
884}
885EXPORT_SYMBOL(netlink_capable);
886
887/**
888 * netlink_net_capable - Netlink network namespace message capability test
889 * @skb: socket buffer holding a netlink command from userspace
890 * @cap: The capability to use
891 *
892 * Test to see if the opener of the socket we received the message
893 * from had when the netlink socket was created and the sender of the
894 * message has has the capability @cap over the network namespace of
895 * the socket we received the message from.
896 */
897bool netlink_net_capable(const struct sk_buff *skb, int cap)
898{
899 return netlink_ns_capable(skb, sock_net(skb->sk)->user_ns, cap);
900}
901EXPORT_SYMBOL(netlink_net_capable);
902
903static inline int netlink_allowed(const struct socket *sock, unsigned int flag)
904{
905 return (nl_table[sock->sk->sk_protocol].flags & flag) ||
906 ns_capable(sock_net(sock->sk)->user_ns, CAP_NET_ADMIN);
907}
908
909static void
910netlink_update_subscriptions(struct sock *sk, unsigned int subscriptions)
911{
912 struct netlink_sock *nlk = nlk_sk(sk);
913
914 if (nlk->subscriptions && !subscriptions)
915 __sk_del_bind_node(sk);
916 else if (!nlk->subscriptions && subscriptions)
917 sk_add_bind_node(sk, &nl_table[sk->sk_protocol].mc_list);
918 nlk->subscriptions = subscriptions;
919}
920
921static int netlink_realloc_groups(struct sock *sk)
922{
923 struct netlink_sock *nlk = nlk_sk(sk);
924 unsigned int groups;
925 unsigned long *new_groups;
926 int err = 0;
927
928 netlink_table_grab();
929
930 groups = nl_table[sk->sk_protocol].groups;
931 if (!nl_table[sk->sk_protocol].registered) {
932 err = -ENOENT;
933 goto out_unlock;
934 }
935
936 if (nlk->ngroups >= groups)
937 goto out_unlock;
938
939 new_groups = krealloc(nlk->groups, NLGRPSZ(groups), GFP_ATOMIC);
940 if (new_groups == NULL) {
941 err = -ENOMEM;
942 goto out_unlock;
943 }
944 memset((char *)new_groups + NLGRPSZ(nlk->ngroups), 0,
945 NLGRPSZ(groups) - NLGRPSZ(nlk->ngroups));
946
947 nlk->groups = new_groups;
948 nlk->ngroups = groups;
949 out_unlock:
950 netlink_table_ungrab();
951 return err;
952}
953
954static void netlink_undo_bind(int group, long unsigned int groups,
955 struct sock *sk)
956{
957 struct netlink_sock *nlk = nlk_sk(sk);
958 int undo;
959
960 if (!nlk->netlink_unbind)
961 return;
962
963 for (undo = 0; undo < group; undo++)
964 if (test_bit(undo, &groups))
965 nlk->netlink_unbind(sock_net(sk), undo + 1);
966}
967
968static int netlink_bind(struct socket *sock, struct sockaddr *addr,
969 int addr_len)
970{
971 struct sock *sk = sock->sk;
972 struct net *net = sock_net(sk);
973 struct netlink_sock *nlk = nlk_sk(sk);
974 struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
975 int err = 0;
976 unsigned long groups;
977 bool bound;
978
979 if (addr_len < sizeof(struct sockaddr_nl))
980 return -EINVAL;
981
982 if (nladdr->nl_family != AF_NETLINK)
983 return -EINVAL;
984 groups = nladdr->nl_groups;
985
986 /* Only superuser is allowed to listen multicasts */
987 if (groups) {
988 if (!netlink_allowed(sock, NL_CFG_F_NONROOT_RECV))
989 return -EPERM;
990 err = netlink_realloc_groups(sk);
991 if (err)
992 return err;
993 }
994
995 if (nlk->ngroups < BITS_PER_LONG)
996 groups &= (1UL << nlk->ngroups) - 1;
997
998 /* Paired with WRITE_ONCE() in netlink_insert() */
999 bound = READ_ONCE(nlk->bound);
1000 if (bound) {
1001 /* Ensure nlk->portid is up-to-date. */
1002 smp_rmb();
1003
1004 if (nladdr->nl_pid != nlk->portid)
1005 return -EINVAL;
1006 }
1007
1008 if (nlk->netlink_bind && groups) {
1009 int group;
1010
1011 /* nl_groups is a u32, so cap the maximum groups we can bind */
1012 for (group = 0; group < BITS_PER_TYPE(u32); group++) {
1013 if (!test_bit(group, &groups))
1014 continue;
1015 err = nlk->netlink_bind(net, group + 1);
1016 if (!err)
1017 continue;
1018 netlink_undo_bind(group, groups, sk);
1019 return err;
1020 }
1021 }
1022
1023 /* No need for barriers here as we return to user-space without
1024 * using any of the bound attributes.
1025 */
1026 netlink_lock_table();
1027 if (!bound) {
1028 err = nladdr->nl_pid ?
1029 netlink_insert(sk, nladdr->nl_pid) :
1030 netlink_autobind(sock);
1031 if (err) {
1032 netlink_undo_bind(BITS_PER_TYPE(u32), groups, sk);
1033 goto unlock;
1034 }
1035 }
1036
1037 if (!groups && (nlk->groups == NULL || !(u32)nlk->groups[0]))
1038 goto unlock;
1039 netlink_unlock_table();
1040
1041 netlink_table_grab();
1042 netlink_update_subscriptions(sk, nlk->subscriptions +
1043 hweight32(groups) -
1044 hweight32(nlk->groups[0]));
1045 nlk->groups[0] = (nlk->groups[0] & ~0xffffffffUL) | groups;
1046 netlink_update_listeners(sk);
1047 netlink_table_ungrab();
1048
1049 return 0;
1050
1051unlock:
1052 netlink_unlock_table();
1053 return err;
1054}
1055
1056static int netlink_connect(struct socket *sock, struct sockaddr *addr,
1057 int alen, int flags)
1058{
1059 int err = 0;
1060 struct sock *sk = sock->sk;
1061 struct netlink_sock *nlk = nlk_sk(sk);
1062 struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
1063
1064 if (alen < sizeof(addr->sa_family))
1065 return -EINVAL;
1066
1067 if (addr->sa_family == AF_UNSPEC) {
1068 /* paired with READ_ONCE() in netlink_getsockbyportid() */
1069 WRITE_ONCE(sk->sk_state, NETLINK_UNCONNECTED);
1070 /* dst_portid and dst_group can be read locklessly */
1071 WRITE_ONCE(nlk->dst_portid, 0);
1072 WRITE_ONCE(nlk->dst_group, 0);
1073 return 0;
1074 }
1075 if (addr->sa_family != AF_NETLINK)
1076 return -EINVAL;
1077
1078 if (alen < sizeof(struct sockaddr_nl))
1079 return -EINVAL;
1080
1081 if ((nladdr->nl_groups || nladdr->nl_pid) &&
1082 !netlink_allowed(sock, NL_CFG_F_NONROOT_SEND))
1083 return -EPERM;
1084
1085 /* No need for barriers here as we return to user-space without
1086 * using any of the bound attributes.
1087 * Paired with WRITE_ONCE() in netlink_insert().
1088 */
1089 if (!READ_ONCE(nlk->bound))
1090 err = netlink_autobind(sock);
1091
1092 if (err == 0) {
1093 /* paired with READ_ONCE() in netlink_getsockbyportid() */
1094 WRITE_ONCE(sk->sk_state, NETLINK_CONNECTED);
1095 /* dst_portid and dst_group can be read locklessly */
1096 WRITE_ONCE(nlk->dst_portid, nladdr->nl_pid);
1097 WRITE_ONCE(nlk->dst_group, ffs(nladdr->nl_groups));
1098 }
1099
1100 return err;
1101}
1102
1103static int netlink_getname(struct socket *sock, struct sockaddr *addr,
1104 int peer)
1105{
1106 struct sock *sk = sock->sk;
1107 struct netlink_sock *nlk = nlk_sk(sk);
1108 DECLARE_SOCKADDR(struct sockaddr_nl *, nladdr, addr);
1109
1110 nladdr->nl_family = AF_NETLINK;
1111 nladdr->nl_pad = 0;
1112
1113 if (peer) {
1114 /* Paired with WRITE_ONCE() in netlink_connect() */
1115 nladdr->nl_pid = READ_ONCE(nlk->dst_portid);
1116 nladdr->nl_groups = netlink_group_mask(READ_ONCE(nlk->dst_group));
1117 } else {
1118 /* Paired with WRITE_ONCE() in netlink_insert() */
1119 nladdr->nl_pid = READ_ONCE(nlk->portid);
1120 netlink_lock_table();
1121 nladdr->nl_groups = nlk->groups ? nlk->groups[0] : 0;
1122 netlink_unlock_table();
1123 }
1124 return sizeof(*nladdr);
1125}
1126
1127static int netlink_ioctl(struct socket *sock, unsigned int cmd,
1128 unsigned long arg)
1129{
1130 /* try to hand this ioctl down to the NIC drivers.
1131 */
1132 return -ENOIOCTLCMD;
1133}
1134
1135static struct sock *netlink_getsockbyportid(struct sock *ssk, u32 portid)
1136{
1137 struct sock *sock;
1138 struct netlink_sock *nlk;
1139
1140 sock = netlink_lookup(sock_net(ssk), ssk->sk_protocol, portid);
1141 if (!sock)
1142 return ERR_PTR(-ECONNREFUSED);
1143
1144 /* Don't bother queuing skb if kernel socket has no input function */
1145 nlk = nlk_sk(sock);
1146 /* dst_portid and sk_state can be changed in netlink_connect() */
1147 if (READ_ONCE(sock->sk_state) == NETLINK_CONNECTED &&
1148 READ_ONCE(nlk->dst_portid) != nlk_sk(ssk)->portid) {
1149 sock_put(sock);
1150 return ERR_PTR(-ECONNREFUSED);
1151 }
1152 return sock;
1153}
1154
1155struct sock *netlink_getsockbyfilp(struct file *filp)
1156{
1157 struct inode *inode = file_inode(filp);
1158 struct sock *sock;
1159
1160 if (!S_ISSOCK(inode->i_mode))
1161 return ERR_PTR(-ENOTSOCK);
1162
1163 sock = SOCKET_I(inode)->sk;
1164 if (sock->sk_family != AF_NETLINK)
1165 return ERR_PTR(-EINVAL);
1166
1167 sock_hold(sock);
1168 return sock;
1169}
1170
1171static struct sk_buff *netlink_alloc_large_skb(unsigned int size,
1172 int broadcast)
1173{
1174 struct sk_buff *skb;
1175 void *data;
1176
1177 if (size <= NLMSG_GOODSIZE || broadcast)
1178 return alloc_skb(size, GFP_KERNEL);
1179
1180 size = SKB_DATA_ALIGN(size) +
1181 SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1182
1183 data = vmalloc(size);
1184 if (data == NULL)
1185 return NULL;
1186
1187 skb = __build_skb(data, size);
1188 if (skb == NULL)
1189 vfree(data);
1190 else
1191 skb->destructor = netlink_skb_destructor;
1192
1193 return skb;
1194}
1195
1196/*
1197 * Attach a skb to a netlink socket.
1198 * The caller must hold a reference to the destination socket. On error, the
1199 * reference is dropped. The skb is not send to the destination, just all
1200 * all error checks are performed and memory in the queue is reserved.
1201 * Return values:
1202 * < 0: error. skb freed, reference to sock dropped.
1203 * 0: continue
1204 * 1: repeat lookup - reference dropped while waiting for socket memory.
1205 */
1206int netlink_attachskb(struct sock *sk, struct sk_buff *skb,
1207 long *timeo, struct sock *ssk)
1208{
1209 struct netlink_sock *nlk;
1210
1211 nlk = nlk_sk(sk);
1212
1213 if ((atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
1214 test_bit(NETLINK_S_CONGESTED, &nlk->state))) {
1215 DECLARE_WAITQUEUE(wait, current);
1216 if (!*timeo) {
1217 if (!ssk || netlink_is_kernel(ssk))
1218 netlink_overrun(sk);
1219 sock_put(sk);
1220 kfree_skb(skb);
1221 return -EAGAIN;
1222 }
1223
1224 __set_current_state(TASK_INTERRUPTIBLE);
1225 add_wait_queue(&nlk->wait, &wait);
1226
1227 if ((atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
1228 test_bit(NETLINK_S_CONGESTED, &nlk->state)) &&
1229 !sock_flag(sk, SOCK_DEAD))
1230 *timeo = schedule_timeout(*timeo);
1231
1232 __set_current_state(TASK_RUNNING);
1233 remove_wait_queue(&nlk->wait, &wait);
1234 sock_put(sk);
1235
1236 if (signal_pending(current)) {
1237 kfree_skb(skb);
1238 return sock_intr_errno(*timeo);
1239 }
1240 return 1;
1241 }
1242 netlink_skb_set_owner_r(skb, sk);
1243 return 0;
1244}
1245
1246static int __netlink_sendskb(struct sock *sk, struct sk_buff *skb)
1247{
1248 int len = skb->len;
1249
1250 netlink_deliver_tap(sock_net(sk), skb);
1251
1252 skb_queue_tail(&sk->sk_receive_queue, skb);
1253 sk->sk_data_ready(sk);
1254 return len;
1255}
1256
1257int netlink_sendskb(struct sock *sk, struct sk_buff *skb)
1258{
1259 int len = __netlink_sendskb(sk, skb);
1260
1261 sock_put(sk);
1262 return len;
1263}
1264
1265void netlink_detachskb(struct sock *sk, struct sk_buff *skb)
1266{
1267 kfree_skb(skb);
1268 sock_put(sk);
1269}
1270
1271static struct sk_buff *netlink_trim(struct sk_buff *skb, gfp_t allocation)
1272{
1273 int delta;
1274
1275 WARN_ON(skb->sk != NULL);
1276 delta = skb->end - skb->tail;
1277 if (is_vmalloc_addr(skb->head) || delta * 2 < skb->truesize)
1278 return skb;
1279
1280 if (skb_shared(skb)) {
1281 struct sk_buff *nskb = skb_clone(skb, allocation);
1282 if (!nskb)
1283 return skb;
1284 consume_skb(skb);
1285 skb = nskb;
1286 }
1287
1288 pskb_expand_head(skb, 0, -delta,
1289 (allocation & ~__GFP_DIRECT_RECLAIM) |
1290 __GFP_NOWARN | __GFP_NORETRY);
1291 return skb;
1292}
1293
1294static int netlink_unicast_kernel(struct sock *sk, struct sk_buff *skb,
1295 struct sock *ssk)
1296{
1297 int ret;
1298 struct netlink_sock *nlk = nlk_sk(sk);
1299
1300 ret = -ECONNREFUSED;
1301 if (nlk->netlink_rcv != NULL) {
1302 ret = skb->len;
1303 netlink_skb_set_owner_r(skb, sk);
1304 NETLINK_CB(skb).sk = ssk;
1305 netlink_deliver_tap_kernel(sk, ssk, skb);
1306 nlk->netlink_rcv(skb);
1307 consume_skb(skb);
1308 } else {
1309 kfree_skb(skb);
1310 }
1311 sock_put(sk);
1312 return ret;
1313}
1314
1315int netlink_unicast(struct sock *ssk, struct sk_buff *skb,
1316 u32 portid, int nonblock)
1317{
1318 struct sock *sk;
1319 int err;
1320 long timeo;
1321
1322 skb = netlink_trim(skb, gfp_any());
1323
1324 timeo = sock_sndtimeo(ssk, nonblock);
1325retry:
1326 sk = netlink_getsockbyportid(ssk, portid);
1327 if (IS_ERR(sk)) {
1328 kfree_skb(skb);
1329 return PTR_ERR(sk);
1330 }
1331 if (netlink_is_kernel(sk))
1332 return netlink_unicast_kernel(sk, skb, ssk);
1333
1334 if (sk_filter(sk, skb)) {
1335 err = skb->len;
1336 kfree_skb(skb);
1337 sock_put(sk);
1338 return err;
1339 }
1340
1341 err = netlink_attachskb(sk, skb, &timeo, ssk);
1342 if (err == 1)
1343 goto retry;
1344 if (err)
1345 return err;
1346
1347 return netlink_sendskb(sk, skb);
1348}
1349EXPORT_SYMBOL(netlink_unicast);
1350
1351int netlink_has_listeners(struct sock *sk, unsigned int group)
1352{
1353 int res = 0;
1354 struct listeners *listeners;
1355
1356 BUG_ON(!netlink_is_kernel(sk));
1357
1358 rcu_read_lock();
1359 listeners = rcu_dereference(nl_table[sk->sk_protocol].listeners);
1360
1361 if (listeners && group - 1 < nl_table[sk->sk_protocol].groups)
1362 res = test_bit(group - 1, listeners->masks);
1363
1364 rcu_read_unlock();
1365
1366 return res;
1367}
1368EXPORT_SYMBOL_GPL(netlink_has_listeners);
1369
1370bool netlink_strict_get_check(struct sk_buff *skb)
1371{
1372 const struct netlink_sock *nlk = nlk_sk(NETLINK_CB(skb).sk);
1373
1374 return nlk->flags & NETLINK_F_STRICT_CHK;
1375}
1376EXPORT_SYMBOL_GPL(netlink_strict_get_check);
1377
1378static int netlink_broadcast_deliver(struct sock *sk, struct sk_buff *skb)
1379{
1380 struct netlink_sock *nlk = nlk_sk(sk);
1381
1382 if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf &&
1383 !test_bit(NETLINK_S_CONGESTED, &nlk->state)) {
1384 netlink_skb_set_owner_r(skb, sk);
1385 __netlink_sendskb(sk, skb);
1386 return atomic_read(&sk->sk_rmem_alloc) > (sk->sk_rcvbuf >> 1);
1387 }
1388 return -1;
1389}
1390
1391struct netlink_broadcast_data {
1392 struct sock *exclude_sk;
1393 struct net *net;
1394 u32 portid;
1395 u32 group;
1396 int failure;
1397 int delivery_failure;
1398 int congested;
1399 int delivered;
1400 gfp_t allocation;
1401 struct sk_buff *skb, *skb2;
1402 int (*tx_filter)(struct sock *dsk, struct sk_buff *skb, void *data);
1403 void *tx_data;
1404};
1405
1406static void do_one_broadcast(struct sock *sk,
1407 struct netlink_broadcast_data *p)
1408{
1409 struct netlink_sock *nlk = nlk_sk(sk);
1410 int val;
1411
1412 if (p->exclude_sk == sk)
1413 return;
1414
1415 if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
1416 !test_bit(p->group - 1, nlk->groups))
1417 return;
1418
1419 if (!net_eq(sock_net(sk), p->net)) {
1420 if (!(nlk->flags & NETLINK_F_LISTEN_ALL_NSID))
1421 return;
1422
1423 if (!peernet_has_id(sock_net(sk), p->net))
1424 return;
1425
1426 if (!file_ns_capable(sk->sk_socket->file, p->net->user_ns,
1427 CAP_NET_BROADCAST))
1428 return;
1429 }
1430
1431 if (p->failure) {
1432 netlink_overrun(sk);
1433 return;
1434 }
1435
1436 sock_hold(sk);
1437 if (p->skb2 == NULL) {
1438 if (skb_shared(p->skb)) {
1439 p->skb2 = skb_clone(p->skb, p->allocation);
1440 } else {
1441 p->skb2 = skb_get(p->skb);
1442 /*
1443 * skb ownership may have been set when
1444 * delivered to a previous socket.
1445 */
1446 skb_orphan(p->skb2);
1447 }
1448 }
1449 if (p->skb2 == NULL) {
1450 netlink_overrun(sk);
1451 /* Clone failed. Notify ALL listeners. */
1452 p->failure = 1;
1453 if (nlk->flags & NETLINK_F_BROADCAST_SEND_ERROR)
1454 p->delivery_failure = 1;
1455 goto out;
1456 }
1457 if (p->tx_filter && p->tx_filter(sk, p->skb2, p->tx_data)) {
1458 kfree_skb(p->skb2);
1459 p->skb2 = NULL;
1460 goto out;
1461 }
1462 if (sk_filter(sk, p->skb2)) {
1463 kfree_skb(p->skb2);
1464 p->skb2 = NULL;
1465 goto out;
1466 }
1467 NETLINK_CB(p->skb2).nsid = peernet2id(sock_net(sk), p->net);
1468 if (NETLINK_CB(p->skb2).nsid != NETNSA_NSID_NOT_ASSIGNED)
1469 NETLINK_CB(p->skb2).nsid_is_set = true;
1470 val = netlink_broadcast_deliver(sk, p->skb2);
1471 if (val < 0) {
1472 netlink_overrun(sk);
1473 if (nlk->flags & NETLINK_F_BROADCAST_SEND_ERROR)
1474 p->delivery_failure = 1;
1475 } else {
1476 p->congested |= val;
1477 p->delivered = 1;
1478 p->skb2 = NULL;
1479 }
1480out:
1481 sock_put(sk);
1482}
1483
1484int netlink_broadcast_filtered(struct sock *ssk, struct sk_buff *skb, u32 portid,
1485 u32 group, gfp_t allocation,
1486 int (*filter)(struct sock *dsk, struct sk_buff *skb, void *data),
1487 void *filter_data)
1488{
1489 struct net *net = sock_net(ssk);
1490 struct netlink_broadcast_data info;
1491 struct sock *sk;
1492
1493 skb = netlink_trim(skb, allocation);
1494
1495 info.exclude_sk = ssk;
1496 info.net = net;
1497 info.portid = portid;
1498 info.group = group;
1499 info.failure = 0;
1500 info.delivery_failure = 0;
1501 info.congested = 0;
1502 info.delivered = 0;
1503 info.allocation = allocation;
1504 info.skb = skb;
1505 info.skb2 = NULL;
1506 info.tx_filter = filter;
1507 info.tx_data = filter_data;
1508
1509 /* While we sleep in clone, do not allow to change socket list */
1510
1511 netlink_lock_table();
1512
1513 sk_for_each_bound(sk, &nl_table[ssk->sk_protocol].mc_list)
1514 do_one_broadcast(sk, &info);
1515
1516 consume_skb(skb);
1517
1518 netlink_unlock_table();
1519
1520 if (info.delivery_failure) {
1521 kfree_skb(info.skb2);
1522 return -ENOBUFS;
1523 }
1524 consume_skb(info.skb2);
1525
1526 if (info.delivered) {
1527 if (info.congested && gfpflags_allow_blocking(allocation))
1528 yield();
1529 return 0;
1530 }
1531 return -ESRCH;
1532}
1533EXPORT_SYMBOL(netlink_broadcast_filtered);
1534
1535int netlink_broadcast(struct sock *ssk, struct sk_buff *skb, u32 portid,
1536 u32 group, gfp_t allocation)
1537{
1538 return netlink_broadcast_filtered(ssk, skb, portid, group, allocation,
1539 NULL, NULL);
1540}
1541EXPORT_SYMBOL(netlink_broadcast);
1542
1543struct netlink_set_err_data {
1544 struct sock *exclude_sk;
1545 u32 portid;
1546 u32 group;
1547 int code;
1548};
1549
1550static int do_one_set_err(struct sock *sk, struct netlink_set_err_data *p)
1551{
1552 struct netlink_sock *nlk = nlk_sk(sk);
1553 int ret = 0;
1554
1555 if (sk == p->exclude_sk)
1556 goto out;
1557
1558 if (!net_eq(sock_net(sk), sock_net(p->exclude_sk)))
1559 goto out;
1560
1561 if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
1562 !test_bit(p->group - 1, nlk->groups))
1563 goto out;
1564
1565 if (p->code == ENOBUFS && nlk->flags & NETLINK_F_RECV_NO_ENOBUFS) {
1566 ret = 1;
1567 goto out;
1568 }
1569
1570 sk->sk_err = p->code;
1571 sk->sk_error_report(sk);
1572out:
1573 return ret;
1574}
1575
1576/**
1577 * netlink_set_err - report error to broadcast listeners
1578 * @ssk: the kernel netlink socket, as returned by netlink_kernel_create()
1579 * @portid: the PORTID of a process that we want to skip (if any)
1580 * @group: the broadcast group that will notice the error
1581 * @code: error code, must be negative (as usual in kernelspace)
1582 *
1583 * This function returns the number of broadcast listeners that have set the
1584 * NETLINK_NO_ENOBUFS socket option.
1585 */
1586int netlink_set_err(struct sock *ssk, u32 portid, u32 group, int code)
1587{
1588 struct netlink_set_err_data info;
1589 unsigned long flags;
1590 struct sock *sk;
1591 int ret = 0;
1592
1593 info.exclude_sk = ssk;
1594 info.portid = portid;
1595 info.group = group;
1596 /* sk->sk_err wants a positive error value */
1597 info.code = -code;
1598
1599 read_lock_irqsave(&nl_table_lock, flags);
1600
1601 sk_for_each_bound(sk, &nl_table[ssk->sk_protocol].mc_list)
1602 ret += do_one_set_err(sk, &info);
1603
1604 read_unlock_irqrestore(&nl_table_lock, flags);
1605 return ret;
1606}
1607EXPORT_SYMBOL(netlink_set_err);
1608
1609/* must be called with netlink table grabbed */
1610static void netlink_update_socket_mc(struct netlink_sock *nlk,
1611 unsigned int group,
1612 int is_new)
1613{
1614 int old, new = !!is_new, subscriptions;
1615
1616 old = test_bit(group - 1, nlk->groups);
1617 subscriptions = nlk->subscriptions - old + new;
1618 if (new)
1619 __set_bit(group - 1, nlk->groups);
1620 else
1621 __clear_bit(group - 1, nlk->groups);
1622 netlink_update_subscriptions(&nlk->sk, subscriptions);
1623 netlink_update_listeners(&nlk->sk);
1624}
1625
1626static int netlink_setsockopt(struct socket *sock, int level, int optname,
1627 char __user *optval, unsigned int optlen)
1628{
1629 struct sock *sk = sock->sk;
1630 struct netlink_sock *nlk = nlk_sk(sk);
1631 unsigned int val = 0;
1632 int err;
1633
1634 if (level != SOL_NETLINK)
1635 return -ENOPROTOOPT;
1636
1637 if (optlen >= sizeof(int) &&
1638 get_user(val, (unsigned int __user *)optval))
1639 return -EFAULT;
1640
1641 switch (optname) {
1642 case NETLINK_PKTINFO:
1643 if (val)
1644 nlk->flags |= NETLINK_F_RECV_PKTINFO;
1645 else
1646 nlk->flags &= ~NETLINK_F_RECV_PKTINFO;
1647 err = 0;
1648 break;
1649 case NETLINK_ADD_MEMBERSHIP:
1650 case NETLINK_DROP_MEMBERSHIP: {
1651 if (!netlink_allowed(sock, NL_CFG_F_NONROOT_RECV))
1652 return -EPERM;
1653 err = netlink_realloc_groups(sk);
1654 if (err)
1655 return err;
1656 if (!val || val - 1 >= nlk->ngroups)
1657 return -EINVAL;
1658 if (optname == NETLINK_ADD_MEMBERSHIP && nlk->netlink_bind) {
1659 err = nlk->netlink_bind(sock_net(sk), val);
1660 if (err)
1661 return err;
1662 }
1663 netlink_table_grab();
1664 netlink_update_socket_mc(nlk, val,
1665 optname == NETLINK_ADD_MEMBERSHIP);
1666 netlink_table_ungrab();
1667 if (optname == NETLINK_DROP_MEMBERSHIP && nlk->netlink_unbind)
1668 nlk->netlink_unbind(sock_net(sk), val);
1669
1670 err = 0;
1671 break;
1672 }
1673 case NETLINK_BROADCAST_ERROR:
1674 if (val)
1675 nlk->flags |= NETLINK_F_BROADCAST_SEND_ERROR;
1676 else
1677 nlk->flags &= ~NETLINK_F_BROADCAST_SEND_ERROR;
1678 err = 0;
1679 break;
1680 case NETLINK_NO_ENOBUFS:
1681 if (val) {
1682 nlk->flags |= NETLINK_F_RECV_NO_ENOBUFS;
1683 clear_bit(NETLINK_S_CONGESTED, &nlk->state);
1684 wake_up_interruptible(&nlk->wait);
1685 } else {
1686 nlk->flags &= ~NETLINK_F_RECV_NO_ENOBUFS;
1687 }
1688 err = 0;
1689 break;
1690 case NETLINK_LISTEN_ALL_NSID:
1691 if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_BROADCAST))
1692 return -EPERM;
1693
1694 if (val)
1695 nlk->flags |= NETLINK_F_LISTEN_ALL_NSID;
1696 else
1697 nlk->flags &= ~NETLINK_F_LISTEN_ALL_NSID;
1698 err = 0;
1699 break;
1700 case NETLINK_CAP_ACK:
1701 if (val)
1702 nlk->flags |= NETLINK_F_CAP_ACK;
1703 else
1704 nlk->flags &= ~NETLINK_F_CAP_ACK;
1705 err = 0;
1706 break;
1707 case NETLINK_EXT_ACK:
1708 if (val)
1709 nlk->flags |= NETLINK_F_EXT_ACK;
1710 else
1711 nlk->flags &= ~NETLINK_F_EXT_ACK;
1712 err = 0;
1713 break;
1714 case NETLINK_GET_STRICT_CHK:
1715 if (val)
1716 nlk->flags |= NETLINK_F_STRICT_CHK;
1717 else
1718 nlk->flags &= ~NETLINK_F_STRICT_CHK;
1719 err = 0;
1720 break;
1721 default:
1722 err = -ENOPROTOOPT;
1723 }
1724 return err;
1725}
1726
1727static int netlink_getsockopt(struct socket *sock, int level, int optname,
1728 char __user *optval, int __user *optlen)
1729{
1730 struct sock *sk = sock->sk;
1731 struct netlink_sock *nlk = nlk_sk(sk);
1732 unsigned int flag;
1733 int len, val;
1734
1735 if (level != SOL_NETLINK)
1736 return -ENOPROTOOPT;
1737
1738 if (get_user(len, optlen))
1739 return -EFAULT;
1740 if (len < 0)
1741 return -EINVAL;
1742
1743 switch (optname) {
1744 case NETLINK_PKTINFO:
1745 flag = NETLINK_F_RECV_PKTINFO;
1746 break;
1747 case NETLINK_BROADCAST_ERROR:
1748 flag = NETLINK_F_BROADCAST_SEND_ERROR;
1749 break;
1750 case NETLINK_NO_ENOBUFS:
1751 flag = NETLINK_F_RECV_NO_ENOBUFS;
1752 break;
1753 case NETLINK_LIST_MEMBERSHIPS: {
1754 int pos, idx, shift, err = 0;
1755
1756 netlink_lock_table();
1757 for (pos = 0; pos * 8 < nlk->ngroups; pos += sizeof(u32)) {
1758 if (len - pos < sizeof(u32))
1759 break;
1760
1761 idx = pos / sizeof(unsigned long);
1762 shift = (pos % sizeof(unsigned long)) * 8;
1763 if (put_user((u32)(nlk->groups[idx] >> shift),
1764 (u32 __user *)(optval + pos))) {
1765 err = -EFAULT;
1766 break;
1767 }
1768 }
1769 if (put_user(ALIGN(BITS_TO_BYTES(nlk->ngroups), sizeof(u32)), optlen))
1770 err = -EFAULT;
1771 netlink_unlock_table();
1772 return err;
1773 }
1774 case NETLINK_CAP_ACK:
1775 flag = NETLINK_F_CAP_ACK;
1776 break;
1777 case NETLINK_EXT_ACK:
1778 flag = NETLINK_F_EXT_ACK;
1779 break;
1780 case NETLINK_GET_STRICT_CHK:
1781 flag = NETLINK_F_STRICT_CHK;
1782 break;
1783 default:
1784 return -ENOPROTOOPT;
1785 }
1786
1787 if (len < sizeof(int))
1788 return -EINVAL;
1789
1790 len = sizeof(int);
1791 val = nlk->flags & flag ? 1 : 0;
1792
1793 if (put_user(len, optlen) ||
1794 copy_to_user(optval, &val, len))
1795 return -EFAULT;
1796
1797 return 0;
1798}
1799
1800static void netlink_cmsg_recv_pktinfo(struct msghdr *msg, struct sk_buff *skb)
1801{
1802 struct nl_pktinfo info;
1803
1804 info.group = NETLINK_CB(skb).dst_group;
1805 put_cmsg(msg, SOL_NETLINK, NETLINK_PKTINFO, sizeof(info), &info);
1806}
1807
1808static void netlink_cmsg_listen_all_nsid(struct sock *sk, struct msghdr *msg,
1809 struct sk_buff *skb)
1810{
1811 if (!NETLINK_CB(skb).nsid_is_set)
1812 return;
1813
1814 put_cmsg(msg, SOL_NETLINK, NETLINK_LISTEN_ALL_NSID, sizeof(int),
1815 &NETLINK_CB(skb).nsid);
1816}
1817
1818static int netlink_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
1819{
1820 struct sock *sk = sock->sk;
1821 struct netlink_sock *nlk = nlk_sk(sk);
1822 DECLARE_SOCKADDR(struct sockaddr_nl *, addr, msg->msg_name);
1823 u32 dst_portid;
1824 u32 dst_group;
1825 struct sk_buff *skb;
1826 int err;
1827 struct scm_cookie scm;
1828 u32 netlink_skb_flags = 0;
1829
1830 if (msg->msg_flags&MSG_OOB)
1831 return -EOPNOTSUPP;
1832
1833 if (len == 0) {
1834 pr_warn_once("Zero length message leads to an empty skb\n");
1835 return -ENODATA;
1836 }
1837
1838 err = scm_send(sock, msg, &scm, true);
1839 if (err < 0)
1840 return err;
1841
1842 if (msg->msg_namelen) {
1843 err = -EINVAL;
1844 if (msg->msg_namelen < sizeof(struct sockaddr_nl))
1845 goto out;
1846 if (addr->nl_family != AF_NETLINK)
1847 goto out;
1848 dst_portid = addr->nl_pid;
1849 dst_group = ffs(addr->nl_groups);
1850 err = -EPERM;
1851 if ((dst_group || dst_portid) &&
1852 !netlink_allowed(sock, NL_CFG_F_NONROOT_SEND))
1853 goto out;
1854 netlink_skb_flags |= NETLINK_SKB_DST;
1855 } else {
1856 /* Paired with WRITE_ONCE() in netlink_connect() */
1857 dst_portid = READ_ONCE(nlk->dst_portid);
1858 dst_group = READ_ONCE(nlk->dst_group);
1859 }
1860
1861 /* Paired with WRITE_ONCE() in netlink_insert() */
1862 if (!READ_ONCE(nlk->bound)) {
1863 err = netlink_autobind(sock);
1864 if (err)
1865 goto out;
1866 } else {
1867 /* Ensure nlk is hashed and visible. */
1868 smp_rmb();
1869 }
1870
1871 err = -EMSGSIZE;
1872 if (len > sk->sk_sndbuf - 32)
1873 goto out;
1874 err = -ENOBUFS;
1875 skb = netlink_alloc_large_skb(len, dst_group);
1876 if (skb == NULL)
1877 goto out;
1878
1879 NETLINK_CB(skb).portid = nlk->portid;
1880 NETLINK_CB(skb).dst_group = dst_group;
1881 NETLINK_CB(skb).creds = scm.creds;
1882 NETLINK_CB(skb).flags = netlink_skb_flags;
1883
1884 err = -EFAULT;
1885 if (memcpy_from_msg(skb_put(skb, len), msg, len)) {
1886 kfree_skb(skb);
1887 goto out;
1888 }
1889
1890 err = security_netlink_send(sk, skb);
1891 if (err) {
1892 kfree_skb(skb);
1893 goto out;
1894 }
1895
1896 if (dst_group) {
1897 refcount_inc(&skb->users);
1898 netlink_broadcast(sk, skb, dst_portid, dst_group, GFP_KERNEL);
1899 }
1900 err = netlink_unicast(sk, skb, dst_portid, msg->msg_flags&MSG_DONTWAIT);
1901
1902out:
1903 scm_destroy(&scm);
1904 return err;
1905}
1906
1907static int netlink_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
1908 int flags)
1909{
1910 struct scm_cookie scm;
1911 struct sock *sk = sock->sk;
1912 struct netlink_sock *nlk = nlk_sk(sk);
1913 int noblock = flags&MSG_DONTWAIT;
1914 size_t copied;
1915 struct sk_buff *skb, *data_skb;
1916 int err, ret;
1917
1918 if (flags&MSG_OOB)
1919 return -EOPNOTSUPP;
1920
1921 copied = 0;
1922
1923 skb = skb_recv_datagram(sk, flags, noblock, &err);
1924 if (skb == NULL)
1925 goto out;
1926
1927 data_skb = skb;
1928
1929#ifdef CONFIG_COMPAT_NETLINK_MESSAGES
1930 if (unlikely(skb_shinfo(skb)->frag_list)) {
1931 /*
1932 * If this skb has a frag_list, then here that means that we
1933 * will have to use the frag_list skb's data for compat tasks
1934 * and the regular skb's data for normal (non-compat) tasks.
1935 *
1936 * If we need to send the compat skb, assign it to the
1937 * 'data_skb' variable so that it will be used below for data
1938 * copying. We keep 'skb' for everything else, including
1939 * freeing both later.
1940 */
1941 if (flags & MSG_CMSG_COMPAT)
1942 data_skb = skb_shinfo(skb)->frag_list;
1943 }
1944#endif
1945
1946 /* Record the max length of recvmsg() calls for future allocations */
1947 nlk->max_recvmsg_len = max(nlk->max_recvmsg_len, len);
1948 nlk->max_recvmsg_len = min_t(size_t, nlk->max_recvmsg_len,
1949 SKB_WITH_OVERHEAD(32768));
1950
1951 copied = data_skb->len;
1952 if (len < copied) {
1953 msg->msg_flags |= MSG_TRUNC;
1954 copied = len;
1955 }
1956
1957 err = skb_copy_datagram_msg(data_skb, 0, msg, copied);
1958
1959 if (msg->msg_name) {
1960 DECLARE_SOCKADDR(struct sockaddr_nl *, addr, msg->msg_name);
1961 addr->nl_family = AF_NETLINK;
1962 addr->nl_pad = 0;
1963 addr->nl_pid = NETLINK_CB(skb).portid;
1964 addr->nl_groups = netlink_group_mask(NETLINK_CB(skb).dst_group);
1965 msg->msg_namelen = sizeof(*addr);
1966 }
1967
1968 if (nlk->flags & NETLINK_F_RECV_PKTINFO)
1969 netlink_cmsg_recv_pktinfo(msg, skb);
1970 if (nlk->flags & NETLINK_F_LISTEN_ALL_NSID)
1971 netlink_cmsg_listen_all_nsid(sk, msg, skb);
1972
1973 memset(&scm, 0, sizeof(scm));
1974 scm.creds = *NETLINK_CREDS(skb);
1975 if (flags & MSG_TRUNC)
1976 copied = data_skb->len;
1977
1978 skb_free_datagram(sk, skb);
1979
1980 if (READ_ONCE(nlk->cb_running) &&
1981 atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf / 2) {
1982 ret = netlink_dump(sk);
1983 if (ret) {
1984 sk->sk_err = -ret;
1985 sk->sk_error_report(sk);
1986 }
1987 }
1988
1989 scm_recv(sock, msg, &scm, flags);
1990out:
1991 netlink_rcv_wake(sk);
1992 return err ? : copied;
1993}
1994
1995static void netlink_data_ready(struct sock *sk)
1996{
1997 BUG();
1998}
1999
2000/*
2001 * We export these functions to other modules. They provide a
2002 * complete set of kernel non-blocking support for message
2003 * queueing.
2004 */
2005
2006struct sock *
2007__netlink_kernel_create(struct net *net, int unit, struct module *module,
2008 struct netlink_kernel_cfg *cfg)
2009{
2010 struct socket *sock;
2011 struct sock *sk;
2012 struct netlink_sock *nlk;
2013 struct listeners *listeners = NULL;
2014 struct mutex *cb_mutex = cfg ? cfg->cb_mutex : NULL;
2015 unsigned int groups;
2016
2017 BUG_ON(!nl_table);
2018
2019 if (unit < 0 || unit >= MAX_LINKS)
2020 return NULL;
2021
2022 if (sock_create_lite(PF_NETLINK, SOCK_DGRAM, unit, &sock))
2023 return NULL;
2024
2025 if (__netlink_create(net, sock, cb_mutex, unit, 1) < 0)
2026 goto out_sock_release_nosk;
2027
2028 sk = sock->sk;
2029
2030 if (!cfg || cfg->groups < 32)
2031 groups = 32;
2032 else
2033 groups = cfg->groups;
2034
2035 listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
2036 if (!listeners)
2037 goto out_sock_release;
2038
2039 sk->sk_data_ready = netlink_data_ready;
2040 if (cfg && cfg->input)
2041 nlk_sk(sk)->netlink_rcv = cfg->input;
2042
2043 if (netlink_insert(sk, 0))
2044 goto out_sock_release;
2045
2046 nlk = nlk_sk(sk);
2047 nlk->flags |= NETLINK_F_KERNEL_SOCKET;
2048
2049 netlink_table_grab();
2050 if (!nl_table[unit].registered) {
2051 nl_table[unit].groups = groups;
2052 rcu_assign_pointer(nl_table[unit].listeners, listeners);
2053 nl_table[unit].cb_mutex = cb_mutex;
2054 nl_table[unit].module = module;
2055 if (cfg) {
2056 nl_table[unit].bind = cfg->bind;
2057 nl_table[unit].unbind = cfg->unbind;
2058 nl_table[unit].flags = cfg->flags;
2059 if (cfg->compare)
2060 nl_table[unit].compare = cfg->compare;
2061 }
2062 nl_table[unit].registered = 1;
2063 } else {
2064 kfree(listeners);
2065 nl_table[unit].registered++;
2066 }
2067 netlink_table_ungrab();
2068 return sk;
2069
2070out_sock_release:
2071 kfree(listeners);
2072 netlink_kernel_release(sk);
2073 return NULL;
2074
2075out_sock_release_nosk:
2076 sock_release(sock);
2077 return NULL;
2078}
2079EXPORT_SYMBOL(__netlink_kernel_create);
2080
2081void
2082netlink_kernel_release(struct sock *sk)
2083{
2084 if (sk == NULL || sk->sk_socket == NULL)
2085 return;
2086
2087 sock_release(sk->sk_socket);
2088}
2089EXPORT_SYMBOL(netlink_kernel_release);
2090
2091int __netlink_change_ngroups(struct sock *sk, unsigned int groups)
2092{
2093 struct listeners *new, *old;
2094 struct netlink_table *tbl = &nl_table[sk->sk_protocol];
2095
2096 if (groups < 32)
2097 groups = 32;
2098
2099 if (NLGRPSZ(tbl->groups) < NLGRPSZ(groups)) {
2100 new = kzalloc(sizeof(*new) + NLGRPSZ(groups), GFP_ATOMIC);
2101 if (!new)
2102 return -ENOMEM;
2103 old = nl_deref_protected(tbl->listeners);
2104 memcpy(new->masks, old->masks, NLGRPSZ(tbl->groups));
2105 rcu_assign_pointer(tbl->listeners, new);
2106
2107 kfree_rcu(old, rcu);
2108 }
2109 tbl->groups = groups;
2110
2111 return 0;
2112}
2113
2114/**
2115 * netlink_change_ngroups - change number of multicast groups
2116 *
2117 * This changes the number of multicast groups that are available
2118 * on a certain netlink family. Note that it is not possible to
2119 * change the number of groups to below 32. Also note that it does
2120 * not implicitly call netlink_clear_multicast_users() when the
2121 * number of groups is reduced.
2122 *
2123 * @sk: The kernel netlink socket, as returned by netlink_kernel_create().
2124 * @groups: The new number of groups.
2125 */
2126int netlink_change_ngroups(struct sock *sk, unsigned int groups)
2127{
2128 int err;
2129
2130 netlink_table_grab();
2131 err = __netlink_change_ngroups(sk, groups);
2132 netlink_table_ungrab();
2133
2134 return err;
2135}
2136
2137void __netlink_clear_multicast_users(struct sock *ksk, unsigned int group)
2138{
2139 struct sock *sk;
2140 struct netlink_table *tbl = &nl_table[ksk->sk_protocol];
2141 struct hlist_node *tmp;
2142
2143 sk_for_each_bound_safe(sk, tmp, &tbl->mc_list)
2144 netlink_update_socket_mc(nlk_sk(sk), group, 0);
2145}
2146
2147struct nlmsghdr *
2148__nlmsg_put(struct sk_buff *skb, u32 portid, u32 seq, int type, int len, int flags)
2149{
2150 struct nlmsghdr *nlh;
2151 int size = nlmsg_msg_size(len);
2152
2153 nlh = skb_put(skb, NLMSG_ALIGN(size));
2154 nlh->nlmsg_type = type;
2155 nlh->nlmsg_len = size;
2156 nlh->nlmsg_flags = flags;
2157 nlh->nlmsg_pid = portid;
2158 nlh->nlmsg_seq = seq;
2159 if (!__builtin_constant_p(size) || NLMSG_ALIGN(size) - size != 0)
2160 memset(nlmsg_data(nlh) + len, 0, NLMSG_ALIGN(size) - size);
2161 return nlh;
2162}
2163EXPORT_SYMBOL(__nlmsg_put);
2164
2165/*
2166 * It looks a bit ugly.
2167 * It would be better to create kernel thread.
2168 */
2169
2170static int netlink_dump(struct sock *sk)
2171{
2172 struct netlink_sock *nlk = nlk_sk(sk);
2173 struct netlink_ext_ack extack = {};
2174 struct netlink_callback *cb;
2175 struct sk_buff *skb = NULL;
2176 struct nlmsghdr *nlh;
2177 struct module *module;
2178 int err = -ENOBUFS;
2179 int alloc_min_size;
2180 int alloc_size;
2181
2182 mutex_lock(nlk->cb_mutex);
2183 if (!nlk->cb_running) {
2184 err = -EINVAL;
2185 goto errout_skb;
2186 }
2187
2188 if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
2189 goto errout_skb;
2190
2191 /* NLMSG_GOODSIZE is small to avoid high order allocations being
2192 * required, but it makes sense to _attempt_ a 16K bytes allocation
2193 * to reduce number of system calls on dump operations, if user
2194 * ever provided a big enough buffer.
2195 */
2196 cb = &nlk->cb;
2197 alloc_min_size = max_t(int, cb->min_dump_alloc, NLMSG_GOODSIZE);
2198
2199 if (alloc_min_size < nlk->max_recvmsg_len) {
2200 alloc_size = nlk->max_recvmsg_len;
2201 skb = alloc_skb(alloc_size,
2202 (GFP_KERNEL & ~__GFP_DIRECT_RECLAIM) |
2203 __GFP_NOWARN | __GFP_NORETRY);
2204 }
2205 if (!skb) {
2206 alloc_size = alloc_min_size;
2207 skb = alloc_skb(alloc_size, GFP_KERNEL);
2208 }
2209 if (!skb)
2210 goto errout_skb;
2211
2212 /* Trim skb to allocated size. User is expected to provide buffer as
2213 * large as max(min_dump_alloc, 16KiB (mac_recvmsg_len capped at
2214 * netlink_recvmsg())). dump will pack as many smaller messages as
2215 * could fit within the allocated skb. skb is typically allocated
2216 * with larger space than required (could be as much as near 2x the
2217 * requested size with align to next power of 2 approach). Allowing
2218 * dump to use the excess space makes it difficult for a user to have a
2219 * reasonable static buffer based on the expected largest dump of a
2220 * single netdev. The outcome is MSG_TRUNC error.
2221 */
2222 skb_reserve(skb, skb_tailroom(skb) - alloc_size);
2223
2224 /* Make sure malicious BPF programs can not read unitialized memory
2225 * from skb->head -> skb->data
2226 */
2227 skb_reset_network_header(skb);
2228 skb_reset_mac_header(skb);
2229
2230 netlink_skb_set_owner_r(skb, sk);
2231
2232 if (nlk->dump_done_errno > 0) {
2233 cb->extack = &extack;
2234 nlk->dump_done_errno = cb->dump(skb, cb);
2235 cb->extack = NULL;
2236 }
2237
2238 if (nlk->dump_done_errno > 0 ||
2239 skb_tailroom(skb) < nlmsg_total_size(sizeof(nlk->dump_done_errno))) {
2240 mutex_unlock(nlk->cb_mutex);
2241
2242 if (sk_filter(sk, skb))
2243 kfree_skb(skb);
2244 else
2245 __netlink_sendskb(sk, skb);
2246 return 0;
2247 }
2248
2249 nlh = nlmsg_put_answer(skb, cb, NLMSG_DONE,
2250 sizeof(nlk->dump_done_errno),
2251 NLM_F_MULTI | cb->answer_flags);
2252 if (WARN_ON(!nlh))
2253 goto errout_skb;
2254
2255 nl_dump_check_consistent(cb, nlh);
2256
2257 memcpy(nlmsg_data(nlh), &nlk->dump_done_errno,
2258 sizeof(nlk->dump_done_errno));
2259
2260 if (extack._msg && nlk->flags & NETLINK_F_EXT_ACK) {
2261 nlh->nlmsg_flags |= NLM_F_ACK_TLVS;
2262 if (!nla_put_string(skb, NLMSGERR_ATTR_MSG, extack._msg))
2263 nlmsg_end(skb, nlh);
2264 }
2265
2266 if (sk_filter(sk, skb))
2267 kfree_skb(skb);
2268 else
2269 __netlink_sendskb(sk, skb);
2270
2271 if (cb->done)
2272 cb->done(cb);
2273
2274 WRITE_ONCE(nlk->cb_running, false);
2275 module = cb->module;
2276 skb = cb->skb;
2277 mutex_unlock(nlk->cb_mutex);
2278 module_put(module);
2279 consume_skb(skb);
2280 return 0;
2281
2282errout_skb:
2283 mutex_unlock(nlk->cb_mutex);
2284 kfree_skb(skb);
2285 return err;
2286}
2287
2288int __netlink_dump_start(struct sock *ssk, struct sk_buff *skb,
2289 const struct nlmsghdr *nlh,
2290 struct netlink_dump_control *control)
2291{
2292 struct netlink_sock *nlk, *nlk2;
2293 struct netlink_callback *cb;
2294 struct sock *sk;
2295 int ret;
2296
2297 refcount_inc(&skb->users);
2298
2299 sk = netlink_lookup(sock_net(ssk), ssk->sk_protocol, NETLINK_CB(skb).portid);
2300 if (sk == NULL) {
2301 ret = -ECONNREFUSED;
2302 goto error_free;
2303 }
2304
2305 nlk = nlk_sk(sk);
2306 mutex_lock(nlk->cb_mutex);
2307 /* A dump is in progress... */
2308 if (nlk->cb_running) {
2309 ret = -EBUSY;
2310 goto error_unlock;
2311 }
2312 /* add reference of module which cb->dump belongs to */
2313 if (!try_module_get(control->module)) {
2314 ret = -EPROTONOSUPPORT;
2315 goto error_unlock;
2316 }
2317
2318 cb = &nlk->cb;
2319 memset(cb, 0, sizeof(*cb));
2320 cb->dump = control->dump;
2321 cb->done = control->done;
2322 cb->nlh = nlh;
2323 cb->data = control->data;
2324 cb->module = control->module;
2325 cb->min_dump_alloc = control->min_dump_alloc;
2326 cb->skb = skb;
2327
2328 nlk2 = nlk_sk(NETLINK_CB(skb).sk);
2329 cb->strict_check = !!(nlk2->flags & NETLINK_F_STRICT_CHK);
2330
2331 if (control->start) {
2332 ret = control->start(cb);
2333 if (ret)
2334 goto error_put;
2335 }
2336
2337 WRITE_ONCE(nlk->cb_running, true);
2338 nlk->dump_done_errno = INT_MAX;
2339
2340 mutex_unlock(nlk->cb_mutex);
2341
2342 ret = netlink_dump(sk);
2343
2344 sock_put(sk);
2345
2346 if (ret)
2347 return ret;
2348
2349 /* We successfully started a dump, by returning -EINTR we
2350 * signal not to send ACK even if it was requested.
2351 */
2352 return -EINTR;
2353
2354error_put:
2355 module_put(control->module);
2356error_unlock:
2357 sock_put(sk);
2358 mutex_unlock(nlk->cb_mutex);
2359error_free:
2360 kfree_skb(skb);
2361 return ret;
2362}
2363EXPORT_SYMBOL(__netlink_dump_start);
2364
2365void netlink_ack(struct sk_buff *in_skb, struct nlmsghdr *nlh, int err,
2366 const struct netlink_ext_ack *extack)
2367{
2368 struct sk_buff *skb;
2369 struct nlmsghdr *rep;
2370 struct nlmsgerr *errmsg;
2371 size_t payload = sizeof(*errmsg);
2372 size_t tlvlen = 0;
2373 struct netlink_sock *nlk = nlk_sk(NETLINK_CB(in_skb).sk);
2374 unsigned int flags = 0;
2375 bool nlk_has_extack = nlk->flags & NETLINK_F_EXT_ACK;
2376
2377 /* Error messages get the original request appened, unless the user
2378 * requests to cap the error message, and get extra error data if
2379 * requested.
2380 */
2381 if (nlk_has_extack && extack && extack->_msg)
2382 tlvlen += nla_total_size(strlen(extack->_msg) + 1);
2383
2384 if (err) {
2385 if (!(nlk->flags & NETLINK_F_CAP_ACK))
2386 payload += nlmsg_len(nlh);
2387 else
2388 flags |= NLM_F_CAPPED;
2389 if (nlk_has_extack && extack && extack->bad_attr)
2390 tlvlen += nla_total_size(sizeof(u32));
2391 } else {
2392 flags |= NLM_F_CAPPED;
2393
2394 if (nlk_has_extack && extack && extack->cookie_len)
2395 tlvlen += nla_total_size(extack->cookie_len);
2396 }
2397
2398 if (tlvlen)
2399 flags |= NLM_F_ACK_TLVS;
2400
2401 skb = nlmsg_new(payload + tlvlen, GFP_KERNEL);
2402 if (!skb) {
2403 NETLINK_CB(in_skb).sk->sk_err = ENOBUFS;
2404 NETLINK_CB(in_skb).sk->sk_error_report(NETLINK_CB(in_skb).sk);
2405 return;
2406 }
2407
2408 rep = __nlmsg_put(skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq,
2409 NLMSG_ERROR, payload, flags);
2410 errmsg = nlmsg_data(rep);
2411 errmsg->error = err;
2412 memcpy(&errmsg->msg, nlh, payload > sizeof(*errmsg) ? nlh->nlmsg_len : sizeof(*nlh));
2413
2414 if (nlk_has_extack && extack) {
2415 if (extack->_msg) {
2416 WARN_ON(nla_put_string(skb, NLMSGERR_ATTR_MSG,
2417 extack->_msg));
2418 }
2419 if (err) {
2420 if (extack->bad_attr &&
2421 !WARN_ON((u8 *)extack->bad_attr < in_skb->data ||
2422 (u8 *)extack->bad_attr >= in_skb->data +
2423 in_skb->len))
2424 WARN_ON(nla_put_u32(skb, NLMSGERR_ATTR_OFFS,
2425 (u8 *)extack->bad_attr -
2426 (u8 *)nlh));
2427 } else {
2428 if (extack->cookie_len)
2429 WARN_ON(nla_put(skb, NLMSGERR_ATTR_COOKIE,
2430 extack->cookie_len,
2431 extack->cookie));
2432 }
2433 }
2434
2435 nlmsg_end(skb, rep);
2436
2437 netlink_unicast(in_skb->sk, skb, NETLINK_CB(in_skb).portid, MSG_DONTWAIT);
2438}
2439EXPORT_SYMBOL(netlink_ack);
2440
2441int netlink_rcv_skb(struct sk_buff *skb, int (*cb)(struct sk_buff *,
2442 struct nlmsghdr *,
2443 struct netlink_ext_ack *))
2444{
2445 struct netlink_ext_ack extack;
2446 struct nlmsghdr *nlh;
2447 int err;
2448
2449 while (skb->len >= nlmsg_total_size(0)) {
2450 int msglen;
2451
2452 memset(&extack, 0, sizeof(extack));
2453 nlh = nlmsg_hdr(skb);
2454 err = 0;
2455
2456 if (nlh->nlmsg_len < NLMSG_HDRLEN || skb->len < nlh->nlmsg_len)
2457 return 0;
2458
2459 /* Only requests are handled by the kernel */
2460 if (!(nlh->nlmsg_flags & NLM_F_REQUEST))
2461 goto ack;
2462
2463 /* Skip control messages */
2464 if (nlh->nlmsg_type < NLMSG_MIN_TYPE)
2465 goto ack;
2466
2467 err = cb(skb, nlh, &extack);
2468 if (err == -EINTR)
2469 goto skip;
2470
2471ack:
2472 if (nlh->nlmsg_flags & NLM_F_ACK || err)
2473 netlink_ack(skb, nlh, err, &extack);
2474
2475skip:
2476 msglen = NLMSG_ALIGN(nlh->nlmsg_len);
2477 if (msglen > skb->len)
2478 msglen = skb->len;
2479 skb_pull(skb, msglen);
2480 }
2481
2482 return 0;
2483}
2484EXPORT_SYMBOL(netlink_rcv_skb);
2485
2486/**
2487 * nlmsg_notify - send a notification netlink message
2488 * @sk: netlink socket to use
2489 * @skb: notification message
2490 * @portid: destination netlink portid for reports or 0
2491 * @group: destination multicast group or 0
2492 * @report: 1 to report back, 0 to disable
2493 * @flags: allocation flags
2494 */
2495int nlmsg_notify(struct sock *sk, struct sk_buff *skb, u32 portid,
2496 unsigned int group, int report, gfp_t flags)
2497{
2498 int err = 0;
2499
2500 if (group) {
2501 int exclude_portid = 0;
2502
2503 if (report) {
2504 refcount_inc(&skb->users);
2505 exclude_portid = portid;
2506 }
2507
2508 /* errors reported via destination sk->sk_err, but propagate
2509 * delivery errors if NETLINK_BROADCAST_ERROR flag is set */
2510 err = nlmsg_multicast(sk, skb, exclude_portid, group, flags);
2511 if (err == -ESRCH)
2512 err = 0;
2513 }
2514
2515 if (report) {
2516 int err2;
2517
2518 err2 = nlmsg_unicast(sk, skb, portid);
2519 if (!err)
2520 err = err2;
2521 }
2522
2523 return err;
2524}
2525EXPORT_SYMBOL(nlmsg_notify);
2526
2527#ifdef CONFIG_PROC_FS
2528struct nl_seq_iter {
2529 struct seq_net_private p;
2530 struct rhashtable_iter hti;
2531 int link;
2532};
2533
2534static void netlink_walk_start(struct nl_seq_iter *iter)
2535{
2536 rhashtable_walk_enter(&nl_table[iter->link].hash, &iter->hti);
2537 rhashtable_walk_start(&iter->hti);
2538}
2539
2540static void netlink_walk_stop(struct nl_seq_iter *iter)
2541{
2542 rhashtable_walk_stop(&iter->hti);
2543 rhashtable_walk_exit(&iter->hti);
2544}
2545
2546static void *__netlink_seq_next(struct seq_file *seq)
2547{
2548 struct nl_seq_iter *iter = seq->private;
2549 struct netlink_sock *nlk;
2550
2551 do {
2552 for (;;) {
2553 nlk = rhashtable_walk_next(&iter->hti);
2554
2555 if (IS_ERR(nlk)) {
2556 if (PTR_ERR(nlk) == -EAGAIN)
2557 continue;
2558
2559 return nlk;
2560 }
2561
2562 if (nlk)
2563 break;
2564
2565 netlink_walk_stop(iter);
2566 if (++iter->link >= MAX_LINKS)
2567 return NULL;
2568
2569 netlink_walk_start(iter);
2570 }
2571 } while (sock_net(&nlk->sk) != seq_file_net(seq));
2572
2573 return nlk;
2574}
2575
2576static void *netlink_seq_start(struct seq_file *seq, loff_t *posp)
2577{
2578 struct nl_seq_iter *iter = seq->private;
2579 void *obj = SEQ_START_TOKEN;
2580 loff_t pos;
2581
2582 iter->link = 0;
2583
2584 netlink_walk_start(iter);
2585
2586 for (pos = *posp; pos && obj && !IS_ERR(obj); pos--)
2587 obj = __netlink_seq_next(seq);
2588
2589 return obj;
2590}
2591
2592static void *netlink_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2593{
2594 ++*pos;
2595 return __netlink_seq_next(seq);
2596}
2597
2598static void netlink_seq_stop(struct seq_file *seq, void *v)
2599{
2600 struct nl_seq_iter *iter = seq->private;
2601
2602 if (iter->link >= MAX_LINKS)
2603 return;
2604
2605 netlink_walk_stop(iter);
2606}
2607
2608
2609static int netlink_seq_show(struct seq_file *seq, void *v)
2610{
2611 if (v == SEQ_START_TOKEN) {
2612 seq_puts(seq,
2613 "sk Eth Pid Groups "
2614 "Rmem Wmem Dump Locks Drops Inode\n");
2615 } else {
2616 struct sock *s = v;
2617 struct netlink_sock *nlk = nlk_sk(s);
2618
2619 seq_printf(seq, "%pK %-3d %-10u %08x %-8d %-8d %-5d %-8d %-8u %-8lu\n",
2620 s,
2621 s->sk_protocol,
2622 nlk->portid,
2623 nlk->groups ? (u32)nlk->groups[0] : 0,
2624 sk_rmem_alloc_get(s),
2625 sk_wmem_alloc_get(s),
2626 READ_ONCE(nlk->cb_running),
2627 refcount_read(&s->sk_refcnt),
2628 atomic_read(&s->sk_drops),
2629 sock_i_ino(s)
2630 );
2631
2632 }
2633 return 0;
2634}
2635
2636static const struct seq_operations netlink_seq_ops = {
2637 .start = netlink_seq_start,
2638 .next = netlink_seq_next,
2639 .stop = netlink_seq_stop,
2640 .show = netlink_seq_show,
2641};
2642#endif
2643
2644int netlink_register_notifier(struct notifier_block *nb)
2645{
2646 return blocking_notifier_chain_register(&netlink_chain, nb);
2647}
2648EXPORT_SYMBOL(netlink_register_notifier);
2649
2650int netlink_unregister_notifier(struct notifier_block *nb)
2651{
2652 return blocking_notifier_chain_unregister(&netlink_chain, nb);
2653}
2654EXPORT_SYMBOL(netlink_unregister_notifier);
2655
2656static const struct proto_ops netlink_ops = {
2657 .family = PF_NETLINK,
2658 .owner = THIS_MODULE,
2659 .release = netlink_release,
2660 .bind = netlink_bind,
2661 .connect = netlink_connect,
2662 .socketpair = sock_no_socketpair,
2663 .accept = sock_no_accept,
2664 .getname = netlink_getname,
2665 .poll = datagram_poll,
2666 .ioctl = netlink_ioctl,
2667 .listen = sock_no_listen,
2668 .shutdown = sock_no_shutdown,
2669 .setsockopt = netlink_setsockopt,
2670 .getsockopt = netlink_getsockopt,
2671 .sendmsg = netlink_sendmsg,
2672 .recvmsg = netlink_recvmsg,
2673 .mmap = sock_no_mmap,
2674 .sendpage = sock_no_sendpage,
2675};
2676
2677static const struct net_proto_family netlink_family_ops = {
2678 .family = PF_NETLINK,
2679 .create = netlink_create,
2680 .owner = THIS_MODULE, /* for consistency 8) */
2681};
2682
2683static int __net_init netlink_net_init(struct net *net)
2684{
2685#ifdef CONFIG_PROC_FS
2686 if (!proc_create_net("netlink", 0, net->proc_net, &netlink_seq_ops,
2687 sizeof(struct nl_seq_iter)))
2688 return -ENOMEM;
2689#endif
2690 return 0;
2691}
2692
2693static void __net_exit netlink_net_exit(struct net *net)
2694{
2695#ifdef CONFIG_PROC_FS
2696 remove_proc_entry("netlink", net->proc_net);
2697#endif
2698}
2699
2700static void __init netlink_add_usersock_entry(void)
2701{
2702 struct listeners *listeners;
2703 int groups = 32;
2704
2705 listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
2706 if (!listeners)
2707 panic("netlink_add_usersock_entry: Cannot allocate listeners\n");
2708
2709 netlink_table_grab();
2710
2711 nl_table[NETLINK_USERSOCK].groups = groups;
2712 rcu_assign_pointer(nl_table[NETLINK_USERSOCK].listeners, listeners);
2713 nl_table[NETLINK_USERSOCK].module = THIS_MODULE;
2714 nl_table[NETLINK_USERSOCK].registered = 1;
2715 nl_table[NETLINK_USERSOCK].flags = NL_CFG_F_NONROOT_SEND;
2716
2717 netlink_table_ungrab();
2718}
2719
2720static struct pernet_operations __net_initdata netlink_net_ops = {
2721 .init = netlink_net_init,
2722 .exit = netlink_net_exit,
2723};
2724
2725static inline u32 netlink_hash(const void *data, u32 len, u32 seed)
2726{
2727 const struct netlink_sock *nlk = data;
2728 struct netlink_compare_arg arg;
2729
2730 netlink_compare_arg_init(&arg, sock_net(&nlk->sk), nlk->portid);
2731 return jhash2((u32 *)&arg, netlink_compare_arg_len / sizeof(u32), seed);
2732}
2733
2734static const struct rhashtable_params netlink_rhashtable_params = {
2735 .head_offset = offsetof(struct netlink_sock, node),
2736 .key_len = netlink_compare_arg_len,
2737 .obj_hashfn = netlink_hash,
2738 .obj_cmpfn = netlink_compare,
2739 .automatic_shrinking = true,
2740};
2741
2742static int __init netlink_proto_init(void)
2743{
2744 int i;
2745 int err = proto_register(&netlink_proto, 0);
2746
2747 if (err != 0)
2748 goto out;
2749
2750 BUILD_BUG_ON(sizeof(struct netlink_skb_parms) > FIELD_SIZEOF(struct sk_buff, cb));
2751
2752 nl_table = kcalloc(MAX_LINKS, sizeof(*nl_table), GFP_KERNEL);
2753 if (!nl_table)
2754 goto panic;
2755
2756 for (i = 0; i < MAX_LINKS; i++) {
2757 if (rhashtable_init(&nl_table[i].hash,
2758 &netlink_rhashtable_params) < 0) {
2759 while (--i > 0)
2760 rhashtable_destroy(&nl_table[i].hash);
2761 kfree(nl_table);
2762 goto panic;
2763 }
2764 }
2765
2766 netlink_add_usersock_entry();
2767
2768 sock_register(&netlink_family_ops);
2769 register_pernet_subsys(&netlink_net_ops);
2770 register_pernet_subsys(&netlink_tap_net_ops);
2771 /* The netlink device handler may be needed early. */
2772 rtnetlink_init();
2773out:
2774 return err;
2775panic:
2776 panic("netlink_init: Cannot allocate nl_table\n");
2777}
2778
2779core_initcall(netlink_proto_init);