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