File Index
Files and directories
Sign in
FILE

icmp.c

File preview with syntax highlighting.

linux-6.19.14/net/ipv4/icmp.c C
   1// SPDX-License-Identifier: GPL-2.0-or-later
   2/*
   3 *	NET3:	Implementation of the ICMP protocol layer.
   4 *
   5 *		Alan Cox, <alan@lxorguk.ukuu.org.uk>
   6 *
   7 *	Some of the function names and the icmp unreach table for this
   8 *	module were derived from [icmp.c 1.0.11 06/02/93] by
   9 *	Ross Biro, Fred N. van Kempen, Mark Evans, Alan Cox, Gerhard Koerting.
  10 *	Other than that this module is a complete rewrite.
  11 *
  12 *	Fixes:
  13 *	Clemens Fruhwirth	:	introduce global icmp rate limiting
  14 *					with icmp type masking ability instead
  15 *					of broken per type icmp timeouts.
  16 *		Mike Shaver	:	RFC1122 checks.
  17 *		Alan Cox	:	Multicast ping reply as self.
  18 *		Alan Cox	:	Fix atomicity lockup in ip_build_xmit
  19 *					call.
  20 *		Alan Cox	:	Added 216,128 byte paths to the MTU
  21 *					code.
  22 *		Martin Mares	:	RFC1812 checks.
  23 *		Martin Mares	:	Can be configured to follow redirects
  24 *					if acting as a router _without_ a
  25 *					routing protocol (RFC 1812).
  26 *		Martin Mares	:	Echo requests may be configured to
  27 *					be ignored (RFC 1812).
  28 *		Martin Mares	:	Limitation of ICMP error message
  29 *					transmit rate (RFC 1812).
  30 *		Martin Mares	:	TOS and Precedence set correctly
  31 *					(RFC 1812).
  32 *		Martin Mares	:	Now copying as much data from the
  33 *					original packet as we can without
  34 *					exceeding 576 bytes (RFC 1812).
  35 *	Willy Konynenberg	:	Transparent proxying support.
  36 *		Keith Owens	:	RFC1191 correction for 4.2BSD based
  37 *					path MTU bug.
  38 *		Thomas Quinot	:	ICMP Dest Unreach codes up to 15 are
  39 *					valid (RFC 1812).
  40 *		Andi Kleen	:	Check all packet lengths properly
  41 *					and moved all kfree_skb() up to
  42 *					icmp_rcv.
  43 *		Andi Kleen	:	Move the rate limit bookkeeping
  44 *					into the dest entry and use a token
  45 *					bucket filter (thanks to ANK). Make
  46 *					the rates sysctl configurable.
  47 *		Yu Tianli	:	Fixed two ugly bugs in icmp_send
  48 *					- IP option length was accounted wrongly
  49 *					- ICMP header length was not accounted
  50 *					  at all.
  51 *              Tristan Greaves :       Added sysctl option to ignore bogus
  52 *              			broadcast responses from broken routers.
  53 *
  54 * To Fix:
  55 *
  56 *	- Should use skb_pull() instead of all the manual checking.
  57 *	  This would also greatly simply some upper layer error handlers. --AK
  58 */
  59
  60#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  61
  62#include <linux/module.h>
  63#include <linux/types.h>
  64#include <linux/jiffies.h>
  65#include <linux/kernel.h>
  66#include <linux/fcntl.h>
  67#include <linux/socket.h>
  68#include <linux/in.h>
  69#include <linux/inet.h>
  70#include <linux/inetdevice.h>
  71#include <linux/netdevice.h>
  72#include <linux/string.h>
  73#include <linux/netfilter_ipv4.h>
  74#include <linux/slab.h>
  75#include <net/flow.h>
  76#include <net/snmp.h>
  77#include <net/ip.h>
  78#include <net/route.h>
  79#include <net/protocol.h>
  80#include <net/icmp.h>
  81#include <net/tcp.h>
  82#include <net/udp.h>
  83#include <net/raw.h>
  84#include <net/ping.h>
  85#include <linux/skbuff.h>
  86#include <net/sock.h>
  87#include <linux/errno.h>
  88#include <linux/timer.h>
  89#include <linux/init.h>
  90#include <linux/uaccess.h>
  91#include <net/checksum.h>
  92#include <net/xfrm.h>
  93#include <net/inet_common.h>
  94#include <net/ip_fib.h>
  95#include <net/l3mdev.h>
  96#include <net/addrconf.h>
  97#include <net/inet_dscp.h>
  98#define CREATE_TRACE_POINTS
  99#include <trace/events/icmp.h>
 100
 101/*
 102 *	Build xmit assembly blocks
 103 */
 104
 105struct icmp_bxm {
 106	struct sk_buff *skb;
 107	int offset;
 108	int data_len;
 109
 110	struct {
 111		struct icmphdr icmph;
 112		__be32	       times[3];
 113	} data;
 114	int head_len;
 115	struct ip_options_data replyopts;
 116};
 117
 118/* An array of errno for error messages from dest unreach. */
 119/* RFC 1122: 3.2.2.1 States that NET_UNREACH, HOST_UNREACH and SR_FAILED MUST be considered 'transient errs'. */
 120
 121const struct icmp_err icmp_err_convert[] = {
 122	{
 123		.errno = ENETUNREACH,	/* ICMP_NET_UNREACH */
 124		.fatal = 0,
 125	},
 126	{
 127		.errno = EHOSTUNREACH,	/* ICMP_HOST_UNREACH */
 128		.fatal = 0,
 129	},
 130	{
 131		.errno = ENOPROTOOPT	/* ICMP_PROT_UNREACH */,
 132		.fatal = 1,
 133	},
 134	{
 135		.errno = ECONNREFUSED,	/* ICMP_PORT_UNREACH */
 136		.fatal = 1,
 137	},
 138	{
 139		.errno = EMSGSIZE,	/* ICMP_FRAG_NEEDED */
 140		.fatal = 0,
 141	},
 142	{
 143		.errno = EOPNOTSUPP,	/* ICMP_SR_FAILED */
 144		.fatal = 0,
 145	},
 146	{
 147		.errno = ENETUNREACH,	/* ICMP_NET_UNKNOWN */
 148		.fatal = 1,
 149	},
 150	{
 151		.errno = EHOSTDOWN,	/* ICMP_HOST_UNKNOWN */
 152		.fatal = 1,
 153	},
 154	{
 155		.errno = ENONET,	/* ICMP_HOST_ISOLATED */
 156		.fatal = 1,
 157	},
 158	{
 159		.errno = ENETUNREACH,	/* ICMP_NET_ANO	*/
 160		.fatal = 1,
 161	},
 162	{
 163		.errno = EHOSTUNREACH,	/* ICMP_HOST_ANO */
 164		.fatal = 1,
 165	},
 166	{
 167		.errno = ENETUNREACH,	/* ICMP_NET_UNR_TOS */
 168		.fatal = 0,
 169	},
 170	{
 171		.errno = EHOSTUNREACH,	/* ICMP_HOST_UNR_TOS */
 172		.fatal = 0,
 173	},
 174	{
 175		.errno = EHOSTUNREACH,	/* ICMP_PKT_FILTERED */
 176		.fatal = 1,
 177	},
 178	{
 179		.errno = EHOSTUNREACH,	/* ICMP_PREC_VIOLATION */
 180		.fatal = 1,
 181	},
 182	{
 183		.errno = EHOSTUNREACH,	/* ICMP_PREC_CUTOFF */
 184		.fatal = 1,
 185	},
 186};
 187EXPORT_SYMBOL(icmp_err_convert);
 188
 189/*
 190 *	ICMP control array. This specifies what to do with each ICMP.
 191 */
 192
 193struct icmp_control {
 194	enum skb_drop_reason (*handler)(struct sk_buff *skb);
 195	short   error;		/* This ICMP is classed as an error message */
 196};
 197
 198static const struct icmp_control icmp_pointers[NR_ICMP_TYPES+1];
 199
 200static DEFINE_PER_CPU(struct sock *, ipv4_icmp_sk);
 201
 202/* Called with BH disabled */
 203static inline struct sock *icmp_xmit_lock(struct net *net)
 204{
 205	struct sock *sk;
 206
 207	sk = this_cpu_read(ipv4_icmp_sk);
 208
 209	if (unlikely(!spin_trylock(&sk->sk_lock.slock))) {
 210		/* This can happen if the output path signals a
 211		 * dst_link_failure() for an outgoing ICMP packet.
 212		 */
 213		return NULL;
 214	}
 215	sock_net_set(sk, net);
 216	return sk;
 217}
 218
 219static inline void icmp_xmit_unlock(struct sock *sk)
 220{
 221	sock_net_set(sk, &init_net);
 222	spin_unlock(&sk->sk_lock.slock);
 223}
 224
 225/**
 226 * icmp_global_allow - Are we allowed to send one more ICMP message ?
 227 * @net: network namespace
 228 *
 229 * Uses a token bucket to limit our ICMP messages to ~sysctl_icmp_msgs_per_sec.
 230 * Returns false if we reached the limit and can not send another packet.
 231 * Works in tandem with icmp_global_consume().
 232 */
 233bool icmp_global_allow(struct net *net)
 234{
 235	u32 delta, now, oldstamp;
 236	int incr, new, old;
 237
 238	/* Note: many cpus could find this condition true.
 239	 * Then later icmp_global_consume() could consume more credits,
 240	 * this is an acceptable race.
 241	 */
 242	if (atomic_read(&net->ipv4.icmp_global_credit) > 0)
 243		return true;
 244
 245	now = jiffies;
 246	oldstamp = READ_ONCE(net->ipv4.icmp_global_stamp);
 247	delta = min_t(u32, now - oldstamp, HZ);
 248	if (delta < HZ / 50)
 249		return false;
 250
 251	incr = READ_ONCE(net->ipv4.sysctl_icmp_msgs_per_sec);
 252	incr = div_u64((u64)incr * delta, HZ);
 253	if (!incr)
 254		return false;
 255
 256	if (cmpxchg(&net->ipv4.icmp_global_stamp, oldstamp, now) == oldstamp) {
 257		old = atomic_read(&net->ipv4.icmp_global_credit);
 258		do {
 259			new = min(old + incr, READ_ONCE(net->ipv4.sysctl_icmp_msgs_burst));
 260		} while (!atomic_try_cmpxchg(&net->ipv4.icmp_global_credit, &old, new));
 261	}
 262	return true;
 263}
 264EXPORT_SYMBOL(icmp_global_allow);
 265
 266void icmp_global_consume(struct net *net)
 267{
 268	int credits = get_random_u32_below(3);
 269
 270	/* Note: this might make icmp_global.credit negative. */
 271	if (credits)
 272		atomic_sub(credits, &net->ipv4.icmp_global_credit);
 273}
 274EXPORT_SYMBOL(icmp_global_consume);
 275
 276static bool icmpv4_mask_allow(struct net *net, int type, int code)
 277{
 278	if (type > NR_ICMP_TYPES)
 279		return true;
 280
 281	/* Don't limit PMTU discovery. */
 282	if (type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED)
 283		return true;
 284
 285	/* Limit if icmp type is enabled in ratemask. */
 286	if (!((1 << type) & READ_ONCE(net->ipv4.sysctl_icmp_ratemask)))
 287		return true;
 288
 289	return false;
 290}
 291
 292static bool icmpv4_global_allow(struct net *net, int type, int code,
 293				bool *apply_ratelimit)
 294{
 295	if (icmpv4_mask_allow(net, type, code))
 296		return true;
 297
 298	if (icmp_global_allow(net)) {
 299		*apply_ratelimit = true;
 300		return true;
 301	}
 302	__ICMP_INC_STATS(net, ICMP_MIB_RATELIMITGLOBAL);
 303	return false;
 304}
 305
 306/*
 307 *	Send an ICMP frame.
 308 */
 309
 310static bool icmpv4_xrlim_allow(struct net *net, struct rtable *rt,
 311			       struct flowi4 *fl4, int type, int code,
 312			       bool apply_ratelimit)
 313{
 314	struct dst_entry *dst = &rt->dst;
 315	struct inet_peer *peer;
 316	struct net_device *dev;
 317	bool rc = true;
 318
 319	if (!apply_ratelimit)
 320		return true;
 321
 322	/* No rate limit on loopback */
 323	rcu_read_lock();
 324	dev = dst_dev_rcu(dst);
 325	if (dev && (dev->flags & IFF_LOOPBACK))
 326		goto out;
 327
 328	peer = inet_getpeer_v4(net->ipv4.peers, fl4->daddr,
 329			       l3mdev_master_ifindex_rcu(dev));
 330	rc = inet_peer_xrlim_allow(peer,
 331				   READ_ONCE(net->ipv4.sysctl_icmp_ratelimit));
 332out:
 333	rcu_read_unlock();
 334	if (!rc)
 335		__ICMP_INC_STATS(net, ICMP_MIB_RATELIMITHOST);
 336	else
 337		icmp_global_consume(net);
 338	return rc;
 339}
 340
 341/*
 342 *	Maintain the counters used in the SNMP statistics for outgoing ICMP
 343 */
 344void icmp_out_count(struct net *net, unsigned char type)
 345{
 346	ICMPMSGOUT_INC_STATS(net, type);
 347	ICMP_INC_STATS(net, ICMP_MIB_OUTMSGS);
 348}
 349
 350/*
 351 *	Checksum each fragment, and on the first include the headers and final
 352 *	checksum.
 353 */
 354static int icmp_glue_bits(void *from, char *to, int offset, int len, int odd,
 355			  struct sk_buff *skb)
 356{
 357	struct icmp_bxm *icmp_param = from;
 358	__wsum csum;
 359
 360	csum = skb_copy_and_csum_bits(icmp_param->skb,
 361				      icmp_param->offset + offset,
 362				      to, len);
 363
 364	skb->csum = csum_block_add(skb->csum, csum, odd);
 365	if (icmp_pointers[icmp_param->data.icmph.type].error)
 366		nf_ct_attach(skb, icmp_param->skb);
 367	return 0;
 368}
 369
 370static void icmp_push_reply(struct sock *sk,
 371			    struct icmp_bxm *icmp_param,
 372			    struct flowi4 *fl4,
 373			    struct ipcm_cookie *ipc, struct rtable **rt)
 374{
 375	struct sk_buff *skb;
 376
 377	if (ip_append_data(sk, fl4, icmp_glue_bits, icmp_param,
 378			   icmp_param->data_len+icmp_param->head_len,
 379			   icmp_param->head_len,
 380			   ipc, rt, MSG_DONTWAIT) < 0) {
 381		__ICMP_INC_STATS(sock_net(sk), ICMP_MIB_OUTERRORS);
 382		ip_flush_pending_frames(sk);
 383	} else if ((skb = skb_peek(&sk->sk_write_queue)) != NULL) {
 384		struct icmphdr *icmph = icmp_hdr(skb);
 385		__wsum csum;
 386		struct sk_buff *skb1;
 387
 388		csum = csum_partial_copy_nocheck((void *)&icmp_param->data,
 389						 (char *)icmph,
 390						 icmp_param->head_len);
 391		skb_queue_walk(&sk->sk_write_queue, skb1) {
 392			csum = csum_add(csum, skb1->csum);
 393		}
 394		icmph->checksum = csum_fold(csum);
 395		skb->ip_summed = CHECKSUM_NONE;
 396		ip_push_pending_frames(sk, fl4);
 397	}
 398}
 399
 400/*
 401 *	Driving logic for building and sending ICMP messages.
 402 */
 403
 404static void icmp_reply(struct icmp_bxm *icmp_param, struct sk_buff *skb)
 405{
 406	struct rtable *rt = skb_rtable(skb);
 407	struct net *net = dev_net_rcu(rt->dst.dev);
 408	bool apply_ratelimit = false;
 409	struct ipcm_cookie ipc;
 410	struct flowi4 fl4;
 411	struct sock *sk;
 412	__be32 daddr, saddr;
 413	u32 mark = IP4_REPLY_MARK(net, skb->mark);
 414	int type = icmp_param->data.icmph.type;
 415	int code = icmp_param->data.icmph.code;
 416
 417	if (ip_options_echo(net, &icmp_param->replyopts.opt.opt, skb))
 418		return;
 419
 420	/* Needed by both icmpv4_global_allow and icmp_xmit_lock */
 421	local_bh_disable();
 422
 423	/* is global icmp_msgs_per_sec exhausted ? */
 424	if (!icmpv4_global_allow(net, type, code, &apply_ratelimit))
 425		goto out_bh_enable;
 426
 427	sk = icmp_xmit_lock(net);
 428	if (!sk)
 429		goto out_bh_enable;
 430
 431	icmp_param->data.icmph.checksum = 0;
 432
 433	ipcm_init(&ipc);
 434	ipc.tos = ip_hdr(skb)->tos;
 435	ipc.sockc.mark = mark;
 436	daddr = ipc.addr = ip_hdr(skb)->saddr;
 437	saddr = fib_compute_spec_dst(skb);
 438
 439	if (icmp_param->replyopts.opt.opt.optlen) {
 440		ipc.opt = &icmp_param->replyopts.opt;
 441		if (ipc.opt->opt.srr)
 442			daddr = icmp_param->replyopts.opt.opt.faddr;
 443	}
 444	memset(&fl4, 0, sizeof(fl4));
 445	fl4.daddr = daddr;
 446	fl4.saddr = saddr;
 447	fl4.flowi4_mark = mark;
 448	fl4.flowi4_uid = sock_net_uid(net, NULL);
 449	fl4.flowi4_dscp = ip4h_dscp(ip_hdr(skb));
 450	fl4.flowi4_proto = IPPROTO_ICMP;
 451	fl4.flowi4_oif = l3mdev_master_ifindex(skb->dev);
 452	security_skb_classify_flow(skb, flowi4_to_flowi_common(&fl4));
 453	rt = ip_route_output_key(net, &fl4);
 454	if (IS_ERR(rt))
 455		goto out_unlock;
 456	if (icmpv4_xrlim_allow(net, rt, &fl4, type, code, apply_ratelimit))
 457		icmp_push_reply(sk, icmp_param, &fl4, &ipc, &rt);
 458	ip_rt_put(rt);
 459out_unlock:
 460	icmp_xmit_unlock(sk);
 461out_bh_enable:
 462	local_bh_enable();
 463}
 464
 465/*
 466 * The device used for looking up which routing table to use for sending an ICMP
 467 * error is preferably the source whenever it is set, which should ensure the
 468 * icmp error can be sent to the source host, else lookup using the routing
 469 * table of the destination device, else use the main routing table (index 0).
 470 */
 471static struct net_device *icmp_get_route_lookup_dev(struct sk_buff *skb)
 472{
 473	struct net_device *dev = skb->dev;
 474	const struct dst_entry *dst;
 475
 476	if (dev)
 477		return dev;
 478	dst = skb_dst(skb);
 479	return dst ? dst_dev(dst) : NULL;
 480}
 481
 482static struct rtable *icmp_route_lookup(struct net *net, struct flowi4 *fl4,
 483					struct sk_buff *skb_in,
 484					const struct iphdr *iph, __be32 saddr,
 485					dscp_t dscp, u32 mark, int type,
 486					int code, struct icmp_bxm *param)
 487{
 488	struct net_device *route_lookup_dev;
 489	struct dst_entry *dst, *dst2;
 490	struct rtable *rt, *rt2;
 491	struct flowi4 fl4_dec;
 492	int err;
 493
 494	memset(fl4, 0, sizeof(*fl4));
 495	fl4->daddr = (param->replyopts.opt.opt.srr ?
 496		      param->replyopts.opt.opt.faddr : iph->saddr);
 497	fl4->saddr = saddr;
 498	fl4->flowi4_mark = mark;
 499	fl4->flowi4_uid = sock_net_uid(net, NULL);
 500	fl4->flowi4_dscp = dscp;
 501	fl4->flowi4_proto = IPPROTO_ICMP;
 502	fl4->fl4_icmp_type = type;
 503	fl4->fl4_icmp_code = code;
 504	route_lookup_dev = icmp_get_route_lookup_dev(skb_in);
 505	fl4->flowi4_oif = l3mdev_master_ifindex(route_lookup_dev);
 506
 507	security_skb_classify_flow(skb_in, flowi4_to_flowi_common(fl4));
 508	rt = ip_route_output_key_hash(net, fl4, skb_in);
 509	if (IS_ERR(rt))
 510		return rt;
 511
 512	/* No need to clone since we're just using its address. */
 513	rt2 = rt;
 514
 515	dst = xfrm_lookup(net, &rt->dst,
 516			  flowi4_to_flowi(fl4), NULL, 0);
 517	rt = dst_rtable(dst);
 518	if (!IS_ERR(dst)) {
 519		if (rt != rt2)
 520			return rt;
 521		if (inet_addr_type_dev_table(net, route_lookup_dev,
 522					     fl4->daddr) == RTN_LOCAL)
 523			return rt;
 524	} else if (PTR_ERR(dst) == -EPERM) {
 525		rt = NULL;
 526	} else {
 527		return rt;
 528	}
 529	err = xfrm_decode_session_reverse(net, skb_in, flowi4_to_flowi(&fl4_dec), AF_INET);
 530	if (err)
 531		goto relookup_failed;
 532
 533	if (inet_addr_type_dev_table(net, route_lookup_dev,
 534				     fl4_dec.saddr) == RTN_LOCAL) {
 535		rt2 = __ip_route_output_key(net, &fl4_dec);
 536		if (IS_ERR(rt2))
 537			err = PTR_ERR(rt2);
 538	} else {
 539		struct flowi4 fl4_2 = {};
 540		unsigned long orefdst;
 541
 542		fl4_2.daddr = fl4_dec.saddr;
 543		rt2 = ip_route_output_key(net, &fl4_2);
 544		if (IS_ERR(rt2)) {
 545			err = PTR_ERR(rt2);
 546			goto relookup_failed;
 547		}
 548		/* Ugh! */
 549		orefdst = skb_dstref_steal(skb_in);
 550		err = ip_route_input(skb_in, fl4_dec.daddr, fl4_dec.saddr,
 551				     dscp, rt2->dst.dev) ? -EINVAL : 0;
 552
 553		dst_release(&rt2->dst);
 554		rt2 = skb_rtable(skb_in);
 555		/* steal dst entry from skb_in, don't drop refcnt */
 556		skb_dstref_steal(skb_in);
 557		skb_dstref_restore(skb_in, orefdst);
 558
 559		/*
 560		 * At this point, fl4_dec.daddr should NOT be local (we
 561		 * checked fl4_dec.saddr above). However, a race condition
 562		 * may occur if the address is added to the interface
 563		 * concurrently. In that case, ip_route_input() returns a
 564		 * LOCAL route with dst.output=ip_rt_bug, which must not
 565		 * be used for output.
 566		 */
 567		if (!err && rt2 && rt2->rt_type == RTN_LOCAL) {
 568			net_warn_ratelimited("detected local route for %pI4 during ICMP sending, src %pI4\n",
 569					     &fl4_dec.daddr, &fl4_dec.saddr);
 570			dst_release(&rt2->dst);
 571			err = -EINVAL;
 572		}
 573	}
 574
 575	if (err)
 576		goto relookup_failed;
 577
 578	dst2 = xfrm_lookup(net, &rt2->dst, flowi4_to_flowi(&fl4_dec), NULL,
 579			   XFRM_LOOKUP_ICMP);
 580	rt2 = dst_rtable(dst2);
 581	if (!IS_ERR(dst2)) {
 582		dst_release(&rt->dst);
 583		memcpy(fl4, &fl4_dec, sizeof(*fl4));
 584		rt = rt2;
 585	} else if (PTR_ERR(dst2) == -EPERM) {
 586		if (rt)
 587			dst_release(&rt->dst);
 588		return rt2;
 589	} else {
 590		err = PTR_ERR(dst2);
 591		goto relookup_failed;
 592	}
 593	return rt;
 594
 595relookup_failed:
 596	if (rt)
 597		return rt;
 598	return ERR_PTR(err);
 599}
 600
 601struct icmp_ext_iio_addr4_subobj {
 602	__be16 afi;
 603	__be16 reserved;
 604	__be32 addr4;
 605};
 606
 607static unsigned int icmp_ext_iio_len(void)
 608{
 609	return sizeof(struct icmp_extobj_hdr) +
 610		/* ifIndex */
 611		sizeof(__be32) +
 612		/* Interface Address Sub-Object */
 613		sizeof(struct icmp_ext_iio_addr4_subobj) +
 614		/* Interface Name Sub-Object. Length must be a multiple of 4
 615		 * bytes.
 616		 */
 617		ALIGN(sizeof(struct icmp_ext_iio_name_subobj), 4) +
 618		/* MTU */
 619		sizeof(__be32);
 620}
 621
 622static unsigned int icmp_ext_max_len(u8 ext_objs)
 623{
 624	unsigned int ext_max_len;
 625
 626	ext_max_len = sizeof(struct icmp_ext_hdr);
 627
 628	if (ext_objs & BIT(ICMP_ERR_EXT_IIO_IIF))
 629		ext_max_len += icmp_ext_iio_len();
 630
 631	return ext_max_len;
 632}
 633
 634static __be32 icmp_ext_iio_addr4_find(const struct net_device *dev)
 635{
 636	struct in_device *in_dev;
 637	struct in_ifaddr *ifa;
 638
 639	in_dev = __in_dev_get_rcu(dev);
 640	if (!in_dev)
 641		return 0;
 642
 643	/* It is unclear from RFC 5837 which IP address should be chosen, but
 644	 * it makes sense to choose a global unicast address.
 645	 */
 646	in_dev_for_each_ifa_rcu(ifa, in_dev) {
 647		if (READ_ONCE(ifa->ifa_flags) & IFA_F_SECONDARY)
 648			continue;
 649		if (ifa->ifa_scope != RT_SCOPE_UNIVERSE ||
 650		    ipv4_is_multicast(ifa->ifa_address))
 651			continue;
 652		return ifa->ifa_address;
 653	}
 654
 655	return 0;
 656}
 657
 658static void icmp_ext_iio_iif_append(struct net *net, struct sk_buff *skb,
 659				    int iif)
 660{
 661	struct icmp_ext_iio_name_subobj *name_subobj;
 662	struct icmp_extobj_hdr *objh;
 663	struct net_device *dev;
 664	__be32 data;
 665
 666	if (!iif)
 667		return;
 668
 669	/* Add the fields in the order specified by RFC 5837. */
 670	objh = skb_put(skb, sizeof(*objh));
 671	objh->class_num = ICMP_EXT_OBJ_CLASS_IIO;
 672	objh->class_type = ICMP_EXT_CTYPE_IIO_ROLE(ICMP_EXT_CTYPE_IIO_ROLE_IIF);
 673
 674	data = htonl(iif);
 675	skb_put_data(skb, &data, sizeof(__be32));
 676	objh->class_type |= ICMP_EXT_CTYPE_IIO_IFINDEX;
 677
 678	rcu_read_lock();
 679
 680	dev = dev_get_by_index_rcu(net, iif);
 681	if (!dev)
 682		goto out;
 683
 684	data = icmp_ext_iio_addr4_find(dev);
 685	if (data) {
 686		struct icmp_ext_iio_addr4_subobj *addr4_subobj;
 687
 688		addr4_subobj = skb_put_zero(skb, sizeof(*addr4_subobj));
 689		addr4_subobj->afi = htons(ICMP_AFI_IP);
 690		addr4_subobj->addr4 = data;
 691		objh->class_type |= ICMP_EXT_CTYPE_IIO_IPADDR;
 692	}
 693
 694	name_subobj = skb_put_zero(skb, ALIGN(sizeof(*name_subobj), 4));
 695	name_subobj->len = ALIGN(sizeof(*name_subobj), 4);
 696	netdev_copy_name(dev, name_subobj->name);
 697	objh->class_type |= ICMP_EXT_CTYPE_IIO_NAME;
 698
 699	data = htonl(READ_ONCE(dev->mtu));
 700	skb_put_data(skb, &data, sizeof(__be32));
 701	objh->class_type |= ICMP_EXT_CTYPE_IIO_MTU;
 702
 703out:
 704	rcu_read_unlock();
 705	objh->length = htons(skb_tail_pointer(skb) - (unsigned char *)objh);
 706}
 707
 708static void icmp_ext_objs_append(struct net *net, struct sk_buff *skb,
 709				 u8 ext_objs, int iif)
 710{
 711	if (ext_objs & BIT(ICMP_ERR_EXT_IIO_IIF))
 712		icmp_ext_iio_iif_append(net, skb, iif);
 713}
 714
 715static struct sk_buff *
 716icmp_ext_append(struct net *net, struct sk_buff *skb_in, struct icmphdr *icmph,
 717		unsigned int room, int iif)
 718{
 719	unsigned int payload_len, ext_max_len, ext_len;
 720	struct icmp_ext_hdr *ext_hdr;
 721	struct sk_buff *skb;
 722	u8 ext_objs;
 723	int nhoff;
 724
 725	switch (icmph->type) {
 726	case ICMP_DEST_UNREACH:
 727	case ICMP_TIME_EXCEEDED:
 728	case ICMP_PARAMETERPROB:
 729		break;
 730	default:
 731		return NULL;
 732	}
 733
 734	ext_objs = READ_ONCE(net->ipv4.sysctl_icmp_errors_extension_mask);
 735	if (!ext_objs)
 736		return NULL;
 737
 738	ext_max_len = icmp_ext_max_len(ext_objs);
 739	if (ICMP_EXT_ORIG_DGRAM_MIN_LEN + ext_max_len > room)
 740		return NULL;
 741
 742	skb = skb_clone(skb_in, GFP_ATOMIC);
 743	if (!skb)
 744		return NULL;
 745
 746	nhoff = skb_network_offset(skb);
 747	payload_len = min(skb->len - nhoff, ICMP_EXT_ORIG_DGRAM_MIN_LEN);
 748
 749	if (!pskb_network_may_pull(skb, payload_len))
 750		goto free_skb;
 751
 752	if (pskb_trim(skb, nhoff + ICMP_EXT_ORIG_DGRAM_MIN_LEN) ||
 753	    __skb_put_padto(skb, nhoff + ICMP_EXT_ORIG_DGRAM_MIN_LEN, false))
 754		goto free_skb;
 755
 756	if (pskb_expand_head(skb, 0, ext_max_len, GFP_ATOMIC))
 757		goto free_skb;
 758
 759	ext_hdr = skb_put_zero(skb, sizeof(*ext_hdr));
 760	ext_hdr->version = ICMP_EXT_VERSION_2;
 761
 762	icmp_ext_objs_append(net, skb, ext_objs, iif);
 763
 764	/* Do not send an empty extension structure. */
 765	ext_len = skb_tail_pointer(skb) - (unsigned char *)ext_hdr;
 766	if (ext_len == sizeof(*ext_hdr))
 767		goto free_skb;
 768
 769	ext_hdr->checksum = ip_compute_csum(ext_hdr, ext_len);
 770	/* The length of the original datagram in 32-bit words (RFC 4884). */
 771	icmph->un.reserved[1] = ICMP_EXT_ORIG_DGRAM_MIN_LEN / sizeof(u32);
 772
 773	return skb;
 774
 775free_skb:
 776	consume_skb(skb);
 777	return NULL;
 778}
 779
 780/*
 781 *	Send an ICMP message in response to a situation
 782 *
 783 *	RFC 1122: 3.2.2	MUST send at least the IP header and 8 bytes of header.
 784 *		  MAY send more (we do).
 785 *			MUST NOT change this header information.
 786 *			MUST NOT reply to a multicast/broadcast IP address.
 787 *			MUST NOT reply to a multicast/broadcast MAC address.
 788 *			MUST reply to only the first fragment.
 789 */
 790
 791void __icmp_send(struct sk_buff *skb_in, int type, int code, __be32 info,
 792		 const struct inet_skb_parm *parm)
 793{
 794	struct iphdr *iph;
 795	int room;
 796	struct icmp_bxm icmp_param;
 797	struct rtable *rt = skb_rtable(skb_in);
 798	bool apply_ratelimit = false;
 799	struct sk_buff *ext_skb;
 800	struct ipcm_cookie ipc;
 801	struct flowi4 fl4;
 802	__be32 saddr;
 803	u8  tos;
 804	u32 mark;
 805	struct net *net;
 806	struct sock *sk;
 807
 808	if (!rt)
 809		return;
 810
 811	rcu_read_lock();
 812
 813	if (rt->dst.dev)
 814		net = dev_net_rcu(rt->dst.dev);
 815	else if (skb_in->dev)
 816		net = dev_net_rcu(skb_in->dev);
 817	else
 818		goto out;
 819
 820	/*
 821	 *	Find the original header. It is expected to be valid, of course.
 822	 *	Check this, icmp_send is called from the most obscure devices
 823	 *	sometimes.
 824	 */
 825	iph = ip_hdr(skb_in);
 826
 827	if ((u8 *)iph < skb_in->head ||
 828	    (skb_network_header(skb_in) + sizeof(*iph)) >
 829	    skb_tail_pointer(skb_in))
 830		goto out;
 831
 832	/*
 833	 *	No replies to physical multicast/broadcast
 834	 */
 835	if (skb_in->pkt_type != PACKET_HOST)
 836		goto out;
 837
 838	/*
 839	 *	Now check at the protocol level
 840	 */
 841	if (rt->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST))
 842		goto out;
 843
 844	/*
 845	 *	Only reply to fragment 0. We byte re-order the constant
 846	 *	mask for efficiency.
 847	 */
 848	if (iph->frag_off & htons(IP_OFFSET))
 849		goto out;
 850
 851	/*
 852	 *	If we send an ICMP error to an ICMP error a mess would result..
 853	 */
 854	if (icmp_pointers[type].error) {
 855		/*
 856		 *	We are an error, check if we are replying to an
 857		 *	ICMP error
 858		 */
 859		if (iph->protocol == IPPROTO_ICMP) {
 860			u8 _inner_type, *itp;
 861
 862			itp = skb_header_pointer(skb_in,
 863						 skb_network_header(skb_in) +
 864						 (iph->ihl << 2) +
 865						 offsetof(struct icmphdr,
 866							  type) -
 867						 skb_in->data,
 868						 sizeof(_inner_type),
 869						 &_inner_type);
 870			if (!itp)
 871				goto out;
 872
 873			/*
 874			 *	Assume any unknown ICMP type is an error. This
 875			 *	isn't specified by the RFC, but think about it..
 876			 */
 877			if (*itp > NR_ICMP_TYPES ||
 878			    icmp_pointers[*itp].error)
 879				goto out;
 880		}
 881	}
 882
 883	/* Needed by both icmpv4_global_allow and icmp_xmit_lock */
 884	local_bh_disable();
 885
 886	/* Check global sysctl_icmp_msgs_per_sec ratelimit, unless
 887	 * incoming dev is loopback.  If outgoing dev change to not be
 888	 * loopback, then peer ratelimit still work (in icmpv4_xrlim_allow)
 889	 */
 890	if (!(skb_in->dev && (skb_in->dev->flags&IFF_LOOPBACK)) &&
 891	      !icmpv4_global_allow(net, type, code, &apply_ratelimit))
 892		goto out_bh_enable;
 893
 894	sk = icmp_xmit_lock(net);
 895	if (!sk)
 896		goto out_bh_enable;
 897
 898	/*
 899	 *	Construct source address and options.
 900	 */
 901
 902	saddr = iph->daddr;
 903	if (!(rt->rt_flags & RTCF_LOCAL)) {
 904		struct net_device *dev = NULL;
 905
 906		rcu_read_lock();
 907		if (rt_is_input_route(rt) &&
 908		    READ_ONCE(net->ipv4.sysctl_icmp_errors_use_inbound_ifaddr))
 909			dev = dev_get_by_index_rcu(net, parm->iif ? parm->iif :
 910						   inet_iif(skb_in));
 911
 912		if (dev)
 913			saddr = inet_select_addr(dev, iph->saddr,
 914						 RT_SCOPE_LINK);
 915		else
 916			saddr = 0;
 917		rcu_read_unlock();
 918	}
 919
 920	tos = icmp_pointers[type].error ? (RT_TOS(iph->tos) |
 921					   IPTOS_PREC_INTERNETCONTROL) :
 922					   iph->tos;
 923	mark = IP4_REPLY_MARK(net, skb_in->mark);
 924
 925	if (__ip_options_echo(net, &icmp_param.replyopts.opt.opt, skb_in,
 926			      &parm->opt))
 927		goto out_unlock;
 928
 929
 930	/*
 931	 *	Prepare data for ICMP header.
 932	 */
 933
 934	icmp_param.data.icmph.type	 = type;
 935	icmp_param.data.icmph.code	 = code;
 936	icmp_param.data.icmph.un.gateway = info;
 937	icmp_param.data.icmph.checksum	 = 0;
 938	icmp_param.skb	  = skb_in;
 939	icmp_param.offset = skb_network_offset(skb_in);
 940	ipcm_init(&ipc);
 941	ipc.tos = tos;
 942	ipc.addr = iph->saddr;
 943	ipc.opt = &icmp_param.replyopts.opt;
 944	ipc.sockc.mark = mark;
 945
 946	rt = icmp_route_lookup(net, &fl4, skb_in, iph, saddr,
 947			       inet_dsfield_to_dscp(tos), mark, type, code,
 948			       &icmp_param);
 949	if (IS_ERR(rt))
 950		goto out_unlock;
 951
 952	/* peer icmp_ratelimit */
 953	if (!icmpv4_xrlim_allow(net, rt, &fl4, type, code, apply_ratelimit))
 954		goto ende;
 955
 956	/* RFC says return as much as we can without exceeding 576 bytes. */
 957
 958	room = dst_mtu(&rt->dst);
 959	if (room > 576)
 960		room = 576;
 961	room -= sizeof(struct iphdr) + icmp_param.replyopts.opt.opt.optlen;
 962	room -= sizeof(struct icmphdr);
 963	/* Guard against tiny mtu. We need to include at least one
 964	 * IP network header for this message to make any sense.
 965	 */
 966	if (room <= (int)sizeof(struct iphdr))
 967		goto ende;
 968
 969	ext_skb = icmp_ext_append(net, skb_in, &icmp_param.data.icmph, room,
 970				  parm->iif);
 971	if (ext_skb)
 972		icmp_param.skb = ext_skb;
 973
 974	icmp_param.data_len = icmp_param.skb->len - icmp_param.offset;
 975	if (icmp_param.data_len > room)
 976		icmp_param.data_len = room;
 977	icmp_param.head_len = sizeof(struct icmphdr);
 978
 979	/* if we don't have a source address at this point, fall back to the
 980	 * dummy address instead of sending out a packet with a source address
 981	 * of 0.0.0.0
 982	 */
 983	if (!fl4.saddr)
 984		fl4.saddr = htonl(INADDR_DUMMY);
 985
 986	trace_icmp_send(skb_in, type, code);
 987
 988	icmp_push_reply(sk, &icmp_param, &fl4, &ipc, &rt);
 989
 990	if (ext_skb)
 991		consume_skb(ext_skb);
 992ende:
 993	ip_rt_put(rt);
 994out_unlock:
 995	icmp_xmit_unlock(sk);
 996out_bh_enable:
 997	local_bh_enable();
 998out:
 999	rcu_read_unlock();
