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