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