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