1000}
1001EXPORT_SYMBOL(__icmp_send);
1002
1003#if IS_ENABLED(CONFIG_NF_NAT)
1004#include <net/netfilter/nf_conntrack.h>
1005void icmp_ndo_send(struct sk_buff *skb_in, int type, int code, __be32 info)
1006{
1007	struct sk_buff *cloned_skb = NULL;
1008	enum ip_conntrack_info ctinfo;
1009	enum ip_conntrack_dir dir;
1010	struct inet_skb_parm parm;
1011	struct nf_conn *ct;
1012	__be32 orig_ip;
1013
1014	memset(&parm, 0, sizeof(parm));
1015	ct = nf_ct_get(skb_in, &ctinfo);
1016	if (!ct || !(READ_ONCE(ct->status) & IPS_NAT_MASK)) {
1017		__icmp_send(skb_in, type, code, info, &parm);
1018		return;
1019	}
1020
1021	if (skb_shared(skb_in))
1022		skb_in = cloned_skb = skb_clone(skb_in, GFP_ATOMIC);
1023
1024	if (unlikely(!skb_in || skb_network_header(skb_in) < skb_in->head ||
1025	    (skb_network_header(skb_in) + sizeof(struct iphdr)) >
1026	    skb_tail_pointer(skb_in) || skb_ensure_writable(skb_in,
1027	    skb_network_offset(skb_in) + sizeof(struct iphdr))))
1028		goto out;
1029
1030	orig_ip = ip_hdr(skb_in)->saddr;
1031	dir = CTINFO2DIR(ctinfo);
1032	ip_hdr(skb_in)->saddr = ct->tuplehash[dir].tuple.src.u3.ip;
1033	__icmp_send(skb_in, type, code, info, &parm);
1034	ip_hdr(skb_in)->saddr = orig_ip;
1035out:
1036	consume_skb(cloned_skb);
1037}
1038EXPORT_SYMBOL(icmp_ndo_send);
1039#endif
1040
1041static void icmp_socket_deliver(struct sk_buff *skb, u32 info)
1042{
1043	const struct iphdr *iph = (const struct iphdr *)skb->data;
1044	const struct net_protocol *ipprot;
1045	int protocol = iph->protocol;
1046
1047	/* Checkin full IP header plus 8 bytes of protocol to
1048	 * avoid additional coding at protocol handlers.
1049	 */
1050	if (!pskb_may_pull(skb, iph->ihl * 4 + 8))
1051		goto out;
1052
1053	/* IPPROTO_RAW sockets are not supposed to receive anything. */
1054	if (protocol == IPPROTO_RAW)
1055		goto out;
1056
1057	raw_icmp_error(skb, protocol, info);
1058
1059	ipprot = rcu_dereference(inet_protos[protocol]);
1060	if (ipprot && ipprot->err_handler)
1061		ipprot->err_handler(skb, info);
1062	return;
1063
1064out:
1065	__ICMP_INC_STATS(dev_net_rcu(skb->dev), ICMP_MIB_INERRORS);
1066}
1067
1068static bool icmp_tag_validation(int proto)
1069{
1070	const struct net_protocol *ipprot;
1071	bool ok;
1072
1073	rcu_read_lock();
1074	ipprot = rcu_dereference(inet_protos[proto]);
1075	ok = ipprot ? ipprot->icmp_strict_tag_validation : false;
1076	rcu_read_unlock();
1077	return ok;
1078}
1079
1080/*
1081 *	Handle ICMP_DEST_UNREACH, ICMP_TIME_EXCEEDED, ICMP_QUENCH, and
1082 *	ICMP_PARAMETERPROB.
1083 */
1084
1085static enum skb_drop_reason icmp_unreach(struct sk_buff *skb)
1086{
1087	enum skb_drop_reason reason = SKB_NOT_DROPPED_YET;
1088	const struct iphdr *iph;
1089	struct icmphdr *icmph;
1090	struct net *net;
1091	u32 info = 0;
1092
1093	net = skb_dst_dev_net_rcu(skb);
1094
1095	/*
1096	 *	Incomplete header ?
1097	 * 	Only checks for the IP header, there should be an
1098	 *	additional check for longer headers in upper levels.
1099	 */
1100
1101	if (!pskb_may_pull(skb, sizeof(struct iphdr)))
1102		goto out_err;
1103
1104	icmph = icmp_hdr(skb);
1105	iph   = (const struct iphdr *)skb->data;
1106
1107	if (iph->ihl < 5)  { /* Mangled header, drop. */
1108		reason = SKB_DROP_REASON_IP_INHDR;
1109		goto out_err;
1110	}
1111
1112	switch (icmph->type) {
1113	case ICMP_DEST_UNREACH:
1114		switch (icmph->code & 15) {
1115		case ICMP_NET_UNREACH:
1116		case ICMP_HOST_UNREACH:
1117		case ICMP_PROT_UNREACH:
1118		case ICMP_PORT_UNREACH:
1119			break;
1120		case ICMP_FRAG_NEEDED:
1121			/* for documentation of the ip_no_pmtu_disc
1122			 * values please see
1123			 * Documentation/networking/ip-sysctl.rst
1124			 */
1125			switch (READ_ONCE(net->ipv4.sysctl_ip_no_pmtu_disc)) {
1126			default:
1127				net_dbg_ratelimited("%pI4: fragmentation needed and DF set\n",
1128						    &iph->daddr);
1129				break;
1130			case 2:
1131				goto out;
1132			case 3:
1133				if (!icmp_tag_validation(iph->protocol))
1134					goto out;
1135				fallthrough;
1136			case 0:
1137				info = ntohs(icmph->un.frag.mtu);
1138			}
1139			break;
1140		case ICMP_SR_FAILED:
1141			net_dbg_ratelimited("%pI4: Source Route Failed\n",
1142					    &iph->daddr);
1143			break;
1144		default:
1145			break;
1146		}
1147		if (icmph->code > NR_ICMP_UNREACH)
1148			goto out;
1149		break;
1150	case ICMP_PARAMETERPROB:
1151		info = ntohl(icmph->un.gateway) >> 24;
1152		break;
1153	case ICMP_TIME_EXCEEDED:
1154		__ICMP_INC_STATS(net, ICMP_MIB_INTIMEEXCDS);
1155		if (icmph->code == ICMP_EXC_FRAGTIME)
1156			goto out;
1157		break;
1158	}
1159
1160	/*
1161	 *	Throw it at our lower layers
1162	 *
1163	 *	RFC 1122: 3.2.2 MUST extract the protocol ID from the passed
1164	 *		  header.
1165	 *	RFC 1122: 3.2.2.1 MUST pass ICMP unreach messages to the
1166	 *		  transport layer.
1167	 *	RFC 1122: 3.2.2.2 MUST pass ICMP time expired messages to
1168	 *		  transport layer.
1169	 */
1170
1171	/*
1172	 *	Check the other end isn't violating RFC 1122. Some routers send
1173	 *	bogus responses to broadcast frames. If you see this message
1174	 *	first check your netmask matches at both ends, if it does then
1175	 *	get the other vendor to fix their kit.
1176	 */
1177
1178	if (!READ_ONCE(net->ipv4.sysctl_icmp_ignore_bogus_error_responses) &&
1179	    inet_addr_type_dev_table(net, skb->dev, iph->daddr) == RTN_BROADCAST) {
1180		net_warn_ratelimited("%pI4 sent an invalid ICMP type %u, code %u error to a broadcast: %pI4 on %s\n",
1181				     &ip_hdr(skb)->saddr,
1182				     icmph->type, icmph->code,
1183				     &iph->daddr, skb->dev->name);
1184		goto out;
1185	}
1186
1187	icmp_socket_deliver(skb, info);
1188
1189out:
1190	return reason;
1191out_err:
1192	__ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
1193	return reason ?: SKB_DROP_REASON_NOT_SPECIFIED;
1194}
1195
1196
1197/*
1198 *	Handle ICMP_REDIRECT.
1199 */
1200
1201static enum skb_drop_reason icmp_redirect(struct sk_buff *skb)
1202{
1203	if (skb->len < sizeof(struct iphdr)) {
1204		__ICMP_INC_STATS(dev_net_rcu(skb->dev), ICMP_MIB_INERRORS);
1205		return SKB_DROP_REASON_PKT_TOO_SMALL;
1206	}
1207
1208	if (!pskb_may_pull(skb, sizeof(struct iphdr))) {
1209		/* there aught to be a stat */
1210		return SKB_DROP_REASON_NOMEM;
1211	}
1212
1213	icmp_socket_deliver(skb, ntohl(icmp_hdr(skb)->un.gateway));
1214	return SKB_NOT_DROPPED_YET;
1215}
1216
1217/*
1218 *	Handle ICMP_ECHO ("ping") and ICMP_EXT_ECHO ("PROBE") requests.
1219 *
1220 *	RFC 1122: 3.2.2.6 MUST have an echo server that answers ICMP echo
1221 *		  requests.
1222 *	RFC 1122: 3.2.2.6 Data received in the ICMP_ECHO request MUST be
1223 *		  included in the reply.
1224 *	RFC 1812: 4.3.3.6 SHOULD have a config option for silently ignoring
1225 *		  echo requests, MUST have default=NOT.
1226 *	RFC 8335: 8 MUST have a config option to enable/disable ICMP
1227 *		  Extended Echo Functionality, MUST be disabled by default
1228 *	See also WRT handling of options once they are done and working.
1229 */
1230
1231static enum skb_drop_reason icmp_echo(struct sk_buff *skb)
1232{
1233	struct icmp_bxm icmp_param;
1234	struct net *net;
1235
1236	net = skb_dst_dev_net_rcu(skb);
1237	/* should there be an ICMP stat for ignored echos? */
1238	if (READ_ONCE(net->ipv4.sysctl_icmp_echo_ignore_all))
1239		return SKB_NOT_DROPPED_YET;
1240
1241	icmp_param.data.icmph	   = *icmp_hdr(skb);
1242	icmp_param.skb		   = skb;
1243	icmp_param.offset	   = 0;
1244	icmp_param.data_len	   = skb->len;
1245	icmp_param.head_len	   = sizeof(struct icmphdr);
1246
1247	if (icmp_param.data.icmph.type == ICMP_ECHO)
1248		icmp_param.data.icmph.type = ICMP_ECHOREPLY;
1249	else if (!icmp_build_probe(skb, &icmp_param.data.icmph))
1250		return SKB_NOT_DROPPED_YET;
1251
1252	icmp_reply(&icmp_param, skb);
1253	return SKB_NOT_DROPPED_YET;
1254}
1255
1256/*	Helper for icmp_echo and icmpv6_echo_reply.
1257 *	Searches for net_device that matches PROBE interface identifier
1258 *		and builds PROBE reply message in icmphdr.
1259 *
1260 *	Returns false if PROBE responses are disabled via sysctl
1261 */
1262
1263bool icmp_build_probe(struct sk_buff *skb, struct icmphdr *icmphdr)
1264{
1265	struct net *net = dev_net_rcu(skb->dev);
1266	struct icmp_ext_hdr *ext_hdr, _ext_hdr;
1267	struct icmp_ext_echo_iio *iio, _iio;
1268	struct inet6_dev *in6_dev;
1269	struct in_device *in_dev;
1270	struct net_device *dev;
1271	char buff[IFNAMSIZ];
1272	u16 ident_len;
1273	u8 status;
1274
1275	if (!READ_ONCE(net->ipv4.sysctl_icmp_echo_enable_probe))
1276		return false;
1277
1278	/* We currently only support probing interfaces on the proxy node
1279	 * Check to ensure L-bit is set
1280	 */
1281	if (!(ntohs(icmphdr->un.echo.sequence) & 1))
1282		return false;
1283	/* Clear status bits in reply message */
1284	icmphdr->un.echo.sequence &= htons(0xFF00);
1285	if (icmphdr->type == ICMP_EXT_ECHO)
1286		icmphdr->type = ICMP_EXT_ECHOREPLY;
1287	else
1288		icmphdr->type = ICMPV6_EXT_ECHO_REPLY;
1289	ext_hdr = skb_header_pointer(skb, 0, sizeof(_ext_hdr), &_ext_hdr);
1290	/* Size of iio is class_type dependent.
1291	 * Only check header here and assign length based on ctype in the switch statement
1292	 */
1293	iio = skb_header_pointer(skb, sizeof(_ext_hdr), sizeof(iio->extobj_hdr), &_iio);
1294	if (!ext_hdr || !iio)
1295		goto send_mal_query;
1296	if (ntohs(iio->extobj_hdr.length) <= sizeof(iio->extobj_hdr) ||
1297	    ntohs(iio->extobj_hdr.length) > sizeof(_iio))
1298		goto send_mal_query;
1299	ident_len = ntohs(iio->extobj_hdr.length) - sizeof(iio->extobj_hdr);
1300	iio = skb_header_pointer(skb, sizeof(_ext_hdr),
1301				 sizeof(iio->extobj_hdr) + ident_len, &_iio);
1302	if (!iio)
1303		goto send_mal_query;
1304
1305	status = 0;
1306	dev = NULL;
1307	switch (iio->extobj_hdr.class_type) {
1308	case ICMP_EXT_ECHO_CTYPE_NAME:
1309		if (ident_len >= IFNAMSIZ)
1310			goto send_mal_query;
1311		memset(buff, 0, sizeof(buff));
1312		memcpy(buff, &iio->ident.name, ident_len);
1313		dev = dev_get_by_name(net, buff);
1314		break;
1315	case ICMP_EXT_ECHO_CTYPE_INDEX:
1316		if (ident_len != sizeof(iio->ident.ifindex))
1317			goto send_mal_query;
1318		dev = dev_get_by_index(net, ntohl(iio->ident.ifindex));
1319		break;
1320	case ICMP_EXT_ECHO_CTYPE_ADDR:
1321		if (ident_len < sizeof(iio->ident.addr.ctype3_hdr) ||
1322		    ident_len != sizeof(iio->ident.addr.ctype3_hdr) +
1323				 iio->ident.addr.ctype3_hdr.addrlen)
1324			goto send_mal_query;
1325		switch (ntohs(iio->ident.addr.ctype3_hdr.afi)) {
1326		case ICMP_AFI_IP:
1327			if (iio->ident.addr.ctype3_hdr.addrlen != sizeof(struct in_addr))
1328				goto send_mal_query;
1329			dev = ip_dev_find(net, iio->ident.addr.ip_addr.ipv4_addr);
1330			break;
1331#if IS_ENABLED(CONFIG_IPV6)
1332		case ICMP_AFI_IP6:
1333			if (iio->ident.addr.ctype3_hdr.addrlen != sizeof(struct in6_addr))
1334				goto send_mal_query;
1335			dev = ipv6_stub->ipv6_dev_find(net, &iio->ident.addr.ip_addr.ipv6_addr, dev);
1336			/*
1337			 * If IPv6 identifier lookup is unavailable, silently
1338			 * discard the request instead of misreporting NO_IF.
1339			 */
1340			if (IS_ERR(dev))
1341				return false;
1342
1343			dev_hold(dev);
1344			break;
1345#endif
1346		default:
1347			goto send_mal_query;
1348		}
1349		break;
1350	default:
1351		goto send_mal_query;
1352	}
1353	if (!dev) {
1354		icmphdr->code = ICMP_EXT_CODE_NO_IF;
1355		return true;
1356	}
1357	/* Fill bits in reply message */
1358	if (dev->flags & IFF_UP)
1359		status |= ICMP_EXT_ECHOREPLY_ACTIVE;
1360
1361	in_dev = __in_dev_get_rcu(dev);
1362	if (in_dev && rcu_access_pointer(in_dev->ifa_list))
1363		status |= ICMP_EXT_ECHOREPLY_IPV4;
1364
1365	in6_dev = __in6_dev_get(dev);
1366	if (in6_dev && !list_empty(&in6_dev->addr_list))
1367		status |= ICMP_EXT_ECHOREPLY_IPV6;
1368
1369	dev_put(dev);
1370	icmphdr->un.echo.sequence |= htons(status);
1371	return true;
1372send_mal_query:
1373	icmphdr->code = ICMP_EXT_CODE_MAL_QUERY;
1374	return true;
1375}
1376EXPORT_SYMBOL_GPL(icmp_build_probe);
1377
1378/*
1379 *	Handle ICMP Timestamp requests.
1380 *	RFC 1122: 3.2.2.8 MAY implement ICMP timestamp requests.
1381 *		  SHOULD be in the kernel for minimum random latency.
1382 *		  MUST be accurate to a few minutes.
1383 *		  MUST be updated at least at 15Hz.
1384 */
1385static enum skb_drop_reason icmp_timestamp(struct sk_buff *skb)
1386{
1387	struct icmp_bxm icmp_param;
1388	/*
1389	 *	Too short.
1390	 */
1391	if (skb->len < 4)
1392		goto out_err;
1393
1394	/*
1395	 *	Fill in the current time as ms since midnight UT:
1396	 */
1397	icmp_param.data.times[1] = inet_current_timestamp();
1398	icmp_param.data.times[2] = icmp_param.data.times[1];
1399
1400	BUG_ON(skb_copy_bits(skb, 0, &icmp_param.data.times[0], 4));
1401
1402	icmp_param.data.icmph	   = *icmp_hdr(skb);
1403	icmp_param.data.icmph.type = ICMP_TIMESTAMPREPLY;
1404	icmp_param.data.icmph.code = 0;
1405	icmp_param.skb		   = skb;
1406	icmp_param.offset	   = 0;
1407	icmp_param.data_len	   = 0;
1408	icmp_param.head_len	   = sizeof(struct icmphdr) + 12;
1409	icmp_reply(&icmp_param, skb);
1410	return SKB_NOT_DROPPED_YET;
1411
1412out_err:
1413	__ICMP_INC_STATS(skb_dst_dev_net_rcu(skb), ICMP_MIB_INERRORS);
1414	return SKB_DROP_REASON_PKT_TOO_SMALL;
1415}
1416
1417static enum skb_drop_reason icmp_discard(struct sk_buff *skb)
1418{
1419	/* pretend it was a success */
1420	return SKB_NOT_DROPPED_YET;
1421}
1422
1423/*
1424 *	Deal with incoming ICMP packets.
1425 */
1426int icmp_rcv(struct sk_buff *skb)
1427{
1428	enum skb_drop_reason reason = SKB_DROP_REASON_NOT_SPECIFIED;
1429	struct rtable *rt = skb_rtable(skb);
1430	struct net *net = dev_net_rcu(rt->dst.dev);
1431	struct icmphdr *icmph;
1432
1433	if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) {
1434		struct sec_path *sp = skb_sec_path(skb);
1435		int nh;
1436
1437		if (!(sp && sp->xvec[sp->len - 1]->props.flags &
1438				 XFRM_STATE_ICMP)) {
1439			reason = SKB_DROP_REASON_XFRM_POLICY;
1440			goto drop;
1441		}
1442
1443		if (!pskb_may_pull(skb, sizeof(*icmph) + sizeof(struct iphdr)))
1444			goto drop;
1445
1446		nh = skb_network_offset(skb);
1447		skb_set_network_header(skb, sizeof(*icmph));
1448
1449		if (!xfrm4_policy_check_reverse(NULL, XFRM_POLICY_IN,
1450						skb)) {
1451			reason = SKB_DROP_REASON_XFRM_POLICY;
1452			goto drop;
1453		}
1454
1455		skb_set_network_header(skb, nh);
1456	}
1457
1458	__ICMP_INC_STATS(net, ICMP_MIB_INMSGS);
1459
1460	if (skb_checksum_simple_validate(skb))
1461		goto csum_error;
1462
1463	if (!pskb_pull(skb, sizeof(*icmph)))
1464		goto error;
1465
1466	icmph = icmp_hdr(skb);
1467
1468	ICMPMSGIN_INC_STATS(net, icmph->type);
1469
1470	/* Check for ICMP Extended Echo (PROBE) messages */
1471	if (icmph->type == ICMP_EXT_ECHO) {
1472		/* We can't use icmp_pointers[].handler() because it is an array of
1473		 * size NR_ICMP_TYPES + 1 (19 elements) and PROBE has code 42.
1474		 */
1475		reason = icmp_echo(skb);
1476		goto reason_check;
1477	}
1478
1479	/*
1480	 *	Parse the ICMP message
1481	 */
1482
1483	if (rt->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST)) {
1484		/*
1485		 *	RFC 1122: 3.2.2.6 An ICMP_ECHO to broadcast MAY be
1486		 *	  silently ignored (we let user decide with a sysctl).
1487		 *	RFC 1122: 3.2.2.8 An ICMP_TIMESTAMP MAY be silently
1488		 *	  discarded if to broadcast/multicast.
1489		 */
1490		if ((icmph->type == ICMP_ECHO ||
1491		     icmph->type == ICMP_TIMESTAMP) &&
1492		    READ_ONCE(net->ipv4.sysctl_icmp_echo_ignore_broadcasts)) {
1493			reason = SKB_DROP_REASON_INVALID_PROTO;
1494			goto error;
1495		}
1496		if (icmph->type != ICMP_ECHO &&
1497		    icmph->type != ICMP_TIMESTAMP &&
1498		    icmph->type != ICMP_ADDRESS &&
1499		    icmph->type != ICMP_ADDRESSREPLY) {
1500			reason = SKB_DROP_REASON_INVALID_PROTO;
1501			goto error;
1502		}
1503	}
1504
1505	if (icmph->type == ICMP_EXT_ECHOREPLY ||
1506	    icmph->type == ICMP_ECHOREPLY) {
1507		reason = ping_rcv(skb);
1508		return reason ? NET_RX_DROP : NET_RX_SUCCESS;
1509	}
1510
1511	/*
1512	 *	18 is the highest 'known' ICMP type. Anything else is a mystery
1513	 *
1514	 *	RFC 1122: 3.2.2  Unknown ICMP messages types MUST be silently
1515	 *		  discarded.
1516	 */
1517	if (icmph->type > NR_ICMP_TYPES) {
1518		reason = SKB_DROP_REASON_UNHANDLED_PROTO;
1519		goto error;
1520	}
1521
1522	reason = icmp_pointers[icmph->type].handler(skb);
1523reason_check:
1524	if (!reason)  {
1525		consume_skb(skb);
1526		return NET_RX_SUCCESS;
1527	}
1528
1529drop:
1530	kfree_skb_reason(skb, reason);
1531	return NET_RX_DROP;
1532csum_error:
1533	reason = SKB_DROP_REASON_ICMP_CSUM;
1534	__ICMP_INC_STATS(net, ICMP_MIB_CSUMERRORS);
1535error:
1536	__ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
1537	goto drop;
1538}
1539
1540static bool ip_icmp_error_rfc4884_validate(const struct sk_buff *skb, int off)
1541{
1542	struct icmp_extobj_hdr *objh, _objh;
1543	struct icmp_ext_hdr *exth, _exth;
1544	u16 olen;
1545
1546	exth = skb_header_pointer(skb, off, sizeof(_exth), &_exth);
1547	if (!exth)
1548		return false;
1549	if (exth->version != 2)
1550		return true;
1551
1552	if (exth->checksum &&
1553	    csum_fold(skb_checksum(skb, off, skb->len - off, 0)))
1554		return false;
1555
1556	off += sizeof(_exth);
1557	while (off < skb->len) {
1558		objh = skb_header_pointer(skb, off, sizeof(_objh), &_objh);
1559		if (!objh)
1560			return false;
1561
1562		olen = ntohs(objh->length);
1563		if (olen < sizeof(_objh))
1564			return false;
1565
1566		off += olen;
1567		if (off > skb->len)
1568			return false;
1569	}
1570
1571	return true;
1572}
1573
1574void ip_icmp_error_rfc4884(const struct sk_buff *skb,
1575			   struct sock_ee_data_rfc4884 *out,
1576			   int thlen, int off)
1577{
1578	int hlen;
1579
1580	/* original datagram headers: end of icmph to payload (skb->data) */
1581	hlen = -skb_transport_offset(skb) - thlen;
1582
1583	/* per rfc 4884: minimal datagram length of 128 bytes */
1584	if (off < 128 || off < hlen)
1585		return;
1586
1587	/* kernel has stripped headers: return payload offset in bytes */
1588	off -= hlen;
1589	if (off + sizeof(struct icmp_ext_hdr) > skb->len)
1590		return;
1591
1592	out->len = off;
1593
1594	if (!ip_icmp_error_rfc4884_validate(skb, off))
1595		out->flags |= SO_EE_RFC4884_FLAG_INVALID;
1596}
1597EXPORT_SYMBOL_GPL(ip_icmp_error_rfc4884);
1598
1599int icmp_err(struct sk_buff *skb, u32 info)
1600{
1601	struct iphdr *iph = (struct iphdr *)skb->data;
1602	int offset = iph->ihl<<2;
1603	struct icmphdr *icmph = (struct icmphdr *)(skb->data + offset);
1604	struct net *net = dev_net_rcu(skb->dev);
1605	int type = icmp_hdr(skb)->type;
1606	int code = icmp_hdr(skb)->code;
1607
1608	/*
1609	 * Use ping_err to handle all icmp errors except those
1610	 * triggered by ICMP_ECHOREPLY which sent from kernel.
1611	 */
1612	if (icmph->type != ICMP_ECHOREPLY) {
1613		ping_err(skb, offset, info);
1614		return 0;
1615	}
1616
1617	if (type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED)
1618		ipv4_update_pmtu(skb, net, info, 0, IPPROTO_ICMP);
1619	else if (type == ICMP_REDIRECT)
1620		ipv4_redirect(skb, net, 0, IPPROTO_ICMP);
1621
1622	return 0;
1623}
1624
1625/*
1626 *	This table is the definition of how we handle ICMP.
1627 */
1628static const struct icmp_control icmp_pointers[NR_ICMP_TYPES + 1] = {
1629	[ICMP_ECHOREPLY] = {
1630		.handler = ping_rcv,
1631	},
1632	[1] = {
1633		.handler = icmp_discard,
1634		.error = 1,
1635	},
1636	[2] = {
1637		.handler = icmp_discard,
1638		.error = 1,
1639	},
1640	[ICMP_DEST_UNREACH] = {
1641		.handler = icmp_unreach,
1642		.error = 1,
1643	},
1644	[ICMP_SOURCE_QUENCH] = {
1645		.handler = icmp_unreach,
1646		.error = 1,
1647	},
1648	[ICMP_REDIRECT] = {
1649		.handler = icmp_redirect,
1650		.error = 1,
1651	},
1652	[6] = {
1653		.handler = icmp_discard,
1654		.error = 1,
1655	},
1656	[7] = {
1657		.handler = icmp_discard,
1658		.error = 1,
1659	},
1660	[ICMP_ECHO] = {
1661		.handler = icmp_echo,
1662	},
1663	[9] = {
1664		.handler = icmp_discard,
1665		.error = 1,
1666	},
1667	[10] = {
1668		.handler = icmp_discard,
1669		.error = 1,
1670	},
1671	[ICMP_TIME_EXCEEDED] = {
1672		.handler = icmp_unreach,
1673		.error = 1,
1674	},
1675	[ICMP_PARAMETERPROB] = {
1676		.handler = icmp_unreach,
1677		.error = 1,
1678	},
1679	[ICMP_TIMESTAMP] = {
1680		.handler = icmp_timestamp,
1681	},
1682	[ICMP_TIMESTAMPREPLY] = {
1683		.handler = icmp_discard,
1684	},
1685	[ICMP_INFO_REQUEST] = {
1686		.handler = icmp_discard,
1687	},
1688	[ICMP_INFO_REPLY] = {
1689		.handler = icmp_discard,
1690	},
1691	[ICMP_ADDRESS] = {
1692		.handler = icmp_discard,
1693	},
1694	[ICMP_ADDRESSREPLY] = {
1695		.handler = icmp_discard,
1696	},
1697};
1698
1699static int __net_init icmp_sk_init(struct net *net)
1700{
1701	/* Control parameters for ECHO replies. */
1702	net->ipv4.sysctl_icmp_echo_ignore_all = 0;
1703	net->ipv4.sysctl_icmp_echo_enable_probe = 0;
1704	net->ipv4.sysctl_icmp_echo_ignore_broadcasts = 1;
1705
1706	/* Control parameter - ignore bogus broadcast responses? */
1707	net->ipv4.sysctl_icmp_ignore_bogus_error_responses = 1;
1708
1709	/*
1710	 * 	Configurable global rate limit.
1711	 *
1712	 *	ratelimit defines tokens/packet consumed for dst->rate_token
1713	 *	bucket ratemask defines which icmp types are ratelimited by
1714	 *	setting	it's bit position.
1715	 *
1716	 *	default:
1717	 *	dest unreachable (3), source quench (4),
1718	 *	time exceeded (11), parameter problem (12)
1719	 */
1720
1721	net->ipv4.sysctl_icmp_ratelimit = 1 * HZ;
1722	net->ipv4.sysctl_icmp_ratemask = 0x1818;
1723	net->ipv4.sysctl_icmp_errors_use_inbound_ifaddr = 0;
1724	net->ipv4.sysctl_icmp_errors_extension_mask = 0;
1725	net->ipv4.sysctl_icmp_msgs_per_sec = 1000;
1726	net->ipv4.sysctl_icmp_msgs_burst = 50;
1727
1728	return 0;
1729}
1730
1731static struct pernet_operations __net_initdata icmp_sk_ops = {
1732       .init = icmp_sk_init,
1733};
1734
1735int __init icmp_init(void)
1736{
1737	int err, i;
1738
1739	for_each_possible_cpu(i) {
1740		struct sock *sk;
1741
1742		err = inet_ctl_sock_create(&sk, PF_INET,
1743					   SOCK_RAW, IPPROTO_ICMP, &init_net);
1744		if (err < 0)
1745			return err;
1746
1747		per_cpu(ipv4_icmp_sk, i) = sk;
1748
1749		/* Enough space for 2 64K ICMP packets, including
1750		 * sk_buff/skb_shared_info struct overhead.
1751		 */
1752		sk->sk_sndbuf =	2 * SKB_TRUESIZE(64 * 1024);
1753
1754		/*
1755		 * Speedup sock_wfree()
1756		 */
1757		sock_set_flag(sk, SOCK_USE_WRITE_QUEUE);
1758		inet_sk(sk)->pmtudisc = IP_PMTUDISC_DONT;
1759	}
1760	return register_pernet_subsys(&icmp_sk_ops);
1761}
~/ Read-only file preview.