xref: /linux/net/ipv4/icmp.c (revision da5b2ad1c2f18834cb1ce429e2e5a5cf5cbdf21b)
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/snmp.h>
76 #include <net/ip.h>
77 #include <net/route.h>
78 #include <net/protocol.h>
79 #include <net/icmp.h>
80 #include <net/tcp.h>
81 #include <net/udp.h>
82 #include <net/raw.h>
83 #include <net/ping.h>
84 #include <linux/skbuff.h>
85 #include <net/sock.h>
86 #include <linux/errno.h>
87 #include <linux/timer.h>
88 #include <linux/init.h>
89 #include <linux/uaccess.h>
90 #include <net/checksum.h>
91 #include <net/xfrm.h>
92 #include <net/inet_common.h>
93 #include <net/ip_fib.h>
94 #include <net/l3mdev.h>
95 #include <net/addrconf.h>
96 #define CREATE_TRACE_POINTS
97 #include <trace/events/icmp.h>
98 
99 /*
100  *	Build xmit assembly blocks
101  */
102 
103 struct icmp_bxm {
104 	struct sk_buff *skb;
105 	int offset;
106 	int data_len;
107 
108 	struct {
109 		struct icmphdr icmph;
110 		__be32	       times[3];
111 	} data;
112 	int head_len;
113 	struct ip_options_data replyopts;
114 };
115 
116 /* An array of errno for error messages from dest unreach. */
117 /* RFC 1122: 3.2.2.1 States that NET_UNREACH, HOST_UNREACH and SR_FAILED MUST be considered 'transient errs'. */
118 
119 const struct icmp_err icmp_err_convert[] = {
120 	{
121 		.errno = ENETUNREACH,	/* ICMP_NET_UNREACH */
122 		.fatal = 0,
123 	},
124 	{
125 		.errno = EHOSTUNREACH,	/* ICMP_HOST_UNREACH */
126 		.fatal = 0,
127 	},
128 	{
129 		.errno = ENOPROTOOPT	/* ICMP_PROT_UNREACH */,
130 		.fatal = 1,
131 	},
132 	{
133 		.errno = ECONNREFUSED,	/* ICMP_PORT_UNREACH */
134 		.fatal = 1,
135 	},
136 	{
137 		.errno = EMSGSIZE,	/* ICMP_FRAG_NEEDED */
138 		.fatal = 0,
139 	},
140 	{
141 		.errno = EOPNOTSUPP,	/* ICMP_SR_FAILED */
142 		.fatal = 0,
143 	},
144 	{
145 		.errno = ENETUNREACH,	/* ICMP_NET_UNKNOWN */
146 		.fatal = 1,
147 	},
148 	{
149 		.errno = EHOSTDOWN,	/* ICMP_HOST_UNKNOWN */
150 		.fatal = 1,
151 	},
152 	{
153 		.errno = ENONET,	/* ICMP_HOST_ISOLATED */
154 		.fatal = 1,
155 	},
156 	{
157 		.errno = ENETUNREACH,	/* ICMP_NET_ANO	*/
158 		.fatal = 1,
159 	},
160 	{
161 		.errno = EHOSTUNREACH,	/* ICMP_HOST_ANO */
162 		.fatal = 1,
163 	},
164 	{
165 		.errno = ENETUNREACH,	/* ICMP_NET_UNR_TOS */
166 		.fatal = 0,
167 	},
168 	{
169 		.errno = EHOSTUNREACH,	/* ICMP_HOST_UNR_TOS */
170 		.fatal = 0,
171 	},
172 	{
173 		.errno = EHOSTUNREACH,	/* ICMP_PKT_FILTERED */
174 		.fatal = 1,
175 	},
176 	{
177 		.errno = EHOSTUNREACH,	/* ICMP_PREC_VIOLATION */
178 		.fatal = 1,
179 	},
180 	{
181 		.errno = EHOSTUNREACH,	/* ICMP_PREC_CUTOFF */
182 		.fatal = 1,
183 	},
184 };
185 EXPORT_SYMBOL(icmp_err_convert);
186 
187 /*
188  *	ICMP control array. This specifies what to do with each ICMP.
189  */
190 
191 struct icmp_control {
192 	enum skb_drop_reason (*handler)(struct sk_buff *skb);
193 	short   error;		/* This ICMP is classed as an error message */
194 };
195 
196 static const struct icmp_control icmp_pointers[NR_ICMP_TYPES+1];
197 
198 static DEFINE_PER_CPU(struct sock *, ipv4_icmp_sk);
199 
200 /* Called with BH disabled */
201 static inline struct sock *icmp_xmit_lock(struct net *net)
202 {
203 	struct sock *sk;
204 
205 	sk = this_cpu_read(ipv4_icmp_sk);
206 
207 	if (unlikely(!spin_trylock(&sk->sk_lock.slock))) {
208 		/* This can happen if the output path signals a
209 		 * dst_link_failure() for an outgoing ICMP packet.
210 		 */
211 		return NULL;
212 	}
213 	sock_net_set(sk, net);
214 	return sk;
215 }
216 
217 static inline void icmp_xmit_unlock(struct sock *sk)
218 {
219 	sock_net_set(sk, &init_net);
220 	spin_unlock(&sk->sk_lock.slock);
221 }
222 
223 int sysctl_icmp_msgs_per_sec __read_mostly = 1000;
224 int sysctl_icmp_msgs_burst __read_mostly = 50;
225 
226 static struct {
227 	spinlock_t	lock;
228 	u32		credit;
229 	u32		stamp;
230 } icmp_global = {
231 	.lock		= __SPIN_LOCK_UNLOCKED(icmp_global.lock),
232 };
233 
234 /**
235  * icmp_global_allow - Are we allowed to send one more ICMP message ?
236  *
237  * Uses a token bucket to limit our ICMP messages to ~sysctl_icmp_msgs_per_sec.
238  * Returns false if we reached the limit and can not send another packet.
239  * Note: called with BH disabled
240  */
241 bool icmp_global_allow(void)
242 {
243 	u32 credit, delta, incr = 0, now = (u32)jiffies;
244 	bool rc = false;
245 
246 	/* Check if token bucket is empty and cannot be refilled
247 	 * without taking the spinlock. The READ_ONCE() are paired
248 	 * with the following WRITE_ONCE() in this same function.
249 	 */
250 	if (!READ_ONCE(icmp_global.credit)) {
251 		delta = min_t(u32, now - READ_ONCE(icmp_global.stamp), HZ);
252 		if (delta < HZ / 50)
253 			return false;
254 	}
255 
256 	spin_lock(&icmp_global.lock);
257 	delta = min_t(u32, now - icmp_global.stamp, HZ);
258 	if (delta >= HZ / 50) {
259 		incr = READ_ONCE(sysctl_icmp_msgs_per_sec) * delta / HZ;
260 		if (incr)
261 			WRITE_ONCE(icmp_global.stamp, now);
262 	}
263 	credit = min_t(u32, icmp_global.credit + incr,
264 		       READ_ONCE(sysctl_icmp_msgs_burst));
265 	if (credit) {
266 		/* We want to use a credit of one in average, but need to randomize
267 		 * it for security reasons.
268 		 */
269 		credit = max_t(int, credit - get_random_u32_below(3), 0);
270 		rc = true;
271 	}
272 	WRITE_ONCE(icmp_global.credit, credit);
273 	spin_unlock(&icmp_global.lock);
274 	return rc;
275 }
276 EXPORT_SYMBOL(icmp_global_allow);
277 
278 static bool icmpv4_mask_allow(struct net *net, int type, int code)
279 {
280 	if (type > NR_ICMP_TYPES)
281 		return true;
282 
283 	/* Don't limit PMTU discovery. */
284 	if (type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED)
285 		return true;
286 
287 	/* Limit if icmp type is enabled in ratemask. */
288 	if (!((1 << type) & READ_ONCE(net->ipv4.sysctl_icmp_ratemask)))
289 		return true;
290 
291 	return false;
292 }
293 
294 static bool icmpv4_global_allow(struct net *net, int type, int code)
295 {
296 	if (icmpv4_mask_allow(net, type, code))
297 		return true;
298 
299 	if (icmp_global_allow())
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 
310 static bool icmpv4_xrlim_allow(struct net *net, struct rtable *rt,
311 			       struct flowi4 *fl4, int type, int code)
312 {
313 	struct dst_entry *dst = &rt->dst;
314 	struct inet_peer *peer;
315 	bool rc = true;
316 	int vif;
317 
318 	if (icmpv4_mask_allow(net, type, code))
319 		goto out;
320 
321 	/* No rate limit on loopback */
322 	if (dst->dev && (dst->dev->flags&IFF_LOOPBACK))
323 		goto out;
324 
325 	vif = l3mdev_master_ifindex(dst->dev);
326 	peer = inet_getpeer_v4(net->ipv4.peers, fl4->daddr, vif, 1);
327 	rc = inet_peer_xrlim_allow(peer,
328 				   READ_ONCE(net->ipv4.sysctl_icmp_ratelimit));
329 	if (peer)
330 		inet_putpeer(peer);
331 out:
332 	if (!rc)
333 		__ICMP_INC_STATS(net, ICMP_MIB_RATELIMITHOST);
334 	return rc;
335 }
336 
337 /*
338  *	Maintain the counters used in the SNMP statistics for outgoing ICMP
339  */
340 void icmp_out_count(struct net *net, unsigned char type)
341 {
342 	ICMPMSGOUT_INC_STATS(net, type);
343 	ICMP_INC_STATS(net, ICMP_MIB_OUTMSGS);
344 }
345 
346 /*
347  *	Checksum each fragment, and on the first include the headers and final
348  *	checksum.
349  */
350 static int icmp_glue_bits(void *from, char *to, int offset, int len, int odd,
351 			  struct sk_buff *skb)
352 {
353 	struct icmp_bxm *icmp_param = from;
354 	__wsum csum;
355 
356 	csum = skb_copy_and_csum_bits(icmp_param->skb,
357 				      icmp_param->offset + offset,
358 				      to, len);
359 
360 	skb->csum = csum_block_add(skb->csum, csum, odd);
361 	if (icmp_pointers[icmp_param->data.icmph.type].error)
362 		nf_ct_attach(skb, icmp_param->skb);
363 	return 0;
364 }
365 
366 static void icmp_push_reply(struct sock *sk,
367 			    struct icmp_bxm *icmp_param,
368 			    struct flowi4 *fl4,
369 			    struct ipcm_cookie *ipc, struct rtable **rt)
370 {
371 	struct sk_buff *skb;
372 
373 	if (ip_append_data(sk, fl4, icmp_glue_bits, icmp_param,
374 			   icmp_param->data_len+icmp_param->head_len,
375 			   icmp_param->head_len,
376 			   ipc, rt, MSG_DONTWAIT) < 0) {
377 		__ICMP_INC_STATS(sock_net(sk), ICMP_MIB_OUTERRORS);
378 		ip_flush_pending_frames(sk);
379 	} else if ((skb = skb_peek(&sk->sk_write_queue)) != NULL) {
380 		struct icmphdr *icmph = icmp_hdr(skb);
381 		__wsum csum;
382 		struct sk_buff *skb1;
383 
384 		csum = csum_partial_copy_nocheck((void *)&icmp_param->data,
385 						 (char *)icmph,
386 						 icmp_param->head_len);
387 		skb_queue_walk(&sk->sk_write_queue, skb1) {
388 			csum = csum_add(csum, skb1->csum);
389 		}
390 		icmph->checksum = csum_fold(csum);
391 		skb->ip_summed = CHECKSUM_NONE;
392 		ip_push_pending_frames(sk, fl4);
393 	}
394 }
395 
396 /*
397  *	Driving logic for building and sending ICMP messages.
398  */
399 
400 static void icmp_reply(struct icmp_bxm *icmp_param, struct sk_buff *skb)
401 {
402 	struct ipcm_cookie ipc;
403 	struct rtable *rt = skb_rtable(skb);
404 	struct net *net = dev_net(rt->dst.dev);
405 	struct flowi4 fl4;
406 	struct sock *sk;
407 	struct inet_sock *inet;
408 	__be32 daddr, saddr;
409 	u32 mark = IP4_REPLY_MARK(net, skb->mark);
410 	int type = icmp_param->data.icmph.type;
411 	int code = icmp_param->data.icmph.code;
412 
413 	if (ip_options_echo(net, &icmp_param->replyopts.opt.opt, skb))
414 		return;
415 
416 	/* Needed by both icmp_global_allow and icmp_xmit_lock */
417 	local_bh_disable();
418 
419 	/* global icmp_msgs_per_sec */
420 	if (!icmpv4_global_allow(net, type, code))
421 		goto out_bh_enable;
422 
423 	sk = icmp_xmit_lock(net);
424 	if (!sk)
425 		goto out_bh_enable;
426 	inet = inet_sk(sk);
427 
428 	icmp_param->data.icmph.checksum = 0;
429 
430 	ipcm_init(&ipc);
431 	inet->tos = ip_hdr(skb)->tos;
432 	ipc.sockc.mark = mark;
433 	daddr = ipc.addr = ip_hdr(skb)->saddr;
434 	saddr = fib_compute_spec_dst(skb);
435 
436 	if (icmp_param->replyopts.opt.opt.optlen) {
437 		ipc.opt = &icmp_param->replyopts.opt;
438 		if (ipc.opt->opt.srr)
439 			daddr = icmp_param->replyopts.opt.opt.faddr;
440 	}
441 	memset(&fl4, 0, sizeof(fl4));
442 	fl4.daddr = daddr;
443 	fl4.saddr = saddr;
444 	fl4.flowi4_mark = mark;
445 	fl4.flowi4_uid = sock_net_uid(net, NULL);
446 	fl4.flowi4_tos = RT_TOS(ip_hdr(skb)->tos);
447 	fl4.flowi4_proto = IPPROTO_ICMP;
448 	fl4.flowi4_oif = l3mdev_master_ifindex(skb->dev);
449 	security_skb_classify_flow(skb, flowi4_to_flowi_common(&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(sk, icmp_param, &fl4, &ipc, &rt);
455 	ip_rt_put(rt);
456 out_unlock:
457 	icmp_xmit_unlock(sk);
458 out_bh_enable:
459 	local_bh_enable();
460 }
461 
462 /*
463  * The device used for looking up which routing table to use for sending an ICMP
464  * error is preferably the source whenever it is set, which should ensure the
465  * icmp error can be sent to the source host, else lookup using the routing
466  * table of the destination device, else use the main routing table (index 0).
467  */
468 static struct net_device *icmp_get_route_lookup_dev(struct sk_buff *skb)
469 {
470 	struct net_device *route_lookup_dev = NULL;
471 
472 	if (skb->dev)
473 		route_lookup_dev = skb->dev;
474 	else if (skb_dst(skb))
475 		route_lookup_dev = skb_dst(skb)->dev;
476 	return route_lookup_dev;
477 }
478 
479 static struct rtable *icmp_route_lookup(struct net *net,
480 					struct flowi4 *fl4,
481 					struct sk_buff *skb_in,
482 					const struct iphdr *iph,
483 					__be32 saddr, u8 tos, u32 mark,
484 					int type, int code,
485 					struct icmp_bxm *param)
486 {
487 	struct net_device *route_lookup_dev;
488 	struct dst_entry *dst, *dst2;
489 	struct rtable *rt, *rt2;
490 	struct flowi4 fl4_dec;
491 	int err;
492 
493 	memset(fl4, 0, sizeof(*fl4));
494 	fl4->daddr = (param->replyopts.opt.opt.srr ?
495 		      param->replyopts.opt.opt.faddr : iph->saddr);
496 	fl4->saddr = saddr;
497 	fl4->flowi4_mark = mark;
498 	fl4->flowi4_uid = sock_net_uid(net, NULL);
499 	fl4->flowi4_tos = RT_TOS(tos);
500 	fl4->flowi4_proto = IPPROTO_ICMP;
501 	fl4->fl4_icmp_type = type;
502 	fl4->fl4_icmp_code = code;
503 	route_lookup_dev = icmp_get_route_lookup_dev(skb_in);
504 	fl4->flowi4_oif = l3mdev_master_ifindex(route_lookup_dev);
505 
506 	security_skb_classify_flow(skb_in, flowi4_to_flowi_common(fl4));
507 	rt = ip_route_output_key_hash(net, fl4, skb_in);
508 	if (IS_ERR(rt))
509 		return rt;
510 
511 	/* No need to clone since we're just using its address. */
512 	rt2 = rt;
513 
514 	dst = xfrm_lookup(net, &rt->dst,
515 			  flowi4_to_flowi(fl4), NULL, 0);
516 	rt = dst_rtable(dst);
517 	if (!IS_ERR(dst)) {
518 		if (rt != rt2)
519 			return rt;
520 	} else if (PTR_ERR(dst) == -EPERM) {
521 		rt = NULL;
522 	} else {
523 		return rt;
524 	}
525 	err = xfrm_decode_session_reverse(net, skb_in, flowi4_to_flowi(&fl4_dec), AF_INET);
526 	if (err)
527 		goto relookup_failed;
528 
529 	if (inet_addr_type_dev_table(net, route_lookup_dev,
530 				     fl4_dec.saddr) == RTN_LOCAL) {
531 		rt2 = __ip_route_output_key(net, &fl4_dec);
532 		if (IS_ERR(rt2))
533 			err = PTR_ERR(rt2);
534 	} else {
535 		struct flowi4 fl4_2 = {};
536 		unsigned long orefdst;
537 
538 		fl4_2.daddr = fl4_dec.saddr;
539 		rt2 = ip_route_output_key(net, &fl4_2);
540 		if (IS_ERR(rt2)) {
541 			err = PTR_ERR(rt2);
542 			goto relookup_failed;
543 		}
544 		/* Ugh! */
545 		orefdst = skb_in->_skb_refdst; /* save old refdst */
546 		skb_dst_set(skb_in, NULL);
547 		err = ip_route_input(skb_in, fl4_dec.daddr, fl4_dec.saddr,
548 				     RT_TOS(tos), rt2->dst.dev);
549 
550 		dst_release(&rt2->dst);
551 		rt2 = skb_rtable(skb_in);
552 		skb_in->_skb_refdst = orefdst; /* restore old refdst */
553 	}
554 
555 	if (err)
556 		goto relookup_failed;
557 
558 	dst2 = xfrm_lookup(net, &rt2->dst, flowi4_to_flowi(&fl4_dec), NULL,
559 			   XFRM_LOOKUP_ICMP);
560 	rt2 = dst_rtable(dst2);
561 	if (!IS_ERR(dst2)) {
562 		dst_release(&rt->dst);
563 		memcpy(fl4, &fl4_dec, sizeof(*fl4));
564 		rt = rt2;
565 	} else if (PTR_ERR(dst2) == -EPERM) {
566 		if (rt)
567 			dst_release(&rt->dst);
568 		return rt2;
569 	} else {
570 		err = PTR_ERR(dst2);
571 		goto relookup_failed;
572 	}
573 	return rt;
574 
575 relookup_failed:
576 	if (rt)
577 		return rt;
578 	return ERR_PTR(err);
579 }
580 
581 /*
582  *	Send an ICMP message in response to a situation
583  *
584  *	RFC 1122: 3.2.2	MUST send at least the IP header and 8 bytes of header.
585  *		  MAY send more (we do).
586  *			MUST NOT change this header information.
587  *			MUST NOT reply to a multicast/broadcast IP address.
588  *			MUST NOT reply to a multicast/broadcast MAC address.
589  *			MUST reply to only the first fragment.
590  */
591 
592 void __icmp_send(struct sk_buff *skb_in, int type, int code, __be32 info,
593 		 const struct ip_options *opt)
594 {
595 	struct iphdr *iph;
596 	int room;
597 	struct icmp_bxm icmp_param;
598 	struct rtable *rt = skb_rtable(skb_in);
599 	struct ipcm_cookie ipc;
600 	struct flowi4 fl4;
601 	__be32 saddr;
602 	u8  tos;
603 	u32 mark;
604 	struct net *net;
605 	struct sock *sk;
606 
607 	if (!rt)
608 		goto out;
609 
610 	if (rt->dst.dev)
611 		net = dev_net(rt->dst.dev);
612 	else if (skb_in->dev)
613 		net = dev_net(skb_in->dev);
614 	else
615 		goto out;
616 
617 	/*
618 	 *	Find the original header. It is expected to be valid, of course.
619 	 *	Check this, icmp_send is called from the most obscure devices
620 	 *	sometimes.
621 	 */
622 	iph = ip_hdr(skb_in);
623 
624 	if ((u8 *)iph < skb_in->head ||
625 	    (skb_network_header(skb_in) + sizeof(*iph)) >
626 	    skb_tail_pointer(skb_in))
627 		goto out;
628 
629 	/*
630 	 *	No replies to physical multicast/broadcast
631 	 */
632 	if (skb_in->pkt_type != PACKET_HOST)
633 		goto out;
634 
635 	/*
636 	 *	Now check at the protocol level
637 	 */
638 	if (rt->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST))
639 		goto out;
640 
641 	/*
642 	 *	Only reply to fragment 0. We byte re-order the constant
643 	 *	mask for efficiency.
644 	 */
645 	if (iph->frag_off & htons(IP_OFFSET))
646 		goto out;
647 
648 	/*
649 	 *	If we send an ICMP error to an ICMP error a mess would result..
650 	 */
651 	if (icmp_pointers[type].error) {
652 		/*
653 		 *	We are an error, check if we are replying to an
654 		 *	ICMP error
655 		 */
656 		if (iph->protocol == IPPROTO_ICMP) {
657 			u8 _inner_type, *itp;
658 
659 			itp = skb_header_pointer(skb_in,
660 						 skb_network_header(skb_in) +
661 						 (iph->ihl << 2) +
662 						 offsetof(struct icmphdr,
663 							  type) -
664 						 skb_in->data,
665 						 sizeof(_inner_type),
666 						 &_inner_type);
667 			if (!itp)
668 				goto out;
669 
670 			/*
671 			 *	Assume any unknown ICMP type is an error. This
672 			 *	isn't specified by the RFC, but think about it..
673 			 */
674 			if (*itp > NR_ICMP_TYPES ||
675 			    icmp_pointers[*itp].error)
676 				goto out;
677 		}
678 	}
679 
680 	/* Needed by both icmp_global_allow and icmp_xmit_lock */
681 	local_bh_disable();
682 
683 	/* Check global sysctl_icmp_msgs_per_sec ratelimit, unless
684 	 * incoming dev is loopback.  If outgoing dev change to not be
685 	 * loopback, then peer ratelimit still work (in icmpv4_xrlim_allow)
686 	 */
687 	if (!(skb_in->dev && (skb_in->dev->flags&IFF_LOOPBACK)) &&
688 	      !icmpv4_global_allow(net, type, code))
689 		goto out_bh_enable;
690 
691 	sk = icmp_xmit_lock(net);
692 	if (!sk)
693 		goto out_bh_enable;
694 
695 	/*
696 	 *	Construct source address and options.
697 	 */
698 
699 	saddr = iph->daddr;
700 	if (!(rt->rt_flags & RTCF_LOCAL)) {
701 		struct net_device *dev = NULL;
702 
703 		rcu_read_lock();
704 		if (rt_is_input_route(rt) &&
705 		    READ_ONCE(net->ipv4.sysctl_icmp_errors_use_inbound_ifaddr))
706 			dev = dev_get_by_index_rcu(net, inet_iif(skb_in));
707 
708 		if (dev)
709 			saddr = inet_select_addr(dev, iph->saddr,
710 						 RT_SCOPE_LINK);
711 		else
712 			saddr = 0;
713 		rcu_read_unlock();
714 	}
715 
716 	tos = icmp_pointers[type].error ? (RT_TOS(iph->tos) |
717 					   IPTOS_PREC_INTERNETCONTROL) :
718 					   iph->tos;
719 	mark = IP4_REPLY_MARK(net, skb_in->mark);
720 
721 	if (__ip_options_echo(net, &icmp_param.replyopts.opt.opt, skb_in, opt))
722 		goto out_unlock;
723 
724 
725 	/*
726 	 *	Prepare data for ICMP header.
727 	 */
728 
729 	icmp_param.data.icmph.type	 = type;
730 	icmp_param.data.icmph.code	 = code;
731 	icmp_param.data.icmph.un.gateway = info;
732 	icmp_param.data.icmph.checksum	 = 0;
733 	icmp_param.skb	  = skb_in;
734 	icmp_param.offset = skb_network_offset(skb_in);
735 	inet_sk(sk)->tos = tos;
736 	ipcm_init(&ipc);
737 	ipc.addr = iph->saddr;
738 	ipc.opt = &icmp_param.replyopts.opt;
739 	ipc.sockc.mark = mark;
740 
741 	rt = icmp_route_lookup(net, &fl4, skb_in, iph, saddr, tos, mark,
742 			       type, code, &icmp_param);
743 	if (IS_ERR(rt))
744 		goto out_unlock;
745 
746 	/* peer icmp_ratelimit */
747 	if (!icmpv4_xrlim_allow(net, rt, &fl4, type, code))
748 		goto ende;
749 
750 	/* RFC says return as much as we can without exceeding 576 bytes. */
751 
752 	room = dst_mtu(&rt->dst);
753 	if (room > 576)
754 		room = 576;
755 	room -= sizeof(struct iphdr) + icmp_param.replyopts.opt.opt.optlen;
756 	room -= sizeof(struct icmphdr);
757 	/* Guard against tiny mtu. We need to include at least one
758 	 * IP network header for this message to make any sense.
759 	 */
760 	if (room <= (int)sizeof(struct iphdr))
761 		goto ende;
762 
763 	icmp_param.data_len = skb_in->len - icmp_param.offset;
764 	if (icmp_param.data_len > room)
765 		icmp_param.data_len = room;
766 	icmp_param.head_len = sizeof(struct icmphdr);
767 
768 	/* if we don't have a source address at this point, fall back to the
769 	 * dummy address instead of sending out a packet with a source address
770 	 * of 0.0.0.0
771 	 */
772 	if (!fl4.saddr)
773 		fl4.saddr = htonl(INADDR_DUMMY);
774 
775 	trace_icmp_send(skb_in, type, code);
776 
777 	icmp_push_reply(sk, &icmp_param, &fl4, &ipc, &rt);
778 ende:
779 	ip_rt_put(rt);
780 out_unlock:
781 	icmp_xmit_unlock(sk);
782 out_bh_enable:
783 	local_bh_enable();
784 out:;
785 }
786 EXPORT_SYMBOL(__icmp_send);
787 
788 #if IS_ENABLED(CONFIG_NF_NAT)
789 #include <net/netfilter/nf_conntrack.h>
790 void icmp_ndo_send(struct sk_buff *skb_in, int type, int code, __be32 info)
791 {
792 	struct sk_buff *cloned_skb = NULL;
793 	struct ip_options opts = { 0 };
794 	enum ip_conntrack_info ctinfo;
795 	struct nf_conn *ct;
796 	__be32 orig_ip;
797 
798 	ct = nf_ct_get(skb_in, &ctinfo);
799 	if (!ct || !(ct->status & IPS_SRC_NAT)) {
800 		__icmp_send(skb_in, type, code, info, &opts);
801 		return;
802 	}
803 
804 	if (skb_shared(skb_in))
805 		skb_in = cloned_skb = skb_clone(skb_in, GFP_ATOMIC);
806 
807 	if (unlikely(!skb_in || skb_network_header(skb_in) < skb_in->head ||
808 	    (skb_network_header(skb_in) + sizeof(struct iphdr)) >
809 	    skb_tail_pointer(skb_in) || skb_ensure_writable(skb_in,
810 	    skb_network_offset(skb_in) + sizeof(struct iphdr))))
811 		goto out;
812 
813 	orig_ip = ip_hdr(skb_in)->saddr;
814 	ip_hdr(skb_in)->saddr = ct->tuplehash[0].tuple.src.u3.ip;
815 	__icmp_send(skb_in, type, code, info, &opts);
816 	ip_hdr(skb_in)->saddr = orig_ip;
817 out:
818 	consume_skb(cloned_skb);
819 }
820 EXPORT_SYMBOL(icmp_ndo_send);
821 #endif
822 
823 static void icmp_socket_deliver(struct sk_buff *skb, u32 info)
824 {
825 	const struct iphdr *iph = (const struct iphdr *)skb->data;
826 	const struct net_protocol *ipprot;
827 	int protocol = iph->protocol;
828 
829 	/* Checkin full IP header plus 8 bytes of protocol to
830 	 * avoid additional coding at protocol handlers.
831 	 */
832 	if (!pskb_may_pull(skb, iph->ihl * 4 + 8)) {
833 		__ICMP_INC_STATS(dev_net(skb->dev), ICMP_MIB_INERRORS);
834 		return;
835 	}
836 
837 	raw_icmp_error(skb, protocol, info);
838 
839 	ipprot = rcu_dereference(inet_protos[protocol]);
840 	if (ipprot && ipprot->err_handler)
841 		ipprot->err_handler(skb, info);
842 }
843 
844 static bool icmp_tag_validation(int proto)
845 {
846 	bool ok;
847 
848 	rcu_read_lock();
849 	ok = rcu_dereference(inet_protos[proto])->icmp_strict_tag_validation;
850 	rcu_read_unlock();
851 	return ok;
852 }
853 
854 /*
855  *	Handle ICMP_DEST_UNREACH, ICMP_TIME_EXCEEDED, ICMP_QUENCH, and
856  *	ICMP_PARAMETERPROB.
857  */
858 
859 static enum skb_drop_reason icmp_unreach(struct sk_buff *skb)
860 {
861 	enum skb_drop_reason reason = SKB_NOT_DROPPED_YET;
862 	const struct iphdr *iph;
863 	struct icmphdr *icmph;
864 	struct net *net;
865 	u32 info = 0;
866 
867 	net = dev_net(skb_dst(skb)->dev);
868 
869 	/*
870 	 *	Incomplete header ?
871 	 * 	Only checks for the IP header, there should be an
872 	 *	additional check for longer headers in upper levels.
873 	 */
874 
875 	if (!pskb_may_pull(skb, sizeof(struct iphdr)))
876 		goto out_err;
877 
878 	icmph = icmp_hdr(skb);
879 	iph   = (const struct iphdr *)skb->data;
880 
881 	if (iph->ihl < 5)  { /* Mangled header, drop. */
882 		reason = SKB_DROP_REASON_IP_INHDR;
883 		goto out_err;
884 	}
885 
886 	switch (icmph->type) {
887 	case ICMP_DEST_UNREACH:
888 		switch (icmph->code & 15) {
889 		case ICMP_NET_UNREACH:
890 		case ICMP_HOST_UNREACH:
891 		case ICMP_PROT_UNREACH:
892 		case ICMP_PORT_UNREACH:
893 			break;
894 		case ICMP_FRAG_NEEDED:
895 			/* for documentation of the ip_no_pmtu_disc
896 			 * values please see
897 			 * Documentation/networking/ip-sysctl.rst
898 			 */
899 			switch (READ_ONCE(net->ipv4.sysctl_ip_no_pmtu_disc)) {
900 			default:
901 				net_dbg_ratelimited("%pI4: fragmentation needed and DF set\n",
902 						    &iph->daddr);
903 				break;
904 			case 2:
905 				goto out;
906 			case 3:
907 				if (!icmp_tag_validation(iph->protocol))
908 					goto out;
909 				fallthrough;
910 			case 0:
911 				info = ntohs(icmph->un.frag.mtu);
912 			}
913 			break;
914 		case ICMP_SR_FAILED:
915 			net_dbg_ratelimited("%pI4: Source Route Failed\n",
916 					    &iph->daddr);
917 			break;
918 		default:
919 			break;
920 		}
921 		if (icmph->code > NR_ICMP_UNREACH)
922 			goto out;
923 		break;
924 	case ICMP_PARAMETERPROB:
925 		info = ntohl(icmph->un.gateway) >> 24;
926 		break;
927 	case ICMP_TIME_EXCEEDED:
928 		__ICMP_INC_STATS(net, ICMP_MIB_INTIMEEXCDS);
929 		if (icmph->code == ICMP_EXC_FRAGTIME)
930 			goto out;
931 		break;
932 	}
933 
934 	/*
935 	 *	Throw it at our lower layers
936 	 *
937 	 *	RFC 1122: 3.2.2 MUST extract the protocol ID from the passed
938 	 *		  header.
939 	 *	RFC 1122: 3.2.2.1 MUST pass ICMP unreach messages to the
940 	 *		  transport layer.
941 	 *	RFC 1122: 3.2.2.2 MUST pass ICMP time expired messages to
942 	 *		  transport layer.
943 	 */
944 
945 	/*
946 	 *	Check the other end isn't violating RFC 1122. Some routers send
947 	 *	bogus responses to broadcast frames. If you see this message
948 	 *	first check your netmask matches at both ends, if it does then
949 	 *	get the other vendor to fix their kit.
950 	 */
951 
952 	if (!READ_ONCE(net->ipv4.sysctl_icmp_ignore_bogus_error_responses) &&
953 	    inet_addr_type_dev_table(net, skb->dev, iph->daddr) == RTN_BROADCAST) {
954 		net_warn_ratelimited("%pI4 sent an invalid ICMP type %u, code %u error to a broadcast: %pI4 on %s\n",
955 				     &ip_hdr(skb)->saddr,
956 				     icmph->type, icmph->code,
957 				     &iph->daddr, skb->dev->name);
958 		goto out;
959 	}
960 
961 	icmp_socket_deliver(skb, info);
962 
963 out:
964 	return reason;
965 out_err:
966 	__ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
967 	return reason ?: SKB_DROP_REASON_NOT_SPECIFIED;
968 }
969 
970 
971 /*
972  *	Handle ICMP_REDIRECT.
973  */
974 
975 static enum skb_drop_reason icmp_redirect(struct sk_buff *skb)
976 {
977 	if (skb->len < sizeof(struct iphdr)) {
978 		__ICMP_INC_STATS(dev_net(skb->dev), ICMP_MIB_INERRORS);
979 		return SKB_DROP_REASON_PKT_TOO_SMALL;
980 	}
981 
982 	if (!pskb_may_pull(skb, sizeof(struct iphdr))) {
983 		/* there aught to be a stat */
984 		return SKB_DROP_REASON_NOMEM;
985 	}
986 
987 	icmp_socket_deliver(skb, ntohl(icmp_hdr(skb)->un.gateway));
988 	return SKB_NOT_DROPPED_YET;
989 }
990 
991 /*
992  *	Handle ICMP_ECHO ("ping") and ICMP_EXT_ECHO ("PROBE") requests.
993  *
994  *	RFC 1122: 3.2.2.6 MUST have an echo server that answers ICMP echo
995  *		  requests.
996  *	RFC 1122: 3.2.2.6 Data received in the ICMP_ECHO request MUST be
997  *		  included in the reply.
998  *	RFC 1812: 4.3.3.6 SHOULD have a config option for silently ignoring
999  *		  echo requests, MUST have default=NOT.
1000  *	RFC 8335: 8 MUST have a config option to enable/disable ICMP
1001  *		  Extended Echo Functionality, MUST be disabled by default
1002  *	See also WRT handling of options once they are done and working.
1003  */
1004 
1005 static enum skb_drop_reason icmp_echo(struct sk_buff *skb)
1006 {
1007 	struct icmp_bxm icmp_param;
1008 	struct net *net;
1009 
1010 	net = dev_net(skb_dst(skb)->dev);
1011 	/* should there be an ICMP stat for ignored echos? */
1012 	if (READ_ONCE(net->ipv4.sysctl_icmp_echo_ignore_all))
1013 		return SKB_NOT_DROPPED_YET;
1014 
1015 	icmp_param.data.icmph	   = *icmp_hdr(skb);
1016 	icmp_param.skb		   = skb;
1017 	icmp_param.offset	   = 0;
1018 	icmp_param.data_len	   = skb->len;
1019 	icmp_param.head_len	   = sizeof(struct icmphdr);
1020 
1021 	if (icmp_param.data.icmph.type == ICMP_ECHO)
1022 		icmp_param.data.icmph.type = ICMP_ECHOREPLY;
1023 	else if (!icmp_build_probe(skb, &icmp_param.data.icmph))
1024 		return SKB_NOT_DROPPED_YET;
1025 
1026 	icmp_reply(&icmp_param, skb);
1027 	return SKB_NOT_DROPPED_YET;
1028 }
1029 
1030 /*	Helper for icmp_echo and icmpv6_echo_reply.
1031  *	Searches for net_device that matches PROBE interface identifier
1032  *		and builds PROBE reply message in icmphdr.
1033  *
1034  *	Returns false if PROBE responses are disabled via sysctl
1035  */
1036 
1037 bool icmp_build_probe(struct sk_buff *skb, struct icmphdr *icmphdr)
1038 {
1039 	struct icmp_ext_hdr *ext_hdr, _ext_hdr;
1040 	struct icmp_ext_echo_iio *iio, _iio;
1041 	struct net *net = dev_net(skb->dev);
1042 	struct inet6_dev *in6_dev;
1043 	struct in_device *in_dev;
1044 	struct net_device *dev;
1045 	char buff[IFNAMSIZ];
1046 	u16 ident_len;
1047 	u8 status;
1048 
1049 	if (!READ_ONCE(net->ipv4.sysctl_icmp_echo_enable_probe))
1050 		return false;
1051 
1052 	/* We currently only support probing interfaces on the proxy node
1053 	 * Check to ensure L-bit is set
1054 	 */
1055 	if (!(ntohs(icmphdr->un.echo.sequence) & 1))
1056 		return false;
1057 	/* Clear status bits in reply message */
1058 	icmphdr->un.echo.sequence &= htons(0xFF00);
1059 	if (icmphdr->type == ICMP_EXT_ECHO)
1060 		icmphdr->type = ICMP_EXT_ECHOREPLY;
1061 	else
1062 		icmphdr->type = ICMPV6_EXT_ECHO_REPLY;
1063 	ext_hdr = skb_header_pointer(skb, 0, sizeof(_ext_hdr), &_ext_hdr);
1064 	/* Size of iio is class_type dependent.
1065 	 * Only check header here and assign length based on ctype in the switch statement
1066 	 */
1067 	iio = skb_header_pointer(skb, sizeof(_ext_hdr), sizeof(iio->extobj_hdr), &_iio);
1068 	if (!ext_hdr || !iio)
1069 		goto send_mal_query;
1070 	if (ntohs(iio->extobj_hdr.length) <= sizeof(iio->extobj_hdr) ||
1071 	    ntohs(iio->extobj_hdr.length) > sizeof(_iio))
1072 		goto send_mal_query;
1073 	ident_len = ntohs(iio->extobj_hdr.length) - sizeof(iio->extobj_hdr);
1074 	iio = skb_header_pointer(skb, sizeof(_ext_hdr),
1075 				 sizeof(iio->extobj_hdr) + ident_len, &_iio);
1076 	if (!iio)
1077 		goto send_mal_query;
1078 
1079 	status = 0;
1080 	dev = NULL;
1081 	switch (iio->extobj_hdr.class_type) {
1082 	case ICMP_EXT_ECHO_CTYPE_NAME:
1083 		if (ident_len >= IFNAMSIZ)
1084 			goto send_mal_query;
1085 		memset(buff, 0, sizeof(buff));
1086 		memcpy(buff, &iio->ident.name, ident_len);
1087 		dev = dev_get_by_name(net, buff);
1088 		break;
1089 	case ICMP_EXT_ECHO_CTYPE_INDEX:
1090 		if (ident_len != sizeof(iio->ident.ifindex))
1091 			goto send_mal_query;
1092 		dev = dev_get_by_index(net, ntohl(iio->ident.ifindex));
1093 		break;
1094 	case ICMP_EXT_ECHO_CTYPE_ADDR:
1095 		if (ident_len < sizeof(iio->ident.addr.ctype3_hdr) ||
1096 		    ident_len != sizeof(iio->ident.addr.ctype3_hdr) +
1097 				 iio->ident.addr.ctype3_hdr.addrlen)
1098 			goto send_mal_query;
1099 		switch (ntohs(iio->ident.addr.ctype3_hdr.afi)) {
1100 		case ICMP_AFI_IP:
1101 			if (iio->ident.addr.ctype3_hdr.addrlen != sizeof(struct in_addr))
1102 				goto send_mal_query;
1103 			dev = ip_dev_find(net, iio->ident.addr.ip_addr.ipv4_addr);
1104 			break;
1105 #if IS_ENABLED(CONFIG_IPV6)
1106 		case ICMP_AFI_IP6:
1107 			if (iio->ident.addr.ctype3_hdr.addrlen != sizeof(struct in6_addr))
1108 				goto send_mal_query;
1109 			dev = ipv6_stub->ipv6_dev_find(net, &iio->ident.addr.ip_addr.ipv6_addr, dev);
1110 			dev_hold(dev);
1111 			break;
1112 #endif
1113 		default:
1114 			goto send_mal_query;
1115 		}
1116 		break;
1117 	default:
1118 		goto send_mal_query;
1119 	}
1120 	if (!dev) {
1121 		icmphdr->code = ICMP_EXT_CODE_NO_IF;
1122 		return true;
1123 	}
1124 	/* Fill bits in reply message */
1125 	if (dev->flags & IFF_UP)
1126 		status |= ICMP_EXT_ECHOREPLY_ACTIVE;
1127 
1128 	in_dev = __in_dev_get_rcu(dev);
1129 	if (in_dev && rcu_access_pointer(in_dev->ifa_list))
1130 		status |= ICMP_EXT_ECHOREPLY_IPV4;
1131 
1132 	in6_dev = __in6_dev_get(dev);
1133 	if (in6_dev && !list_empty(&in6_dev->addr_list))
1134 		status |= ICMP_EXT_ECHOREPLY_IPV6;
1135 
1136 	dev_put(dev);
1137 	icmphdr->un.echo.sequence |= htons(status);
1138 	return true;
1139 send_mal_query:
1140 	icmphdr->code = ICMP_EXT_CODE_MAL_QUERY;
1141 	return true;
1142 }
1143 EXPORT_SYMBOL_GPL(icmp_build_probe);
1144 
1145 /*
1146  *	Handle ICMP Timestamp requests.
1147  *	RFC 1122: 3.2.2.8 MAY implement ICMP timestamp requests.
1148  *		  SHOULD be in the kernel for minimum random latency.
1149  *		  MUST be accurate to a few minutes.
1150  *		  MUST be updated at least at 15Hz.
1151  */
1152 static enum skb_drop_reason icmp_timestamp(struct sk_buff *skb)
1153 {
1154 	struct icmp_bxm icmp_param;
1155 	/*
1156 	 *	Too short.
1157 	 */
1158 	if (skb->len < 4)
1159 		goto out_err;
1160 
1161 	/*
1162 	 *	Fill in the current time as ms since midnight UT:
1163 	 */
1164 	icmp_param.data.times[1] = inet_current_timestamp();
1165 	icmp_param.data.times[2] = icmp_param.data.times[1];
1166 
1167 	BUG_ON(skb_copy_bits(skb, 0, &icmp_param.data.times[0], 4));
1168 
1169 	icmp_param.data.icmph	   = *icmp_hdr(skb);
1170 	icmp_param.data.icmph.type = ICMP_TIMESTAMPREPLY;
1171 	icmp_param.data.icmph.code = 0;
1172 	icmp_param.skb		   = skb;
1173 	icmp_param.offset	   = 0;
1174 	icmp_param.data_len	   = 0;
1175 	icmp_param.head_len	   = sizeof(struct icmphdr) + 12;
1176 	icmp_reply(&icmp_param, skb);
1177 	return SKB_NOT_DROPPED_YET;
1178 
1179 out_err:
1180 	__ICMP_INC_STATS(dev_net(skb_dst(skb)->dev), ICMP_MIB_INERRORS);
1181 	return SKB_DROP_REASON_PKT_TOO_SMALL;
1182 }
1183 
1184 static enum skb_drop_reason icmp_discard(struct sk_buff *skb)
1185 {
1186 	/* pretend it was a success */
1187 	return SKB_NOT_DROPPED_YET;
1188 }
1189 
1190 /*
1191  *	Deal with incoming ICMP packets.
1192  */
1193 int icmp_rcv(struct sk_buff *skb)
1194 {
1195 	enum skb_drop_reason reason = SKB_DROP_REASON_NOT_SPECIFIED;
1196 	struct rtable *rt = skb_rtable(skb);
1197 	struct net *net = dev_net(rt->dst.dev);
1198 	struct icmphdr *icmph;
1199 
1200 	if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb)) {
1201 		struct sec_path *sp = skb_sec_path(skb);
1202 		int nh;
1203 
1204 		if (!(sp && sp->xvec[sp->len - 1]->props.flags &
1205 				 XFRM_STATE_ICMP)) {
1206 			reason = SKB_DROP_REASON_XFRM_POLICY;
1207 			goto drop;
1208 		}
1209 
1210 		if (!pskb_may_pull(skb, sizeof(*icmph) + sizeof(struct iphdr)))
1211 			goto drop;
1212 
1213 		nh = skb_network_offset(skb);
1214 		skb_set_network_header(skb, sizeof(*icmph));
1215 
1216 		if (!xfrm4_policy_check_reverse(NULL, XFRM_POLICY_IN,
1217 						skb)) {
1218 			reason = SKB_DROP_REASON_XFRM_POLICY;
1219 			goto drop;
1220 		}
1221 
1222 		skb_set_network_header(skb, nh);
1223 	}
1224 
1225 	__ICMP_INC_STATS(net, ICMP_MIB_INMSGS);
1226 
1227 	if (skb_checksum_simple_validate(skb))
1228 		goto csum_error;
1229 
1230 	if (!pskb_pull(skb, sizeof(*icmph)))
1231 		goto error;
1232 
1233 	icmph = icmp_hdr(skb);
1234 
1235 	ICMPMSGIN_INC_STATS(net, icmph->type);
1236 
1237 	/* Check for ICMP Extended Echo (PROBE) messages */
1238 	if (icmph->type == ICMP_EXT_ECHO) {
1239 		/* We can't use icmp_pointers[].handler() because it is an array of
1240 		 * size NR_ICMP_TYPES + 1 (19 elements) and PROBE has code 42.
1241 		 */
1242 		reason = icmp_echo(skb);
1243 		goto reason_check;
1244 	}
1245 
1246 	if (icmph->type == ICMP_EXT_ECHOREPLY) {
1247 		reason = ping_rcv(skb);
1248 		goto reason_check;
1249 	}
1250 
1251 	/*
1252 	 *	18 is the highest 'known' ICMP type. Anything else is a mystery
1253 	 *
1254 	 *	RFC 1122: 3.2.2  Unknown ICMP messages types MUST be silently
1255 	 *		  discarded.
1256 	 */
1257 	if (icmph->type > NR_ICMP_TYPES) {
1258 		reason = SKB_DROP_REASON_UNHANDLED_PROTO;
1259 		goto error;
1260 	}
1261 
1262 	/*
1263 	 *	Parse the ICMP message
1264 	 */
1265 
1266 	if (rt->rt_flags & (RTCF_BROADCAST | RTCF_MULTICAST)) {
1267 		/*
1268 		 *	RFC 1122: 3.2.2.6 An ICMP_ECHO to broadcast MAY be
1269 		 *	  silently ignored (we let user decide with a sysctl).
1270 		 *	RFC 1122: 3.2.2.8 An ICMP_TIMESTAMP MAY be silently
1271 		 *	  discarded if to broadcast/multicast.
1272 		 */
1273 		if ((icmph->type == ICMP_ECHO ||
1274 		     icmph->type == ICMP_TIMESTAMP) &&
1275 		    READ_ONCE(net->ipv4.sysctl_icmp_echo_ignore_broadcasts)) {
1276 			reason = SKB_DROP_REASON_INVALID_PROTO;
1277 			goto error;
1278 		}
1279 		if (icmph->type != ICMP_ECHO &&
1280 		    icmph->type != ICMP_TIMESTAMP &&
1281 		    icmph->type != ICMP_ADDRESS &&
1282 		    icmph->type != ICMP_ADDRESSREPLY) {
1283 			reason = SKB_DROP_REASON_INVALID_PROTO;
1284 			goto error;
1285 		}
1286 	}
1287 
1288 	reason = icmp_pointers[icmph->type].handler(skb);
1289 reason_check:
1290 	if (!reason)  {
1291 		consume_skb(skb);
1292 		return NET_RX_SUCCESS;
1293 	}
1294 
1295 drop:
1296 	kfree_skb_reason(skb, reason);
1297 	return NET_RX_DROP;
1298 csum_error:
1299 	reason = SKB_DROP_REASON_ICMP_CSUM;
1300 	__ICMP_INC_STATS(net, ICMP_MIB_CSUMERRORS);
1301 error:
1302 	__ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
1303 	goto drop;
1304 }
1305 
1306 static bool ip_icmp_error_rfc4884_validate(const struct sk_buff *skb, int off)
1307 {
1308 	struct icmp_extobj_hdr *objh, _objh;
1309 	struct icmp_ext_hdr *exth, _exth;
1310 	u16 olen;
1311 
1312 	exth = skb_header_pointer(skb, off, sizeof(_exth), &_exth);
1313 	if (!exth)
1314 		return false;
1315 	if (exth->version != 2)
1316 		return true;
1317 
1318 	if (exth->checksum &&
1319 	    csum_fold(skb_checksum(skb, off, skb->len - off, 0)))
1320 		return false;
1321 
1322 	off += sizeof(_exth);
1323 	while (off < skb->len) {
1324 		objh = skb_header_pointer(skb, off, sizeof(_objh), &_objh);
1325 		if (!objh)
1326 			return false;
1327 
1328 		olen = ntohs(objh->length);
1329 		if (olen < sizeof(_objh))
1330 			return false;
1331 
1332 		off += olen;
1333 		if (off > skb->len)
1334 			return false;
1335 	}
1336 
1337 	return true;
1338 }
1339 
1340 void ip_icmp_error_rfc4884(const struct sk_buff *skb,
1341 			   struct sock_ee_data_rfc4884 *out,
1342 			   int thlen, int off)
1343 {
1344 	int hlen;
1345 
1346 	/* original datagram headers: end of icmph to payload (skb->data) */
1347 	hlen = -skb_transport_offset(skb) - thlen;
1348 
1349 	/* per rfc 4884: minimal datagram length of 128 bytes */
1350 	if (off < 128 || off < hlen)
1351 		return;
1352 
1353 	/* kernel has stripped headers: return payload offset in bytes */
1354 	off -= hlen;
1355 	if (off + sizeof(struct icmp_ext_hdr) > skb->len)
1356 		return;
1357 
1358 	out->len = off;
1359 
1360 	if (!ip_icmp_error_rfc4884_validate(skb, off))
1361 		out->flags |= SO_EE_RFC4884_FLAG_INVALID;
1362 }
1363 EXPORT_SYMBOL_GPL(ip_icmp_error_rfc4884);
1364 
1365 int icmp_err(struct sk_buff *skb, u32 info)
1366 {
1367 	struct iphdr *iph = (struct iphdr *)skb->data;
1368 	int offset = iph->ihl<<2;
1369 	struct icmphdr *icmph = (struct icmphdr *)(skb->data + offset);
1370 	int type = icmp_hdr(skb)->type;
1371 	int code = icmp_hdr(skb)->code;
1372 	struct net *net = dev_net(skb->dev);
1373 
1374 	/*
1375 	 * Use ping_err to handle all icmp errors except those
1376 	 * triggered by ICMP_ECHOREPLY which sent from kernel.
1377 	 */
1378 	if (icmph->type != ICMP_ECHOREPLY) {
1379 		ping_err(skb, offset, info);
1380 		return 0;
1381 	}
1382 
1383 	if (type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED)
1384 		ipv4_update_pmtu(skb, net, info, 0, IPPROTO_ICMP);
1385 	else if (type == ICMP_REDIRECT)
1386 		ipv4_redirect(skb, net, 0, IPPROTO_ICMP);
1387 
1388 	return 0;
1389 }
1390 
1391 /*
1392  *	This table is the definition of how we handle ICMP.
1393  */
1394 static const struct icmp_control icmp_pointers[NR_ICMP_TYPES + 1] = {
1395 	[ICMP_ECHOREPLY] = {
1396 		.handler = ping_rcv,
1397 	},
1398 	[1] = {
1399 		.handler = icmp_discard,
1400 		.error = 1,
1401 	},
1402 	[2] = {
1403 		.handler = icmp_discard,
1404 		.error = 1,
1405 	},
1406 	[ICMP_DEST_UNREACH] = {
1407 		.handler = icmp_unreach,
1408 		.error = 1,
1409 	},
1410 	[ICMP_SOURCE_QUENCH] = {
1411 		.handler = icmp_unreach,
1412 		.error = 1,
1413 	},
1414 	[ICMP_REDIRECT] = {
1415 		.handler = icmp_redirect,
1416 		.error = 1,
1417 	},
1418 	[6] = {
1419 		.handler = icmp_discard,
1420 		.error = 1,
1421 	},
1422 	[7] = {
1423 		.handler = icmp_discard,
1424 		.error = 1,
1425 	},
1426 	[ICMP_ECHO] = {
1427 		.handler = icmp_echo,
1428 	},
1429 	[9] = {
1430 		.handler = icmp_discard,
1431 		.error = 1,
1432 	},
1433 	[10] = {
1434 		.handler = icmp_discard,
1435 		.error = 1,
1436 	},
1437 	[ICMP_TIME_EXCEEDED] = {
1438 		.handler = icmp_unreach,
1439 		.error = 1,
1440 	},
1441 	[ICMP_PARAMETERPROB] = {
1442 		.handler = icmp_unreach,
1443 		.error = 1,
1444 	},
1445 	[ICMP_TIMESTAMP] = {
1446 		.handler = icmp_timestamp,
1447 	},
1448 	[ICMP_TIMESTAMPREPLY] = {
1449 		.handler = icmp_discard,
1450 	},
1451 	[ICMP_INFO_REQUEST] = {
1452 		.handler = icmp_discard,
1453 	},
1454 	[ICMP_INFO_REPLY] = {
1455 		.handler = icmp_discard,
1456 	},
1457 	[ICMP_ADDRESS] = {
1458 		.handler = icmp_discard,
1459 	},
1460 	[ICMP_ADDRESSREPLY] = {
1461 		.handler = icmp_discard,
1462 	},
1463 };
1464 
1465 static int __net_init icmp_sk_init(struct net *net)
1466 {
1467 	/* Control parameters for ECHO replies. */
1468 	net->ipv4.sysctl_icmp_echo_ignore_all = 0;
1469 	net->ipv4.sysctl_icmp_echo_enable_probe = 0;
1470 	net->ipv4.sysctl_icmp_echo_ignore_broadcasts = 1;
1471 
1472 	/* Control parameter - ignore bogus broadcast responses? */
1473 	net->ipv4.sysctl_icmp_ignore_bogus_error_responses = 1;
1474 
1475 	/*
1476 	 * 	Configurable global rate limit.
1477 	 *
1478 	 *	ratelimit defines tokens/packet consumed for dst->rate_token
1479 	 *	bucket ratemask defines which icmp types are ratelimited by
1480 	 *	setting	it's bit position.
1481 	 *
1482 	 *	default:
1483 	 *	dest unreachable (3), source quench (4),
1484 	 *	time exceeded (11), parameter problem (12)
1485 	 */
1486 
1487 	net->ipv4.sysctl_icmp_ratelimit = 1 * HZ;
1488 	net->ipv4.sysctl_icmp_ratemask = 0x1818;
1489 	net->ipv4.sysctl_icmp_errors_use_inbound_ifaddr = 0;
1490 
1491 	return 0;
1492 }
1493 
1494 static struct pernet_operations __net_initdata icmp_sk_ops = {
1495        .init = icmp_sk_init,
1496 };
1497 
1498 int __init icmp_init(void)
1499 {
1500 	int err, i;
1501 
1502 	for_each_possible_cpu(i) {
1503 		struct sock *sk;
1504 
1505 		err = inet_ctl_sock_create(&sk, PF_INET,
1506 					   SOCK_RAW, IPPROTO_ICMP, &init_net);
1507 		if (err < 0)
1508 			return err;
1509 
1510 		per_cpu(ipv4_icmp_sk, i) = sk;
1511 
1512 		/* Enough space for 2 64K ICMP packets, including
1513 		 * sk_buff/skb_shared_info struct overhead.
1514 		 */
1515 		sk->sk_sndbuf =	2 * SKB_TRUESIZE(64 * 1024);
1516 
1517 		/*
1518 		 * Speedup sock_wfree()
1519 		 */
1520 		sock_set_flag(sk, SOCK_USE_WRITE_QUEUE);
1521 		inet_sk(sk)->pmtudisc = IP_PMTUDISC_DONT;
1522 	}
1523 	return register_pernet_subsys(&icmp_sk_ops);
1524 }
1525