xref: /freebsd/sys/netinet/ip_icmp.c (revision 0957b409)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1988, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	@(#)ip_icmp.c	8.2 (Berkeley) 1/4/94
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include "opt_inet.h"
38 
39 #include <sys/param.h>
40 #include <sys/systm.h>
41 #include <sys/mbuf.h>
42 #include <sys/protosw.h>
43 #include <sys/socket.h>
44 #include <sys/time.h>
45 #include <sys/kernel.h>
46 #include <sys/lock.h>
47 #include <sys/rmlock.h>
48 #include <sys/sysctl.h>
49 #include <sys/syslog.h>
50 
51 #include <net/if.h>
52 #include <net/if_var.h>
53 #include <net/if_types.h>
54 #include <net/route.h>
55 #include <net/vnet.h>
56 
57 #include <netinet/in.h>
58 #include <netinet/in_fib.h>
59 #include <netinet/in_pcb.h>
60 #include <netinet/in_systm.h>
61 #include <netinet/in_var.h>
62 #include <netinet/ip.h>
63 #include <netinet/ip_icmp.h>
64 #include <netinet/ip_var.h>
65 #include <netinet/ip_options.h>
66 #include <netinet/sctp.h>
67 #include <netinet/tcp.h>
68 #include <netinet/tcp_var.h>
69 #include <netinet/tcpip.h>
70 #include <netinet/icmp_var.h>
71 
72 
73 #ifdef INET
74 
75 #include <machine/in_cksum.h>
76 
77 #include <security/mac/mac_framework.h>
78 #endif /* INET */
79 
80 /*
81  * ICMP routines: error generation, receive packet processing, and
82  * routines to turnaround packets back to the originator, and
83  * host table maintenance routines.
84  */
85 VNET_DEFINE_STATIC(int, icmplim) = 200;
86 #define	V_icmplim			VNET(icmplim)
87 SYSCTL_INT(_net_inet_icmp, ICMPCTL_ICMPLIM, icmplim, CTLFLAG_VNET | CTLFLAG_RW,
88 	&VNET_NAME(icmplim), 0,
89 	"Maximum number of ICMP responses per second");
90 
91 VNET_DEFINE_STATIC(int, icmplim_output) = 1;
92 #define	V_icmplim_output		VNET(icmplim_output)
93 SYSCTL_INT(_net_inet_icmp, OID_AUTO, icmplim_output, CTLFLAG_VNET | CTLFLAG_RW,
94 	&VNET_NAME(icmplim_output), 0,
95 	"Enable logging of ICMP response rate limiting");
96 
97 #ifdef INET
98 VNET_PCPUSTAT_DEFINE(struct icmpstat, icmpstat);
99 VNET_PCPUSTAT_SYSINIT(icmpstat);
100 SYSCTL_VNET_PCPUSTAT(_net_inet_icmp, ICMPCTL_STATS, stats, struct icmpstat,
101     icmpstat, "ICMP statistics (struct icmpstat, netinet/icmp_var.h)");
102 
103 #ifdef VIMAGE
104 VNET_PCPUSTAT_SYSUNINIT(icmpstat);
105 #endif /* VIMAGE */
106 
107 VNET_DEFINE_STATIC(int, icmpmaskrepl) = 0;
108 #define	V_icmpmaskrepl			VNET(icmpmaskrepl)
109 SYSCTL_INT(_net_inet_icmp, ICMPCTL_MASKREPL, maskrepl, CTLFLAG_VNET | CTLFLAG_RW,
110 	&VNET_NAME(icmpmaskrepl), 0,
111 	"Reply to ICMP Address Mask Request packets");
112 
113 VNET_DEFINE_STATIC(u_int, icmpmaskfake) = 0;
114 #define	V_icmpmaskfake			VNET(icmpmaskfake)
115 SYSCTL_UINT(_net_inet_icmp, OID_AUTO, maskfake, CTLFLAG_VNET | CTLFLAG_RW,
116 	&VNET_NAME(icmpmaskfake), 0,
117 	"Fake reply to ICMP Address Mask Request packets");
118 
119 VNET_DEFINE(int, drop_redirect) = 0;
120 #define	V_drop_redirect			VNET(drop_redirect)
121 SYSCTL_INT(_net_inet_icmp, OID_AUTO, drop_redirect, CTLFLAG_VNET | CTLFLAG_RW,
122 	&VNET_NAME(drop_redirect), 0,
123 	"Ignore ICMP redirects");
124 
125 VNET_DEFINE_STATIC(int, log_redirect) = 0;
126 #define	V_log_redirect			VNET(log_redirect)
127 SYSCTL_INT(_net_inet_icmp, OID_AUTO, log_redirect, CTLFLAG_VNET | CTLFLAG_RW,
128 	&VNET_NAME(log_redirect), 0,
129 	"Log ICMP redirects to the console");
130 
131 VNET_DEFINE_STATIC(char, reply_src[IFNAMSIZ]);
132 #define	V_reply_src			VNET(reply_src)
133 SYSCTL_STRING(_net_inet_icmp, OID_AUTO, reply_src, CTLFLAG_VNET | CTLFLAG_RW,
134 	&VNET_NAME(reply_src), IFNAMSIZ,
135 	"ICMP reply source for non-local packets");
136 
137 VNET_DEFINE_STATIC(int, icmp_rfi) = 0;
138 #define	V_icmp_rfi			VNET(icmp_rfi)
139 SYSCTL_INT(_net_inet_icmp, OID_AUTO, reply_from_interface, CTLFLAG_VNET | CTLFLAG_RW,
140 	&VNET_NAME(icmp_rfi), 0,
141 	"ICMP reply from incoming interface for non-local packets");
142 /* Router requirements RFC 1812 section 4.3.2.3 requires 576 - 28. */
143 VNET_DEFINE_STATIC(int, icmp_quotelen) = 548;
144 #define	V_icmp_quotelen			VNET(icmp_quotelen)
145 SYSCTL_INT(_net_inet_icmp, OID_AUTO, quotelen, CTLFLAG_VNET | CTLFLAG_RW,
146 	&VNET_NAME(icmp_quotelen), 0,
147 	"Number of bytes from original packet to quote in ICMP reply");
148 
149 VNET_DEFINE_STATIC(int, icmpbmcastecho) = 0;
150 #define	V_icmpbmcastecho		VNET(icmpbmcastecho)
151 SYSCTL_INT(_net_inet_icmp, OID_AUTO, bmcastecho, CTLFLAG_VNET | CTLFLAG_RW,
152 	&VNET_NAME(icmpbmcastecho), 0,
153 	"Reply to multicast ICMP Echo Request and Timestamp packets");
154 
155 VNET_DEFINE_STATIC(int, icmptstamprepl) = 1;
156 #define	V_icmptstamprepl		VNET(icmptstamprepl)
157 SYSCTL_INT(_net_inet_icmp, OID_AUTO, tstamprepl, CTLFLAG_RW,
158 	&VNET_NAME(icmptstamprepl), 0,
159 	"Respond to ICMP Timestamp packets");
160 
161 VNET_DEFINE_STATIC(int, error_keeptags) = 0;
162 #define	V_error_keeptags		VNET(error_keeptags)
163 SYSCTL_INT(_net_inet_icmp, OID_AUTO, error_keeptags, CTLFLAG_VNET | CTLFLAG_RW,
164 	&VNET_NAME(error_keeptags), 0,
165 	"ICMP error response keeps copy of mbuf_tags of original packet");
166 
167 #ifdef ICMPPRINTFS
168 int	icmpprintfs = 0;
169 #endif
170 
171 static void	icmp_reflect(struct mbuf *);
172 static void	icmp_send(struct mbuf *, struct mbuf *);
173 
174 extern	struct protosw inetsw[];
175 
176 /*
177  * Kernel module interface for updating icmpstat.  The argument is an index
178  * into icmpstat treated as an array of u_long.  While this encodes the
179  * general layout of icmpstat into the caller, it doesn't encode its
180  * location, so that future changes to add, for example, per-CPU stats
181  * support won't cause binary compatibility problems for kernel modules.
182  */
183 void
184 kmod_icmpstat_inc(int statnum)
185 {
186 
187 	counter_u64_add(VNET(icmpstat)[statnum], 1);
188 }
189 
190 /*
191  * Generate an error packet of type error
192  * in response to bad packet ip.
193  */
194 void
195 icmp_error(struct mbuf *n, int type, int code, uint32_t dest, int mtu)
196 {
197 	struct ip *oip, *nip;
198 	struct icmp *icp;
199 	struct mbuf *m;
200 	unsigned icmplen, icmpelen, nlen, oiphlen;
201 
202 	KASSERT((u_int)type <= ICMP_MAXTYPE, ("%s: illegal ICMP type",
203 	    __func__));
204 
205 	if (type != ICMP_REDIRECT)
206 		ICMPSTAT_INC(icps_error);
207 	/*
208 	 * Don't send error:
209 	 *  if the original packet was encrypted.
210 	 *  if not the first fragment of message.
211 	 *  in response to a multicast or broadcast packet.
212 	 *  if the old packet protocol was an ICMP error message.
213 	 */
214 	if (n->m_flags & M_DECRYPTED)
215 		goto freeit;
216 	if (n->m_flags & (M_BCAST|M_MCAST))
217 		goto freeit;
218 
219 	/* Drop if IP header plus 8 bytes is not contiguous in first mbuf. */
220 	if (n->m_len < sizeof(struct ip) + ICMP_MINLEN)
221 		goto freeit;
222 	oip = mtod(n, struct ip *);
223 	oiphlen = oip->ip_hl << 2;
224 	if (n->m_len < oiphlen + ICMP_MINLEN)
225 		goto freeit;
226 #ifdef ICMPPRINTFS
227 	if (icmpprintfs)
228 		printf("icmp_error(%p, %x, %d)\n", oip, type, code);
229 #endif
230 	if (oip->ip_off & htons(~(IP_MF|IP_DF)))
231 		goto freeit;
232 	if (oip->ip_p == IPPROTO_ICMP && type != ICMP_REDIRECT &&
233 	    !ICMP_INFOTYPE(((struct icmp *)((caddr_t)oip +
234 		oiphlen))->icmp_type)) {
235 		ICMPSTAT_INC(icps_oldicmp);
236 		goto freeit;
237 	}
238 	/*
239 	 * Calculate length to quote from original packet and
240 	 * prevent the ICMP mbuf from overflowing.
241 	 * Unfortunately this is non-trivial since ip_forward()
242 	 * sends us truncated packets.
243 	 */
244 	nlen = m_length(n, NULL);
245 	if (oip->ip_p == IPPROTO_TCP) {
246 		struct tcphdr *th;
247 		int tcphlen;
248 
249 		if (oiphlen + sizeof(struct tcphdr) > n->m_len &&
250 		    n->m_next == NULL)
251 			goto stdreply;
252 		if (n->m_len < oiphlen + sizeof(struct tcphdr) &&
253 		    (n = m_pullup(n, oiphlen + sizeof(struct tcphdr))) == NULL)
254 			goto freeit;
255 		oip = mtod(n, struct ip *);
256 		th = mtodo(n, oiphlen);
257 		tcphlen = th->th_off << 2;
258 		if (tcphlen < sizeof(struct tcphdr))
259 			goto freeit;
260 		if (ntohs(oip->ip_len) < oiphlen + tcphlen)
261 			goto freeit;
262 		if (oiphlen + tcphlen > n->m_len && n->m_next == NULL)
263 			goto stdreply;
264 		if (n->m_len < oiphlen + tcphlen &&
265 		    (n = m_pullup(n, oiphlen + tcphlen)) == NULL)
266 			goto freeit;
267 		oip = mtod(n, struct ip *);
268 		icmpelen = max(tcphlen, min(V_icmp_quotelen,
269 		    ntohs(oip->ip_len) - oiphlen));
270 	} else if (oip->ip_p == IPPROTO_SCTP) {
271 		struct sctphdr *sh;
272 		struct sctp_chunkhdr *ch;
273 
274 		if (ntohs(oip->ip_len) < oiphlen + sizeof(struct sctphdr))
275 			goto stdreply;
276 		if (oiphlen + sizeof(struct sctphdr) > n->m_len &&
277 		    n->m_next == NULL)
278 			goto stdreply;
279 		if (n->m_len < oiphlen + sizeof(struct sctphdr) &&
280 		    (n = m_pullup(n, oiphlen + sizeof(struct sctphdr))) == NULL)
281 			goto freeit;
282 		oip = mtod(n, struct ip *);
283 		icmpelen = max(sizeof(struct sctphdr),
284 		    min(V_icmp_quotelen, ntohs(oip->ip_len) - oiphlen));
285 		sh = mtodo(n, oiphlen);
286 		if (ntohl(sh->v_tag) == 0 &&
287 		    ntohs(oip->ip_len) >= oiphlen +
288 		    sizeof(struct sctphdr) + 8 &&
289 		    (n->m_len >= oiphlen + sizeof(struct sctphdr) + 8 ||
290 		     n->m_next != NULL)) {
291 			if (n->m_len < oiphlen + sizeof(struct sctphdr) + 8 &&
292 			    (n = m_pullup(n, oiphlen +
293 			    sizeof(struct sctphdr) + 8)) == NULL)
294 				goto freeit;
295 			oip = mtod(n, struct ip *);
296 			sh = mtodo(n, oiphlen);
297 			ch = (struct sctp_chunkhdr *)(sh + 1);
298 			if (ch->chunk_type == SCTP_INITIATION) {
299 				icmpelen = max(sizeof(struct sctphdr) + 8,
300 				    min(V_icmp_quotelen, ntohs(oip->ip_len) -
301 				    oiphlen));
302 			}
303 		}
304 	} else
305 stdreply:	icmpelen = max(8, min(V_icmp_quotelen, ntohs(oip->ip_len) -
306 		    oiphlen));
307 
308 	icmplen = min(oiphlen + icmpelen, nlen);
309 	if (icmplen < sizeof(struct ip))
310 		goto freeit;
311 
312 	if (MHLEN > sizeof(struct ip) + ICMP_MINLEN + icmplen)
313 		m = m_gethdr(M_NOWAIT, MT_DATA);
314 	else
315 		m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
316 	if (m == NULL)
317 		goto freeit;
318 #ifdef MAC
319 	mac_netinet_icmp_reply(n, m);
320 #endif
321 	icmplen = min(icmplen, M_TRAILINGSPACE(m) -
322 	    sizeof(struct ip) - ICMP_MINLEN);
323 	m_align(m, sizeof(struct ip) + ICMP_MINLEN + icmplen);
324 	m->m_data += sizeof(struct ip);
325 	m->m_len = ICMP_MINLEN + icmplen;
326 
327 	/* XXX MRT  make the outgoing packet use the same FIB
328 	 * that was associated with the incoming packet
329 	 */
330 	M_SETFIB(m, M_GETFIB(n));
331 	icp = mtod(m, struct icmp *);
332 	ICMPSTAT_INC(icps_outhist[type]);
333 	icp->icmp_type = type;
334 	if (type == ICMP_REDIRECT)
335 		icp->icmp_gwaddr.s_addr = dest;
336 	else {
337 		icp->icmp_void = 0;
338 		/*
339 		 * The following assignments assume an overlay with the
340 		 * just zeroed icmp_void field.
341 		 */
342 		if (type == ICMP_PARAMPROB) {
343 			icp->icmp_pptr = code;
344 			code = 0;
345 		} else if (type == ICMP_UNREACH &&
346 			code == ICMP_UNREACH_NEEDFRAG && mtu) {
347 			icp->icmp_nextmtu = htons(mtu);
348 		}
349 	}
350 	icp->icmp_code = code;
351 
352 	/*
353 	 * Copy the quotation into ICMP message and
354 	 * convert quoted IP header back to network representation.
355 	 */
356 	m_copydata(n, 0, icmplen, (caddr_t)&icp->icmp_ip);
357 	nip = &icp->icmp_ip;
358 
359 	/*
360 	 * Set up ICMP message mbuf and copy old IP header (without options
361 	 * in front of ICMP message.
362 	 * If the original mbuf was meant to bypass the firewall, the error
363 	 * reply should bypass as well.
364 	 */
365 	m->m_flags |= n->m_flags & M_SKIP_FIREWALL;
366 	KASSERT(M_LEADINGSPACE(m) >= sizeof(struct ip),
367 	    ("insufficient space for ip header"));
368 	m->m_data -= sizeof(struct ip);
369 	m->m_len += sizeof(struct ip);
370 	m->m_pkthdr.len = m->m_len;
371 	m->m_pkthdr.rcvif = n->m_pkthdr.rcvif;
372 	nip = mtod(m, struct ip *);
373 	bcopy((caddr_t)oip, (caddr_t)nip, sizeof(struct ip));
374 	nip->ip_len = htons(m->m_len);
375 	nip->ip_v = IPVERSION;
376 	nip->ip_hl = 5;
377 	nip->ip_p = IPPROTO_ICMP;
378 	nip->ip_tos = 0;
379 	nip->ip_off = 0;
380 
381 	if (V_error_keeptags)
382 		m_tag_copy_chain(m, n, M_NOWAIT);
383 
384 	icmp_reflect(m);
385 
386 freeit:
387 	m_freem(n);
388 }
389 
390 /*
391  * Process a received ICMP message.
392  */
393 int
394 icmp_input(struct mbuf **mp, int *offp, int proto)
395 {
396 	struct epoch_tracker et;
397 	struct icmp *icp;
398 	struct in_ifaddr *ia;
399 	struct mbuf *m = *mp;
400 	struct ip *ip = mtod(m, struct ip *);
401 	struct sockaddr_in icmpsrc, icmpdst, icmpgw;
402 	int hlen = *offp;
403 	int icmplen = ntohs(ip->ip_len) - *offp;
404 	int i, code;
405 	void (*ctlfunc)(int, struct sockaddr *, void *);
406 	int fibnum;
407 
408 	*mp = NULL;
409 
410 	/*
411 	 * Locate icmp structure in mbuf, and check
412 	 * that not corrupted and of at least minimum length.
413 	 */
414 #ifdef ICMPPRINTFS
415 	if (icmpprintfs) {
416 		char srcbuf[INET_ADDRSTRLEN];
417 		char dstbuf[INET_ADDRSTRLEN];
418 
419 		printf("icmp_input from %s to %s, len %d\n",
420 		    inet_ntoa_r(ip->ip_src, srcbuf),
421 		    inet_ntoa_r(ip->ip_dst, dstbuf), icmplen);
422 	}
423 #endif
424 	NET_EPOCH_ENTER(et);
425 	if (icmplen < ICMP_MINLEN) {
426 		ICMPSTAT_INC(icps_tooshort);
427 		goto freeit;
428 	}
429 	i = hlen + min(icmplen, ICMP_ADVLENMIN);
430 	if (m->m_len < i && (m = m_pullup(m, i)) == NULL)  {
431 		ICMPSTAT_INC(icps_tooshort);
432 		NET_EPOCH_EXIT(et);
433 		return (IPPROTO_DONE);
434 	}
435 	ip = mtod(m, struct ip *);
436 	m->m_len -= hlen;
437 	m->m_data += hlen;
438 	icp = mtod(m, struct icmp *);
439 	if (in_cksum(m, icmplen)) {
440 		ICMPSTAT_INC(icps_checksum);
441 		goto freeit;
442 	}
443 	m->m_len += hlen;
444 	m->m_data -= hlen;
445 
446 #ifdef ICMPPRINTFS
447 	if (icmpprintfs)
448 		printf("icmp_input, type %d code %d\n", icp->icmp_type,
449 		    icp->icmp_code);
450 #endif
451 
452 	/*
453 	 * Message type specific processing.
454 	 */
455 	if (icp->icmp_type > ICMP_MAXTYPE)
456 		goto raw;
457 
458 	/* Initialize */
459 	bzero(&icmpsrc, sizeof(icmpsrc));
460 	icmpsrc.sin_len = sizeof(struct sockaddr_in);
461 	icmpsrc.sin_family = AF_INET;
462 	bzero(&icmpdst, sizeof(icmpdst));
463 	icmpdst.sin_len = sizeof(struct sockaddr_in);
464 	icmpdst.sin_family = AF_INET;
465 	bzero(&icmpgw, sizeof(icmpgw));
466 	icmpgw.sin_len = sizeof(struct sockaddr_in);
467 	icmpgw.sin_family = AF_INET;
468 
469 	ICMPSTAT_INC(icps_inhist[icp->icmp_type]);
470 	code = icp->icmp_code;
471 	switch (icp->icmp_type) {
472 
473 	case ICMP_UNREACH:
474 		switch (code) {
475 			case ICMP_UNREACH_NET:
476 			case ICMP_UNREACH_HOST:
477 			case ICMP_UNREACH_SRCFAIL:
478 			case ICMP_UNREACH_NET_UNKNOWN:
479 			case ICMP_UNREACH_HOST_UNKNOWN:
480 			case ICMP_UNREACH_ISOLATED:
481 			case ICMP_UNREACH_TOSNET:
482 			case ICMP_UNREACH_TOSHOST:
483 			case ICMP_UNREACH_HOST_PRECEDENCE:
484 			case ICMP_UNREACH_PRECEDENCE_CUTOFF:
485 				code = PRC_UNREACH_NET;
486 				break;
487 
488 			case ICMP_UNREACH_NEEDFRAG:
489 				code = PRC_MSGSIZE;
490 				break;
491 
492 			/*
493 			 * RFC 1122, Sections 3.2.2.1 and 4.2.3.9.
494 			 * Treat subcodes 2,3 as immediate RST
495 			 */
496 			case ICMP_UNREACH_PROTOCOL:
497 				code = PRC_UNREACH_PROTOCOL;
498 				break;
499 			case ICMP_UNREACH_PORT:
500 				code = PRC_UNREACH_PORT;
501 				break;
502 
503 			case ICMP_UNREACH_NET_PROHIB:
504 			case ICMP_UNREACH_HOST_PROHIB:
505 			case ICMP_UNREACH_FILTER_PROHIB:
506 				code = PRC_UNREACH_ADMIN_PROHIB;
507 				break;
508 
509 			default:
510 				goto badcode;
511 		}
512 		goto deliver;
513 
514 	case ICMP_TIMXCEED:
515 		if (code > 1)
516 			goto badcode;
517 		code += PRC_TIMXCEED_INTRANS;
518 		goto deliver;
519 
520 	case ICMP_PARAMPROB:
521 		if (code > 1)
522 			goto badcode;
523 		code = PRC_PARAMPROB;
524 	deliver:
525 		/*
526 		 * Problem with datagram; advise higher level routines.
527 		 */
528 		if (icmplen < ICMP_ADVLENMIN || icmplen < ICMP_ADVLEN(icp) ||
529 		    icp->icmp_ip.ip_hl < (sizeof(struct ip) >> 2)) {
530 			ICMPSTAT_INC(icps_badlen);
531 			goto freeit;
532 		}
533 		/* Discard ICMP's in response to multicast packets */
534 		if (IN_MULTICAST(ntohl(icp->icmp_ip.ip_dst.s_addr)))
535 			goto badcode;
536 #ifdef ICMPPRINTFS
537 		if (icmpprintfs)
538 			printf("deliver to protocol %d\n", icp->icmp_ip.ip_p);
539 #endif
540 		icmpsrc.sin_addr = icp->icmp_ip.ip_dst;
541 		/*
542 		 * XXX if the packet contains [IPv4 AH TCP], we can't make a
543 		 * notification to TCP layer.
544 		 */
545 		i = sizeof(struct ip) + min(icmplen, ICMP_ADVLENPREF(icp));
546 		ip_stripoptions(m);
547 		if (m->m_len < i && (m = m_pullup(m, i)) == NULL) {
548 			/* This should actually not happen */
549 			ICMPSTAT_INC(icps_tooshort);
550 			NET_EPOCH_EXIT(et);
551 			return (IPPROTO_DONE);
552 		}
553 		ip = mtod(m, struct ip *);
554 		icp = (struct icmp *)(ip + 1);
555 		/*
556 		 * The upper layer handler can rely on:
557 		 * - The outer IP header has no options.
558 		 * - The outer IP header, the ICMP header, the inner IP header,
559 		 *   and the first n bytes of the inner payload are contiguous.
560 		 *   n is at least 8, but might be larger based on
561 		 *   ICMP_ADVLENPREF. See its definition in ip_icmp.h.
562 		 */
563 		ctlfunc = inetsw[ip_protox[icp->icmp_ip.ip_p]].pr_ctlinput;
564 		if (ctlfunc)
565 			(*ctlfunc)(code, (struct sockaddr *)&icmpsrc,
566 				   (void *)&icp->icmp_ip);
567 		break;
568 
569 	badcode:
570 		ICMPSTAT_INC(icps_badcode);
571 		break;
572 
573 	case ICMP_ECHO:
574 		if (!V_icmpbmcastecho
575 		    && (m->m_flags & (M_MCAST | M_BCAST)) != 0) {
576 			ICMPSTAT_INC(icps_bmcastecho);
577 			break;
578 		}
579 		if (badport_bandlim(BANDLIM_ICMP_ECHO) < 0)
580 			goto freeit;
581 		icp->icmp_type = ICMP_ECHOREPLY;
582 		goto reflect;
583 
584 	case ICMP_TSTAMP:
585 		if (V_icmptstamprepl == 0)
586 			break;
587 		if (!V_icmpbmcastecho
588 		    && (m->m_flags & (M_MCAST | M_BCAST)) != 0) {
589 			ICMPSTAT_INC(icps_bmcasttstamp);
590 			break;
591 		}
592 		if (icmplen < ICMP_TSLEN) {
593 			ICMPSTAT_INC(icps_badlen);
594 			break;
595 		}
596 		if (badport_bandlim(BANDLIM_ICMP_TSTAMP) < 0)
597 			goto freeit;
598 		icp->icmp_type = ICMP_TSTAMPREPLY;
599 		icp->icmp_rtime = iptime();
600 		icp->icmp_ttime = icp->icmp_rtime;	/* bogus, do later! */
601 		goto reflect;
602 
603 	case ICMP_MASKREQ:
604 		if (V_icmpmaskrepl == 0)
605 			break;
606 		/*
607 		 * We are not able to respond with all ones broadcast
608 		 * unless we receive it over a point-to-point interface.
609 		 */
610 		if (icmplen < ICMP_MASKLEN)
611 			break;
612 		switch (ip->ip_dst.s_addr) {
613 
614 		case INADDR_BROADCAST:
615 		case INADDR_ANY:
616 			icmpdst.sin_addr = ip->ip_src;
617 			break;
618 
619 		default:
620 			icmpdst.sin_addr = ip->ip_dst;
621 		}
622 		ia = (struct in_ifaddr *)ifaof_ifpforaddr(
623 			    (struct sockaddr *)&icmpdst, m->m_pkthdr.rcvif);
624 		if (ia == NULL)
625 			break;
626 		if (ia->ia_ifp == NULL)
627 			break;
628 		icp->icmp_type = ICMP_MASKREPLY;
629 		if (V_icmpmaskfake == 0)
630 			icp->icmp_mask = ia->ia_sockmask.sin_addr.s_addr;
631 		else
632 			icp->icmp_mask = V_icmpmaskfake;
633 		if (ip->ip_src.s_addr == 0) {
634 			if (ia->ia_ifp->if_flags & IFF_BROADCAST)
635 			    ip->ip_src = satosin(&ia->ia_broadaddr)->sin_addr;
636 			else if (ia->ia_ifp->if_flags & IFF_POINTOPOINT)
637 			    ip->ip_src = satosin(&ia->ia_dstaddr)->sin_addr;
638 		}
639 reflect:
640 		ICMPSTAT_INC(icps_reflect);
641 		ICMPSTAT_INC(icps_outhist[icp->icmp_type]);
642 		icmp_reflect(m);
643 		NET_EPOCH_EXIT(et);
644 		return (IPPROTO_DONE);
645 
646 	case ICMP_REDIRECT:
647 		if (V_log_redirect) {
648 			u_long src, dst, gw;
649 
650 			src = ntohl(ip->ip_src.s_addr);
651 			dst = ntohl(icp->icmp_ip.ip_dst.s_addr);
652 			gw = ntohl(icp->icmp_gwaddr.s_addr);
653 			printf("icmp redirect from %d.%d.%d.%d: "
654 			       "%d.%d.%d.%d => %d.%d.%d.%d\n",
655 			       (int)(src >> 24), (int)((src >> 16) & 0xff),
656 			       (int)((src >> 8) & 0xff), (int)(src & 0xff),
657 			       (int)(dst >> 24), (int)((dst >> 16) & 0xff),
658 			       (int)((dst >> 8) & 0xff), (int)(dst & 0xff),
659 			       (int)(gw >> 24), (int)((gw >> 16) & 0xff),
660 			       (int)((gw >> 8) & 0xff), (int)(gw & 0xff));
661 		}
662 		/*
663 		 * RFC1812 says we must ignore ICMP redirects if we
664 		 * are acting as router.
665 		 */
666 		if (V_drop_redirect || V_ipforwarding)
667 			break;
668 		if (code > 3)
669 			goto badcode;
670 		if (icmplen < ICMP_ADVLENMIN || icmplen < ICMP_ADVLEN(icp) ||
671 		    icp->icmp_ip.ip_hl < (sizeof(struct ip) >> 2)) {
672 			ICMPSTAT_INC(icps_badlen);
673 			break;
674 		}
675 		/*
676 		 * Short circuit routing redirects to force
677 		 * immediate change in the kernel's routing
678 		 * tables.  The message is also handed to anyone
679 		 * listening on a raw socket (e.g. the routing
680 		 * daemon for use in updating its tables).
681 		 */
682 		icmpgw.sin_addr = ip->ip_src;
683 		icmpdst.sin_addr = icp->icmp_gwaddr;
684 #ifdef	ICMPPRINTFS
685 		if (icmpprintfs) {
686 			char dstbuf[INET_ADDRSTRLEN];
687 			char gwbuf[INET_ADDRSTRLEN];
688 
689 			printf("redirect dst %s to %s\n",
690 			       inet_ntoa_r(icp->icmp_ip.ip_dst, dstbuf),
691 			       inet_ntoa_r(icp->icmp_gwaddr, gwbuf));
692 		}
693 #endif
694 		icmpsrc.sin_addr = icp->icmp_ip.ip_dst;
695 		for ( fibnum = 0; fibnum < rt_numfibs; fibnum++) {
696 			in_rtredirect((struct sockaddr *)&icmpsrc,
697 			  (struct sockaddr *)&icmpdst,
698 			  (struct sockaddr *)0, RTF_GATEWAY | RTF_HOST,
699 			  (struct sockaddr *)&icmpgw, fibnum);
700 		}
701 		pfctlinput(PRC_REDIRECT_HOST, (struct sockaddr *)&icmpsrc);
702 		break;
703 
704 	/*
705 	 * No kernel processing for the following;
706 	 * just fall through to send to raw listener.
707 	 */
708 	case ICMP_ECHOREPLY:
709 	case ICMP_ROUTERADVERT:
710 	case ICMP_ROUTERSOLICIT:
711 	case ICMP_TSTAMPREPLY:
712 	case ICMP_IREQREPLY:
713 	case ICMP_MASKREPLY:
714 	case ICMP_SOURCEQUENCH:
715 	default:
716 		break;
717 	}
718 
719 raw:
720 	NET_EPOCH_EXIT(et);
721 	*mp = m;
722 	rip_input(mp, offp, proto);
723 	return (IPPROTO_DONE);
724 
725 freeit:
726 	NET_EPOCH_EXIT(et);
727 	m_freem(m);
728 	return (IPPROTO_DONE);
729 }
730 
731 /*
732  * Reflect the ip packet back to the source
733  */
734 static void
735 icmp_reflect(struct mbuf *m)
736 {
737 	struct rm_priotracker in_ifa_tracker;
738 	struct epoch_tracker et;
739 	struct ip *ip = mtod(m, struct ip *);
740 	struct ifaddr *ifa;
741 	struct ifnet *ifp;
742 	struct in_ifaddr *ia;
743 	struct in_addr t;
744 	struct nhop4_extended nh_ext;
745 	struct mbuf *opts = NULL;
746 	int optlen = (ip->ip_hl << 2) - sizeof(struct ip);
747 
748 	if (IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
749 	    IN_EXPERIMENTAL(ntohl(ip->ip_src.s_addr)) ||
750 	    IN_ZERONET(ntohl(ip->ip_src.s_addr)) ) {
751 		m_freem(m);	/* Bad return address */
752 		ICMPSTAT_INC(icps_badaddr);
753 		goto done;	/* Ip_output() will check for broadcast */
754 	}
755 
756 	t = ip->ip_dst;
757 	ip->ip_dst = ip->ip_src;
758 
759 	/*
760 	 * Source selection for ICMP replies:
761 	 *
762 	 * If the incoming packet was addressed directly to one of our
763 	 * own addresses, use dst as the src for the reply.
764 	 */
765 	IN_IFADDR_RLOCK(&in_ifa_tracker);
766 	LIST_FOREACH(ia, INADDR_HASH(t.s_addr), ia_hash) {
767 		if (t.s_addr == IA_SIN(ia)->sin_addr.s_addr) {
768 			t = IA_SIN(ia)->sin_addr;
769 			IN_IFADDR_RUNLOCK(&in_ifa_tracker);
770 			goto match;
771 		}
772 	}
773 	IN_IFADDR_RUNLOCK(&in_ifa_tracker);
774 
775 	/*
776 	 * If the incoming packet was addressed to one of our broadcast
777 	 * addresses, use the first non-broadcast address which corresponds
778 	 * to the incoming interface.
779 	 */
780 	ifp = m->m_pkthdr.rcvif;
781 	if (ifp != NULL && ifp->if_flags & IFF_BROADCAST) {
782 		NET_EPOCH_ENTER(et);
783 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
784 			if (ifa->ifa_addr->sa_family != AF_INET)
785 				continue;
786 			ia = ifatoia(ifa);
787 			if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
788 			    t.s_addr) {
789 				t = IA_SIN(ia)->sin_addr;
790 				NET_EPOCH_EXIT(et);
791 				goto match;
792 			}
793 		}
794 		NET_EPOCH_EXIT(et);
795 	}
796 	/*
797 	 * If the packet was transiting through us, use the address of
798 	 * the interface the packet came through in.  If that interface
799 	 * doesn't have a suitable IP address, the normal selection
800 	 * criteria apply.
801 	 */
802 	if (V_icmp_rfi && ifp != NULL) {
803 		NET_EPOCH_ENTER(et);
804 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
805 			if (ifa->ifa_addr->sa_family != AF_INET)
806 				continue;
807 			ia = ifatoia(ifa);
808 			t = IA_SIN(ia)->sin_addr;
809 			NET_EPOCH_EXIT(et);
810 			goto match;
811 		}
812 		NET_EPOCH_EXIT(et);
813 	}
814 	/*
815 	 * If the incoming packet was not addressed directly to us, use
816 	 * designated interface for icmp replies specified by sysctl
817 	 * net.inet.icmp.reply_src (default not set). Otherwise continue
818 	 * with normal source selection.
819 	 */
820 	if (V_reply_src[0] != '\0' && (ifp = ifunit(V_reply_src))) {
821 		NET_EPOCH_ENTER(et);
822 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
823 			if (ifa->ifa_addr->sa_family != AF_INET)
824 				continue;
825 			ia = ifatoia(ifa);
826 			t = IA_SIN(ia)->sin_addr;
827 			NET_EPOCH_EXIT(et);
828 			goto match;
829 		}
830 		NET_EPOCH_EXIT(et);
831 	}
832 	/*
833 	 * If the packet was transiting through us, use the address of
834 	 * the interface that is the closest to the packet source.
835 	 * When we don't have a route back to the packet source, stop here
836 	 * and drop the packet.
837 	 */
838 	if (fib4_lookup_nh_ext(M_GETFIB(m), ip->ip_dst, 0, 0, &nh_ext) != 0) {
839 		m_freem(m);
840 		ICMPSTAT_INC(icps_noroute);
841 		goto done;
842 	}
843 	t = nh_ext.nh_src;
844 match:
845 #ifdef MAC
846 	mac_netinet_icmp_replyinplace(m);
847 #endif
848 	ip->ip_src = t;
849 	ip->ip_ttl = V_ip_defttl;
850 
851 	if (optlen > 0) {
852 		u_char *cp;
853 		int opt, cnt;
854 		u_int len;
855 
856 		/*
857 		 * Retrieve any source routing from the incoming packet;
858 		 * add on any record-route or timestamp options.
859 		 */
860 		cp = (u_char *) (ip + 1);
861 		if ((opts = ip_srcroute(m)) == NULL &&
862 		    (opts = m_gethdr(M_NOWAIT, MT_DATA))) {
863 			opts->m_len = sizeof(struct in_addr);
864 			mtod(opts, struct in_addr *)->s_addr = 0;
865 		}
866 		if (opts) {
867 #ifdef ICMPPRINTFS
868 		    if (icmpprintfs)
869 			    printf("icmp_reflect optlen %d rt %d => ",
870 				optlen, opts->m_len);
871 #endif
872 		    for (cnt = optlen; cnt > 0; cnt -= len, cp += len) {
873 			    opt = cp[IPOPT_OPTVAL];
874 			    if (opt == IPOPT_EOL)
875 				    break;
876 			    if (opt == IPOPT_NOP)
877 				    len = 1;
878 			    else {
879 				    if (cnt < IPOPT_OLEN + sizeof(*cp))
880 					    break;
881 				    len = cp[IPOPT_OLEN];
882 				    if (len < IPOPT_OLEN + sizeof(*cp) ||
883 				        len > cnt)
884 					    break;
885 			    }
886 			    /*
887 			     * Should check for overflow, but it "can't happen"
888 			     */
889 			    if (opt == IPOPT_RR || opt == IPOPT_TS ||
890 				opt == IPOPT_SECURITY) {
891 				    bcopy((caddr_t)cp,
892 					mtod(opts, caddr_t) + opts->m_len, len);
893 				    opts->m_len += len;
894 			    }
895 		    }
896 		    /* Terminate & pad, if necessary */
897 		    cnt = opts->m_len % 4;
898 		    if (cnt) {
899 			    for (; cnt < 4; cnt++) {
900 				    *(mtod(opts, caddr_t) + opts->m_len) =
901 					IPOPT_EOL;
902 				    opts->m_len++;
903 			    }
904 		    }
905 #ifdef ICMPPRINTFS
906 		    if (icmpprintfs)
907 			    printf("%d\n", opts->m_len);
908 #endif
909 		}
910 		ip_stripoptions(m);
911 	}
912 	m_tag_delete_nonpersistent(m);
913 	m->m_flags &= ~(M_BCAST|M_MCAST);
914 	icmp_send(m, opts);
915 done:
916 	if (opts)
917 		(void)m_free(opts);
918 }
919 
920 /*
921  * Send an icmp packet back to the ip level,
922  * after supplying a checksum.
923  */
924 static void
925 icmp_send(struct mbuf *m, struct mbuf *opts)
926 {
927 	struct ip *ip = mtod(m, struct ip *);
928 	int hlen;
929 	struct icmp *icp;
930 
931 	hlen = ip->ip_hl << 2;
932 	m->m_data += hlen;
933 	m->m_len -= hlen;
934 	icp = mtod(m, struct icmp *);
935 	icp->icmp_cksum = 0;
936 	icp->icmp_cksum = in_cksum(m, ntohs(ip->ip_len) - hlen);
937 	m->m_data -= hlen;
938 	m->m_len += hlen;
939 	m->m_pkthdr.rcvif = (struct ifnet *)0;
940 #ifdef ICMPPRINTFS
941 	if (icmpprintfs) {
942 		char dstbuf[INET_ADDRSTRLEN];
943 		char srcbuf[INET_ADDRSTRLEN];
944 
945 		printf("icmp_send dst %s src %s\n",
946 		    inet_ntoa_r(ip->ip_dst, dstbuf),
947 		    inet_ntoa_r(ip->ip_src, srcbuf));
948 	}
949 #endif
950 	(void) ip_output(m, opts, NULL, 0, NULL, NULL);
951 }
952 
953 /*
954  * Return milliseconds since 00:00 UTC in network format.
955  */
956 uint32_t
957 iptime(void)
958 {
959 	struct timeval atv;
960 	u_long t;
961 
962 	getmicrotime(&atv);
963 	t = (atv.tv_sec % (24*60*60)) * 1000 + atv.tv_usec / 1000;
964 	return (htonl(t));
965 }
966 
967 /*
968  * Return the next larger or smaller MTU plateau (table from RFC 1191)
969  * given current value MTU.  If DIR is less than zero, a larger plateau
970  * is returned; otherwise, a smaller value is returned.
971  */
972 int
973 ip_next_mtu(int mtu, int dir)
974 {
975 	static int mtutab[] = {
976 		65535, 32000, 17914, 8166, 4352, 2002, 1492, 1280, 1006, 508,
977 		296, 68, 0
978 	};
979 	int i, size;
980 
981 	size = (sizeof mtutab) / (sizeof mtutab[0]);
982 	if (dir >= 0) {
983 		for (i = 0; i < size; i++)
984 			if (mtu > mtutab[i])
985 				return mtutab[i];
986 	} else {
987 		for (i = size - 1; i >= 0; i--)
988 			if (mtu < mtutab[i])
989 				return mtutab[i];
990 		if (mtu == mtutab[0])
991 			return mtutab[0];
992 	}
993 	return 0;
994 }
995 #endif /* INET */
996 
997 
998 /*
999  * badport_bandlim() - check for ICMP bandwidth limit
1000  *
1001  *	Return 0 if it is ok to send an ICMP error response, -1 if we have
1002  *	hit our bandwidth limit and it is not ok.
1003  *
1004  *	If icmplim is <= 0, the feature is disabled and 0 is returned.
1005  *
1006  *	For now we separate the TCP and UDP subsystems w/ different 'which'
1007  *	values.  We may eventually remove this separation (and simplify the
1008  *	code further).
1009  *
1010  *	Note that the printing of the error message is delayed so we can
1011  *	properly print the icmp error rate that the system was trying to do
1012  *	(i.e. 22000/100 pps, etc...).  This can cause long delays in printing
1013  *	the 'final' error, but it doesn't make sense to solve the printing
1014  *	delay with more complex code.
1015  */
1016 struct icmp_rate {
1017 	const char *descr;
1018 	struct counter_rate cr;
1019 };
1020 VNET_DEFINE_STATIC(struct icmp_rate, icmp_rates[BANDLIM_MAX]) = {
1021 	{ "icmp unreach response" },
1022 	{ "icmp ping response" },
1023 	{ "icmp tstamp response" },
1024 	{ "closed port RST response" },
1025 	{ "open port RST response" },
1026 	{ "icmp6 unreach response" },
1027 	{ "sctp ootb response" }
1028 };
1029 #define	V_icmp_rates	VNET(icmp_rates)
1030 
1031 static void
1032 icmp_bandlimit_init(void)
1033 {
1034 
1035 	for (int i = 0; i < BANDLIM_MAX; i++) {
1036 		V_icmp_rates[i].cr.cr_rate = counter_u64_alloc(M_WAITOK);
1037 		V_icmp_rates[i].cr.cr_ticks = ticks;
1038 	}
1039 }
1040 VNET_SYSINIT(icmp_bandlimit, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY,
1041     icmp_bandlimit_init, NULL);
1042 
1043 static void
1044 icmp_bandlimit_uninit(void)
1045 {
1046 
1047 	for (int i = 0; i < BANDLIM_MAX; i++)
1048 		counter_u64_free(V_icmp_rates[i].cr.cr_rate);
1049 }
1050 VNET_SYSUNINIT(icmp_bandlimit, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD,
1051     icmp_bandlimit_uninit, NULL);
1052 
1053 int
1054 badport_bandlim(int which)
1055 {
1056 	int64_t pps;
1057 
1058 	if (V_icmplim == 0 || which == BANDLIM_UNLIMITED)
1059 		return (0);
1060 
1061 	KASSERT(which >= 0 && which < BANDLIM_MAX,
1062 	    ("%s: which %d", __func__, which));
1063 
1064 	pps = counter_ratecheck(&V_icmp_rates[which].cr, V_icmplim);
1065 	if (pps == -1)
1066 		return (-1);
1067 	if (pps > 0 && V_icmplim_output)
1068 		log(LOG_NOTICE, "Limiting %s from %jd to %d packets/sec\n",
1069 			V_icmp_rates[which].descr, (intmax_t )pps, V_icmplim);
1070 	return (0);
1071 }
1072