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