xref: /linux/net/ipv4/inet_diag.c (revision c698f5cc940de5871ea3c65c94f5fd7fbc6844e3)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * inet_diag.c	Module for monitoring INET transport protocols sockets.
4  *
5  * Authors:	Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
6  */
7 
8 #include <linux/kernel.h>
9 #include <linux/module.h>
10 #include <linux/types.h>
11 #include <linux/fcntl.h>
12 #include <linux/random.h>
13 #include <linux/slab.h>
14 #include <linux/cache.h>
15 #include <linux/init.h>
16 #include <linux/time.h>
17 
18 #include <net/icmp.h>
19 #include <net/tcp.h>
20 #include <net/ipv6.h>
21 #include <net/inet_common.h>
22 #include <net/inet_connection_sock.h>
23 #include <net/bpf_sk_storage.h>
24 #include <net/netlink.h>
25 
26 #include <linux/inet.h>
27 #include <linux/stddef.h>
28 
29 #include <linux/inet_diag.h>
30 #include <linux/sock_diag.h>
31 
32 static const struct inet_diag_handler __rcu **inet_diag_table;
33 
34 struct inet_diag_entry {
35 	const __be32 *saddr;
36 	const __be32 *daddr;
37 	u16 sport;
38 	u16 dport;
39 	u16 family;
40 	u16 userlocks;
41 	u32 ifindex;
42 	u32 mark;
43 #ifdef CONFIG_SOCK_CGROUP_DATA
44 	u64 cgroup_id;
45 #endif
46 };
47 
48 static const struct inet_diag_handler *inet_diag_lock_handler(int proto)
49 {
50 	const struct inet_diag_handler *handler;
51 
52 	if (proto < 0 || proto >= IPPROTO_MAX)
53 		return NULL;
54 
55 	if (!READ_ONCE(inet_diag_table[proto]))
56 		sock_load_diag_module(AF_INET, proto);
57 
58 	rcu_read_lock();
59 	handler = rcu_dereference(inet_diag_table[proto]);
60 	if (handler && !try_module_get(handler->owner))
61 		handler = NULL;
62 	rcu_read_unlock();
63 
64 	return handler;
65 }
66 
67 static void inet_diag_unlock_handler(const struct inet_diag_handler *handler)
68 {
69 	module_put(handler->owner);
70 }
71 
72 void inet_diag_msg_common_fill(struct inet_diag_msg *r, struct sock *sk)
73 {
74 	r->idiag_family = READ_ONCE(sk->sk_family);
75 
76 	r->id.idiag_sport = htons(READ_ONCE(sk->sk_num));
77 	r->id.idiag_dport = READ_ONCE(sk->sk_dport);
78 	r->id.idiag_if = READ_ONCE(sk->sk_bound_dev_if);
79 	sock_diag_save_cookie(sk, r->id.idiag_cookie);
80 
81 #if IS_ENABLED(CONFIG_IPV6)
82 	if (r->idiag_family == AF_INET6) {
83 		data_race(*(struct in6_addr *)r->id.idiag_src = sk->sk_v6_rcv_saddr);
84 		data_race(*(struct in6_addr *)r->id.idiag_dst = sk->sk_v6_daddr);
85 	} else
86 #endif
87 	{
88 	memset(&r->id.idiag_src, 0, sizeof(r->id.idiag_src));
89 	memset(&r->id.idiag_dst, 0, sizeof(r->id.idiag_dst));
90 
91 	r->id.idiag_src[0] = READ_ONCE(sk->sk_rcv_saddr);
92 	r->id.idiag_dst[0] = READ_ONCE(sk->sk_daddr);
93 	}
94 }
95 EXPORT_SYMBOL_GPL(inet_diag_msg_common_fill);
96 
97 int inet_diag_msg_attrs_fill(struct sock *sk, struct sk_buff *skb,
98 			     struct inet_diag_msg *r, int ext,
99 			     struct user_namespace *user_ns,
100 			     bool net_admin)
101 {
102 	const struct inet_sock *inet = inet_sk(sk);
103 	struct inet_diag_sockopt inet_sockopt;
104 
105 	if (nla_put_u8(skb, INET_DIAG_SHUTDOWN, sk->sk_shutdown))
106 		goto errout;
107 
108 	/* IPv6 dual-stack sockets use inet->tos for IPv4 connections,
109 	 * hence this needs to be included regardless of socket family.
110 	 */
111 	if (ext & (1 << (INET_DIAG_TOS - 1)))
112 		if (nla_put_u8(skb, INET_DIAG_TOS, READ_ONCE(inet->tos)) < 0)
113 			goto errout;
114 
115 #if IS_ENABLED(CONFIG_IPV6)
116 	if (r->idiag_family == AF_INET6) {
117 		if (ext & (1 << (INET_DIAG_TCLASS - 1)))
118 			if (nla_put_u8(skb, INET_DIAG_TCLASS,
119 				       inet6_sk(sk)->tclass) < 0)
120 				goto errout;
121 
122 		if (((1 << sk->sk_state) & (TCPF_LISTEN | TCPF_CLOSE)) &&
123 		    nla_put_u8(skb, INET_DIAG_SKV6ONLY, ipv6_only_sock(sk)))
124 			goto errout;
125 	}
126 #endif
127 
128 	if (net_admin && nla_put_u32(skb, INET_DIAG_MARK, READ_ONCE(sk->sk_mark)))
129 		goto errout;
130 
131 	if (ext & (1 << (INET_DIAG_CLASS_ID - 1)) ||
132 	    ext & (1 << (INET_DIAG_TCLASS - 1))) {
133 		u32 classid = 0;
134 
135 #ifdef CONFIG_CGROUP_NET_CLASSID
136 		classid = sock_cgroup_classid(&sk->sk_cgrp_data);
137 #endif
138 		/* Fallback to socket priority if class id isn't set.
139 		 * Classful qdiscs use it as direct reference to class.
140 		 * For cgroup2 classid is always zero.
141 		 */
142 		if (!classid)
143 			classid = READ_ONCE(sk->sk_priority);
144 
145 		if (nla_put_u32(skb, INET_DIAG_CLASS_ID, classid))
146 			goto errout;
147 	}
148 
149 #ifdef CONFIG_SOCK_CGROUP_DATA
150 	if (nla_put_u64_64bit(skb, INET_DIAG_CGROUP_ID,
151 			      cgroup_id(sock_cgroup_ptr(&sk->sk_cgrp_data)),
152 			      INET_DIAG_PAD))
153 		goto errout;
154 #endif
155 
156 	r->idiag_uid = from_kuid_munged(user_ns, sk_uid(sk));
157 	r->idiag_inode = sock_i_ino(sk);
158 
159 	memset(&inet_sockopt, 0, sizeof(inet_sockopt));
160 	inet_sockopt.recverr	= inet_test_bit(RECVERR, sk);
161 	inet_sockopt.is_icsk	= inet_test_bit(IS_ICSK, sk);
162 	inet_sockopt.freebind	= inet_test_bit(FREEBIND, sk);
163 	inet_sockopt.hdrincl	= inet_test_bit(HDRINCL, sk);
164 	inet_sockopt.mc_loop	= inet_test_bit(MC_LOOP, sk);
165 	inet_sockopt.transparent = inet_test_bit(TRANSPARENT, sk);
166 	inet_sockopt.mc_all	= inet_test_bit(MC_ALL, sk);
167 	inet_sockopt.nodefrag	= inet_test_bit(NODEFRAG, sk);
168 	inet_sockopt.bind_address_no_port = inet_test_bit(BIND_ADDRESS_NO_PORT, sk);
169 	inet_sockopt.recverr_rfc4884 = inet_test_bit(RECVERR_RFC4884, sk);
170 	inet_sockopt.defer_connect = inet_test_bit(DEFER_CONNECT, sk);
171 	if (nla_put(skb, INET_DIAG_SOCKOPT, sizeof(inet_sockopt),
172 		    &inet_sockopt))
173 		goto errout;
174 
175 	return 0;
176 errout:
177 	return 1;
178 }
179 EXPORT_SYMBOL_GPL(inet_diag_msg_attrs_fill);
180 
181 static int inet_diag_parse_attrs(const struct nlmsghdr *nlh, int hdrlen,
182 				 struct nlattr **req_nlas)
183 {
184 	struct nlattr *nla;
185 	int remaining;
186 
187 	nlmsg_for_each_attr(nla, nlh, hdrlen, remaining) {
188 		int type = nla_type(nla);
189 
190 		if (type == INET_DIAG_REQ_PROTOCOL && nla_len(nla) != sizeof(u32))
191 			return -EINVAL;
192 
193 		if (type < __INET_DIAG_REQ_MAX)
194 			req_nlas[type] = nla;
195 	}
196 	return 0;
197 }
198 
199 static int inet_diag_get_protocol(const struct inet_diag_req_v2 *req,
200 				  const struct inet_diag_dump_data *data)
201 {
202 	if (data->req_nlas[INET_DIAG_REQ_PROTOCOL])
203 		return nla_get_u32(data->req_nlas[INET_DIAG_REQ_PROTOCOL]);
204 	return req->sdiag_protocol;
205 }
206 
207 #define MAX_DUMP_ALLOC_SIZE (KMALLOC_MAX_SIZE - SKB_DATA_ALIGN(sizeof(struct skb_shared_info)))
208 
209 int inet_sk_diag_fill(struct sock *sk, struct inet_connection_sock *icsk,
210 		      struct sk_buff *skb, struct netlink_callback *cb,
211 		      const struct inet_diag_req_v2 *req,
212 		      u16 nlmsg_flags, bool net_admin)
213 {
214 	const struct tcp_congestion_ops *ca_ops;
215 	const struct inet_diag_handler *handler;
216 	struct inet_diag_dump_data *cb_data;
217 	int ext = req->idiag_ext;
218 	struct inet_diag_msg *r;
219 	struct nlmsghdr  *nlh;
220 	struct nlattr *attr;
221 	void *info = NULL;
222 	u8 icsk_pending;
223 	int protocol;
224 
225 	cb_data = cb->data;
226 	protocol = inet_diag_get_protocol(req, cb_data);
227 
228 	/* inet_diag_lock_handler() made sure inet_diag_table[] is stable. */
229 	handler = rcu_dereference_protected(inet_diag_table[protocol], 1);
230 	DEBUG_NET_WARN_ON_ONCE(!handler);
231 	if (!handler)
232 		return -ENXIO;
233 
234 	nlh = nlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
235 			cb->nlh->nlmsg_type, sizeof(*r), nlmsg_flags);
236 	if (!nlh)
237 		return -EMSGSIZE;
238 
239 	r = nlmsg_data(nlh);
240 	BUG_ON(!sk_fullsock(sk));
241 
242 	inet_diag_msg_common_fill(r, sk);
243 	r->idiag_state = sk->sk_state;
244 	r->idiag_timer = IDIAG_TIMER_OFF;
245 	r->idiag_retrans = 0;
246 	r->idiag_expires = 0;
247 
248 	if (inet_diag_msg_attrs_fill(sk, skb, r, ext,
249 				     sk_user_ns(NETLINK_CB(cb->skb).sk),
250 				     net_admin))
251 		goto errout;
252 
253 	if (ext & (1 << (INET_DIAG_MEMINFO - 1))) {
254 		struct inet_diag_meminfo minfo = {
255 			.idiag_rmem = sk_rmem_alloc_get(sk),
256 			.idiag_wmem = READ_ONCE(sk->sk_wmem_queued),
257 			.idiag_fmem = READ_ONCE(sk->sk_forward_alloc),
258 			.idiag_tmem = sk_wmem_alloc_get(sk),
259 		};
260 
261 		if (nla_put(skb, INET_DIAG_MEMINFO, sizeof(minfo), &minfo) < 0)
262 			goto errout;
263 	}
264 
265 	if (ext & (1 << (INET_DIAG_SKMEMINFO - 1)))
266 		if (sock_diag_put_meminfo(sk, skb, INET_DIAG_SKMEMINFO))
267 			goto errout;
268 
269 	/*
270 	 * RAW sockets might have user-defined protocols assigned,
271 	 * so report the one supplied on socket creation.
272 	 */
273 	if (sk->sk_type == SOCK_RAW) {
274 		if (nla_put_u8(skb, INET_DIAG_PROTOCOL, sk->sk_protocol))
275 			goto errout;
276 	}
277 
278 	if (!icsk) {
279 		handler->idiag_get_info(sk, r, NULL);
280 		goto out;
281 	}
282 
283 	icsk_pending = smp_load_acquire(&icsk->icsk_pending);
284 	if (icsk_pending == ICSK_TIME_RETRANS ||
285 	    icsk_pending == ICSK_TIME_REO_TIMEOUT ||
286 	    icsk_pending == ICSK_TIME_LOSS_PROBE) {
287 		r->idiag_timer = IDIAG_TIMER_ON;
288 		r->idiag_retrans = READ_ONCE(icsk->icsk_retransmits);
289 		r->idiag_expires =
290 			jiffies_delta_to_msecs(tcp_timeout_expires(sk) - jiffies);
291 	} else if (icsk_pending == ICSK_TIME_PROBE0) {
292 		r->idiag_timer = IDIAG_TIMER_PROBE0;
293 		r->idiag_retrans = READ_ONCE(icsk->icsk_probes_out);
294 		r->idiag_expires =
295 			jiffies_delta_to_msecs(tcp_timeout_expires(sk) - jiffies);
296 	} else if (timer_pending(&icsk->icsk_keepalive_timer)) {
297 		r->idiag_timer = IDIAG_TIMER_KEEPALIVE;
298 		r->idiag_retrans = READ_ONCE(icsk->icsk_probes_out);
299 		r->idiag_expires =
300 			jiffies_delta_to_msecs(icsk->icsk_keepalive_timer.expires - jiffies);
301 	} else if ((READ_ONCE(icsk->icsk_ack.pending) & ICSK_ACK_TIMER) &&
302 		   timer_pending(&icsk->icsk_delack_timer)) {
303 		r->idiag_timer = IDIAG_TIMER_DELACK;
304 		r->idiag_expires =
305 			jiffies_delta_to_msecs(icsk_delack_timeout(icsk) - jiffies);
306 	}
307 
308 	if ((ext & (1 << (INET_DIAG_INFO - 1))) && handler->idiag_info_size) {
309 		attr = nla_reserve_64bit(skb, INET_DIAG_INFO,
310 					 handler->idiag_info_size,
311 					 INET_DIAG_PAD);
312 		if (!attr)
313 			goto errout;
314 
315 		info = nla_data(attr);
316 	}
317 
318 	if (ext & (1 << (INET_DIAG_CONG - 1))) {
319 		int err = 0;
320 
321 		rcu_read_lock();
322 		ca_ops = READ_ONCE(icsk->icsk_ca_ops);
323 		if (ca_ops)
324 			err = nla_put_string(skb, INET_DIAG_CONG, ca_ops->name);
325 		rcu_read_unlock();
326 		if (err < 0)
327 			goto errout;
328 	}
329 
330 	handler->idiag_get_info(sk, r, info);
331 
332 	if (ext & (1 << (INET_DIAG_INFO - 1)) && handler->idiag_get_aux)
333 		if (handler->idiag_get_aux(sk, net_admin, skb) < 0)
334 			goto errout;
335 
336 	if (sk->sk_state < TCP_TIME_WAIT) {
337 		union tcp_cc_info info;
338 		size_t sz = 0;
339 		int attr;
340 
341 		rcu_read_lock();
342 		ca_ops = READ_ONCE(icsk->icsk_ca_ops);
343 		if (ca_ops && ca_ops->get_info)
344 			sz = ca_ops->get_info(sk, ext, &attr, &info);
345 		rcu_read_unlock();
346 		if (sz && nla_put(skb, attr, sz, &info) < 0)
347 			goto errout;
348 	}
349 
350 	/* Keep it at the end for potential retry with a larger skb,
351 	 * or else do best-effort fitting, which is only done for the
352 	 * first_nlmsg.
353 	 */
354 	if (cb_data->bpf_stg_diag) {
355 		bool first_nlmsg = ((unsigned char *)nlh == skb->data);
356 		unsigned int prev_min_dump_alloc;
357 		unsigned int total_nla_size = 0;
358 		unsigned int msg_len;
359 		int err;
360 
361 		msg_len = skb_tail_pointer(skb) - (unsigned char *)nlh;
362 		err = bpf_sk_storage_diag_put(cb_data->bpf_stg_diag, sk, skb,
363 					      INET_DIAG_SK_BPF_STORAGES,
364 					      &total_nla_size);
365 
366 		if (!err)
367 			goto out;
368 
369 		total_nla_size += msg_len;
370 		prev_min_dump_alloc = cb->min_dump_alloc;
371 		if (total_nla_size > prev_min_dump_alloc)
372 			cb->min_dump_alloc = min_t(u32, total_nla_size,
373 						   MAX_DUMP_ALLOC_SIZE);
374 
375 		if (!first_nlmsg)
376 			goto errout;
377 
378 		if (cb->min_dump_alloc > prev_min_dump_alloc)
379 			/* Retry with pskb_expand_head() with
380 			 * __GFP_DIRECT_RECLAIM
381 			 */
382 			goto errout;
383 
384 		WARN_ON_ONCE(total_nla_size <= prev_min_dump_alloc);
385 
386 		/* Send what we have for this sk
387 		 * and move on to the next sk in the following
388 		 * dump()
389 		 */
390 	}
391 
392 out:
393 	nlmsg_end(skb, nlh);
394 	return 0;
395 
396 errout:
397 	nlmsg_cancel(skb, nlh);
398 	return -EMSGSIZE;
399 }
400 EXPORT_SYMBOL_GPL(inet_sk_diag_fill);
401 
402 static int inet_diag_cmd_exact(int cmd, struct sk_buff *in_skb,
403 			       const struct nlmsghdr *nlh,
404 			       int hdrlen,
405 			       const struct inet_diag_req_v2 *req)
406 {
407 	const struct inet_diag_handler *handler;
408 	struct inet_diag_dump_data dump_data;
409 	int err, protocol;
410 
411 	memset(&dump_data, 0, sizeof(dump_data));
412 	err = inet_diag_parse_attrs(nlh, hdrlen, dump_data.req_nlas);
413 	if (err)
414 		return err;
415 
416 	protocol = inet_diag_get_protocol(req, &dump_data);
417 
418 	handler = inet_diag_lock_handler(protocol);
419 	if (!handler)
420 		return -ENOENT;
421 
422 	if (cmd == SOCK_DIAG_BY_FAMILY) {
423 		struct netlink_callback cb = {
424 			.nlh = nlh,
425 			.skb = in_skb,
426 			.data = &dump_data,
427 		};
428 		err = handler->dump_one(&cb, req);
429 	} else if (cmd == SOCK_DESTROY && handler->destroy) {
430 		err = handler->destroy(in_skb, req);
431 	} else {
432 		err = -EOPNOTSUPP;
433 	}
434 	inet_diag_unlock_handler(handler);
435 
436 	return err;
437 }
438 
439 static int bitstring_match(const __be32 *a1, const __be32 *a2, int bits)
440 {
441 	int words = bits >> 5;
442 
443 	bits &= 0x1f;
444 
445 	if (words) {
446 		if (memcmp(a1, a2, words << 2))
447 			return 0;
448 	}
449 	if (bits) {
450 		__be32 w1, w2;
451 		__be32 mask;
452 
453 		w1 = a1[words];
454 		w2 = a2[words];
455 
456 		mask = htonl((0xffffffff) << (32 - bits));
457 
458 		if ((w1 ^ w2) & mask)
459 			return 0;
460 	}
461 
462 	return 1;
463 }
464 
465 static int inet_diag_bc_run(const struct nlattr *_bc,
466 			    const struct inet_diag_entry *entry)
467 {
468 	const void *bc = nla_data(_bc);
469 	int len = nla_len(_bc);
470 
471 	while (len > 0) {
472 		int yes = 1;
473 		const struct inet_diag_bc_op *op = bc;
474 
475 		switch (op->code) {
476 		case INET_DIAG_BC_NOP:
477 			break;
478 		case INET_DIAG_BC_JMP:
479 			yes = 0;
480 			break;
481 		case INET_DIAG_BC_S_EQ:
482 			yes = entry->sport == op[1].no;
483 			break;
484 		case INET_DIAG_BC_S_GE:
485 			yes = entry->sport >= op[1].no;
486 			break;
487 		case INET_DIAG_BC_S_LE:
488 			yes = entry->sport <= op[1].no;
489 			break;
490 		case INET_DIAG_BC_D_EQ:
491 			yes = entry->dport == op[1].no;
492 			break;
493 		case INET_DIAG_BC_D_GE:
494 			yes = entry->dport >= op[1].no;
495 			break;
496 		case INET_DIAG_BC_D_LE:
497 			yes = entry->dport <= op[1].no;
498 			break;
499 		case INET_DIAG_BC_AUTO:
500 			yes = !(entry->userlocks & SOCK_BINDPORT_LOCK);
501 			break;
502 		case INET_DIAG_BC_S_COND:
503 		case INET_DIAG_BC_D_COND: {
504 			const struct inet_diag_hostcond *cond;
505 			const __be32 *addr;
506 
507 			cond = (const struct inet_diag_hostcond *)(op + 1);
508 			if (cond->port != -1 &&
509 			    cond->port != (op->code == INET_DIAG_BC_S_COND ?
510 					     entry->sport : entry->dport)) {
511 				yes = 0;
512 				break;
513 			}
514 
515 			if (op->code == INET_DIAG_BC_S_COND)
516 				addr = entry->saddr;
517 			else
518 				addr = entry->daddr;
519 
520 			if (cond->family != AF_UNSPEC &&
521 			    cond->family != entry->family) {
522 				if (entry->family == AF_INET6 &&
523 				    cond->family == AF_INET) {
524 					if (addr[0] == 0 && addr[1] == 0 &&
525 					    addr[2] == htonl(0xffff) &&
526 					    bitstring_match(addr + 3,
527 							    cond->addr,
528 							    cond->prefix_len))
529 						break;
530 				}
531 				yes = 0;
532 				break;
533 			}
534 
535 			if (cond->prefix_len == 0)
536 				break;
537 			if (bitstring_match(addr, cond->addr,
538 					    cond->prefix_len))
539 				break;
540 			yes = 0;
541 			break;
542 		}
543 		case INET_DIAG_BC_DEV_COND: {
544 			u32 ifindex;
545 
546 			ifindex = *((const u32 *)(op + 1));
547 			if (ifindex != entry->ifindex)
548 				yes = 0;
549 			break;
550 		}
551 		case INET_DIAG_BC_MARK_COND: {
552 			struct inet_diag_markcond *cond;
553 
554 			cond = (struct inet_diag_markcond *)(op + 1);
555 			if ((entry->mark & cond->mask) != cond->mark)
556 				yes = 0;
557 			break;
558 		}
559 #ifdef CONFIG_SOCK_CGROUP_DATA
560 		case INET_DIAG_BC_CGROUP_COND: {
561 			u64 cgroup_id;
562 
563 			cgroup_id = get_unaligned((const u64 *)(op + 1));
564 			if (cgroup_id != entry->cgroup_id)
565 				yes = 0;
566 			break;
567 		}
568 #endif
569 		}
570 
571 		if (yes) {
572 			len -= op->yes;
573 			bc += op->yes;
574 		} else {
575 			len -= op->no;
576 			bc += op->no;
577 		}
578 	}
579 	return len == 0;
580 }
581 
582 /* This helper is available for all sockets (ESTABLISH, TIMEWAIT, SYN_RECV)
583  */
584 static void entry_fill_addrs(struct inet_diag_entry *entry,
585 			     const struct sock *sk)
586 {
587 #if IS_ENABLED(CONFIG_IPV6)
588 	if (entry->family == AF_INET6) {
589 		entry->saddr = sk->sk_v6_rcv_saddr.s6_addr32;
590 		entry->daddr = sk->sk_v6_daddr.s6_addr32;
591 	} else
592 #endif
593 	{
594 		entry->saddr = &sk->sk_rcv_saddr;
595 		entry->daddr = &sk->sk_daddr;
596 	}
597 }
598 
599 int inet_diag_bc_sk(const struct inet_diag_dump_data *cb_data, struct sock *sk)
600 {
601 	const struct nlattr *bc = cb_data->inet_diag_nla_bc;
602 	const struct inet_sock *inet = inet_sk(sk);
603 	struct inet_diag_entry entry;
604 
605 	if (!bc)
606 		return 1;
607 
608 	entry.family = READ_ONCE(sk->sk_family);
609 	entry_fill_addrs(&entry, sk);
610 	entry.sport = READ_ONCE(inet->inet_num);
611 	entry.dport = ntohs(READ_ONCE(inet->inet_dport));
612 	entry.ifindex = READ_ONCE(sk->sk_bound_dev_if);
613 	if (cb_data->userlocks_needed)
614 		entry.userlocks = sk_fullsock(sk) ? READ_ONCE(sk->sk_userlocks) : 0;
615 	if (cb_data->mark_needed) {
616 		if (sk_fullsock(sk))
617 			entry.mark = READ_ONCE(sk->sk_mark);
618 		else if (sk->sk_state == TCP_NEW_SYN_RECV)
619 			entry.mark = inet_rsk(inet_reqsk(sk))->ir_mark;
620 		else if (sk->sk_state == TCP_TIME_WAIT)
621 			entry.mark = inet_twsk(sk)->tw_mark;
622 		else
623 			entry.mark = 0;
624 	}
625 #ifdef CONFIG_SOCK_CGROUP_DATA
626 	if (cb_data->cgroup_needed)
627 		entry.cgroup_id = sk_fullsock(sk) ?
628 			cgroup_id(sock_cgroup_ptr(&sk->sk_cgrp_data)) : 0;
629 #endif
630 
631 	return inet_diag_bc_run(bc, &entry);
632 }
633 EXPORT_SYMBOL_GPL(inet_diag_bc_sk);
634 
635 static int valid_cc(const void *bc, int len, int cc)
636 {
637 	while (len >= 0) {
638 		const struct inet_diag_bc_op *op = bc;
639 
640 		if (cc > len)
641 			return 0;
642 		if (cc == len)
643 			return 1;
644 		if (op->yes < 4 || op->yes & 3)
645 			return 0;
646 		len -= op->yes;
647 		bc  += op->yes;
648 	}
649 	return 0;
650 }
651 
652 /* data is u32 ifindex */
653 static bool valid_devcond(const struct inet_diag_bc_op *op, int len,
654 			  int *min_len)
655 {
656 	/* Check ifindex space. */
657 	*min_len += sizeof(u32);
658 	if (len < *min_len)
659 		return false;
660 
661 	return true;
662 }
663 /* Validate an inet_diag_hostcond. */
664 static bool valid_hostcond(const struct inet_diag_bc_op *op, int len,
665 			   int *min_len)
666 {
667 	struct inet_diag_hostcond *cond;
668 	int addr_len;
669 
670 	/* Check hostcond space. */
671 	*min_len += sizeof(struct inet_diag_hostcond);
672 	if (len < *min_len)
673 		return false;
674 	cond = (struct inet_diag_hostcond *)(op + 1);
675 
676 	/* Check address family and address length. */
677 	switch (cond->family) {
678 	case AF_UNSPEC:
679 		addr_len = 0;
680 		break;
681 	case AF_INET:
682 		addr_len = sizeof(struct in_addr);
683 		break;
684 	case AF_INET6:
685 		addr_len = sizeof(struct in6_addr);
686 		break;
687 	default:
688 		return false;
689 	}
690 	*min_len += addr_len;
691 	if (len < *min_len)
692 		return false;
693 
694 	/* Check prefix length (in bits) vs address length (in bytes). */
695 	if (cond->prefix_len > 8 * addr_len)
696 		return false;
697 
698 	return true;
699 }
700 
701 /* Validate a port comparison operator. */
702 static bool valid_port_comparison(const struct inet_diag_bc_op *op,
703 				  int len, int *min_len)
704 {
705 	/* Port comparisons put the port in a follow-on inet_diag_bc_op. */
706 	*min_len += sizeof(struct inet_diag_bc_op);
707 	if (len < *min_len)
708 		return false;
709 	return true;
710 }
711 
712 static bool valid_markcond(const struct inet_diag_bc_op *op, int len,
713 			   int *min_len)
714 {
715 	*min_len += sizeof(struct inet_diag_markcond);
716 	return len >= *min_len;
717 }
718 
719 #ifdef CONFIG_SOCK_CGROUP_DATA
720 static bool valid_cgroupcond(const struct inet_diag_bc_op *op, int len,
721 			     int *min_len)
722 {
723 	*min_len += sizeof(u64);
724 	return len >= *min_len;
725 }
726 #endif
727 
728 static int inet_diag_bc_audit(struct inet_diag_dump_data *cb_data,
729 			      const struct sk_buff *skb)
730 {
731 	const struct nlattr *attr = cb_data->inet_diag_nla_bc;
732 	const void *bytecode, *bc;
733 	int bytecode_len, len;
734 	bool net_admin;
735 
736 	if (!attr)
737 		return 0;
738 
739 	if (nla_len(attr) < sizeof(struct inet_diag_bc_op))
740 		return -EINVAL;
741 
742 	net_admin = netlink_net_capable(skb, CAP_NET_ADMIN);
743 	bytecode = bc = nla_data(attr);
744 	len = bytecode_len = nla_len(attr);
745 
746 	while (len > 0) {
747 		int min_len = sizeof(struct inet_diag_bc_op);
748 		const struct inet_diag_bc_op *op = bc;
749 
750 		switch (op->code) {
751 		case INET_DIAG_BC_S_COND:
752 		case INET_DIAG_BC_D_COND:
753 			if (!valid_hostcond(bc, len, &min_len))
754 				return -EINVAL;
755 			break;
756 		case INET_DIAG_BC_DEV_COND:
757 			if (!valid_devcond(bc, len, &min_len))
758 				return -EINVAL;
759 			break;
760 		case INET_DIAG_BC_S_EQ:
761 		case INET_DIAG_BC_S_GE:
762 		case INET_DIAG_BC_S_LE:
763 		case INET_DIAG_BC_D_EQ:
764 		case INET_DIAG_BC_D_GE:
765 		case INET_DIAG_BC_D_LE:
766 			if (!valid_port_comparison(bc, len, &min_len))
767 				return -EINVAL;
768 			break;
769 		case INET_DIAG_BC_MARK_COND:
770 			if (!net_admin)
771 				return -EPERM;
772 			if (!valid_markcond(bc, len, &min_len))
773 				return -EINVAL;
774 			cb_data->mark_needed = true;
775 			break;
776 #ifdef CONFIG_SOCK_CGROUP_DATA
777 		case INET_DIAG_BC_CGROUP_COND:
778 			if (!valid_cgroupcond(bc, len, &min_len))
779 				return -EINVAL;
780 			cb_data->cgroup_needed = true;
781 			break;
782 #endif
783 		case INET_DIAG_BC_AUTO:
784 			cb_data->userlocks_needed = true;
785 			fallthrough;
786 		case INET_DIAG_BC_JMP:
787 		case INET_DIAG_BC_NOP:
788 			break;
789 		default:
790 			return -EINVAL;
791 		}
792 
793 		if (op->code != INET_DIAG_BC_NOP) {
794 			if (op->no < min_len || op->no > len + 4 || op->no & 3)
795 				return -EINVAL;
796 			if (op->no < len &&
797 			    !valid_cc(bytecode, bytecode_len, len - op->no))
798 				return -EINVAL;
799 		}
800 
801 		if (op->yes < min_len || op->yes > len + 4 || op->yes & 3)
802 			return -EINVAL;
803 		bc  += op->yes;
804 		len -= op->yes;
805 	}
806 	return len == 0 ? 0 : -EINVAL;
807 }
808 
809 static int __inet_diag_dump(struct sk_buff *skb, struct netlink_callback *cb,
810 			    const struct inet_diag_req_v2 *r)
811 {
812 	struct inet_diag_dump_data *cb_data = cb->data;
813 	const struct inet_diag_handler *handler;
814 	u32 prev_min_dump_alloc;
815 	int protocol, err = 0;
816 
817 	protocol = inet_diag_get_protocol(r, cb_data);
818 
819 again:
820 	prev_min_dump_alloc = cb->min_dump_alloc;
821 	handler = inet_diag_lock_handler(protocol);
822 	if (handler) {
823 		handler->dump(skb, cb, r);
824 		inet_diag_unlock_handler(handler);
825 	} else {
826 		err = -ENOENT;
827 	}
828 	/* The skb is not large enough to fit one sk info and
829 	 * inet_sk_diag_fill() has requested for a larger skb.
830 	 */
831 	if (!skb->len && cb->min_dump_alloc > prev_min_dump_alloc) {
832 		err = pskb_expand_head(skb, 0, cb->min_dump_alloc, GFP_KERNEL);
833 		if (!err)
834 			goto again;
835 	}
836 
837 	return err ? : skb->len;
838 }
839 
840 static int inet_diag_dump(struct sk_buff *skb, struct netlink_callback *cb)
841 {
842 	return __inet_diag_dump(skb, cb, nlmsg_data(cb->nlh));
843 }
844 
845 static int __inet_diag_dump_start(struct netlink_callback *cb, int hdrlen)
846 {
847 	const struct nlmsghdr *nlh = cb->nlh;
848 	struct inet_diag_dump_data *cb_data;
849 	struct sk_buff *skb = cb->skb;
850 	struct nlattr *nla;
851 	int err;
852 
853 	cb_data = kzalloc_obj(*cb_data);
854 	if (!cb_data)
855 		return -ENOMEM;
856 
857 	err = inet_diag_parse_attrs(nlh, hdrlen, cb_data->req_nlas);
858 	if (err) {
859 		kfree(cb_data);
860 		return err;
861 	}
862 	err = inet_diag_bc_audit(cb_data, skb);
863 	if (err) {
864 		kfree(cb_data);
865 		return err;
866 	}
867 
868 	nla = cb_data->inet_diag_nla_bpf_stgs;
869 	if (nla) {
870 		struct bpf_sk_storage_diag *bpf_stg_diag;
871 
872 		bpf_stg_diag = bpf_sk_storage_diag_alloc(nla);
873 		if (IS_ERR(bpf_stg_diag)) {
874 			kfree(cb_data);
875 			return PTR_ERR(bpf_stg_diag);
876 		}
877 		cb_data->bpf_stg_diag = bpf_stg_diag;
878 	}
879 
880 	cb->data = cb_data;
881 	return 0;
882 }
883 
884 static int inet_diag_dump_start(struct netlink_callback *cb)
885 {
886 	return __inet_diag_dump_start(cb, sizeof(struct inet_diag_req_v2));
887 }
888 
889 static int inet_diag_dump_start_compat(struct netlink_callback *cb)
890 {
891 	return __inet_diag_dump_start(cb, sizeof(struct inet_diag_req));
892 }
893 
894 static int inet_diag_dump_done(struct netlink_callback *cb)
895 {
896 	struct inet_diag_dump_data *cb_data = cb->data;
897 
898 	bpf_sk_storage_diag_free(cb_data->bpf_stg_diag);
899 	kfree(cb->data);
900 
901 	return 0;
902 }
903 
904 static int inet_diag_type2proto(int type)
905 {
906 	switch (type) {
907 	case TCPDIAG_GETSOCK:
908 		return IPPROTO_TCP;
909 	default:
910 		return 0;
911 	}
912 }
913 
914 static int inet_diag_dump_compat(struct sk_buff *skb,
915 				 struct netlink_callback *cb)
916 {
917 	struct inet_diag_req *rc = nlmsg_data(cb->nlh);
918 	struct inet_diag_req_v2 req;
919 
920 	req.sdiag_family = AF_UNSPEC; /* compatibility */
921 	req.sdiag_protocol = inet_diag_type2proto(cb->nlh->nlmsg_type);
922 	req.idiag_ext = rc->idiag_ext;
923 	req.pad = 0;
924 	req.idiag_states = rc->idiag_states;
925 	req.id = rc->id;
926 
927 	return __inet_diag_dump(skb, cb, &req);
928 }
929 
930 static int inet_diag_get_exact_compat(struct sk_buff *in_skb,
931 				      const struct nlmsghdr *nlh)
932 {
933 	struct inet_diag_req *rc = nlmsg_data(nlh);
934 	struct inet_diag_req_v2 req;
935 
936 	req.sdiag_family = rc->idiag_family;
937 	req.sdiag_protocol = inet_diag_type2proto(nlh->nlmsg_type);
938 	req.idiag_ext = rc->idiag_ext;
939 	req.pad = 0;
940 	req.idiag_states = rc->idiag_states;
941 	req.id = rc->id;
942 
943 	return inet_diag_cmd_exact(SOCK_DIAG_BY_FAMILY, in_skb, nlh,
944 				   sizeof(struct inet_diag_req), &req);
945 }
946 
947 static int inet_diag_rcv_msg_compat(struct sk_buff *skb, struct nlmsghdr *nlh)
948 {
949 	int hdrlen = sizeof(struct inet_diag_req);
950 	struct net *net = sock_net(skb->sk);
951 
952 	if (nlh->nlmsg_type >= INET_DIAG_GETSOCK_MAX ||
953 	    nlmsg_len(nlh) < hdrlen)
954 		return -EINVAL;
955 
956 	if (nlh->nlmsg_flags & NLM_F_DUMP) {
957 		struct netlink_dump_control c = {
958 			.start = inet_diag_dump_start_compat,
959 			.done = inet_diag_dump_done,
960 			.dump = inet_diag_dump_compat,
961 		};
962 		return netlink_dump_start(net->diag_nlsk, skb, nlh, &c);
963 	}
964 
965 	return inet_diag_get_exact_compat(skb, nlh);
966 }
967 
968 static int inet_diag_handler_cmd(struct sk_buff *skb, struct nlmsghdr *h)
969 {
970 	int hdrlen = sizeof(struct inet_diag_req_v2);
971 	struct net *net = sock_net(skb->sk);
972 
973 	if (nlmsg_len(h) < hdrlen)
974 		return -EINVAL;
975 
976 	if (h->nlmsg_type == SOCK_DIAG_BY_FAMILY &&
977 	    h->nlmsg_flags & NLM_F_DUMP) {
978 		struct netlink_dump_control c = {
979 			.start = inet_diag_dump_start,
980 			.done = inet_diag_dump_done,
981 			.dump = inet_diag_dump,
982 		};
983 		return netlink_dump_start(net->diag_nlsk, skb, h, &c);
984 	}
985 
986 	return inet_diag_cmd_exact(h->nlmsg_type, skb, h, hdrlen,
987 				   nlmsg_data(h));
988 }
989 
990 static
991 int inet_diag_handler_get_info(struct sk_buff *skb, struct sock *sk)
992 {
993 	const struct inet_diag_handler *handler;
994 	struct nlmsghdr *nlh;
995 	struct nlattr *attr;
996 	struct inet_diag_msg *r;
997 	void *info = NULL;
998 	int err = 0;
999 
1000 	nlh = nlmsg_put(skb, 0, 0, SOCK_DIAG_BY_FAMILY, sizeof(*r), 0);
1001 	if (!nlh)
1002 		return -ENOMEM;
1003 
1004 	r = nlmsg_data(nlh);
1005 	memset(r, 0, sizeof(*r));
1006 	inet_diag_msg_common_fill(r, sk);
1007 	if (sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_STREAM)
1008 		r->id.idiag_sport = inet_sk(sk)->inet_sport;
1009 	r->idiag_state = sk->sk_state;
1010 
1011 	if ((err = nla_put_u8(skb, INET_DIAG_PROTOCOL, sk->sk_protocol))) {
1012 		nlmsg_cancel(skb, nlh);
1013 		return err;
1014 	}
1015 
1016 	handler = inet_diag_lock_handler(sk->sk_protocol);
1017 	if (!handler) {
1018 		nlmsg_cancel(skb, nlh);
1019 		return -ENOENT;
1020 	}
1021 
1022 	attr = handler->idiag_info_size
1023 		? nla_reserve_64bit(skb, INET_DIAG_INFO,
1024 				    handler->idiag_info_size,
1025 				    INET_DIAG_PAD)
1026 		: NULL;
1027 	if (attr)
1028 		info = nla_data(attr);
1029 
1030 	handler->idiag_get_info(sk, r, info);
1031 	inet_diag_unlock_handler(handler);
1032 
1033 	nlmsg_end(skb, nlh);
1034 	return 0;
1035 }
1036 
1037 static const struct sock_diag_handler inet_diag_handler = {
1038 	.owner = THIS_MODULE,
1039 	.family = AF_INET,
1040 	.dump = inet_diag_handler_cmd,
1041 	.get_info = inet_diag_handler_get_info,
1042 	.destroy = inet_diag_handler_cmd,
1043 };
1044 
1045 static const struct sock_diag_handler inet6_diag_handler = {
1046 	.owner = THIS_MODULE,
1047 	.family = AF_INET6,
1048 	.dump = inet_diag_handler_cmd,
1049 	.get_info = inet_diag_handler_get_info,
1050 	.destroy = inet_diag_handler_cmd,
1051 };
1052 
1053 int inet_diag_register(const struct inet_diag_handler *h)
1054 {
1055 	const __u16 type = h->idiag_type;
1056 
1057 	if (type >= IPPROTO_MAX)
1058 		return -EINVAL;
1059 
1060 	return !cmpxchg((const struct inet_diag_handler **)&inet_diag_table[type],
1061 			NULL, h) ? 0 : -EEXIST;
1062 }
1063 EXPORT_SYMBOL_GPL(inet_diag_register);
1064 
1065 void inet_diag_unregister(const struct inet_diag_handler *h)
1066 {
1067 	const __u16 type = h->idiag_type;
1068 
1069 	if (type >= IPPROTO_MAX)
1070 		return;
1071 
1072 	xchg((const struct inet_diag_handler **)&inet_diag_table[type],
1073 	     NULL);
1074 }
1075 EXPORT_SYMBOL_GPL(inet_diag_unregister);
1076 
1077 static const struct sock_diag_inet_compat inet_diag_compat = {
1078 	.owner	= THIS_MODULE,
1079 	.fn	= inet_diag_rcv_msg_compat,
1080 };
1081 
1082 static int __init inet_diag_init(void)
1083 {
1084 	const int inet_diag_table_size = (IPPROTO_MAX *
1085 					  sizeof(struct inet_diag_handler *));
1086 	int err = -ENOMEM;
1087 
1088 	inet_diag_table = kzalloc(inet_diag_table_size, GFP_KERNEL);
1089 	if (!inet_diag_table)
1090 		goto out;
1091 
1092 	err = sock_diag_register(&inet_diag_handler);
1093 	if (err)
1094 		goto out_free_nl;
1095 
1096 	err = sock_diag_register(&inet6_diag_handler);
1097 	if (err)
1098 		goto out_free_inet;
1099 
1100 	sock_diag_register_inet_compat(&inet_diag_compat);
1101 out:
1102 	return err;
1103 
1104 out_free_inet:
1105 	sock_diag_unregister(&inet_diag_handler);
1106 out_free_nl:
1107 	kfree(inet_diag_table);
1108 	goto out;
1109 }
1110 
1111 static void __exit inet_diag_exit(void)
1112 {
1113 	sock_diag_unregister(&inet6_diag_handler);
1114 	sock_diag_unregister(&inet_diag_handler);
1115 	sock_diag_unregister_inet_compat(&inet_diag_compat);
1116 	kfree(inet_diag_table);
1117 }
1118 
1119 module_init(inet_diag_init);
1120 module_exit(inet_diag_exit);
1121 MODULE_LICENSE("GPL");
1122 MODULE_DESCRIPTION("INET/INET6: socket monitoring via SOCK_DIAG");
1123 MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_NETLINK, NETLINK_SOCK_DIAG, 2 /* AF_INET */);
1124 MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_NETLINK, NETLINK_SOCK_DIAG, 10 /* AF_INET6 */);
1125