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