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
 462static struct rtable *icmp_route_lookup(struct net *net,
 463                                        struct flowi4 *fl4,
 464                                        struct sk_buff *skb_in,
 465                                        const struct iphdr *iph,
 466                                        __be32 saddr, u8 tos, u32 mark,
 467                                        int type, int code,
 468                                        struct icmp_bxm *param)
 469{
 470        struct rtable *rt, *rt2;
 471        struct flowi4 fl4_dec;
 472        int err;
 473
 474        memset(fl4, 0, sizeof(*fl4));
 475        fl4->daddr = (param->replyopts.opt.opt.srr ?
 476                      param->replyopts.opt.opt.faddr : iph->saddr);
 477        fl4->saddr = saddr;
 478        fl4->flowi4_mark = mark;
 479        fl4->flowi4_tos = RT_TOS(tos);
 480        fl4->flowi4_proto = IPPROTO_ICMP;
 481        fl4->fl4_icmp_type = type;
 482        fl4->fl4_icmp_code = code;
 483        security_skb_classify_flow(skb_in, flowi4_to_flowi(fl4));
 484        rt = __ip_route_output_key_hash(net, fl4, skb_in);
 485        if (IS_ERR(rt))
 486                return rt;
 487
 488        /* No need to clone since we're just using its address. */
 489        rt2 = rt;
 490
 491        rt = (struct rtable *) xfrm_lookup(net, &rt->dst,
 492                                           flowi4_to_flowi(fl4), NULL, 0);
 493        if (!IS_ERR(rt)) {
 494                if (rt != rt2)
 495                        return rt;
 496        } else if (PTR_ERR(rt) == -EPERM) {
 497                rt = NULL;
 498        } else
 499                return rt;
 500
 501        err = xfrm_decode_session_reverse(skb_in, flowi4_to_flowi(&fl4_dec), AF_INET);
 502        if (err)
 503                goto relookup_failed;
 504
 505        if (inet_addr_type(net, fl4_dec.saddr) == RTN_LOCAL) {
 506                rt2 = __ip_route_output_key(net, &fl4_dec);
 507                if (IS_ERR(rt2))
 508                        err = PTR_ERR(rt2);
 509        } else {
 510                struct flowi4 fl4_2 = {};
 511                unsigned long orefdst;
 512
 513                fl4_2.daddr = fl4_dec.saddr;
 514                rt2 = ip_route_output_key(net, &fl4_2);
 515                if (IS_ERR(rt2)) {
 516                        err = PTR_ERR(rt2);
 517                        goto relookup_failed;
 518                }
 519                /* Ugh! */
 520                orefdst = skb_in->_skb_refdst; /* save old refdst */
 521                skb_dst_set(skb_in, NULL);
 522                err = ip_route_input(skb_in, fl4_dec.daddr, fl4_dec.saddr,
 523                                     RT_TOS(tos), rt2->dst.dev);
 524
 525                dst_release(&rt2->dst);
 526                rt2 = skb_rtable(skb_in);
 527                skb_in->_skb_refdst = orefdst; /* restore old refdst */
 528        }
 529
 530        if (err)
 531                goto relookup_failed;
 532
 533        rt2 = (struct rtable *) xfrm_lookup(net, &rt2->dst,
 534                                            flowi4_to_flowi(&fl4_dec), NULL,
 535                                            XFRM_LOOKUP_ICMP);
 536        if (!IS_ERR(rt2)) {
 537                dst_release(&rt->dst);
 538                memcpy(fl4, &fl4_dec, sizeof(*fl4));
 539                rt = rt2;
 540        } else if (PTR_ERR(rt2) == -EPERM) {
 541                if (rt)
 542                        dst_release(&rt->dst);
 543                return rt2;
 544        } else {
 545                err = PTR_ERR(rt2);
 546                goto relookup_failed;
 547        }
 548        return rt;
 549
 550relookup_failed:
 551        if (rt)
 552                return rt;
 553        return ERR_PTR(err);
 554}
 555
 556/*
 557 *      Send an ICMP message in response to a situation
 558 *
 559 *      RFC 1122: 3.2.2 MUST send at least the IP header and 8 bytes of header.
 560 *                MAY send more (we do).
 561 *                      MUST NOT change this header information.
 562 *                      MUST NOT reply to a multicast/broadcast IP address.
 563 *                      MUST NOT reply to a multicast/broadcast MAC address.
 564 *                      MUST reply to only the first fragment.
 565 */
 566
 567void icmp_send(struct sk_buff *skb_in, int type, int code, __be32 info)
 568{
 569        struct iphdr *iph;
 570        int room;
 571        struct icmp_bxm icmp_param;
 572        struct rtable *rt = skb_rtable(skb_in);
 573        struct ipcm_cookie ipc;
 574        struct flowi4 fl4;
 575        __be32 saddr;
 576        u8  tos;
 577        u32 mark;
 578        struct net *net;
 579        struct sock *sk;
 580
 581        if (!rt)
 582                goto out;
 583
 584        if (rt->dst.dev)
 585                net = dev_net(rt->dst.dev);
 586        else if (skb_in->dev)
 587                net = dev_net(skb_in->dev);
 588        else
 589                goto out;
 590
 591        /*
 592         *      Find the original header. It is expected to be valid, of course.
 593         *      Check this, icmp_send is called from the most obscure devices
 594         *      sometimes.
 595         */
 596        iph = ip_hdr(skb_in);
 597
 598        if ((u8 *)iph < skb_in->head ||
 599            (skb_network_header(skb_in) + sizeof(*iph)) >
 600            skb_tail_pointer(skb_in))
 601                goto out;
 602
 603        /*
 604         *      No replies to physical multicast/broadcast
 605         */
 606        if (skb_in->pkt_type != PACKET_HOST)
 607                goto out;
 608
 609        /*
 610         *      Now check at the protocol level
 611         */
 612        if (rt->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST))
 613                goto out;
 614
 615        /*
 616         *      Only reply to fragment 0. We byte re-order the constant
 617         *      mask for efficiency.
 618         */
 619        if (iph->frag_off & htons(IP_OFFSET))
 620                goto out;
 621
 622        /*
 623         *      If we send an ICMP error to an ICMP error a mess would result..
 624         */
 625        if (icmp_pointers[type].error) {
 626                /*
 627                 *      We are an error, check if we are replying to an
 628                 *      ICMP error
 629                 */
 630                if (iph->protocol == IPPROTO_ICMP) {
 631                        u8 _inner_type, *itp;
 632
 633                        itp = skb_header_pointer(skb_in,
 634                                                 skb_network_header(skb_in) +
 635                                                 (iph->ihl << 2) +
 636                                                 offsetof(struct icmphdr,
 637                                                          type) -
 638                                                 skb_in->data,
 639                                                 sizeof(_inner_type),
 640                                                 &_inner_type);
 641                        if (itp == NULL)
 642                                goto out;
 643
 644                        /*
 645                         *      Assume any unknown ICMP type is an error. This
 646                         *      isn't specified by the RFC, but think about it..
 647                         */
 648                        if (*itp > NR_ICMP_TYPES ||
 649                            icmp_pointers[*itp].error)
 650                                goto out;
 651                }
 652        }
 653
 654        /* Needed by both icmp_global_allow and icmp_xmit_lock */
 655        local_bh_disable();
 656
 657        /* Check global sysctl_icmp_msgs_per_sec ratelimit, unless
 658         * incoming dev is loopback.  If outgoing dev change to not be
 659         * loopback, then peer ratelimit still work (in icmpv4_xrlim_allow)
 660         */
 661        if (!(skb_in->dev && (skb_in->dev->flags&IFF_LOOPBACK)) &&
 662              !icmpv4_global_allow(net, type, code))
 663                goto out_bh_enable;
 664
 665        sk = icmp_xmit_lock(net);
 666        if (!sk)
 667                goto out_bh_enable;
 668
 669        /*
 670         *      Construct source address and options.
 671         */
 672
 673        saddr = iph->daddr;
 674        if (!(rt->rt_flags & RTCF_LOCAL)) {
 675                struct net_device *dev = NULL;
 676
 677                rcu_read_lock();
 678                if (rt_is_input_route(rt) &&
 679                    net->ipv4.sysctl_icmp_errors_use_inbound_ifaddr)
 680                        dev = dev_get_by_index_rcu(net, inet_iif(skb_in));
 681
 682                if (dev)
 683                        saddr = inet_select_addr(dev, 0, RT_SCOPE_LINK);
 684                else
 685                        saddr = 0;
 686                rcu_read_unlock();
 687        }
 688
 689        tos = icmp_pointers[type].error ? ((iph->tos & IPTOS_TOS_MASK) |
 690                                           IPTOS_PREC_INTERNETCONTROL) :
 691                                          iph->tos;
 692        mark = IP4_REPLY_MARK(net, skb_in->mark);
 693
 694        if (ip_options_echo(&icmp_param.replyopts.opt.opt, skb_in))
 695                goto out_unlock;
 696
 697
 698        /*
 699         *      Prepare data for ICMP header.
 700         */
 701
 702        icmp_param.data.icmph.type       = type;
 703        icmp_param.data.icmph.code       = code;
 704        icmp_param.data.icmph.un.gateway = info;
 705        icmp_param.data.icmph.checksum   = 0;
 706        icmp_param.skb    = skb_in;
 707        icmp_param.offset = skb_network_offset(skb_in);
 708        inet_sk(sk)->tos = tos;
 709        sk->sk_mark = mark;
 710        ipc.addr = iph->saddr;
 711        ipc.opt = &icmp_param.replyopts.opt;
 712        ipc.tx_flags = 0;
 713        ipc.ttl = 0;
 714        ipc.tos = -1;
 715
 716        rt = icmp_route_lookup(net, &fl4, skb_in, iph, saddr, tos, mark,
 717                               type, code, &icmp_param);
 718        if (IS_ERR(rt))
 719                goto out_unlock;
 720
 721        /* peer icmp_ratelimit */
 722        if (!icmpv4_xrlim_allow(net, rt, &fl4, type, code))
 723                goto ende;
 724
 725        /* RFC says return as much as we can without exceeding 576 bytes. */
 726
 727        room = dst_mtu(&rt->dst);
 728        if (room > 576)
 729                room = 576;
 730        room -= sizeof(struct iphdr) + icmp_param.replyopts.opt.opt.optlen;
 731        room -= sizeof(struct icmphdr);
 732
 733        icmp_param.data_len = skb_in->len - icmp_param.offset;
 734        if (icmp_param.data_len > room)
 735                icmp_param.data_len = room;
 736        icmp_param.head_len = sizeof(struct icmphdr);
 737
 738        icmp_push_reply(&icmp_param, &fl4, &ipc, &rt);
 739ende:
 740        ip_rt_put(rt);
 741out_unlock:
 742        icmp_xmit_unlock(sk);
 743out_bh_enable:
 744        local_bh_enable();
 745out:;
 746}
 747EXPORT_SYMBOL(icmp_send);
 748
 749
 750static void icmp_socket_deliver(struct sk_buff *skb, u32 info)
 751{
 752        const struct iphdr *iph = (const struct iphdr *) skb->data;
 753        const struct net_protocol *ipprot;
 754        int protocol = iph->protocol;
 755
 756        /* Checkin full IP header plus 8 bytes of protocol to
 757         * avoid additional coding at protocol handlers.
 758         */
 759        if (!pskb_may_pull(skb, iph->ihl * 4 + 8)) {
 760                ICMP_INC_STATS_BH(dev_net(skb->dev), ICMP_MIB_INERRORS);
 761                return;
 762        }
 763
 764        raw_icmp_error(skb, protocol, info);
 765
 766        rcu_read_lock();
 767        ipprot = rcu_dereference(inet_protos[protocol]);
 768        if (ipprot && ipprot->err_handler)
 769                ipprot->err_handler(skb, info);
 770        rcu_read_unlock();
 771}
 772
 773/*
 774 *      Handle ICMP_DEST_UNREACH, ICMP_TIME_EXCEED, and ICMP_QUENCH.
 775 */
 776
 777static void icmp_unreach(struct sk_buff *skb)
 778{
 779        const struct iphdr *iph;
 780        struct icmphdr *icmph;
 781        struct net *net;
 782        u32 info = 0;
 783
 784        net = dev_net(skb_dst(skb)->dev);
 785
 786        /*
 787         *      Incomplete header ?
 788         *      Only checks for the IP header, there should be an
 789         *      additional check for longer headers in upper levels.
 790         */
 791
 792        if (!pskb_may_pull(skb, sizeof(struct iphdr)))
 793                goto out_err;
 794
 795        icmph = icmp_hdr(skb);
 796        iph   = (const struct iphdr *)skb->data;
 797
 798        if (iph->ihl < 5) /* Mangled header, drop. */
 799                goto out_err;
 800
 801        if (icmph->type == ICMP_DEST_UNREACH) {
 802                switch (icmph->code & 15) {
 803                case ICMP_NET_UNREACH:
 804                case ICMP_HOST_UNREACH:
 805                case ICMP_PROT_UNREACH:
 806                case ICMP_PORT_UNREACH:
 807                        break;
 808                case ICMP_FRAG_NEEDED:
 809                        if (net->sysctl_ip_no_pmtu_disc == 2) {
 810                                goto out;
 811                        } else if (net->sysctl_ip_no_pmtu_disc) {
 812                                LIMIT_NETDEBUG(KERN_INFO pr_fmt("%pI4: fragmentation needed and DF set\n"),
 813                                               &iph->daddr);
 814                        } else {
 815                                info = ntohs(icmph->un.frag.mtu);
 816                                if (!info)
 817                                        goto out;
 818                        }
 819                        break;
 820                case ICMP_SR_FAILED:
 821                        LIMIT_NETDEBUG(KERN_INFO pr_fmt("%pI4: Source Route Failed\n"),
 822                                       &iph->daddr);
 823                        break;
 824                default:
 825                        break;
 826                }
 827                if (icmph->code > NR_ICMP_UNREACH)
 828                        goto out;
 829        } else if (icmph->type == ICMP_PARAMETERPROB)
 830                info = ntohl(icmph->un.gateway) >> 24;
 831
 832        /*
 833         *      Throw it at our lower layers
 834         *
 835         *      RFC 1122: 3.2.2 MUST extract the protocol ID from the passed
 836         *                header.
 837         *      RFC 1122: 3.2.2.1 MUST pass ICMP unreach messages to the
 838         *                transport layer.
 839         *      RFC 1122: 3.2.2.2 MUST pass ICMP time expired messages to
 840         *                transport layer.
 841         */
 842
 843        /*
 844         *      Check the other end isn't violating RFC 1122. Some routers send
 845         *      bogus responses to broadcast frames. If you see this message
 846         *      first check your netmask matches at both ends, if it does then
 847         *      get the other vendor to fix their kit.
 848         */
 849
 850        if (!net->ipv4.sysctl_icmp_ignore_bogus_error_responses &&
 851            inet_addr_type(net, iph->daddr) == RTN_BROADCAST) {
 852                net_warn_ratelimited("%pI4 sent an invalid ICMP type %u, code %u error to a broadcast: %pI4 on %s\n",
 853                                     &ip_hdr(skb)->saddr,
 854                                     icmph->type, icmph->code,
 855                                     &iph->daddr, skb->dev->name);
 856                goto out;
 857        }
 858
 859        icmp_socket_deliver(skb, info);
 860
 861out:
 862        return;
 863out_err:
 864        ICMP_INC_STATS_BH(net, ICMP_MIB_INERRORS);
 865        goto out;
 866}
 867
 868
 869/*
 870 *      Handle ICMP_REDIRECT.
 871 */
 872
 873static void icmp_redirect(struct sk_buff *skb)
 874{
 875        if (skb->len < sizeof(struct iphdr)) {
 876                ICMP_INC_STATS_BH(dev_net(skb->dev), ICMP_MIB_INERRORS);
 877                return;
 878        }
 879
 880        if (!pskb_may_pull(skb, sizeof(struct iphdr)))
 881                return;
 882
 883        icmp_socket_deliver(skb, icmp_hdr(skb)->un.gateway);
 884}
 885
 886/*
 887 *      Handle ICMP_ECHO ("ping") requests.
 888 *
 889 *      RFC 1122: 3.2.2.6 MUST have an echo server that answers ICMP echo
 890 *                requests.
 891 *      RFC 1122: 3.2.2.6 Data received in the ICMP_ECHO request MUST be
 892 *                included in the reply.
 893 *      RFC 1812: 4.3.3.6 SHOULD have a config option for silently ignoring
 894 *                echo requests, MUST have default=NOT.
 895 *      See also WRT handling of options once they are done and working.
 896 */
 897
 898static void icmp_echo(struct sk_buff *skb)
 899{
 900        struct net *net;
 901
 902        net = dev_net(skb_dst(skb)->dev);
 903        if (!net->ipv4.sysctl_icmp_echo_ignore_all) {
 904                struct icmp_bxm icmp_param;
 905
 906                icmp_param.data.icmph      = *icmp_hdr(skb);
 907                icmp_param.data.icmph.type = ICMP_ECHOREPLY;
 908                icmp_param.skb             = skb;
 909                icmp_param.offset          = 0;
 910                icmp_param.data_len        = skb->len;
 911                icmp_param.head_len        = sizeof(struct icmphdr);
 912                icmp_reply(&icmp_param, skb);
 913        }
 914}
 915
 916/*
 917 *      Handle ICMP Timestamp requests.
 918 *      RFC 1122: 3.2.2.8 MAY implement ICMP timestamp requests.
 919 *                SHOULD be in the kernel for minimum random latency.
 920 *                MUST be accurate to a few minutes.
 921 *                MUST be updated at least at 15Hz.
 922 */
 923static void icmp_timestamp(struct sk_buff *skb)
 924{
 925        struct timespec tv;
 926        struct icmp_bxm icmp_param;
 927        /*
 928         *      Too short.
 929         */
 930        if (skb->len < 4)
 931                goto out_err;
 932
 933        /*
 934         *      Fill in the current time as ms since midnight UT:
 935         */
 936        getnstimeofday(&tv);
 937        icmp_param.data.times[1] = htonl((tv.tv_sec % 86400) * MSEC_PER_SEC +
 938                                         tv.tv_nsec / NSEC_PER_MSEC);
 939        icmp_param.data.times[2] = icmp_param.data.times[1];
 940        if (skb_copy_bits(skb, 0, &icmp_param.data.times[0], 4))
 941                BUG();
 942        icmp_param.data.icmph      = *icmp_hdr(skb);
 943        icmp_param.data.icmph.type = ICMP_TIMESTAMPREPLY;
 944        icmp_param.data.icmph.code = 0;
 945        icmp_param.skb             = skb;
 946        icmp_param.offset          = 0;
 947        icmp_param.data_len        = 0;
 948        icmp_param.head_len        = sizeof(struct icmphdr) + 12;
 949        icmp_reply(&icmp_param, skb);
 950out:
 951        return;
 952out_err:
 953        ICMP_INC_STATS_BH(dev_net(skb_dst(skb)->dev), ICMP_MIB_INERRORS);
 954        goto out;
 955}
 956
 957static void icmp_discard(struct sk_buff *skb)
 958{
 959}
 960
 961/*
 962 *      Deal with incoming ICMP packets.
 963 */
 964int icmp_rcv(struct sk_buff *skb)
 965{
 966        struct icmphdr *icmph;
 967        struct rtable *rt = skb_rtable(skb);
 968        struct net *net = dev_net(rt->dst.dev);
 969
 970        if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) {
 971                struct sec_path *sp = skb_sec_path(skb);
 972                int nh;
 973
 974                if (!(sp && sp->xvec[sp->len - 1]->props.flags &
 975                                 XFRM_STATE_ICMP))
 976                        goto drop;
 977
 978                if (!pskb_may_pull(skb, sizeof(*icmph) + sizeof(struct iphdr)))
 979                        goto drop;
 980
 981                nh = skb_network_offset(skb);
 982                skb_set_network_header(skb, sizeof(*icmph));
 983
 984                if (!xfrm4_policy_check_reverse(NULL, XFRM_POLICY_IN, skb))
 985                        goto drop;
 986
 987                skb_set_network_header(skb, nh);
 988        }
 989
 990        ICMP_INC_STATS_BH(net, ICMP_MIB_INMSGS);
 991
 992        if (skb_checksum_simple_validate(skb))
 993                goto csum_error;
 994
 995        if (!pskb_pull(skb, sizeof(*icmph)))
 996                goto error;
 997
 998        icmph = icmp_hdr(skb);
 999
