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