GNU Linux-libre 4.19.286-gnu1
[releases.git] / net / ipv4 / icmp.c
1 /*
2  *      NET3:   Implementation of the ICMP protocol layer.
3  *
4  *              Alan Cox, <alan@lxorguk.ukuu.org.uk>
5  *
6  *      This program is free software; you can redistribute it and/or
7  *      modify it under the terms of the GNU General Public License
8  *      as published by the Free Software Foundation; either version
9  *      2 of the License, or (at your option) any later version.
10  *
11  *      Some of the function names and the icmp unreach table for this
12  *      module were derived from [icmp.c 1.0.11 06/02/93] by
13  *      Ross Biro, Fred N. van Kempen, Mark Evans, Alan Cox, Gerhard Koerting.
14  *      Other than that this module is a complete rewrite.
15  *
16  *      Fixes:
17  *      Clemens Fruhwirth       :       introduce global icmp rate limiting
18  *                                      with icmp type masking ability instead
19  *                                      of broken per type icmp timeouts.
20  *              Mike Shaver     :       RFC1122 checks.
21  *              Alan Cox        :       Multicast ping reply as self.
22  *              Alan Cox        :       Fix atomicity lockup in ip_build_xmit
23  *                                      call.
24  *              Alan Cox        :       Added 216,128 byte paths to the MTU
25  *                                      code.
26  *              Martin Mares    :       RFC1812 checks.
27  *              Martin Mares    :       Can be configured to follow redirects
28  *                                      if acting as a router _without_ a
29  *                                      routing protocol (RFC 1812).
30  *              Martin Mares    :       Echo requests may be configured to
31  *                                      be ignored (RFC 1812).
32  *              Martin Mares    :       Limitation of ICMP error message
33  *                                      transmit rate (RFC 1812).
34  *              Martin Mares    :       TOS and Precedence set correctly
35  *                                      (RFC 1812).
36  *              Martin Mares    :       Now copying as much data from the
37  *                                      original packet as we can without
38  *                                      exceeding 576 bytes (RFC 1812).
39  *      Willy Konynenberg       :       Transparent proxying support.
40  *              Keith Owens     :       RFC1191 correction for 4.2BSD based
41  *                                      path MTU bug.
42  *              Thomas Quinot   :       ICMP Dest Unreach codes up to 15 are
43  *                                      valid (RFC 1812).
44  *              Andi Kleen      :       Check all packet lengths properly
45  *                                      and moved all kfree_skb() up to
46  *                                      icmp_rcv.
47  *              Andi Kleen      :       Move the rate limit bookkeeping
48  *                                      into the dest entry and use a token
49  *                                      bucket filter (thanks to ANK). Make
50  *                                      the rates sysctl configurable.
51  *              Yu Tianli       :       Fixed two ugly bugs in icmp_send
52  *                                      - IP option length was accounted wrongly
53  *                                      - ICMP header length was not accounted
54  *                                        at all.
55  *              Tristan Greaves :       Added sysctl option to ignore bogus
56  *                                      broadcast responses from broken routers.
57  *
58  * To Fix:
59  *
60  *      - Should use skb_pull() instead of all the manual checking.
61  *        This would also greatly simply some upper layer error handlers. --AK
62  *
63  */
64
65 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
66
67 #include <linux/module.h>
68 #include <linux/types.h>
69 #include <linux/jiffies.h>
70 #include <linux/kernel.h>
71 #include <linux/fcntl.h>
72 #include <linux/socket.h>
73 #include <linux/in.h>
74 #include <linux/inet.h>
75 #include <linux/inetdevice.h>
76 #include <linux/netdevice.h>
77 #include <linux/string.h>
78 #include <linux/netfilter_ipv4.h>
79 #include <linux/slab.h>
80 #include <net/snmp.h>
81 #include <net/ip.h>
82 #include <net/route.h>
83 #include <net/protocol.h>
84 #include <net/icmp.h>
85 #include <net/tcp.h>
86 #include <net/udp.h>
87 #include <net/raw.h>
88 #include <net/ping.h>
89 #include <linux/skbuff.h>
90 #include <net/sock.h>
91 #include <linux/errno.h>
92 #include <linux/timer.h>
93 #include <linux/init.h>
94 #include <linux/uaccess.h>
95 #include <net/checksum.h>
96 #include <net/xfrm.h>
97 #include <net/inet_common.h>
98 #include <net/ip_fib.h>
99 #include <net/l3mdev.h>
100
101 /*
102  *      Build xmit assembly blocks
103  */
104
105 struct icmp_bxm {
106         struct sk_buff *skb;
107         int offset;
108         int data_len;
109
110         struct {
111                 struct icmphdr icmph;
112                 __be32         times[3];
113         } data;
114         int head_len;
115         struct ip_options_data replyopts;
116 };
117
118 /* An array of errno for error messages from dest unreach. */
119 /* RFC 1122: 3.2.2.1 States that NET_UNREACH, HOST_UNREACH and SR_FAILED MUST be considered 'transient errs'. */
120
121 const struct icmp_err icmp_err_convert[] = {
122         {
123                 .errno = ENETUNREACH,   /* ICMP_NET_UNREACH */
124                 .fatal = 0,
125         },
126         {
127                 .errno = EHOSTUNREACH,  /* ICMP_HOST_UNREACH */
128                 .fatal = 0,
129         },
130         {
131                 .errno = ENOPROTOOPT    /* ICMP_PROT_UNREACH */,
132                 .fatal = 1,
133         },
134         {
135                 .errno = ECONNREFUSED,  /* ICMP_PORT_UNREACH */
136                 .fatal = 1,
137         },
138         {
139                 .errno = EMSGSIZE,      /* ICMP_FRAG_NEEDED */
140                 .fatal = 0,
141         },
142         {
143                 .errno = EOPNOTSUPP,    /* ICMP_SR_FAILED */
144                 .fatal = 0,
145         },
146         {
147                 .errno = ENETUNREACH,   /* ICMP_NET_UNKNOWN */
148                 .fatal = 1,
149         },
150         {
151                 .errno = EHOSTDOWN,     /* ICMP_HOST_UNKNOWN */
152                 .fatal = 1,
153         },
154         {
155                 .errno = ENONET,        /* ICMP_HOST_ISOLATED */
156                 .fatal = 1,
157         },
158         {
159                 .errno = ENETUNREACH,   /* ICMP_NET_ANO */
160                 .fatal = 1,
161         },
162         {
163                 .errno = EHOSTUNREACH,  /* ICMP_HOST_ANO */
164                 .fatal = 1,
165         },
166         {
167                 .errno = ENETUNREACH,   /* ICMP_NET_UNR_TOS */
168                 .fatal = 0,
169         },
170         {
171                 .errno = EHOSTUNREACH,  /* ICMP_HOST_UNR_TOS */
172                 .fatal = 0,
173         },
174         {
175                 .errno = EHOSTUNREACH,  /* ICMP_PKT_FILTERED */
176                 .fatal = 1,
177         },
178         {
179                 .errno = EHOSTUNREACH,  /* ICMP_PREC_VIOLATION */
180                 .fatal = 1,
181         },
182         {
183                 .errno = EHOSTUNREACH,  /* ICMP_PREC_CUTOFF */
184                 .fatal = 1,
185         },
186 };
187 EXPORT_SYMBOL(icmp_err_convert);
188
189 /*
190  *      ICMP control array. This specifies what to do with each ICMP.
191  */
192
193 struct icmp_control {
194         bool (*handler)(struct sk_buff *skb);
195         short   error;          /* This ICMP is classed as an error message */
196 };
197
198 static const struct icmp_control icmp_pointers[NR_ICMP_TYPES+1];
199
200 /*
201  *      The ICMP socket(s). This is the most convenient way to flow control
202  *      our ICMP output as well as maintain a clean interface throughout
203  *      all layers. All Socketless IP sends will soon be gone.
204  *
205  *      On SMP we have one ICMP socket per-cpu.
206  */
207 static struct sock *icmp_sk(struct net *net)
208 {
209         return *this_cpu_ptr(net->ipv4.icmp_sk);
210 }
211
212 /* Called with BH disabled */
213 static inline struct sock *icmp_xmit_lock(struct net *net)
214 {
215         struct sock *sk;
216
217         sk = icmp_sk(net);
218
219         if (unlikely(!spin_trylock(&sk->sk_lock.slock))) {
220                 /* This can happen if the output path signals a
221                  * dst_link_failure() for an outgoing ICMP packet.
222                  */
223                 return NULL;
224         }
225         return sk;
226 }
227
228 static inline void icmp_xmit_unlock(struct sock *sk)
229 {
230         spin_unlock(&sk->sk_lock.slock);
231 }
232
233 int sysctl_icmp_msgs_per_sec __read_mostly = 1000;
234 int sysctl_icmp_msgs_burst __read_mostly = 50;
235
236 static struct {
237         spinlock_t      lock;
238         u32             credit;
239         u32             stamp;
240 } icmp_global = {
241         .lock           = __SPIN_LOCK_UNLOCKED(icmp_global.lock),
242 };
243
244 /**
245  * icmp_global_allow - Are we allowed to send one more ICMP message ?
246  *
247  * Uses a token bucket to limit our ICMP messages to ~sysctl_icmp_msgs_per_sec.
248  * Returns false if we reached the limit and can not send another packet.
249  * Note: called with BH disabled
250  */
251 bool icmp_global_allow(void)
252 {
253         u32 credit, delta, incr = 0, now = (u32)jiffies;
254         bool rc = false;
255
256         /* Check if token bucket is empty and cannot be refilled
257          * without taking the spinlock. The READ_ONCE() are paired
258          * with the following WRITE_ONCE() in this same function.
259          */
260         if (!READ_ONCE(icmp_global.credit)) {
261                 delta = min_t(u32, now - READ_ONCE(icmp_global.stamp), HZ);
262                 if (delta < HZ / 50)
263                         return false;
264         }
265
266         spin_lock(&icmp_global.lock);
267         delta = min_t(u32, now - icmp_global.stamp, HZ);
268         if (delta >= HZ / 50) {
269                 incr = READ_ONCE(sysctl_icmp_msgs_per_sec) * delta / HZ;
270                 if (incr)
271                         WRITE_ONCE(icmp_global.stamp, now);
272         }
273         credit = min_t(u32, icmp_global.credit + incr,
274                        READ_ONCE(sysctl_icmp_msgs_burst));
275         if (credit) {
276                 /* We want to use a credit of one in average, but need to randomize
277                  * it for security reasons.
278                  */
279                 credit = max_t(int, credit - prandom_u32_max(3), 0);
280                 rc = true;
281         }
282         WRITE_ONCE(icmp_global.credit, credit);
283         spin_unlock(&icmp_global.lock);
284         return rc;
285 }
286 EXPORT_SYMBOL(icmp_global_allow);
287
288 static bool icmpv4_mask_allow(struct net *net, int type, int code)
289 {
290         if (type > NR_ICMP_TYPES)
291                 return true;
292
293         /* Don't limit PMTU discovery. */
294         if (type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED)
295                 return true;
296
297         /* Limit if icmp type is enabled in ratemask. */
298         if (!((1 << type) & READ_ONCE(net->ipv4.sysctl_icmp_ratemask)))
299                 return true;
300
301         return false;
302 }
303
304 static bool icmpv4_global_allow(struct net *net, int type, int code)
305 {
306         if (icmpv4_mask_allow(net, type, code))
307                 return true;
308
309         if (icmp_global_allow())
310                 return true;
311
312         return false;
313 }
314
315 /*
316  *      Send an ICMP frame.
317  */
318
319 static bool icmpv4_xrlim_allow(struct net *net, struct rtable *rt,
320                                struct flowi4 *fl4, int type, int code)
321 {
322         struct dst_entry *dst = &rt->dst;
323         struct inet_peer *peer;
324         bool rc = true;
325         int vif;
326
327         if (icmpv4_mask_allow(net, type, code))
328                 goto out;
329
330         /* No rate limit on loopback */
331         if (dst->dev && (dst->dev->flags&IFF_LOOPBACK))
332                 goto out;
333
334         vif = l3mdev_master_ifindex(dst->dev);
335         peer = inet_getpeer_v4(net->ipv4.peers, fl4->daddr, vif, 1);
336         rc = inet_peer_xrlim_allow(peer,
337                                    READ_ONCE(net->ipv4.sysctl_icmp_ratelimit));
338         if (peer)
339                 inet_putpeer(peer);
340 out:
341         return rc;
342 }
343
344 /*
345  *      Maintain the counters used in the SNMP statistics for outgoing ICMP
346  */
347 void icmp_out_count(struct net *net, unsigned char type)
348 {
349         ICMPMSGOUT_INC_STATS(net, type);
350         ICMP_INC_STATS(net, ICMP_MIB_OUTMSGS);
351 }
352
353 /*
354  *      Checksum each fragment, and on the first include the headers and final
355  *      checksum.
356  */
357 static int icmp_glue_bits(void *from, char *to, int offset, int len, int odd,
358                           struct sk_buff *skb)
359 {
360         struct icmp_bxm *icmp_param = (struct icmp_bxm *)from;
361         __wsum csum;
362
363         csum = skb_copy_and_csum_bits(icmp_param->skb,
364                                       icmp_param->offset + offset,
365                                       to, len, 0);
366
367         skb->csum = csum_block_add(skb->csum, csum, odd);
368         if (icmp_pointers[icmp_param->data.icmph.type].error)
369                 nf_ct_attach(skb, icmp_param->skb);
370         return 0;
371 }
372
373 static void icmp_push_reply(struct icmp_bxm *icmp_param,
374                             struct flowi4 *fl4,
375                             struct ipcm_cookie *ipc, struct rtable **rt)
376 {
377         struct sock *sk;
378         struct sk_buff *skb;
379
380         sk = icmp_sk(dev_net((*rt)->dst.dev));
381         if (ip_append_data(sk, fl4, icmp_glue_bits, icmp_param,
382                            icmp_param->data_len+icmp_param->head_len,
383                            icmp_param->head_len,
384                            ipc, rt, MSG_DONTWAIT) < 0) {
385                 __ICMP_INC_STATS(sock_net(sk), ICMP_MIB_OUTERRORS);
386                 ip_flush_pending_frames(sk);
387         } else if ((skb = skb_peek(&sk->sk_write_queue)) != NULL) {
388                 struct icmphdr *icmph = icmp_hdr(skb);
389                 __wsum csum = 0;
390                 struct sk_buff *skb1;
391
392                 skb_queue_walk(&sk->sk_write_queue, skb1) {
393                         csum = csum_add(csum, skb1->csum);
394                 }
395                 csum = csum_partial_copy_nocheck((void *)&icmp_param->data,
396                                                  (char *)icmph,
397                                                  icmp_param->head_len, csum);
398                 icmph->checksum = csum_fold(csum);
399                 skb->ip_summed = CHECKSUM_NONE;
400                 ip_push_pending_frames(sk, fl4);
401         }
402 }
403
404 /*
405  *      Driving logic for building and sending ICMP messages.
406  */
407
408 static void icmp_reply(struct icmp_bxm *icmp_param, struct sk_buff *skb)
409 {
410         struct ipcm_cookie ipc;
411         struct rtable *rt = skb_rtable(skb);
412         struct net *net = dev_net(rt->dst.dev);
413         struct flowi4 fl4;
414         struct sock *sk;
415         struct inet_sock *inet;
416         __be32 daddr, saddr;
417         u32 mark = IP4_REPLY_MARK(net, skb->mark);
418         int type = icmp_param->data.icmph.type;
419         int code = icmp_param->data.icmph.code;
420
421         if (ip_options_echo(net, &icmp_param->replyopts.opt.opt, skb))
422                 return;
423
424         /* Needed by both icmp_global_allow and icmp_xmit_lock */
425         local_bh_disable();
426
427         /* global icmp_msgs_per_sec */
428         if (!icmpv4_global_allow(net, type, code))
429                 goto out_bh_enable;
430
431         sk = icmp_xmit_lock(net);
432         if (!sk)
433                 goto out_bh_enable;
434         inet = inet_sk(sk);
435
436         icmp_param->data.icmph.checksum = 0;
437
438         ipcm_init(&ipc);
439         inet->tos = ip_hdr(skb)->tos;
440         sk->sk_mark = mark;
441         daddr = ipc.addr = ip_hdr(skb)->saddr;
442         saddr = fib_compute_spec_dst(skb);
443
444         if (icmp_param->replyopts.opt.opt.optlen) {
445                 ipc.opt = &icmp_param->replyopts.opt;
446                 if (ipc.opt->opt.srr)
447                         daddr = icmp_param->replyopts.opt.opt.faddr;
448         }
449         memset(&fl4, 0, sizeof(fl4));
450         fl4.daddr = daddr;
451         fl4.saddr = saddr;
452         fl4.flowi4_mark = mark;
453         fl4.flowi4_uid = sock_net_uid(net, NULL);
454         fl4.flowi4_tos = RT_TOS(ip_hdr(skb)->tos);
455         fl4.flowi4_proto = IPPROTO_ICMP;
456         fl4.flowi4_oif = l3mdev_master_ifindex(skb->dev);
457         security_skb_classify_flow(skb, flowi4_to_flowi(&fl4));
458         rt = ip_route_output_key(net, &fl4);
459         if (IS_ERR(rt))
460                 goto out_unlock;
461         if (icmpv4_xrlim_allow(net, rt, &fl4, type, code))
462                 icmp_push_reply(icmp_param, &fl4, &ipc, &rt);
463         ip_rt_put(rt);
464 out_unlock:
465         icmp_xmit_unlock(sk);
466 out_bh_enable:
467         local_bh_enable();
468 }
469
470 /*
471  * The device used for looking up which routing table to use for sending an ICMP
472  * error is preferably the source whenever it is set, which should ensure the
473  * icmp error can be sent to the source host, else lookup using the routing
474  * table of the destination device, else use the main routing table (index 0).
475  */
476 static struct net_device *icmp_get_route_lookup_dev(struct sk_buff *skb)
477 {
478         struct net_device *route_lookup_dev = NULL;
479
480         if (skb->dev)
481                 route_lookup_dev = skb->dev;
482         else if (skb_dst(skb))
483                 route_lookup_dev = skb_dst(skb)->dev;
484         return route_lookup_dev;
485 }
486
487 static struct rtable *icmp_route_lookup(struct net *net,
488                                         struct flowi4 *fl4,
489                                         struct sk_buff *skb_in,
490                                         const struct iphdr *iph,
491                                         __be32 saddr, u8 tos, u32 mark,
492                                         int type, int code,
493                                         struct icmp_bxm *param)
494 {
495         struct net_device *route_lookup_dev;
496         struct rtable *rt, *rt2;
497         struct flowi4 fl4_dec;
498         int err;
499
500         memset(fl4, 0, sizeof(*fl4));
501         fl4->daddr = (param->replyopts.opt.opt.srr ?
502                       param->replyopts.opt.opt.faddr : iph->saddr);
503         fl4->saddr = saddr;
504         fl4->flowi4_mark = mark;
505         fl4->flowi4_uid = sock_net_uid(net, NULL);
506         fl4->flowi4_tos = RT_TOS(tos);
507         fl4->flowi4_proto = IPPROTO_ICMP;
508         fl4->fl4_icmp_type = type;
509         fl4->fl4_icmp_code = code;
510         route_lookup_dev = icmp_get_route_lookup_dev(skb_in);
511         fl4->flowi4_oif = l3mdev_master_ifindex(route_lookup_dev);
512
513         security_skb_classify_flow(skb_in, flowi4_to_flowi(fl4));
514         rt = ip_route_output_key_hash(net, fl4, skb_in);
515         if (IS_ERR(rt))
516                 return rt;
517
518         /* No need to clone since we're just using its address. */
519         rt2 = rt;
520
521         rt = (struct rtable *) xfrm_lookup(net, &rt->dst,
522                                            flowi4_to_flowi(fl4), NULL, 0);
523         if (!IS_ERR(rt)) {
524                 if (rt != rt2)
525                         return rt;
526         } else if (PTR_ERR(rt) == -EPERM) {
527                 rt = NULL;
528         } else
529                 return rt;
530
531         err = xfrm_decode_session_reverse(skb_in, flowi4_to_flowi(&fl4_dec), AF_INET);
532         if (err)
533                 goto relookup_failed;
534
535         if (inet_addr_type_dev_table(net, route_lookup_dev,
536                                      fl4_dec.saddr) == RTN_LOCAL) {
537                 rt2 = __ip_route_output_key(net, &fl4_dec);
538                 if (IS_ERR(rt2))
539                         err = PTR_ERR(rt2);
540         } else {
541                 struct flowi4 fl4_2 = {};
542                 unsigned long orefdst;
543
544                 fl4_2.daddr = fl4_dec.saddr;
545                 rt2 = ip_route_output_key(net, &fl4_2);
546                 if (IS_ERR(rt2)) {
547                         err = PTR_ERR(rt2);
548                         goto relookup_failed;
549                 }
550                 /* Ugh! */
551                 orefdst = skb_in->_skb_refdst; /* save old refdst */
552                 skb_dst_set(skb_in, NULL);
553                 err = ip_route_input(skb_in, fl4_dec.daddr, fl4_dec.saddr,
554                                      RT_TOS(tos), rt2->dst.dev);
555
556                 dst_release(&rt2->dst);
557                 rt2 = skb_rtable(skb_in);
558                 skb_in->_skb_refdst = orefdst; /* restore old refdst */
559         }
560
561         if (err)
562                 goto relookup_failed;
563
564         rt2 = (struct rtable *) xfrm_lookup(net, &rt2->dst,
565                                             flowi4_to_flowi(&fl4_dec), NULL,
566                                             XFRM_LOOKUP_ICMP);
567         if (!IS_ERR(rt2)) {
568                 dst_release(&rt->dst);
569                 memcpy(fl4, &fl4_dec, sizeof(*fl4));
570                 rt = rt2;
571         } else if (PTR_ERR(rt2) == -EPERM) {
572                 if (rt)
573                         dst_release(&rt->dst);
574                 return rt2;
575         } else {
576                 err = PTR_ERR(rt2);
577                 goto relookup_failed;
578         }
579         return rt;
580
581 relookup_failed:
582         if (rt)
583                 return rt;
584         return ERR_PTR(err);
585 }
586
587 /*
588  *      Send an ICMP message in response to a situation
589  *
590  *      RFC 1122: 3.2.2 MUST send at least the IP header and 8 bytes of header.
591  *                MAY send more (we do).
592  *                      MUST NOT change this header information.
593  *                      MUST NOT reply to a multicast/broadcast IP address.
594  *                      MUST NOT reply to a multicast/broadcast MAC address.
595  *                      MUST reply to only the first fragment.
596  */
597
598 void __icmp_send(struct sk_buff *skb_in, int type, int code, __be32 info,
599                  const struct ip_options *opt)
600 {
601         struct iphdr *iph;
602         int room;
603         struct icmp_bxm icmp_param;
604         struct rtable *rt = skb_rtable(skb_in);
605         struct ipcm_cookie ipc;
606         struct flowi4 fl4;
607         __be32 saddr;
608         u8  tos;
609         u32 mark;
610         struct net *net;
611         struct sock *sk;
612
613         if (!rt)
614                 goto out;
615
616         if (rt->dst.dev)
617                 net = dev_net(rt->dst.dev);
618         else if (skb_in->dev)
619                 net = dev_net(skb_in->dev);
620         else
621                 goto out;
622
623         /*
624          *      Find the original header. It is expected to be valid, of course.
625          *      Check this, icmp_send is called from the most obscure devices
626          *      sometimes.
627          */
628         iph = ip_hdr(skb_in);
629
630         if ((u8 *)iph < skb_in->head ||
631             (skb_network_header(skb_in) + sizeof(*iph)) >
632             skb_tail_pointer(skb_in))
633                 goto out;
634
635         /*
636          *      No replies to physical multicast/broadcast
637          */
638         if (skb_in->pkt_type != PACKET_HOST)
639                 goto out;
640
641         /*
642          *      Now check at the protocol level
643          */
644         if (rt->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST))
645                 goto out;
646
647         /*
648          *      Only reply to fragment 0. We byte re-order the constant
649          *      mask for efficiency.
650          */
651         if (iph->frag_off & htons(IP_OFFSET))
652                 goto out;
653
654         /*
655          *      If we send an ICMP error to an ICMP error a mess would result..
656          */
657         if (icmp_pointers[type].error) {
658                 /*
659                  *      We are an error, check if we are replying to an
660                  *      ICMP error
661                  */
662                 if (iph->protocol == IPPROTO_ICMP) {
663                         u8 _inner_type, *itp;
664
665                         itp = skb_header_pointer(skb_in,
666                                                  skb_network_header(skb_in) +
667                                                  (iph->ihl << 2) +
668                                                  offsetof(struct icmphdr,
669                                                           type) -
670                                                  skb_in->data,
671                                                  sizeof(_inner_type),
672                                                  &_inner_type);
673                         if (!itp)
674                                 goto out;
675
676                         /*
677                          *      Assume any unknown ICMP type is an error. This
678                          *      isn't specified by the RFC, but think about it..
679                          */
680                         if (*itp > NR_ICMP_TYPES ||
681                             icmp_pointers[*itp].error)
682                                 goto out;
683                 }
684         }
685
686         /* Needed by both icmp_global_allow and icmp_xmit_lock */
687         local_bh_disable();
688
689         /* Check global sysctl_icmp_msgs_per_sec ratelimit, unless
690          * incoming dev is loopback.  If outgoing dev change to not be
691          * loopback, then peer ratelimit still work (in icmpv4_xrlim_allow)
692          */
693         if (!(skb_in->dev && (skb_in->dev->flags&IFF_LOOPBACK)) &&
694               !icmpv4_global_allow(net, type, code))
695                 goto out_bh_enable;
696
697         sk = icmp_xmit_lock(net);
698         if (!sk)
699                 goto out_bh_enable;
700
701         /*
702          *      Construct source address and options.
703          */
704
705         saddr = iph->daddr;
706         if (!(rt->rt_flags & RTCF_LOCAL)) {
707                 struct net_device *dev = NULL;
708
709                 rcu_read_lock();
710                 if (rt_is_input_route(rt) &&
711                     net->ipv4.sysctl_icmp_errors_use_inbound_ifaddr)
712                         dev = dev_get_by_index_rcu(net, inet_iif(skb_in));
713
714                 if (dev)
715                         saddr = inet_select_addr(dev, 0, RT_SCOPE_LINK);
716                 else
717                         saddr = 0;
718                 rcu_read_unlock();
719         }
720
721         tos = icmp_pointers[type].error ? ((iph->tos & IPTOS_TOS_MASK) |
722                                            IPTOS_PREC_INTERNETCONTROL) :
723                                           iph->tos;
724         mark = IP4_REPLY_MARK(net, skb_in->mark);
725
726         if (__ip_options_echo(net, &icmp_param.replyopts.opt.opt, skb_in, opt))
727                 goto out_unlock;
728
729
730         /*
731          *      Prepare data for ICMP header.
732          */
733
734         icmp_param.data.icmph.type       = type;
735         icmp_param.data.icmph.code       = code;
736         icmp_param.data.icmph.un.gateway = info;
737         icmp_param.data.icmph.checksum   = 0;
738         icmp_param.skb    = skb_in;
739         icmp_param.offset = skb_network_offset(skb_in);
740         inet_sk(sk)->tos = tos;
741         sk->sk_mark = mark;
742         ipcm_init(&ipc);
743         ipc.addr = iph->saddr;
744         ipc.opt = &icmp_param.replyopts.opt;
745
746         rt = icmp_route_lookup(net, &fl4, skb_in, iph, saddr, tos, mark,
747                                type, code, &icmp_param);
748         if (IS_ERR(rt))
749                 goto out_unlock;
750
751         /* peer icmp_ratelimit */
752         if (!icmpv4_xrlim_allow(net, rt, &fl4, type, code))
753                 goto ende;
754
755         /* RFC says return as much as we can without exceeding 576 bytes. */
756
757         room = dst_mtu(&rt->dst);
758         if (room > 576)
759                 room = 576;
760         room -= sizeof(struct iphdr) + icmp_param.replyopts.opt.opt.optlen;
761         room -= sizeof(struct icmphdr);
762         /* Guard against tiny mtu. We need to include at least one
763          * IP network header for this message to make any sense.
764          */
765         if (room <= (int)sizeof(struct iphdr))
766                 goto ende;
767
768         icmp_param.data_len = skb_in->len - icmp_param.offset;
769         if (icmp_param.data_len > room)
770                 icmp_param.data_len = room;
771         icmp_param.head_len = sizeof(struct icmphdr);
772
773         /* if we don't have a source address at this point, fall back to the
774          * dummy address instead of sending out a packet with a source address
775          * of 0.0.0.0
776          */
777         if (!fl4.saddr)
778                 fl4.saddr = htonl(INADDR_DUMMY);
779
780         icmp_push_reply(&icmp_param, &fl4, &ipc, &rt);
781 ende:
782         ip_rt_put(rt);
783 out_unlock:
784         icmp_xmit_unlock(sk);
785 out_bh_enable:
786         local_bh_enable();
787 out:;
788 }
789 EXPORT_SYMBOL(__icmp_send);
790
791 #if IS_ENABLED(CONFIG_NF_NAT)
792 #include <net/netfilter/nf_conntrack.h>
793 void icmp_ndo_send(struct sk_buff *skb_in, int type, int code, __be32 info)
794 {
795         struct sk_buff *cloned_skb = NULL;
796         struct ip_options opts = { 0 };
797         enum ip_conntrack_info ctinfo;
798         struct nf_conn *ct;
799         __be32 orig_ip;
800
801         ct = nf_ct_get(skb_in, &ctinfo);
802         if (!ct || !(ct->status & IPS_SRC_NAT)) {
803                 __icmp_send(skb_in, type, code, info, &opts);
804                 return;
805         }
806
807         if (skb_shared(skb_in))
808                 skb_in = cloned_skb = skb_clone(skb_in, GFP_ATOMIC);
809
810         if (unlikely(!skb_in || skb_network_header(skb_in) < skb_in->head ||
811             (skb_network_header(skb_in) + sizeof(struct iphdr)) >
812             skb_tail_pointer(skb_in) || skb_ensure_writable(skb_in,
813             skb_network_offset(skb_in) + sizeof(struct iphdr))))
814                 goto out;
815
816         orig_ip = ip_hdr(skb_in)->saddr;
817         ip_hdr(skb_in)->saddr = ct->tuplehash[0].tuple.src.u3.ip;
818         __icmp_send(skb_in, type, code, info, &opts);
819         ip_hdr(skb_in)->saddr = orig_ip;
820 out:
821         consume_skb(cloned_skb);
822 }
823 EXPORT_SYMBOL(icmp_ndo_send);
824 #endif
825
826 static void icmp_socket_deliver(struct sk_buff *skb, u32 info)
827 {
828         const struct iphdr *iph = (const struct iphdr *) skb->data;
829         const struct net_protocol *ipprot;
830         int protocol = iph->protocol;
831
832         /* Checkin full IP header plus 8 bytes of protocol to
833          * avoid additional coding at protocol handlers.
834          */
835         if (!pskb_may_pull(skb, iph->ihl * 4 + 8)) {
836                 __ICMP_INC_STATS(dev_net(skb->dev), ICMP_MIB_INERRORS);
837                 return;
838         }
839
840         raw_icmp_error(skb, protocol, info);
841
842         ipprot = rcu_dereference(inet_protos[protocol]);
843         if (ipprot && ipprot->err_handler)
844                 ipprot->err_handler(skb, info);
845 }
846
847 static bool icmp_tag_validation(int proto)
848 {
849         bool ok;
850
851         rcu_read_lock();
852         ok = rcu_dereference(inet_protos[proto])->icmp_strict_tag_validation;
853         rcu_read_unlock();
854         return ok;
855 }
856
857 /*
858  *      Handle ICMP_DEST_UNREACH, ICMP_TIME_EXCEEDED, ICMP_QUENCH, and
859  *      ICMP_PARAMETERPROB.
860  */
861
862 static bool icmp_unreach(struct sk_buff *skb)
863 {
864         const struct iphdr *iph;
865         struct icmphdr *icmph;
866         struct net *net;
867         u32 info = 0;
868
869         net = dev_net(skb_dst(skb)->dev);
870
871         /*
872          *      Incomplete header ?
873          *      Only checks for the IP header, there should be an
874          *      additional check for longer headers in upper levels.
875          */
876
877         if (!pskb_may_pull(skb, sizeof(struct iphdr)))
878                 goto out_err;
879
880         icmph = icmp_hdr(skb);
881         iph   = (const struct iphdr *)skb->data;
882
883         if (iph->ihl < 5) /* Mangled header, drop. */
884                 goto out_err;
885
886         switch (icmph->type) {
887         case ICMP_DEST_UNREACH:
888                 switch (icmph->code & 15) {
889                 case ICMP_NET_UNREACH:
890                 case ICMP_HOST_UNREACH:
891                 case ICMP_PROT_UNREACH:
892                 case ICMP_PORT_UNREACH:
893                         break;
894                 case ICMP_FRAG_NEEDED:
895                         /* for documentation of the ip_no_pmtu_disc
896                          * values please see
897                          * Documentation/networking/ip-sysctl.txt
898                          */
899                         switch (net->ipv4.sysctl_ip_no_pmtu_disc) {
900                         default:
901                                 net_dbg_ratelimited("%pI4: fragmentation needed and DF set\n",
902                                                     &iph->daddr);
903                                 break;
904                         case 2:
905                                 goto out;
906                         case 3:
907                                 if (!icmp_tag_validation(iph->protocol))
908                                         goto out;
909                                 /* fall through */
910                         case 0:
911                                 info = ntohs(icmph->un.frag.mtu);
912                         }
913                         break;
914                 case ICMP_SR_FAILED:
915                         net_dbg_ratelimited("%pI4: Source Route Failed\n",
916                                             &iph->daddr);
917                         break;
918                 default:
919                         break;
920                 }
921                 if (icmph->code > NR_ICMP_UNREACH)
922                         goto out;
923                 break;
924         case ICMP_PARAMETERPROB:
925                 info = ntohl(icmph->un.gateway) >> 24;
926                 break;
927         case ICMP_TIME_EXCEEDED:
928                 __ICMP_INC_STATS(net, ICMP_MIB_INTIMEEXCDS);
929                 if (icmph->code == ICMP_EXC_FRAGTIME)
930                         goto out;
931                 break;
932         }
933
934         /*
935          *      Throw it at our lower layers
936          *
937          *      RFC 1122: 3.2.2 MUST extract the protocol ID from the passed
938          *                header.
939          *      RFC 1122: 3.2.2.1 MUST pass ICMP unreach messages to the
940          *                transport layer.
941          *      RFC 1122: 3.2.2.2 MUST pass ICMP time expired messages to
942          *                transport layer.
943          */
944
945         /*
946          *      Check the other end isn't violating RFC 1122. Some routers send
947          *      bogus responses to broadcast frames. If you see this message
948          *      first check your netmask matches at both ends, if it does then
949          *      get the other vendor to fix their kit.
950          */
951
952         if (!net->ipv4.sysctl_icmp_ignore_bogus_error_responses &&
953             inet_addr_type_dev_table(net, skb->dev, iph->daddr) == RTN_BROADCAST) {
954                 net_warn_ratelimited("%pI4 sent an invalid ICMP type %u, code %u error to a broadcast: %pI4 on %s\n",
955                                      &ip_hdr(skb)->saddr,
956                                      icmph->type, icmph->code,
957                                      &iph->daddr, skb->dev->name);
958                 goto out;
959         }
960
961         icmp_socket_deliver(skb, info);
962
963 out:
964         return true;
965 out_err:
966         __ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
967         return false;
968 }
969
970
971 /*
972  *      Handle ICMP_REDIRECT.
973  */
974
975 static bool icmp_redirect(struct sk_buff *skb)
976 {
977         if (skb->len < sizeof(struct iphdr)) {
978                 __ICMP_INC_STATS(dev_net(skb->dev), ICMP_MIB_INERRORS);
979                 return false;
980         }
981
982         if (!pskb_may_pull(skb, sizeof(struct iphdr))) {
983                 /* there aught to be a stat */
984                 return false;
985         }
986
987         icmp_socket_deliver(skb, icmp_hdr(skb)->un.gateway);
988         return true;
989 }
990
991 /*
992  *      Handle ICMP_ECHO ("ping") requests.
993  *
994  *      RFC 1122: 3.2.2.6 MUST have an echo server that answers ICMP echo
995  *                requests.
996  *      RFC 1122: 3.2.2.6 Data received in the ICMP_ECHO request MUST be
997  *                included in the reply.
998  *      RFC 1812: 4.3.3.6 SHOULD have a config option for silently ignoring
999  *                echo requests, MUST have default=NOT.
1000  *      See also WRT handling of options once they are done and working.
1001  */
1002
1003 static bool icmp_echo(struct sk_buff *skb)
1004 {
1005         struct net *net;
1006
1007         net = dev_net(skb_dst(skb)->dev);
1008         if (!net->ipv4.sysctl_icmp_echo_ignore_all) {
1009                 struct icmp_bxm icmp_param;
1010
1011                 icmp_param.data.icmph      = *icmp_hdr(skb);
1012                 icmp_param.data.icmph.type = ICMP_ECHOREPLY;
1013                 icmp_param.skb             = skb;
1014                 icmp_param.offset          = 0;
1015                 icmp_param.data_len        = skb->len;
1016                 icmp_param.head_len        = sizeof(struct icmphdr);
1017                 icmp_reply(&icmp_param, skb);
1018         }
1019         /* should there be an ICMP stat for ignored echos? */
1020         return true;
1021 }
1022
1023 /*
1024  *      Handle ICMP Timestamp requests.
1025  *      RFC 1122: 3.2.2.8 MAY implement ICMP timestamp requests.
1026  *                SHOULD be in the kernel for minimum random latency.
1027  *                MUST be accurate to a few minutes.
1028  *                MUST be updated at least at 15Hz.
1029  */
1030 static bool icmp_timestamp(struct sk_buff *skb)
1031 {
1032         struct icmp_bxm icmp_param;
1033         /*
1034          *      Too short.
1035          */
1036         if (skb->len < 4)
1037                 goto out_err;
1038
1039         /*
1040          *      Fill in the current time as ms since midnight UT:
1041          */
1042         icmp_param.data.times[1] = inet_current_timestamp();
1043         icmp_param.data.times[2] = icmp_param.data.times[1];
1044
1045         BUG_ON(skb_copy_bits(skb, 0, &icmp_param.data.times[0], 4));
1046
1047         icmp_param.data.icmph      = *icmp_hdr(skb);
1048         icmp_param.data.icmph.type = ICMP_TIMESTAMPREPLY;
1049         icmp_param.data.icmph.code = 0;
1050         icmp_param.skb             = skb;
1051         icmp_param.offset          = 0;
1052         icmp_param.data_len        = 0;
1053         icmp_param.head_len        = sizeof(struct icmphdr) + 12;
1054         icmp_reply(&icmp_param, skb);
1055         return true;
1056
1057 out_err:
1058         __ICMP_INC_STATS(dev_net(skb_dst(skb)->dev), ICMP_MIB_INERRORS);
1059         return false;
1060 }
1061
1062 static bool icmp_discard(struct sk_buff *skb)
1063 {
1064         /* pretend it was a success */
1065         return true;
1066 }
1067
1068 /*
1069  *      Deal with incoming ICMP packets.
1070  */
1071 int icmp_rcv(struct sk_buff *skb)
1072 {
1073         struct icmphdr *icmph;
1074         struct rtable *rt = skb_rtable(skb);
1075         struct net *net = dev_net(rt->dst.dev);
1076         bool success;
1077
1078         if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) {
1079                 struct sec_path *sp = skb_sec_path(skb);
1080                 int nh;
1081
1082                 if (!(sp && sp->xvec[sp->len - 1]->props.flags &
1083                                  XFRM_STATE_ICMP))
1084                         goto drop;
1085
1086                 if (!pskb_may_pull(skb, sizeof(*icmph) + sizeof(struct iphdr)))
1087                         goto drop;
1088
1089                 nh = skb_network_offset(skb);
1090                 skb_set_network_header(skb, sizeof(*icmph));
1091
1092                 if (!xfrm4_policy_check_reverse(NULL, XFRM_POLICY_IN, skb))
1093                         goto drop;
1094
1095                 skb_set_network_header(skb, nh);
1096         }
1097
1098         __ICMP_INC_STATS(net, ICMP_MIB_INMSGS);
1099
1100         if (skb_checksum_simple_validate(skb))
1101                 goto csum_error;
1102
1103         if (!pskb_pull(skb, sizeof(*icmph)))
1104                 goto error;
1105
1106         icmph = icmp_hdr(skb);
1107
1108         ICMPMSGIN_INC_STATS(net, icmph->type);
1109         /*
1110          *      18 is the highest 'known' ICMP type. Anything else is a mystery
1111          *
1112          *      RFC 1122: 3.2.2  Unknown ICMP messages types MUST be silently
1113          *                discarded.
1114          */
1115         if (icmph->type > NR_ICMP_TYPES)
1116                 goto error;
1117
1118
1119         /*
1120          *      Parse the ICMP message
1121          */
1122
1123         if (rt->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST)) {
1124                 /*
1125                  *      RFC 1122: 3.2.2.6 An ICMP_ECHO to broadcast MAY be
1126                  *        silently ignored (we let user decide with a sysctl).
1127                  *      RFC 1122: 3.2.2.8 An ICMP_TIMESTAMP MAY be silently
1128                  *        discarded if to broadcast/multicast.
1129                  */
1130                 if ((icmph->type == ICMP_ECHO ||
1131                      icmph->type == ICMP_TIMESTAMP) &&
1132                     net->ipv4.sysctl_icmp_echo_ignore_broadcasts) {
1133                         goto error;
1134                 }
1135                 if (icmph->type != ICMP_ECHO &&
1136                     icmph->type != ICMP_TIMESTAMP &&
1137                     icmph->type != ICMP_ADDRESS &&
1138                     icmph->type != ICMP_ADDRESSREPLY) {
1139                         goto error;
1140                 }
1141         }
1142
1143         success = icmp_pointers[icmph->type].handler(skb);
1144
1145         if (success)  {
1146                 consume_skb(skb);
1147                 return NET_RX_SUCCESS;
1148         }
1149
1150 drop:
1151         kfree_skb(skb);
1152         return NET_RX_DROP;
1153 csum_error:
1154         __ICMP_INC_STATS(net, ICMP_MIB_CSUMERRORS);
1155 error:
1156         __ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
1157         goto drop;
1158 }
1159
1160 void icmp_err(struct sk_buff *skb, u32 info)
1161 {
1162         struct iphdr *iph = (struct iphdr *)skb->data;
1163         int offset = iph->ihl<<2;
1164         struct icmphdr *icmph = (struct icmphdr *)(skb->data + offset);
1165         int type = icmp_hdr(skb)->type;
1166         int code = icmp_hdr(skb)->code;
1167         struct net *net = dev_net(skb->dev);
1168
1169         /*
1170          * Use ping_err to handle all icmp errors except those
1171          * triggered by ICMP_ECHOREPLY which sent from kernel.
1172          */
1173         if (icmph->type != ICMP_ECHOREPLY) {
1174                 ping_err(skb, offset, info);
1175                 return;
1176         }
1177
1178         if (type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED)
1179                 ipv4_update_pmtu(skb, net, info, 0, 0, IPPROTO_ICMP, 0);
1180         else if (type == ICMP_REDIRECT)
1181                 ipv4_redirect(skb, net, 0, 0, IPPROTO_ICMP, 0);
1182 }
1183
1184 /*
1185  *      This table is the definition of how we handle ICMP.
1186  */
1187 static const struct icmp_control icmp_pointers[NR_ICMP_TYPES + 1] = {
1188         [ICMP_ECHOREPLY] = {
1189                 .handler = ping_rcv,
1190         },
1191         [1] = {
1192                 .handler = icmp_discard,
1193                 .error = 1,
1194         },
1195         [2] = {
1196                 .handler = icmp_discard,
1197                 .error = 1,
1198         },
1199         [ICMP_DEST_UNREACH] = {
1200                 .handler = icmp_unreach,
1201                 .error = 1,
1202         },
1203         [ICMP_SOURCE_QUENCH] = {
1204                 .handler = icmp_unreach,
1205                 .error = 1,
1206         },
1207         [ICMP_REDIRECT] = {
1208                 .handler = icmp_redirect,
1209                 .error = 1,
1210         },
1211         [6] = {
1212                 .handler = icmp_discard,
1213                 .error = 1,
1214         },
1215         [7] = {
1216                 .handler = icmp_discard,
1217                 .error = 1,
1218         },
1219         [ICMP_ECHO] = {
1220                 .handler = icmp_echo,
1221         },
1222         [9] = {
1223                 .handler = icmp_discard,
1224                 .error = 1,
1225         },
1226         [10] = {
1227                 .handler = icmp_discard,
1228                 .error = 1,
1229         },
1230         [ICMP_TIME_EXCEEDED] = {
1231                 .handler = icmp_unreach,
1232                 .error = 1,
1233         },
1234         [ICMP_PARAMETERPROB] = {
1235                 .handler = icmp_unreach,
1236                 .error = 1,
1237         },
1238         [ICMP_TIMESTAMP] = {
1239                 .handler = icmp_timestamp,
1240         },
1241         [ICMP_TIMESTAMPREPLY] = {
1242                 .handler = icmp_discard,
1243         },
1244         [ICMP_INFO_REQUEST] = {
1245                 .handler = icmp_discard,
1246         },
1247         [ICMP_INFO_REPLY] = {
1248                 .handler = icmp_discard,
1249         },
1250         [ICMP_ADDRESS] = {
1251                 .handler = icmp_discard,
1252         },
1253         [ICMP_ADDRESSREPLY] = {
1254                 .handler = icmp_discard,
1255         },
1256 };
1257
1258 static void __net_exit icmp_sk_exit(struct net *net)
1259 {
1260         int i;
1261
1262         for_each_possible_cpu(i)
1263                 inet_ctl_sock_destroy(*per_cpu_ptr(net->ipv4.icmp_sk, i));
1264         free_percpu(net->ipv4.icmp_sk);
1265         net->ipv4.icmp_sk = NULL;
1266 }
1267
1268 static int __net_init icmp_sk_init(struct net *net)
1269 {
1270         int i, err;
1271
1272         net->ipv4.icmp_sk = alloc_percpu(struct sock *);
1273         if (!net->ipv4.icmp_sk)
1274                 return -ENOMEM;
1275
1276         for_each_possible_cpu(i) {
1277                 struct sock *sk;
1278
1279                 err = inet_ctl_sock_create(&sk, PF_INET,
1280                                            SOCK_RAW, IPPROTO_ICMP, net);
1281                 if (err < 0)
1282                         goto fail;
1283
1284                 *per_cpu_ptr(net->ipv4.icmp_sk, i) = sk;
1285
1286                 /* Enough space for 2 64K ICMP packets, including
1287                  * sk_buff/skb_shared_info struct overhead.
1288                  */
1289                 sk->sk_sndbuf = 2 * SKB_TRUESIZE(64 * 1024);
1290
1291                 /*
1292                  * Speedup sock_wfree()
1293                  */
1294                 sock_set_flag(sk, SOCK_USE_WRITE_QUEUE);
1295                 inet_sk(sk)->pmtudisc = IP_PMTUDISC_DONT;
1296         }
1297
1298         /* Control parameters for ECHO replies. */
1299         net->ipv4.sysctl_icmp_echo_ignore_all = 0;
1300         net->ipv4.sysctl_icmp_echo_ignore_broadcasts = 1;
1301
1302         /* Control parameter - ignore bogus broadcast responses? */
1303         net->ipv4.sysctl_icmp_ignore_bogus_error_responses = 1;
1304
1305         /*
1306          *      Configurable global rate limit.
1307          *
1308          *      ratelimit defines tokens/packet consumed for dst->rate_token
1309          *      bucket ratemask defines which icmp types are ratelimited by
1310          *      setting it's bit position.
1311          *
1312          *      default:
1313          *      dest unreachable (3), source quench (4),
1314          *      time exceeded (11), parameter problem (12)
1315          */
1316
1317         net->ipv4.sysctl_icmp_ratelimit = 1 * HZ;
1318         net->ipv4.sysctl_icmp_ratemask = 0x1818;
1319         net->ipv4.sysctl_icmp_errors_use_inbound_ifaddr = 0;
1320
1321         return 0;
1322
1323 fail:
1324         for_each_possible_cpu(i)
1325                 inet_ctl_sock_destroy(*per_cpu_ptr(net->ipv4.icmp_sk, i));
1326         free_percpu(net->ipv4.icmp_sk);
1327         return err;
1328 }
1329
1330 static struct pernet_operations __net_initdata icmp_sk_ops = {
1331        .init = icmp_sk_init,
1332        .exit = icmp_sk_exit,
1333 };
1334
1335 int __init icmp_init(void)
1336 {
1337         return register_pernet_subsys(&icmp_sk_ops);
1338 }