• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * INET		An implementation of the TCP/IP protocol suite for the LINUX
4  *		operating system.  INET is implemented using the  BSD Socket
5  *		interface as the means of communication with the user level.
6  *
7  *		"Ping" sockets
8  *
9  * Based on ipv4/udp.c code.
10  *
11  * Authors:	Vasiliy Kulikov / Openwall (for Linux 2.6),
12  *		Pavel Kankovsky (for Linux 2.4.32)
13  *
14  * Pavel gave all rights to bugs to Vasiliy,
15  * none of the bugs are Pavel's now.
16  */
17 
18 #include <linux/uaccess.h>
19 #include <linux/types.h>
20 #include <linux/fcntl.h>
21 #include <linux/socket.h>
22 #include <linux/sockios.h>
23 #include <linux/in.h>
24 #include <linux/errno.h>
25 #include <linux/timer.h>
26 #include <linux/mm.h>
27 #include <linux/inet.h>
28 #include <linux/netdevice.h>
29 #include <net/snmp.h>
30 #include <net/ip.h>
31 #include <net/icmp.h>
32 #include <net/protocol.h>
33 #include <linux/skbuff.h>
34 #include <linux/proc_fs.h>
35 #include <linux/export.h>
36 #include <net/sock.h>
37 #include <net/ping.h>
38 #include <net/udp.h>
39 #include <net/route.h>
40 #include <net/inet_common.h>
41 #include <net/checksum.h>
42 
43 #if IS_ENABLED(CONFIG_IPV6)
44 #include <linux/in6.h>
45 #include <linux/icmpv6.h>
46 #include <net/addrconf.h>
47 #include <net/ipv6.h>
48 #include <net/transp_v6.h>
49 #endif
50 
51 struct ping_table {
52 	struct hlist_nulls_head	hash[PING_HTABLE_SIZE];
53 	rwlock_t		lock;
54 };
55 
56 static struct ping_table ping_table;
57 struct pingv6_ops pingv6_ops;
58 EXPORT_SYMBOL_GPL(pingv6_ops);
59 
60 static u16 ping_port_rover;
61 
ping_hashfn(const struct net * net,u32 num,u32 mask)62 static inline u32 ping_hashfn(const struct net *net, u32 num, u32 mask)
63 {
64 	u32 res = (num + net_hash_mix(net)) & mask;
65 
66 	pr_debug("hash(%u) = %u\n", num, res);
67 	return res;
68 }
69 EXPORT_SYMBOL_GPL(ping_hash);
70 
ping_hashslot(struct ping_table * table,struct net * net,unsigned int num)71 static inline struct hlist_nulls_head *ping_hashslot(struct ping_table *table,
72 					     struct net *net, unsigned int num)
73 {
74 	return &table->hash[ping_hashfn(net, num, PING_HTABLE_MASK)];
75 }
76 
ping_get_port(struct sock * sk,unsigned short ident)77 int ping_get_port(struct sock *sk, unsigned short ident)
78 {
79 	struct hlist_nulls_node *node;
80 	struct hlist_nulls_head *hlist;
81 	struct inet_sock *isk, *isk2;
82 	struct sock *sk2 = NULL;
83 
84 	isk = inet_sk(sk);
85 	write_lock_bh(&ping_table.lock);
86 	if (ident == 0) {
87 		u32 i;
88 		u16 result = ping_port_rover + 1;
89 
90 		for (i = 0; i < (1L << 16); i++, result++) {
91 			if (!result)
92 				result++; /* avoid zero */
93 			hlist = ping_hashslot(&ping_table, sock_net(sk),
94 					    result);
95 			ping_portaddr_for_each_entry(sk2, node, hlist) {
96 				isk2 = inet_sk(sk2);
97 
98 				if (isk2->inet_num == result)
99 					goto next_port;
100 			}
101 
102 			/* found */
103 			ping_port_rover = ident = result;
104 			break;
105 next_port:
106 			;
107 		}
108 		if (i >= (1L << 16))
109 			goto fail;
110 	} else {
111 		hlist = ping_hashslot(&ping_table, sock_net(sk), ident);
112 		ping_portaddr_for_each_entry(sk2, node, hlist) {
113 			isk2 = inet_sk(sk2);
114 
115 			/* BUG? Why is this reuse and not reuseaddr? ping.c
116 			 * doesn't turn off SO_REUSEADDR, and it doesn't expect
117 			 * that other ping processes can steal its packets.
118 			 */
119 			if ((isk2->inet_num == ident) &&
120 			    (sk2 != sk) &&
121 			    (!sk2->sk_reuse || !sk->sk_reuse))
122 				goto fail;
123 		}
124 	}
125 
126 	pr_debug("found port/ident = %d\n", ident);
127 	isk->inet_num = ident;
128 	if (sk_unhashed(sk)) {
129 		pr_debug("was not hashed\n");
130 		sock_hold(sk);
131 		hlist_nulls_add_head(&sk->sk_nulls_node, hlist);
132 		sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
133 	}
134 	write_unlock_bh(&ping_table.lock);
135 	return 0;
136 
137 fail:
138 	write_unlock_bh(&ping_table.lock);
139 	return 1;
140 }
141 EXPORT_SYMBOL_GPL(ping_get_port);
142 
ping_hash(struct sock * sk)143 int ping_hash(struct sock *sk)
144 {
145 	pr_debug("ping_hash(sk->port=%u)\n", inet_sk(sk)->inet_num);
146 	BUG(); /* "Please do not press this button again." */
147 
148 	return 0;
149 }
150 
ping_unhash(struct sock * sk)151 void ping_unhash(struct sock *sk)
152 {
153 	struct inet_sock *isk = inet_sk(sk);
154 
155 	pr_debug("ping_unhash(isk=%p,isk->num=%u)\n", isk, isk->inet_num);
156 	write_lock_bh(&ping_table.lock);
157 	if (sk_hashed(sk)) {
158 		hlist_nulls_del(&sk->sk_nulls_node);
159 		sk_nulls_node_init(&sk->sk_nulls_node);
160 		sock_put(sk);
161 		isk->inet_num = 0;
162 		isk->inet_sport = 0;
163 		sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
164 	}
165 	write_unlock_bh(&ping_table.lock);
166 }
167 EXPORT_SYMBOL_GPL(ping_unhash);
168 
ping_lookup(struct net * net,struct sk_buff * skb,u16 ident)169 static struct sock *ping_lookup(struct net *net, struct sk_buff *skb, u16 ident)
170 {
171 	struct hlist_nulls_head *hslot = ping_hashslot(&ping_table, net, ident);
172 	struct sock *sk = NULL;
173 	struct inet_sock *isk;
174 	struct hlist_nulls_node *hnode;
175 	int dif = skb->dev->ifindex;
176 
177 	if (skb->protocol == htons(ETH_P_IP)) {
178 		pr_debug("try to find: num = %d, daddr = %pI4, dif = %d\n",
179 			 (int)ident, &ip_hdr(skb)->daddr, dif);
180 #if IS_ENABLED(CONFIG_IPV6)
181 	} else if (skb->protocol == htons(ETH_P_IPV6)) {
182 		pr_debug("try to find: num = %d, daddr = %pI6c, dif = %d\n",
183 			 (int)ident, &ipv6_hdr(skb)->daddr, dif);
184 #endif
185 	}
186 
187 	read_lock_bh(&ping_table.lock);
188 
189 	ping_portaddr_for_each_entry(sk, hnode, hslot) {
190 		isk = inet_sk(sk);
191 
192 		pr_debug("iterate\n");
193 		if (isk->inet_num != ident)
194 			continue;
195 
196 		if (skb->protocol == htons(ETH_P_IP) &&
197 		    sk->sk_family == AF_INET) {
198 			pr_debug("found: %p: num=%d, daddr=%pI4, dif=%d\n", sk,
199 				 (int) isk->inet_num, &isk->inet_rcv_saddr,
200 				 sk->sk_bound_dev_if);
201 
202 			if (isk->inet_rcv_saddr &&
203 			    isk->inet_rcv_saddr != ip_hdr(skb)->daddr)
204 				continue;
205 #if IS_ENABLED(CONFIG_IPV6)
206 		} else if (skb->protocol == htons(ETH_P_IPV6) &&
207 			   sk->sk_family == AF_INET6) {
208 
209 			pr_debug("found: %p: num=%d, daddr=%pI6c, dif=%d\n", sk,
210 				 (int) isk->inet_num,
211 				 &sk->sk_v6_rcv_saddr,
212 				 sk->sk_bound_dev_if);
213 
214 			if (!ipv6_addr_any(&sk->sk_v6_rcv_saddr) &&
215 			    !ipv6_addr_equal(&sk->sk_v6_rcv_saddr,
216 					     &ipv6_hdr(skb)->daddr))
217 				continue;
218 #endif
219 		} else {
220 			continue;
221 		}
222 
223 		if (sk->sk_bound_dev_if && sk->sk_bound_dev_if != dif &&
224 		    sk->sk_bound_dev_if != inet_sdif(skb))
225 			continue;
226 
227 		sock_hold(sk);
228 		goto exit;
229 	}
230 
231 	sk = NULL;
232 exit:
233 	read_unlock_bh(&ping_table.lock);
234 
235 	return sk;
236 }
237 
inet_get_ping_group_range_net(struct net * net,kgid_t * low,kgid_t * high)238 static void inet_get_ping_group_range_net(struct net *net, kgid_t *low,
239 					  kgid_t *high)
240 {
241 	kgid_t *data = net->ipv4.ping_group_range.range;
242 	unsigned int seq;
243 
244 	do {
245 		seq = read_seqbegin(&net->ipv4.ping_group_range.lock);
246 
247 		*low = data[0];
248 		*high = data[1];
249 	} while (read_seqretry(&net->ipv4.ping_group_range.lock, seq));
250 }
251 
252 
ping_init_sock(struct sock * sk)253 int ping_init_sock(struct sock *sk)
254 {
255 	struct net *net = sock_net(sk);
256 	kgid_t group = current_egid();
257 	struct group_info *group_info;
258 	int i;
259 	kgid_t low, high;
260 	int ret = 0;
261 
262 	if (sk->sk_family == AF_INET6)
263 		sk->sk_ipv6only = 1;
264 
265 	inet_get_ping_group_range_net(net, &low, &high);
266 	if (gid_lte(low, group) && gid_lte(group, high))
267 		return 0;
268 
269 	group_info = get_current_groups();
270 	for (i = 0; i < group_info->ngroups; i++) {
271 		kgid_t gid = group_info->gid[i];
272 
273 		if (gid_lte(low, gid) && gid_lte(gid, high))
274 			goto out_release_group;
275 	}
276 
277 	ret = -EACCES;
278 
279 out_release_group:
280 	put_group_info(group_info);
281 	return ret;
282 }
283 EXPORT_SYMBOL_GPL(ping_init_sock);
284 
ping_close(struct sock * sk,long timeout)285 void ping_close(struct sock *sk, long timeout)
286 {
287 	pr_debug("ping_close(sk=%p,sk->num=%u)\n",
288 		 inet_sk(sk), inet_sk(sk)->inet_num);
289 	pr_debug("isk->refcnt = %d\n", refcount_read(&sk->sk_refcnt));
290 
291 	sk_common_release(sk);
292 }
293 EXPORT_SYMBOL_GPL(ping_close);
294 
295 /* Checks the bind address and possibly modifies sk->sk_bound_dev_if. */
ping_check_bind_addr(struct sock * sk,struct inet_sock * isk,struct sockaddr * uaddr,int addr_len)296 static int ping_check_bind_addr(struct sock *sk, struct inet_sock *isk,
297 				struct sockaddr *uaddr, int addr_len)
298 {
299 	struct net *net = sock_net(sk);
300 	if (sk->sk_family == AF_INET) {
301 		struct sockaddr_in *addr = (struct sockaddr_in *) uaddr;
302 		int chk_addr_ret;
303 
304 		if (addr_len < sizeof(*addr))
305 			return -EINVAL;
306 
307 		if (addr->sin_family != AF_INET &&
308 		    !(addr->sin_family == AF_UNSPEC &&
309 		      addr->sin_addr.s_addr == htonl(INADDR_ANY)))
310 			return -EAFNOSUPPORT;
311 
312 		pr_debug("ping_check_bind_addr(sk=%p,addr=%pI4,port=%d)\n",
313 			 sk, &addr->sin_addr.s_addr, ntohs(addr->sin_port));
314 
315 		if (addr->sin_addr.s_addr == htonl(INADDR_ANY))
316 			chk_addr_ret = RTN_LOCAL;
317 		else
318 			chk_addr_ret = inet_addr_type(net, addr->sin_addr.s_addr);
319 
320 		if ((!inet_can_nonlocal_bind(net, isk) &&
321 		     chk_addr_ret != RTN_LOCAL) ||
322 		    chk_addr_ret == RTN_MULTICAST ||
323 		    chk_addr_ret == RTN_BROADCAST)
324 			return -EADDRNOTAVAIL;
325 
326 #if IS_ENABLED(CONFIG_IPV6)
327 	} else if (sk->sk_family == AF_INET6) {
328 		struct sockaddr_in6 *addr = (struct sockaddr_in6 *) uaddr;
329 		int addr_type, scoped, has_addr;
330 		struct net_device *dev = NULL;
331 
332 		if (addr_len < sizeof(*addr))
333 			return -EINVAL;
334 
335 		if (addr->sin6_family != AF_INET6)
336 			return -EAFNOSUPPORT;
337 
338 		pr_debug("ping_check_bind_addr(sk=%p,addr=%pI6c,port=%d)\n",
339 			 sk, addr->sin6_addr.s6_addr, ntohs(addr->sin6_port));
340 
341 		addr_type = ipv6_addr_type(&addr->sin6_addr);
342 		scoped = __ipv6_addr_needs_scope_id(addr_type);
343 		if ((addr_type != IPV6_ADDR_ANY &&
344 		     !(addr_type & IPV6_ADDR_UNICAST)) ||
345 		    (scoped && !addr->sin6_scope_id))
346 			return -EINVAL;
347 
348 		rcu_read_lock();
349 		if (addr->sin6_scope_id) {
350 			dev = dev_get_by_index_rcu(net, addr->sin6_scope_id);
351 			if (!dev) {
352 				rcu_read_unlock();
353 				return -ENODEV;
354 			}
355 		}
356 		has_addr = pingv6_ops.ipv6_chk_addr(net, &addr->sin6_addr, dev,
357 						    scoped);
358 		rcu_read_unlock();
359 
360 		if (!(ipv6_can_nonlocal_bind(net, isk) || has_addr ||
361 		      addr_type == IPV6_ADDR_ANY))
362 			return -EADDRNOTAVAIL;
363 
364 		if (scoped)
365 			sk->sk_bound_dev_if = addr->sin6_scope_id;
366 #endif
367 	} else {
368 		return -EAFNOSUPPORT;
369 	}
370 	return 0;
371 }
372 
ping_set_saddr(struct sock * sk,struct sockaddr * saddr)373 static void ping_set_saddr(struct sock *sk, struct sockaddr *saddr)
374 {
375 	if (saddr->sa_family == AF_INET) {
376 		struct inet_sock *isk = inet_sk(sk);
377 		struct sockaddr_in *addr = (struct sockaddr_in *) saddr;
378 		isk->inet_rcv_saddr = isk->inet_saddr = addr->sin_addr.s_addr;
379 #if IS_ENABLED(CONFIG_IPV6)
380 	} else if (saddr->sa_family == AF_INET6) {
381 		struct sockaddr_in6 *addr = (struct sockaddr_in6 *) saddr;
382 		struct ipv6_pinfo *np = inet6_sk(sk);
383 		sk->sk_v6_rcv_saddr = np->saddr = addr->sin6_addr;
384 #endif
385 	}
386 }
387 
388 /*
389  * We need our own bind because there are no privileged id's == local ports.
390  * Moreover, we don't allow binding to multi- and broadcast addresses.
391  */
392 
ping_bind(struct sock * sk,struct sockaddr * uaddr,int addr_len)393 int ping_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len)
394 {
395 	struct inet_sock *isk = inet_sk(sk);
396 	unsigned short snum;
397 	int err;
398 	int dif = sk->sk_bound_dev_if;
399 
400 	err = ping_check_bind_addr(sk, isk, uaddr, addr_len);
401 	if (err)
402 		return err;
403 
404 	lock_sock(sk);
405 
406 	err = -EINVAL;
407 	if (isk->inet_num != 0)
408 		goto out;
409 
410 	err = -EADDRINUSE;
411 	snum = ntohs(((struct sockaddr_in *)uaddr)->sin_port);
412 	if (ping_get_port(sk, snum) != 0) {
413 		/* Restore possibly modified sk->sk_bound_dev_if by ping_check_bind_addr(). */
414 		sk->sk_bound_dev_if = dif;
415 		goto out;
416 	}
417 	ping_set_saddr(sk, uaddr);
418 
419 	pr_debug("after bind(): num = %hu, dif = %d\n",
420 		 isk->inet_num,
421 		 sk->sk_bound_dev_if);
422 
423 	err = 0;
424 	if (sk->sk_family == AF_INET && isk->inet_rcv_saddr)
425 		sk->sk_userlocks |= SOCK_BINDADDR_LOCK;
426 #if IS_ENABLED(CONFIG_IPV6)
427 	if (sk->sk_family == AF_INET6 && !ipv6_addr_any(&sk->sk_v6_rcv_saddr))
428 		sk->sk_userlocks |= SOCK_BINDADDR_LOCK;
429 #endif
430 
431 	if (snum)
432 		sk->sk_userlocks |= SOCK_BINDPORT_LOCK;
433 	isk->inet_sport = htons(isk->inet_num);
434 	isk->inet_daddr = 0;
435 	isk->inet_dport = 0;
436 
437 #if IS_ENABLED(CONFIG_IPV6)
438 	if (sk->sk_family == AF_INET6)
439 		memset(&sk->sk_v6_daddr, 0, sizeof(sk->sk_v6_daddr));
440 #endif
441 
442 	sk_dst_reset(sk);
443 out:
444 	release_sock(sk);
445 	pr_debug("ping_v4_bind -> %d\n", err);
446 	return err;
447 }
448 EXPORT_SYMBOL_GPL(ping_bind);
449 
450 /*
451  * Is this a supported type of ICMP message?
452  */
453 
ping_supported(int family,int type,int code)454 static inline int ping_supported(int family, int type, int code)
455 {
456 	return (family == AF_INET && type == ICMP_ECHO && code == 0) ||
457 	       (family == AF_INET6 && type == ICMPV6_ECHO_REQUEST && code == 0);
458 }
459 
460 /*
461  * This routine is called by the ICMP module when it gets some
462  * sort of error condition.
463  */
464 
ping_err(struct sk_buff * skb,int offset,u32 info)465 void ping_err(struct sk_buff *skb, int offset, u32 info)
466 {
467 	int family;
468 	struct icmphdr *icmph;
469 	struct inet_sock *inet_sock;
470 	int type;
471 	int code;
472 	struct net *net = dev_net(skb->dev);
473 	struct sock *sk;
474 	int harderr;
475 	int err;
476 
477 	if (skb->protocol == htons(ETH_P_IP)) {
478 		family = AF_INET;
479 		type = icmp_hdr(skb)->type;
480 		code = icmp_hdr(skb)->code;
481 		icmph = (struct icmphdr *)(skb->data + offset);
482 	} else if (skb->protocol == htons(ETH_P_IPV6)) {
483 		family = AF_INET6;
484 		type = icmp6_hdr(skb)->icmp6_type;
485 		code = icmp6_hdr(skb)->icmp6_code;
486 		icmph = (struct icmphdr *) (skb->data + offset);
487 	} else {
488 		BUG();
489 	}
490 
491 	/* We assume the packet has already been checked by icmp_unreach */
492 
493 	if (!ping_supported(family, icmph->type, icmph->code))
494 		return;
495 
496 	pr_debug("ping_err(proto=0x%x,type=%d,code=%d,id=%04x,seq=%04x)\n",
497 		 skb->protocol, type, code, ntohs(icmph->un.echo.id),
498 		 ntohs(icmph->un.echo.sequence));
499 
500 	sk = ping_lookup(net, skb, ntohs(icmph->un.echo.id));
501 	if (!sk) {
502 		pr_debug("no socket, dropping\n");
503 		return;	/* No socket for error */
504 	}
505 	pr_debug("err on socket %p\n", sk);
506 
507 	err = 0;
508 	harderr = 0;
509 	inet_sock = inet_sk(sk);
510 
511 	if (skb->protocol == htons(ETH_P_IP)) {
512 		switch (type) {
513 		default:
514 		case ICMP_TIME_EXCEEDED:
515 			err = EHOSTUNREACH;
516 			break;
517 		case ICMP_SOURCE_QUENCH:
518 			/* This is not a real error but ping wants to see it.
519 			 * Report it with some fake errno.
520 			 */
521 			err = EREMOTEIO;
522 			break;
523 		case ICMP_PARAMETERPROB:
524 			err = EPROTO;
525 			harderr = 1;
526 			break;
527 		case ICMP_DEST_UNREACH:
528 			if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
529 				ipv4_sk_update_pmtu(skb, sk, info);
530 				if (inet_sock->pmtudisc != IP_PMTUDISC_DONT) {
531 					err = EMSGSIZE;
532 					harderr = 1;
533 					break;
534 				}
535 				goto out;
536 			}
537 			err = EHOSTUNREACH;
538 			if (code <= NR_ICMP_UNREACH) {
539 				harderr = icmp_err_convert[code].fatal;
540 				err = icmp_err_convert[code].errno;
541 			}
542 			break;
543 		case ICMP_REDIRECT:
544 			/* See ICMP_SOURCE_QUENCH */
545 			ipv4_sk_redirect(skb, sk);
546 			err = EREMOTEIO;
547 			break;
548 		}
549 #if IS_ENABLED(CONFIG_IPV6)
550 	} else if (skb->protocol == htons(ETH_P_IPV6)) {
551 		harderr = pingv6_ops.icmpv6_err_convert(type, code, &err);
552 #endif
553 	}
554 
555 	/*
556 	 *      RFC1122: OK.  Passes ICMP errors back to application, as per
557 	 *	4.1.3.3.
558 	 */
559 	if ((family == AF_INET && !inet_sock->recverr) ||
560 	    (family == AF_INET6 && !inet6_sk(sk)->recverr)) {
561 		if (!harderr || sk->sk_state != TCP_ESTABLISHED)
562 			goto out;
563 	} else {
564 		if (family == AF_INET) {
565 			ip_icmp_error(sk, skb, err, 0 /* no remote port */,
566 				      info, (u8 *)icmph);
567 #if IS_ENABLED(CONFIG_IPV6)
568 		} else if (family == AF_INET6) {
569 			pingv6_ops.ipv6_icmp_error(sk, skb, err, 0,
570 						   info, (u8 *)icmph);
571 #endif
572 		}
573 	}
574 	sk->sk_err = err;
575 	sk->sk_error_report(sk);
576 out:
577 	sock_put(sk);
578 }
579 EXPORT_SYMBOL_GPL(ping_err);
580 
581 /*
582  *	Copy and checksum an ICMP Echo packet from user space into a buffer
583  *	starting from the payload.
584  */
585 
ping_getfrag(void * from,char * to,int offset,int fraglen,int odd,struct sk_buff * skb)586 int ping_getfrag(void *from, char *to,
587 		 int offset, int fraglen, int odd, struct sk_buff *skb)
588 {
589 	struct pingfakehdr *pfh = (struct pingfakehdr *)from;
590 
591 	if (offset == 0) {
592 		fraglen -= sizeof(struct icmphdr);
593 		if (fraglen < 0)
594 			BUG();
595 		if (!csum_and_copy_from_iter_full(to + sizeof(struct icmphdr),
596 			    fraglen, &pfh->wcheck,
597 			    &pfh->msg->msg_iter))
598 			return -EFAULT;
599 	} else if (offset < sizeof(struct icmphdr)) {
600 			BUG();
601 	} else {
602 		if (!csum_and_copy_from_iter_full(to, fraglen, &pfh->wcheck,
603 					    &pfh->msg->msg_iter))
604 			return -EFAULT;
605 	}
606 
607 #if IS_ENABLED(CONFIG_IPV6)
608 	/* For IPv6, checksum each skb as we go along, as expected by
609 	 * icmpv6_push_pending_frames. For IPv4, accumulate the checksum in
610 	 * wcheck, it will be finalized in ping_v4_push_pending_frames.
611 	 */
612 	if (pfh->family == AF_INET6) {
613 		skb->csum = pfh->wcheck;
614 		skb->ip_summed = CHECKSUM_NONE;
615 		pfh->wcheck = 0;
616 	}
617 #endif
618 
619 	return 0;
620 }
621 EXPORT_SYMBOL_GPL(ping_getfrag);
622 
ping_v4_push_pending_frames(struct sock * sk,struct pingfakehdr * pfh,struct flowi4 * fl4)623 static int ping_v4_push_pending_frames(struct sock *sk, struct pingfakehdr *pfh,
624 				       struct flowi4 *fl4)
625 {
626 	struct sk_buff *skb = skb_peek(&sk->sk_write_queue);
627 
628 	if (!skb)
629 		return 0;
630 	pfh->wcheck = csum_partial((char *)&pfh->icmph,
631 		sizeof(struct icmphdr), pfh->wcheck);
632 	pfh->icmph.checksum = csum_fold(pfh->wcheck);
633 	memcpy(icmp_hdr(skb), &pfh->icmph, sizeof(struct icmphdr));
634 	skb->ip_summed = CHECKSUM_NONE;
635 	return ip_push_pending_frames(sk, fl4);
636 }
637 
ping_common_sendmsg(int family,struct msghdr * msg,size_t len,void * user_icmph,size_t icmph_len)638 int ping_common_sendmsg(int family, struct msghdr *msg, size_t len,
639 			void *user_icmph, size_t icmph_len)
640 {
641 	u8 type, code;
642 
643 	if (len > 0xFFFF)
644 		return -EMSGSIZE;
645 
646 	/* Must have at least a full ICMP header. */
647 	if (len < icmph_len)
648 		return -EINVAL;
649 
650 	/*
651 	 *	Check the flags.
652 	 */
653 
654 	/* Mirror BSD error message compatibility */
655 	if (msg->msg_flags & MSG_OOB)
656 		return -EOPNOTSUPP;
657 
658 	/*
659 	 *	Fetch the ICMP header provided by the userland.
660 	 *	iovec is modified! The ICMP header is consumed.
661 	 */
662 	if (memcpy_from_msg(user_icmph, msg, icmph_len))
663 		return -EFAULT;
664 
665 	if (family == AF_INET) {
666 		type = ((struct icmphdr *) user_icmph)->type;
667 		code = ((struct icmphdr *) user_icmph)->code;
668 #if IS_ENABLED(CONFIG_IPV6)
669 	} else if (family == AF_INET6) {
670 		type = ((struct icmp6hdr *) user_icmph)->icmp6_type;
671 		code = ((struct icmp6hdr *) user_icmph)->icmp6_code;
672 #endif
673 	} else {
674 		BUG();
675 	}
676 
677 	if (!ping_supported(family, type, code))
678 		return -EINVAL;
679 
680 	return 0;
681 }
682 EXPORT_SYMBOL_GPL(ping_common_sendmsg);
683 
ping_v4_sendmsg(struct sock * sk,struct msghdr * msg,size_t len)684 static int ping_v4_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
685 {
686 	struct net *net = sock_net(sk);
687 	struct flowi4 fl4;
688 	struct inet_sock *inet = inet_sk(sk);
689 	struct ipcm_cookie ipc;
690 	struct icmphdr user_icmph;
691 	struct pingfakehdr pfh;
692 	struct rtable *rt = NULL;
693 	struct ip_options_data opt_copy;
694 	int free = 0;
695 	__be32 saddr, daddr, faddr;
696 	u8  tos;
697 	int err;
698 
699 	pr_debug("ping_v4_sendmsg(sk=%p,sk->num=%u)\n", inet, inet->inet_num);
700 
701 	err = ping_common_sendmsg(AF_INET, msg, len, &user_icmph,
702 				  sizeof(user_icmph));
703 	if (err)
704 		return err;
705 
706 	/*
707 	 *	Get and verify the address.
708 	 */
709 
710 	if (msg->msg_name) {
711 		DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
712 		if (msg->msg_namelen < sizeof(*usin))
713 			return -EINVAL;
714 		if (usin->sin_family != AF_INET)
715 			return -EAFNOSUPPORT;
716 		daddr = usin->sin_addr.s_addr;
717 		/* no remote port */
718 	} else {
719 		if (sk->sk_state != TCP_ESTABLISHED)
720 			return -EDESTADDRREQ;
721 		daddr = inet->inet_daddr;
722 		/* no remote port */
723 	}
724 
725 	ipcm_init_sk(&ipc, inet);
726 
727 	if (msg->msg_controllen) {
728 		err = ip_cmsg_send(sk, msg, &ipc, false);
729 		if (unlikely(err)) {
730 			kfree(ipc.opt);
731 			return err;
732 		}
733 		if (ipc.opt)
734 			free = 1;
735 	}
736 	if (!ipc.opt) {
737 		struct ip_options_rcu *inet_opt;
738 
739 		rcu_read_lock();
740 		inet_opt = rcu_dereference(inet->inet_opt);
741 		if (inet_opt) {
742 			memcpy(&opt_copy, inet_opt,
743 			       sizeof(*inet_opt) + inet_opt->opt.optlen);
744 			ipc.opt = &opt_copy.opt;
745 		}
746 		rcu_read_unlock();
747 	}
748 
749 	saddr = ipc.addr;
750 	ipc.addr = faddr = daddr;
751 
752 	if (ipc.opt && ipc.opt->opt.srr) {
753 		if (!daddr) {
754 			err = -EINVAL;
755 			goto out_free;
756 		}
757 		faddr = ipc.opt->opt.faddr;
758 	}
759 	tos = get_rttos(&ipc, inet);
760 	if (sock_flag(sk, SOCK_LOCALROUTE) ||
761 	    (msg->msg_flags & MSG_DONTROUTE) ||
762 	    (ipc.opt && ipc.opt->opt.is_strictroute)) {
763 		tos |= RTO_ONLINK;
764 	}
765 
766 	if (ipv4_is_multicast(daddr)) {
767 		if (!ipc.oif || netif_index_is_l3_master(sock_net(sk), ipc.oif))
768 			ipc.oif = inet->mc_index;
769 		if (!saddr)
770 			saddr = inet->mc_addr;
771 	} else if (!ipc.oif)
772 		ipc.oif = inet->uc_index;
773 
774 	flowi4_init_output(&fl4, ipc.oif, ipc.sockc.mark, tos,
775 			   RT_SCOPE_UNIVERSE, sk->sk_protocol,
776 			   inet_sk_flowi_flags(sk), faddr, saddr, 0, 0,
777 			   sk->sk_uid);
778 
779 	fl4.fl4_icmp_type = user_icmph.type;
780 	fl4.fl4_icmp_code = user_icmph.code;
781 
782 	security_sk_classify_flow(sk, flowi4_to_flowi(&fl4));
783 	rt = ip_route_output_flow(net, &fl4, sk);
784 	if (IS_ERR(rt)) {
785 		err = PTR_ERR(rt);
786 		rt = NULL;
787 		if (err == -ENETUNREACH)
788 			IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
789 		goto out;
790 	}
791 
792 	err = -EACCES;
793 	if ((rt->rt_flags & RTCF_BROADCAST) &&
794 	    !sock_flag(sk, SOCK_BROADCAST))
795 		goto out;
796 
797 	if (msg->msg_flags & MSG_CONFIRM)
798 		goto do_confirm;
799 back_from_confirm:
800 
801 	if (!ipc.addr)
802 		ipc.addr = fl4.daddr;
803 
804 	lock_sock(sk);
805 
806 	pfh.icmph.type = user_icmph.type; /* already checked */
807 	pfh.icmph.code = user_icmph.code; /* ditto */
808 	pfh.icmph.checksum = 0;
809 	pfh.icmph.un.echo.id = inet->inet_sport;
810 	pfh.icmph.un.echo.sequence = user_icmph.un.echo.sequence;
811 	pfh.msg = msg;
812 	pfh.wcheck = 0;
813 	pfh.family = AF_INET;
814 
815 	err = ip_append_data(sk, &fl4, ping_getfrag, &pfh, len,
816 			0, &ipc, &rt, msg->msg_flags);
817 	if (err)
818 		ip_flush_pending_frames(sk);
819 	else
820 		err = ping_v4_push_pending_frames(sk, &pfh, &fl4);
821 	release_sock(sk);
822 
823 out:
824 	ip_rt_put(rt);
825 out_free:
826 	if (free)
827 		kfree(ipc.opt);
828 	if (!err) {
829 		icmp_out_count(sock_net(sk), user_icmph.type);
830 		return len;
831 	}
832 	return err;
833 
834 do_confirm:
835 	if (msg->msg_flags & MSG_PROBE)
836 		dst_confirm_neigh(&rt->dst, &fl4.daddr);
837 	if (!(msg->msg_flags & MSG_PROBE) || len)
838 		goto back_from_confirm;
839 	err = 0;
840 	goto out;
841 }
842 
ping_recvmsg(struct sock * sk,struct msghdr * msg,size_t len,int noblock,int flags,int * addr_len)843 int ping_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int noblock,
844 		 int flags, int *addr_len)
845 {
846 	struct inet_sock *isk = inet_sk(sk);
847 	int family = sk->sk_family;
848 	struct sk_buff *skb;
849 	int copied, err;
850 
851 	pr_debug("ping_recvmsg(sk=%p,sk->num=%u)\n", isk, isk->inet_num);
852 
853 	err = -EOPNOTSUPP;
854 	if (flags & MSG_OOB)
855 		goto out;
856 
857 	if (flags & MSG_ERRQUEUE)
858 		return inet_recv_error(sk, msg, len, addr_len);
859 
860 	skb = skb_recv_datagram(sk, flags, noblock, &err);
861 	if (!skb)
862 		goto out;
863 
864 	copied = skb->len;
865 	if (copied > len) {
866 		msg->msg_flags |= MSG_TRUNC;
867 		copied = len;
868 	}
869 
870 	/* Don't bother checking the checksum */
871 	err = skb_copy_datagram_msg(skb, 0, msg, copied);
872 	if (err)
873 		goto done;
874 
875 	sock_recv_timestamp(msg, sk, skb);
876 
877 	/* Copy the address and add cmsg data. */
878 	if (family == AF_INET) {
879 		DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
880 
881 		if (sin) {
882 			sin->sin_family = AF_INET;
883 			sin->sin_port = 0 /* skb->h.uh->source */;
884 			sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
885 			memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
886 			*addr_len = sizeof(*sin);
887 		}
888 
889 		if (isk->cmsg_flags)
890 			ip_cmsg_recv(msg, skb);
891 
892 #if IS_ENABLED(CONFIG_IPV6)
893 	} else if (family == AF_INET6) {
894 		struct ipv6_pinfo *np = inet6_sk(sk);
895 		struct ipv6hdr *ip6 = ipv6_hdr(skb);
896 		DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
897 
898 		if (sin6) {
899 			sin6->sin6_family = AF_INET6;
900 			sin6->sin6_port = 0;
901 			sin6->sin6_addr = ip6->saddr;
902 			sin6->sin6_flowinfo = 0;
903 			if (np->sndflow)
904 				sin6->sin6_flowinfo = ip6_flowinfo(ip6);
905 			sin6->sin6_scope_id =
906 				ipv6_iface_scope_id(&sin6->sin6_addr,
907 						    inet6_iif(skb));
908 			*addr_len = sizeof(*sin6);
909 		}
910 
911 		if (inet6_sk(sk)->rxopt.all)
912 			pingv6_ops.ip6_datagram_recv_common_ctl(sk, msg, skb);
913 		if (skb->protocol == htons(ETH_P_IPV6) &&
914 		    inet6_sk(sk)->rxopt.all)
915 			pingv6_ops.ip6_datagram_recv_specific_ctl(sk, msg, skb);
916 		else if (skb->protocol == htons(ETH_P_IP) && isk->cmsg_flags)
917 			ip_cmsg_recv(msg, skb);
918 #endif
919 	} else {
920 		BUG();
921 	}
922 
923 	err = copied;
924 
925 done:
926 	skb_free_datagram(sk, skb);
927 out:
928 	pr_debug("ping_recvmsg -> %d\n", err);
929 	return err;
930 }
931 EXPORT_SYMBOL_GPL(ping_recvmsg);
932 
ping_queue_rcv_skb(struct sock * sk,struct sk_buff * skb)933 int ping_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
934 {
935 	pr_debug("ping_queue_rcv_skb(sk=%p,sk->num=%d,skb=%p)\n",
936 		 inet_sk(sk), inet_sk(sk)->inet_num, skb);
937 	if (sock_queue_rcv_skb(sk, skb) < 0) {
938 		kfree_skb(skb);
939 		pr_debug("ping_queue_rcv_skb -> failed\n");
940 		return -1;
941 	}
942 	return 0;
943 }
944 EXPORT_SYMBOL_GPL(ping_queue_rcv_skb);
945 
946 
947 /*
948  *	All we need to do is get the socket.
949  */
950 
ping_rcv(struct sk_buff * skb)951 bool ping_rcv(struct sk_buff *skb)
952 {
953 	struct sock *sk;
954 	struct net *net = dev_net(skb->dev);
955 	struct icmphdr *icmph = icmp_hdr(skb);
956 	bool rc = false;
957 
958 	/* We assume the packet has already been checked by icmp_rcv */
959 
960 	pr_debug("ping_rcv(skb=%p,id=%04x,seq=%04x)\n",
961 		 skb, ntohs(icmph->un.echo.id), ntohs(icmph->un.echo.sequence));
962 
963 	/* Push ICMP header back */
964 	skb_push(skb, skb->data - (u8 *)icmph);
965 
966 	sk = ping_lookup(net, skb, ntohs(icmph->un.echo.id));
967 	if (sk) {
968 		struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC);
969 
970 		pr_debug("rcv on socket %p\n", sk);
971 		if (skb2 && !ping_queue_rcv_skb(sk, skb2))
972 			rc = true;
973 		sock_put(sk);
974 	}
975 
976 	if (!rc)
977 		pr_debug("no socket, dropping\n");
978 
979 	return rc;
980 }
981 EXPORT_SYMBOL_GPL(ping_rcv);
982 
983 struct proto ping_prot = {
984 	.name =		"PING",
985 	.owner =	THIS_MODULE,
986 	.init =		ping_init_sock,
987 	.close =	ping_close,
988 	.connect =	ip4_datagram_connect,
989 	.disconnect =	__udp_disconnect,
990 	.setsockopt =	ip_setsockopt,
991 	.getsockopt =	ip_getsockopt,
992 	.sendmsg =	ping_v4_sendmsg,
993 	.recvmsg =	ping_recvmsg,
994 	.bind =		ping_bind,
995 	.backlog_rcv =	ping_queue_rcv_skb,
996 	.release_cb =	ip4_datagram_release_cb,
997 	.hash =		ping_hash,
998 	.unhash =	ping_unhash,
999 	.get_port =	ping_get_port,
1000 	.obj_size =	sizeof(struct inet_sock),
1001 };
1002 EXPORT_SYMBOL(ping_prot);
1003 
1004 #ifdef CONFIG_PROC_FS
1005 
ping_get_first(struct seq_file * seq,int start)1006 static struct sock *ping_get_first(struct seq_file *seq, int start)
1007 {
1008 	struct sock *sk;
1009 	struct ping_iter_state *state = seq->private;
1010 	struct net *net = seq_file_net(seq);
1011 
1012 	for (state->bucket = start; state->bucket < PING_HTABLE_SIZE;
1013 	     ++state->bucket) {
1014 		struct hlist_nulls_node *node;
1015 		struct hlist_nulls_head *hslot;
1016 
1017 		hslot = &ping_table.hash[state->bucket];
1018 
1019 		if (hlist_nulls_empty(hslot))
1020 			continue;
1021 
1022 		sk_nulls_for_each(sk, node, hslot) {
1023 			if (net_eq(sock_net(sk), net) &&
1024 			    sk->sk_family == state->family)
1025 				goto found;
1026 		}
1027 	}
1028 	sk = NULL;
1029 found:
1030 	return sk;
1031 }
1032 
ping_get_next(struct seq_file * seq,struct sock * sk)1033 static struct sock *ping_get_next(struct seq_file *seq, struct sock *sk)
1034 {
1035 	struct ping_iter_state *state = seq->private;
1036 	struct net *net = seq_file_net(seq);
1037 
1038 	do {
1039 		sk = sk_nulls_next(sk);
1040 	} while (sk && (!net_eq(sock_net(sk), net)));
1041 
1042 	if (!sk)
1043 		return ping_get_first(seq, state->bucket + 1);
1044 	return sk;
1045 }
1046 
ping_get_idx(struct seq_file * seq,loff_t pos)1047 static struct sock *ping_get_idx(struct seq_file *seq, loff_t pos)
1048 {
1049 	struct sock *sk = ping_get_first(seq, 0);
1050 
1051 	if (sk)
1052 		while (pos && (sk = ping_get_next(seq, sk)) != NULL)
1053 			--pos;
1054 	return pos ? NULL : sk;
1055 }
1056 
ping_seq_start(struct seq_file * seq,loff_t * pos,sa_family_t family)1057 void *ping_seq_start(struct seq_file *seq, loff_t *pos, sa_family_t family)
1058 	__acquires(ping_table.lock)
1059 {
1060 	struct ping_iter_state *state = seq->private;
1061 	state->bucket = 0;
1062 	state->family = family;
1063 
1064 	read_lock_bh(&ping_table.lock);
1065 
1066 	return *pos ? ping_get_idx(seq, *pos-1) : SEQ_START_TOKEN;
1067 }
1068 EXPORT_SYMBOL_GPL(ping_seq_start);
1069 
ping_v4_seq_start(struct seq_file * seq,loff_t * pos)1070 static void *ping_v4_seq_start(struct seq_file *seq, loff_t *pos)
1071 {
1072 	return ping_seq_start(seq, pos, AF_INET);
1073 }
1074 
ping_seq_next(struct seq_file * seq,void * v,loff_t * pos)1075 void *ping_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1076 {
1077 	struct sock *sk;
1078 
1079 	if (v == SEQ_START_TOKEN)
1080 		sk = ping_get_idx(seq, 0);
1081 	else
1082 		sk = ping_get_next(seq, v);
1083 
1084 	++*pos;
1085 	return sk;
1086 }
1087 EXPORT_SYMBOL_GPL(ping_seq_next);
1088 
ping_seq_stop(struct seq_file * seq,void * v)1089 void ping_seq_stop(struct seq_file *seq, void *v)
1090 	__releases(ping_table.lock)
1091 {
1092 	read_unlock_bh(&ping_table.lock);
1093 }
1094 EXPORT_SYMBOL_GPL(ping_seq_stop);
1095 
ping_v4_format_sock(struct sock * sp,struct seq_file * f,int bucket)1096 static void ping_v4_format_sock(struct sock *sp, struct seq_file *f,
1097 		int bucket)
1098 {
1099 	struct inet_sock *inet = inet_sk(sp);
1100 	__be32 dest = inet->inet_daddr;
1101 	__be32 src = inet->inet_rcv_saddr;
1102 	__u16 destp = ntohs(inet->inet_dport);
1103 	__u16 srcp = ntohs(inet->inet_sport);
1104 
1105 	seq_printf(f, "%5d: %08X:%04X %08X:%04X"
1106 		" %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %u",
1107 		bucket, src, srcp, dest, destp, sp->sk_state,
1108 		sk_wmem_alloc_get(sp),
1109 		sk_rmem_alloc_get(sp),
1110 		0, 0L, 0,
1111 		from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)),
1112 		0, sock_i_ino(sp),
1113 		refcount_read(&sp->sk_refcnt), sp,
1114 		atomic_read(&sp->sk_drops));
1115 }
1116 
ping_v4_seq_show(struct seq_file * seq,void * v)1117 static int ping_v4_seq_show(struct seq_file *seq, void *v)
1118 {
1119 	seq_setwidth(seq, 127);
1120 	if (v == SEQ_START_TOKEN)
1121 		seq_puts(seq, "  sl  local_address rem_address   st tx_queue "
1122 			   "rx_queue tr tm->when retrnsmt   uid  timeout "
1123 			   "inode ref pointer drops");
1124 	else {
1125 		struct ping_iter_state *state = seq->private;
1126 
1127 		ping_v4_format_sock(v, seq, state->bucket);
1128 	}
1129 	seq_pad(seq, '\n');
1130 	return 0;
1131 }
1132 
1133 static const struct seq_operations ping_v4_seq_ops = {
1134 	.start		= ping_v4_seq_start,
1135 	.show		= ping_v4_seq_show,
1136 	.next		= ping_seq_next,
1137 	.stop		= ping_seq_stop,
1138 };
1139 
ping_v4_proc_init_net(struct net * net)1140 static int __net_init ping_v4_proc_init_net(struct net *net)
1141 {
1142 	if (!proc_create_net("icmp", 0444, net->proc_net, &ping_v4_seq_ops,
1143 			sizeof(struct ping_iter_state)))
1144 		return -ENOMEM;
1145 	return 0;
1146 }
1147 
ping_v4_proc_exit_net(struct net * net)1148 static void __net_exit ping_v4_proc_exit_net(struct net *net)
1149 {
1150 	remove_proc_entry("icmp", net->proc_net);
1151 }
1152 
1153 static struct pernet_operations ping_v4_net_ops = {
1154 	.init = ping_v4_proc_init_net,
1155 	.exit = ping_v4_proc_exit_net,
1156 };
1157 
ping_proc_init(void)1158 int __init ping_proc_init(void)
1159 {
1160 	return register_pernet_subsys(&ping_v4_net_ops);
1161 }
1162 
ping_proc_exit(void)1163 void ping_proc_exit(void)
1164 {
1165 	unregister_pernet_subsys(&ping_v4_net_ops);
1166 }
1167 
1168 #endif
1169 
ping_init(void)1170 void __init ping_init(void)
1171 {
1172 	int i;
1173 
1174 	for (i = 0; i < PING_HTABLE_SIZE; i++)
1175 		INIT_HLIST_NULLS_HEAD(&ping_table.hash[i], i);
1176 	rwlock_init(&ping_table.lock);
1177 }
1178