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