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