1000        ICMPMSGIN_INC_STATS_BH(net, icmph->type);
1001        /*
1002         *      18 is the highest 'known' ICMP type. Anything else is a mystery
1003         *
1004         *      RFC 1122: 3.2.2  Unknown ICMP messages types MUST be silently
1005         *                discarded.
1006         */
1007        if (icmph->type > NR_ICMP_TYPES)
1008                goto error;
1009
1010
1011        /*
1012         *      Parse the ICMP message
1013         */
1014
1015        if (rt->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST)) {
1016                /*
1017                 *      RFC 1122: 3.2.2.6 An ICMP_ECHO to broadcast MAY be
1018                 *        silently ignored (we let user decide with a sysctl).
1019                 *      RFC 1122: 3.2.2.8 An ICMP_TIMESTAMP MAY be silently
1020                 *        discarded if to broadcast/multicast.
1021                 */
1022                if ((icmph->type == ICMP_ECHO ||
1023                     icmph->type == ICMP_TIMESTAMP) &&
1024                    net->ipv4.sysctl_icmp_echo_ignore_broadcasts) {
1025                        goto error;
1026                }
1027                if (icmph->type != ICMP_ECHO &&
1028                    icmph->type != ICMP_TIMESTAMP &&
1029                    icmph->type != ICMP_ADDRESS &&
1030                    icmph->type != ICMP_ADDRESSREPLY) {
1031                        goto error;
1032                }
1033        }
1034
1035        icmp_pointers[icmph->type].handler(skb);
1036
1037drop:
1038        kfree_skb(skb);
1039        return 0;
1040csum_error:
1041        ICMP_INC_STATS_BH(net, ICMP_MIB_CSUMERRORS);
1042error:
1043        ICMP_INC_STATS_BH(net, ICMP_MIB_INERRORS);
1044        goto drop;
1045}
1046
1047void icmp_err(struct sk_buff *skb, u32 info)
1048{
1049        struct iphdr *iph = (struct iphdr *)skb->data;
1050        struct icmphdr *icmph = (struct icmphdr *)(skb->data+(iph->ihl<<2));
1051        int type = icmp_hdr(skb)->type;
1052        int code = icmp_hdr(skb)->code;
1053        struct net *net = dev_net(skb->dev);
1054
1055        /*
1056         * Use ping_err to handle all icmp errors except those
1057         * triggered by ICMP_ECHOREPLY which sent from kernel.
1058         */
1059        if (icmph->type != ICMP_ECHOREPLY) {
1060                ping_err(skb, info);
1061                return;
1062        }
1063
1064        if (type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED)
1065                ipv4_update_pmtu(skb, net, info, 0, 0, IPPROTO_ICMP, 0);
1066        else if (type == ICMP_REDIRECT)
1067                ipv4_redirect(skb, net, 0, 0, IPPROTO_ICMP, 0);
1068}
1069
1070/*
1071 *      This table is the definition of how we handle ICMP.
1072 */
1073static const struct icmp_control icmp_pointers[NR_ICMP_TYPES + 1] = {
1074        [ICMP_ECHOREPLY] = {
1075                .handler = ping_rcv,
1076        },
1077        [1] = {
1078                .handler = icmp_discard,
1079                .error = 1,
1080        },
1081        [2] = {
1082                .handler = icmp_discard,
1083                .error = 1,
1084        },
1085        [ICMP_DEST_UNREACH] = {
1086                .handler = icmp_unreach,
1087                .error = 1,
1088        },
1089        [ICMP_SOURCE_QUENCH] = {
1090                .handler = icmp_unreach,
1091                .error = 1,
1092        },
1093        [ICMP_REDIRECT] = {
1094                .handler = icmp_redirect,
1095                .error = 1,
1096        },
1097        [6] = {
1098                .handler = icmp_discard,
1099                .error = 1,
1100        },
1101        [7] = {
1102                .handler = icmp_discard,
1103                .error = 1,
1104        },
1105        [ICMP_ECHO] = {
1106                .handler = icmp_echo,
1107        },
1108        [9] = {
1109                .handler = icmp_discard,
1110                .error = 1,
1111        },
1112        [10] = {
1113                .handler = icmp_discard,
1114                .error = 1,
1115        },
1116        [ICMP_TIME_EXCEEDED] = {
1117                .handler = icmp_unreach,
1118                .error = 1,
1119        },
1120        [ICMP_PARAMETERPROB] = {
1121                .handler = icmp_unreach,
1122                .error = 1,
1123        },
1124        [ICMP_TIMESTAMP] = {
1125                .handler = icmp_timestamp,
1126        },
1127        [ICMP_TIMESTAMPREPLY] = {
1128                .handler = icmp_discard,
1129        },
1130        [ICMP_INFO_REQUEST] = {
1131                .handler = icmp_discard,
1132        },
1133        [ICMP_INFO_REPLY] = {
1134                .handler = icmp_discard,
1135        },
1136        [ICMP_ADDRESS] = {
1137                .handler = icmp_discard,
1138        },
1139        [ICMP_ADDRESSREPLY] = {
1140                .handler = icmp_discard,
1141        },
1142};
1143
1144static void __net_exit icmp_sk_exit(struct net *net)
1145{
1146        int i;
1147
1148        for_each_possible_cpu(i)
1149                inet_ctl_sock_destroy(net->ipv4.icmp_sk[i]);
1150        kfree(net->ipv4.icmp_sk);
1151        net->ipv4.icmp_sk = NULL;
1152}
1153
1154static int __net_init icmp_sk_init(struct net *net)
1155{
1156        int i, err;
1157
1158        net->ipv4.icmp_sk =
1159                kzalloc(nr_cpu_ids * sizeof(struct sock *), GFP_KERNEL);
1160        if (net->ipv4.icmp_sk == NULL)
1161                return -ENOMEM;
1162
1163        for_each_possible_cpu(i) {
1164                struct sock *sk;
1165
1166                err = inet_ctl_sock_create(&sk, PF_INET,
1167                                           SOCK_RAW, IPPROTO_ICMP, net);
1168                if (err < 0)
1169                        goto fail;
1170
1171                net->ipv4.icmp_sk[i] = sk;
1172
1173                /* Enough space for 2 64K ICMP packets, including
1174                 * sk_buff/skb_shared_info struct overhead.
1175                 */
1176                sk->sk_sndbuf = 2 * SKB_TRUESIZE(64 * 1024);
1177
1178                /*
1179                 * Speedup sock_wfree()
1180                 */
1181                sock_set_flag(sk, SOCK_USE_WRITE_QUEUE);
1182                inet_sk(sk)->pmtudisc = IP_PMTUDISC_DONT;
1183        }
1184
1185        /* Control parameters for ECHO replies. */
1186        net->ipv4.sysctl_icmp_echo_ignore_all = 0;
1187        net->ipv4.sysctl_icmp_echo_ignore_broadcasts = 1;
1188
1189        /* Control parameter - ignore bogus broadcast responses? */
1190        net->ipv4.sysctl_icmp_ignore_bogus_error_responses = 1;
1191
1192        /*
1193         *      Configurable global rate limit.
1194         *
1195         *      ratelimit defines tokens/packet consumed for dst->rate_token
1196         *      bucket ratemask defines which icmp types are ratelimited by
1197         *      setting it's bit position.
1198         *
1199         *      default:
1200         *      dest unreachable (3), source quench (4),
1201         *      time exceeded (11), parameter problem (12)
1202         */
1203
1204        net->ipv4.sysctl_icmp_ratelimit = 1 * HZ;
1205        net->ipv4.sysctl_icmp_ratemask = 0x1818;
1206        net->ipv4.sysctl_icmp_errors_use_inbound_ifaddr = 0;
1207
1208        return 0;
1209
1210fail:
1211        for_each_possible_cpu(i)
1212                inet_ctl_sock_destroy(net->ipv4.icmp_sk[i]);
1213        kfree(net->ipv4.icmp_sk);
1214        return err;
1215}
1216
1217static struct pernet_operations __net_initdata icmp_sk_ops = {
1218       .init = icmp_sk_init,
1219       .exit = icmp_sk_exit,
1220};
1221
1222int __init icmp_init(void)
1223{
1224        return register_pernet_subsys(&icmp_sk_ops);
1225}
1226