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