xref: /openbsd-src/sys/netinet/ip_icmp.c (revision f2da64fbbbf1b03f09f390ab01267c93dfd77c4c)
1 /*	$OpenBSD: ip_icmp.c,v 1.152 2016/08/22 15:37:23 mpi Exp $	*/
2 /*	$NetBSD: ip_icmp.c,v 1.19 1996/02/13 23:42:22 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1988, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)COPYRIGHT	1.1 (NRL) 17 January 1995
33  *
34  * NRL grants permission for redistribution and use in source and binary
35  * forms, with or without modification, of the software and documentation
36  * created at NRL provided that the following conditions are met:
37  *
38  * 1. Redistributions of source code must retain the above copyright
39  *    notice, this list of conditions and the following disclaimer.
40  * 2. Redistributions in binary form must reproduce the above copyright
41  *    notice, this list of conditions and the following disclaimer in the
42  *    documentation and/or other materials provided with the distribution.
43  * 3. All advertising materials mentioning features or use of this software
44  *    must display the following acknowledgements:
45  *	This product includes software developed by the University of
46  *	California, Berkeley and its contributors.
47  *	This product includes software developed at the Information
48  *	Technology Division, US Naval Research Laboratory.
49  * 4. Neither the name of the NRL nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THE SOFTWARE PROVIDED BY NRL IS PROVIDED BY NRL AND CONTRIBUTORS ``AS
54  * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
55  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
56  * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL NRL OR
57  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
58  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
59  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
60  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
61  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
62  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
63  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64  *
65  * The views and conclusions contained in the software and documentation
66  * are those of the authors and should not be interpreted as representing
67  * official policies, either expressed or implied, of the US Naval
68  * Research Laboratory (NRL).
69  */
70 
71 #include "carp.h"
72 #include "pf.h"
73 
74 #include <sys/param.h>
75 #include <sys/systm.h>
76 #include <sys/mbuf.h>
77 #include <sys/protosw.h>
78 #include <sys/socket.h>
79 #include <sys/sysctl.h>
80 
81 #include <net/if.h>
82 #include <net/if_var.h>
83 #include <net/route.h>
84 
85 #include <netinet/in.h>
86 #include <netinet/in_systm.h>
87 #include <netinet/in_var.h>
88 #include <netinet/ip.h>
89 #include <netinet/ip_icmp.h>
90 #include <netinet/ip_var.h>
91 #include <netinet/icmp_var.h>
92 
93 #if NCARP > 0
94 #include <net/if_types.h>
95 #include <netinet/ip_carp.h>
96 #endif
97 
98 #if NPF > 0
99 #include <net/pfvar.h>
100 #endif
101 
102 /*
103  * ICMP routines: error generation, receive packet processing, and
104  * routines to turnaround packets back to the originator, and
105  * host table maintenance routines.
106  */
107 
108 #ifdef ICMPPRINTFS
109 int	icmpprintfs = 0;	/* Settable from ddb */
110 #endif
111 
112 /* values controllable via sysctl */
113 int	icmpmaskrepl = 0;
114 int	icmpbmcastecho = 0;
115 int	icmptstamprepl = 1;
116 int	icmperrppslim = 100;
117 int	icmp_rediraccept = 0;
118 int	icmp_redirtimeout = 10 * 60;
119 
120 static int icmperrpps_count = 0;
121 static struct timeval icmperrppslim_last;
122 
123 static struct rttimer_queue *icmp_redirect_timeout_q = NULL;
124 struct	icmpstat icmpstat;
125 
126 int *icmpctl_vars[ICMPCTL_MAXID] = ICMPCTL_VARS;
127 
128 void icmp_mtudisc_timeout(struct rtentry *, struct rttimer *);
129 int icmp_ratelimit(const struct in_addr *, const int, const int);
130 void icmp_redirect_timeout(struct rtentry *, struct rttimer *);
131 void icmp_input_if(struct ifnet *, struct mbuf *, int);
132 
133 void
134 icmp_init(void)
135 {
136 	/*
137 	 * This is only useful if the user initializes redirtimeout to
138 	 * something other than zero.
139 	 */
140 	if (icmp_redirtimeout != 0) {
141 		icmp_redirect_timeout_q =
142 		    rt_timer_queue_create(icmp_redirtimeout);
143 	}
144 }
145 
146 struct mbuf *
147 icmp_do_error(struct mbuf *n, int type, int code, u_int32_t dest, int destmtu)
148 {
149 	struct ip *oip = mtod(n, struct ip *), *nip;
150 	unsigned oiplen = oip->ip_hl << 2;
151 	struct icmp *icp;
152 	struct mbuf *m;
153 	unsigned icmplen, mblen;
154 
155 #ifdef ICMPPRINTFS
156 	if (icmpprintfs)
157 		printf("icmp_error(%x, %d, %d)\n", oip, type, code);
158 #endif
159 	if (type != ICMP_REDIRECT)
160 		icmpstat.icps_error++;
161 	/*
162 	 * Don't send error if not the first fragment of message.
163 	 * Don't error if the old packet protocol was ICMP
164 	 * error message, only known informational types.
165 	 */
166 	if (oip->ip_off & htons(IP_OFFMASK))
167 		goto freeit;
168 	if (oip->ip_p == IPPROTO_ICMP && type != ICMP_REDIRECT &&
169 	    n->m_len >= oiplen + ICMP_MINLEN &&
170 	    !ICMP_INFOTYPE(((struct icmp *)
171 	    ((caddr_t)oip + oiplen))->icmp_type)) {
172 		icmpstat.icps_oldicmp++;
173 		goto freeit;
174 	}
175 	/* Don't send error in response to a multicast or broadcast packet */
176 	if (n->m_flags & (M_BCAST|M_MCAST))
177 		goto freeit;
178 
179 	/*
180 	 * First, do a rate limitation check.
181 	 */
182 	if (icmp_ratelimit(&oip->ip_src, type, code)) {
183 		icmpstat.icps_toofreq++;
184 		goto freeit;
185 	}
186 
187 	/*
188 	 * Now, formulate icmp message
189 	 */
190 	icmplen = oiplen + min(8, ntohs(oip->ip_len));
191 	/*
192 	 * Defend against mbuf chains shorter than oip->ip_len:
193 	 */
194 	mblen = 0;
195 	for (m = n; m && (mblen < icmplen); m = m->m_next)
196 		mblen += m->m_len;
197 	icmplen = min(mblen, icmplen);
198 
199 	/*
200 	 * As we are not required to return everything we have,
201 	 * we return whatever we can return at ease.
202 	 *
203 	 * Note that ICMP datagrams longer than 576 octets are out of spec
204 	 * according to RFC1812;
205 	 */
206 
207 	KASSERT(ICMP_MINLEN <= MCLBYTES);
208 
209 	if (icmplen + ICMP_MINLEN > MCLBYTES)
210 		icmplen = MCLBYTES - ICMP_MINLEN - sizeof (struct ip);
211 
212 	m = m_gethdr(M_DONTWAIT, MT_HEADER);
213 	if (m && (sizeof (struct ip) + icmplen + ICMP_MINLEN > MHLEN)) {
214 		MCLGET(m, M_DONTWAIT);
215 		if ((m->m_flags & M_EXT) == 0) {
216 			m_freem(m);
217 			m = NULL;
218 		}
219 	}
220 	if (m == NULL)
221 		goto freeit;
222 	/* keep in same rtable */
223 	m->m_pkthdr.ph_rtableid = n->m_pkthdr.ph_rtableid;
224 	m->m_len = icmplen + ICMP_MINLEN;
225 	if ((m->m_flags & M_EXT) == 0)
226 		MH_ALIGN(m, m->m_len);
227 	icp = mtod(m, struct icmp *);
228 	if ((u_int)type > ICMP_MAXTYPE)
229 		panic("icmp_error");
230 	icmpstat.icps_outhist[type]++;
231 	icp->icmp_type = type;
232 	if (type == ICMP_REDIRECT)
233 		icp->icmp_gwaddr.s_addr = dest;
234 	else {
235 		icp->icmp_void = 0;
236 		/*
237 		 * The following assignments assume an overlay with the
238 		 * zeroed icmp_void field.
239 		 */
240 		if (type == ICMP_PARAMPROB) {
241 			icp->icmp_pptr = code;
242 			code = 0;
243 		} else if (type == ICMP_UNREACH &&
244 		    code == ICMP_UNREACH_NEEDFRAG && destmtu)
245 			icp->icmp_nextmtu = htons(destmtu);
246 	}
247 
248 	icp->icmp_code = code;
249 	m_copydata(n, 0, icmplen, (caddr_t)&icp->icmp_ip);
250 
251 	/*
252 	 * Now, copy old ip header (without options)
253 	 * in front of icmp message.
254 	 */
255 	if ((m->m_flags & M_EXT) == 0 &&
256 	    m->m_data - sizeof(struct ip) < m->m_pktdat)
257 		panic("icmp len");
258 	m->m_data -= sizeof(struct ip);
259 	m->m_len += sizeof(struct ip);
260 	m->m_pkthdr.len = m->m_len;
261 	m->m_pkthdr.ph_ifidx = n->m_pkthdr.ph_ifidx;
262 	nip = mtod(m, struct ip *);
263 	/* ip_v set in ip_output */
264 	nip->ip_hl = sizeof(struct ip) >> 2;
265 	nip->ip_tos = 0;
266 	nip->ip_len = htons(m->m_len);
267 	/* ip_id set in ip_output */
268 	nip->ip_off = 0;
269 	/* ip_ttl set in icmp_reflect */
270 	nip->ip_p = IPPROTO_ICMP;
271 	nip->ip_src = oip->ip_src;
272 	nip->ip_dst = oip->ip_dst;
273 
274 	/* move PF_GENERATED to new packet, if existent XXX preserve more? */
275 	if (n->m_pkthdr.pf.flags & PF_TAG_GENERATED)
276 		m->m_pkthdr.pf.flags |= PF_TAG_GENERATED;
277 
278 	m_freem(n);
279 	return (m);
280 
281 freeit:
282 	m_freem(n);
283 	return (NULL);
284 }
285 
286 /*
287  * Generate an error packet of type error
288  * in response to bad packet ip.
289  *
290  * The ip packet inside has ip_off and ip_len in host byte order.
291  */
292 void
293 icmp_error(struct mbuf *n, int type, int code, u_int32_t dest, int destmtu)
294 {
295 	struct mbuf *m;
296 
297 	m = icmp_do_error(n, type, code, dest, destmtu);
298 	if (m != NULL)
299 		if (!icmp_reflect(m, NULL, NULL))
300 			icmp_send(m, NULL);
301 }
302 
303 /*
304  * Process a received ICMP message.
305  */
306 void
307 icmp_input(struct mbuf *m, ...)
308 {
309 	struct ifnet *ifp;
310 	int hlen;
311 	va_list ap;
312 
313 	va_start(ap, m);
314 	hlen = va_arg(ap, int);
315 	va_end(ap);
316 
317 	ifp = if_get(m->m_pkthdr.ph_ifidx);
318 	if (ifp == NULL) {
319 		m_freem(m);
320 		return;
321 	}
322 
323 	icmp_input_if(ifp, m, hlen);
324 	if_put(ifp);
325 }
326 
327 void
328 icmp_input_if(struct ifnet *ifp, struct mbuf *m, int hlen)
329 {
330 	struct icmp *icp;
331 	struct ip *ip = mtod(m, struct ip *);
332 	struct sockaddr_in sin;
333 	int icmplen, i, code;
334 	struct in_ifaddr *ia;
335 	void *(*ctlfunc)(int, struct sockaddr *, u_int, void *);
336 	struct mbuf *opts;
337 
338 	/*
339 	 * Locate icmp structure in mbuf, and check
340 	 * that not corrupted and of at least minimum length.
341 	 */
342 	icmplen = ntohs(ip->ip_len) - hlen;
343 #ifdef ICMPPRINTFS
344 	if (icmpprintfs) {
345 		char dst[INET_ADDRSTRLEN], src[INET_ADDRSTRLEN];
346 
347 		inet_ntop(AF_INET, &ip->ip_dst, dst, sizeof(dst));
348 		inet_ntop(AF_INET, &ip->ip_src, src, sizeof(src));
349 
350 		printf("icmp_input from %s to %s, len %d\n", src, dst, icmplen);
351 	}
352 #endif
353 	if (icmplen < ICMP_MINLEN) {
354 		icmpstat.icps_tooshort++;
355 		goto freeit;
356 	}
357 	i = hlen + min(icmplen, ICMP_ADVLENMIN);
358 	if (m->m_len < i && (m = m_pullup(m, i)) == NULL) {
359 		icmpstat.icps_tooshort++;
360 		return;
361 	}
362 	ip = mtod(m, struct ip *);
363 	if (in4_cksum(m, 0, hlen, icmplen)) {
364 		icmpstat.icps_checksum++;
365 		goto freeit;
366 	}
367 
368 	icp = (struct icmp *)(mtod(m, caddr_t) + hlen);
369 #ifdef ICMPPRINTFS
370 	/*
371 	 * Message type specific processing.
372 	 */
373 	if (icmpprintfs)
374 		printf("icmp_input, type %d code %d\n", icp->icmp_type,
375 		    icp->icmp_code);
376 #endif
377 	if (icp->icmp_type > ICMP_MAXTYPE)
378 		goto raw;
379 #if NPF > 0
380 	if (m->m_pkthdr.pf.flags & PF_TAG_DIVERTED) {
381 		switch (icp->icmp_type) {
382 		/*
383 		 * These ICMP types map to other connections.  They must be
384 		 * delivered to pr_ctlinput() also for diverted connections.
385 		 */
386 		case ICMP_UNREACH:
387 		case ICMP_TIMXCEED:
388 		case ICMP_PARAMPROB:
389 		case ICMP_SOURCEQUENCH:
390 			break;
391 		 /*
392 		  * Although pf_icmp_mapping() considers redirects belonging
393 		  * to a diverted connection, we must process it here anyway.
394 		  */
395 		case ICMP_REDIRECT:
396 			break;
397 		default:
398 			goto raw;
399 		}
400 	}
401 #endif /* NPF */
402 	icmpstat.icps_inhist[icp->icmp_type]++;
403 	code = icp->icmp_code;
404 	switch (icp->icmp_type) {
405 
406 	case ICMP_UNREACH:
407 		switch (code) {
408 		case ICMP_UNREACH_NET:
409 		case ICMP_UNREACH_HOST:
410 		case ICMP_UNREACH_PROTOCOL:
411 		case ICMP_UNREACH_PORT:
412 		case ICMP_UNREACH_SRCFAIL:
413 			code += PRC_UNREACH_NET;
414 			break;
415 
416 		case ICMP_UNREACH_NEEDFRAG:
417 			code = PRC_MSGSIZE;
418 			break;
419 
420 		case ICMP_UNREACH_NET_UNKNOWN:
421 		case ICMP_UNREACH_NET_PROHIB:
422 		case ICMP_UNREACH_TOSNET:
423 			code = PRC_UNREACH_NET;
424 			break;
425 
426 		case ICMP_UNREACH_HOST_UNKNOWN:
427 		case ICMP_UNREACH_ISOLATED:
428 		case ICMP_UNREACH_HOST_PROHIB:
429 		case ICMP_UNREACH_TOSHOST:
430 		case ICMP_UNREACH_FILTER_PROHIB:
431 		case ICMP_UNREACH_HOST_PRECEDENCE:
432 		case ICMP_UNREACH_PRECEDENCE_CUTOFF:
433 			code = PRC_UNREACH_HOST;
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 		/* Free packet atttributes */
459 		if (m->m_flags & M_PKTHDR)
460 			m_tag_delete_chain(m);
461 
462 		/*
463 		 * Problem with datagram; advise higher level routines.
464 		 */
465 		if (icmplen < ICMP_ADVLENMIN || icmplen < ICMP_ADVLEN(icp) ||
466 		    icp->icmp_ip.ip_hl < (sizeof(struct ip) >> 2)) {
467 			icmpstat.icps_badlen++;
468 			goto freeit;
469 		}
470 		if (IN_MULTICAST(icp->icmp_ip.ip_dst.s_addr))
471 			goto badcode;
472 #ifdef INET6
473 		/* Get more contiguous data for a v6 in v4 ICMP message. */
474 		if (icp->icmp_ip.ip_p == IPPROTO_IPV6) {
475 			if (icmplen < ICMP_V6ADVLENMIN ||
476 			    icmplen < ICMP_V6ADVLEN(icp)) {
477 				icmpstat.icps_badlen++;
478 				goto freeit;
479 			} else {
480 				if ((m = m_pullup(m, (ip->ip_hl << 2) +
481 				    ICMP_V6ADVLEN(icp))) == NULL) {
482 					icmpstat.icps_tooshort++;
483 					return;
484 				}
485 				ip = mtod(m, struct ip *);
486 				icp = (struct icmp *)
487 				    (m->m_data + (ip->ip_hl << 2));
488 			}
489 		}
490 #endif /* INET6 */
491 #ifdef ICMPPRINTFS
492 		if (icmpprintfs)
493 			printf("deliver to protocol %d\n", icp->icmp_ip.ip_p);
494 #endif
495 		memset(&sin, 0, sizeof(sin));
496 		sin.sin_family = AF_INET;
497 		sin.sin_len = sizeof(struct sockaddr_in);
498 		sin.sin_addr = icp->icmp_ip.ip_dst;
499 #if NCARP > 0
500 		if (ifp->if_type == IFT_CARP &&
501 		    carp_lsdrop(m, AF_INET, &sin.sin_addr.s_addr,
502 		    &ip->ip_dst.s_addr))
503 			goto freeit;
504 #endif
505 		/*
506 		 * XXX if the packet contains [IPv4 AH TCP], we can't make a
507 		 * notification to TCP layer.
508 		 */
509 		ctlfunc = inetsw[ip_protox[icp->icmp_ip.ip_p]].pr_ctlinput;
510 		if (ctlfunc)
511 			(*ctlfunc)(code, sintosa(&sin), m->m_pkthdr.ph_rtableid,
512 			    &icp->icmp_ip);
513 		break;
514 
515 	badcode:
516 		icmpstat.icps_badcode++;
517 		break;
518 
519 	case ICMP_ECHO:
520 		if (!icmpbmcastecho &&
521 		    (m->m_flags & (M_MCAST | M_BCAST)) != 0) {
522 			icmpstat.icps_bmcastecho++;
523 			break;
524 		}
525 		icp->icmp_type = ICMP_ECHOREPLY;
526 		goto reflect;
527 
528 	case ICMP_TSTAMP:
529 		if (icmptstamprepl == 0)
530 			break;
531 
532 		if (!icmpbmcastecho &&
533 		    (m->m_flags & (M_MCAST | M_BCAST)) != 0) {
534 			icmpstat.icps_bmcastecho++;
535 			break;
536 		}
537 		if (icmplen < ICMP_TSLEN) {
538 			icmpstat.icps_badlen++;
539 			break;
540 		}
541 		icp->icmp_type = ICMP_TSTAMPREPLY;
542 		icp->icmp_rtime = iptime();
543 		icp->icmp_ttime = icp->icmp_rtime;	/* bogus, do later! */
544 		goto reflect;
545 
546 	case ICMP_MASKREQ:
547 		if (icmpmaskrepl == 0)
548 			break;
549 		if (icmplen < ICMP_MASKLEN) {
550 			icmpstat.icps_badlen++;
551 			break;
552 		}
553 		/*
554 		 * We are not able to respond with all ones broadcast
555 		 * unless we receive it over a point-to-point interface.
556 		 */
557 		memset(&sin, 0, sizeof(sin));
558 		sin.sin_family = AF_INET;
559 		sin.sin_len = sizeof(struct sockaddr_in);
560 		if (ip->ip_dst.s_addr == INADDR_BROADCAST ||
561 		    ip->ip_dst.s_addr == INADDR_ANY)
562 			sin.sin_addr = ip->ip_src;
563 		else
564 			sin.sin_addr = ip->ip_dst;
565 		if (ifp == NULL)
566 			break;
567 		ia = ifatoia(ifaof_ifpforaddr(sintosa(&sin), ifp));
568 		if (ia == NULL)
569 			break;
570 		icp->icmp_type = ICMP_MASKREPLY;
571 		icp->icmp_mask = ia->ia_sockmask.sin_addr.s_addr;
572 		if (ip->ip_src.s_addr == 0) {
573 			if (ifp->if_flags & IFF_BROADCAST) {
574 				if (ia->ia_broadaddr.sin_addr.s_addr)
575 					ip->ip_src = ia->ia_broadaddr.sin_addr;
576 				else
577 					ip->ip_src.s_addr = INADDR_BROADCAST;
578 			}
579 			else if (ifp->if_flags & IFF_POINTOPOINT)
580 				ip->ip_src = ia->ia_dstaddr.sin_addr;
581 		}
582 reflect:
583 #if NCARP > 0
584 		if (ifp->if_type == IFT_CARP &&
585 		    carp_lsdrop(m, AF_INET, &ip->ip_src.s_addr,
586 		    &ip->ip_dst.s_addr))
587 			goto freeit;
588 #endif
589 		/* Free packet atttributes */
590 		if (m->m_flags & M_PKTHDR)
591 			m_tag_delete_chain(m);
592 
593 		icmpstat.icps_reflect++;
594 		icmpstat.icps_outhist[icp->icmp_type]++;
595 		if (!icmp_reflect(m, &opts, NULL))
596 			icmp_send(m, opts);
597 		return;
598 
599 	case ICMP_REDIRECT:
600 	{
601 		struct sockaddr_in sdst;
602 		struct sockaddr_in sgw;
603 		struct sockaddr_in ssrc;
604 		struct rtentry *newrt = NULL;
605 
606 		/* Free packet atttributes */
607 		if (m->m_flags & M_PKTHDR)
608 			m_tag_delete_chain(m);
609 		if (icmp_rediraccept == 0 || ipforwarding == 1)
610 			goto freeit;
611 		if (code > 3)
612 			goto badcode;
613 		if (icmplen < ICMP_ADVLENMIN || icmplen < ICMP_ADVLEN(icp) ||
614 		    icp->icmp_ip.ip_hl < (sizeof(struct ip) >> 2)) {
615 			icmpstat.icps_badlen++;
616 			break;
617 		}
618 		/*
619 		 * Short circuit routing redirects to force
620 		 * immediate change in the kernel's routing
621 		 * tables.  The message is also handed to anyone
622 		 * listening on a raw socket (e.g. the routing
623 		 * daemon for use in updating its tables).
624 		 */
625 		memset(&sdst, 0, sizeof(sdst));
626 		memset(&sgw, 0, sizeof(sgw));
627 		memset(&ssrc, 0, sizeof(ssrc));
628 		sdst.sin_family = sgw.sin_family = ssrc.sin_family = AF_INET;
629 		sdst.sin_len = sgw.sin_len = ssrc.sin_len = sizeof(sdst);
630 		memcpy(&sdst.sin_addr, &icp->icmp_ip.ip_dst,
631 		    sizeof(sdst.sin_addr));
632 		memcpy(&sgw.sin_addr, &icp->icmp_gwaddr,
633 		    sizeof(sgw.sin_addr));
634 		memcpy(&ssrc.sin_addr, &ip->ip_src,
635 		    sizeof(ssrc.sin_addr));
636 
637 #ifdef	ICMPPRINTFS
638 		if (icmpprintfs) {
639 			char gw[INET_ADDRSTRLEN], dst[INET_ADDRSTRLEN];
640 
641 			inet_ntop(AF_INET, &icp->icmp_gwaddr, gw, sizeof(gw));
642 			inet_ntop(AF_INET, &icp->icmp_ip.ip_dst,
643 			    dst, sizeof(dst));
644 
645 			printf("redirect dst %s to %s\n", dst, gw);
646 		}
647 #endif
648 
649 #if NCARP > 0
650 		if (ifp->if_type == IFT_CARP &&
651 		    carp_lsdrop(m, AF_INET, &sdst.sin_addr.s_addr,
652 		    &ip->ip_dst.s_addr))
653 			goto freeit;
654 #endif
655 		rtredirect(sintosa(&sdst), sintosa(&sgw),
656 		    sintosa(&ssrc), &newrt, m->m_pkthdr.ph_rtableid);
657 		if (newrt != NULL && icmp_redirtimeout != 0) {
658 			(void)rt_timer_add(newrt, icmp_redirect_timeout,
659 			    icmp_redirect_timeout_q, m->m_pkthdr.ph_rtableid);
660 		}
661 		if (newrt != NULL)
662 			rtfree(newrt);
663 		pfctlinput(PRC_REDIRECT_HOST, sintosa(&sdst));
664 		break;
665 	}
666 	/*
667 	 * No kernel processing for the following;
668 	 * just fall through to send to raw listener.
669 	 */
670 	case ICMP_ECHOREPLY:
671 	case ICMP_ROUTERADVERT:
672 	case ICMP_ROUTERSOLICIT:
673 	case ICMP_TSTAMPREPLY:
674 	case ICMP_IREQREPLY:
675 	case ICMP_MASKREPLY:
676 	case ICMP_TRACEROUTE:
677 	case ICMP_DATACONVERR:
678 	case ICMP_MOBILE_REDIRECT:
679 	case ICMP_IPV6_WHEREAREYOU:
680 	case ICMP_IPV6_IAMHERE:
681 	case ICMP_MOBILE_REGREQUEST:
682 	case ICMP_MOBILE_REGREPLY:
683 	case ICMP_PHOTURIS:
684 	default:
685 		break;
686 	}
687 
688 raw:
689 	rip_input(m);
690 	return;
691 
692 freeit:
693 	m_freem(m);
694 }
695 
696 /*
697  * Reflect the ip packet back to the source
698  */
699 int
700 icmp_reflect(struct mbuf *m, struct mbuf **op, struct in_ifaddr *ia)
701 {
702 	struct ip *ip = mtod(m, struct ip *);
703 	struct mbuf *opts = NULL;
704 	struct sockaddr_in sin;
705 	struct rtentry *rt = NULL;
706 	int optlen = (ip->ip_hl << 2) - sizeof(struct ip);
707 	u_int rtableid;
708 
709 	if (!in_canforward(ip->ip_src) &&
710 	    ((ip->ip_src.s_addr & IN_CLASSA_NET) !=
711 	    htonl(IN_LOOPBACKNET << IN_CLASSA_NSHIFT))) {
712 		m_freem(m);		/* Bad return address */
713 		return (EHOSTUNREACH);
714 	}
715 
716 #if NPF > 0
717 	pf_pkt_addr_changed(m);
718 #endif
719 	rtableid = m->m_pkthdr.ph_rtableid;
720 
721 	/*
722 	 * If the incoming packet was addressed directly to us,
723 	 * use dst as the src for the reply.  For broadcast, use
724 	 * the address which corresponds to the incoming interface.
725 	 */
726 	if (ia == NULL) {
727 		memset(&sin, 0, sizeof(sin));
728 		sin.sin_len = sizeof(sin);
729 		sin.sin_family = AF_INET;
730 		sin.sin_addr = ip->ip_dst;
731 
732 		rt = rtalloc(sintosa(&sin), 0, rtableid);
733 		if (rtisvalid(rt) &&
734 		    ISSET(rt->rt_flags, RTF_LOCAL|RTF_BROADCAST))
735 			ia = ifatoia(rt->rt_ifa);
736 	}
737 
738 	/*
739 	 * The following happens if the packet was not addressed to us.
740 	 * Use the new source address and do a route lookup. If it fails
741 	 * drop the packet as there is no path to the host.
742 	 */
743 	if (ia == NULL) {
744 		rtfree(rt);
745 
746 		memset(&sin, 0, sizeof(sin));
747 		sin.sin_len = sizeof(sin);
748 		sin.sin_family = AF_INET;
749 		sin.sin_addr = ip->ip_src;
750 
751 		/* keep packet in the original virtual instance */
752 		rt = rtalloc(sintosa(&sin), RT_RESOLVE, rtableid);
753 		if (rt == NULL) {
754 			ipstat.ips_noroute++;
755 			m_freem(m);
756 			return (EHOSTUNREACH);
757 		}
758 
759 		ia = ifatoia(rt->rt_ifa);
760 	}
761 
762 	ip->ip_dst = ip->ip_src;
763 	ip->ip_ttl = MAXTTL;
764 
765 	/* It is safe to dereference ``ia'' iff ``rt'' is valid. */
766 	ip->ip_src = ia->ia_addr.sin_addr;
767 	rtfree(rt);
768 
769 	if (optlen > 0) {
770 		u_char *cp;
771 		int opt, cnt;
772 		u_int len;
773 
774 		/*
775 		 * Retrieve any source routing from the incoming packet;
776 		 * add on any record-route or timestamp options.
777 		 */
778 		cp = (u_char *) (ip + 1);
779 		if (op && (opts = ip_srcroute(m)) == NULL &&
780 		    (opts = m_gethdr(M_DONTWAIT, MT_HEADER))) {
781 			opts->m_len = sizeof(struct in_addr);
782 			mtod(opts, struct in_addr *)->s_addr = 0;
783 		}
784 		if (op && opts) {
785 #ifdef ICMPPRINTFS
786 			if (icmpprintfs)
787 				printf("icmp_reflect optlen %d rt %d => ",
788 				    optlen, opts->m_len);
789 #endif
790 			for (cnt = optlen; cnt > 0; cnt -= len, cp += len) {
791 				opt = cp[IPOPT_OPTVAL];
792 				if (opt == IPOPT_EOL)
793 					break;
794 				if (opt == IPOPT_NOP)
795 					len = 1;
796 				else {
797 					if (cnt < IPOPT_OLEN + sizeof(*cp))
798 						break;
799 					len = cp[IPOPT_OLEN];
800 					if (len < IPOPT_OLEN + sizeof(*cp) ||
801 					    len > cnt)
802 						break;
803 				}
804 				/*
805 				 * Should check for overflow, but it
806 				 * "can't happen"
807 				 */
808 				if (opt == IPOPT_RR || opt == IPOPT_TS ||
809 				    opt == IPOPT_SECURITY) {
810 					memcpy(mtod(opts, caddr_t) +
811 					    opts->m_len, cp, len);
812 					opts->m_len += len;
813 				}
814 			}
815 			/* Terminate & pad, if necessary */
816 			if ((cnt = opts->m_len % 4) != 0)
817 				for (; cnt < 4; cnt++) {
818 					*(mtod(opts, caddr_t) + opts->m_len) =
819 					    IPOPT_EOL;
820 					opts->m_len++;
821 				}
822 #ifdef ICMPPRINTFS
823 			if (icmpprintfs)
824 				printf("%d\n", opts->m_len);
825 #endif
826 		}
827 		ip_stripoptions(m);
828 	}
829 	m->m_flags &= ~(M_BCAST|M_MCAST);
830 	if (op)
831 		*op = opts;
832 
833 	return (0);
834 }
835 
836 /*
837  * Send an icmp packet back to the ip level
838  */
839 void
840 icmp_send(struct mbuf *m, struct mbuf *opts)
841 {
842 	struct ip *ip = mtod(m, struct ip *);
843 	int hlen;
844 	struct icmp *icp;
845 
846 	hlen = ip->ip_hl << 2;
847 	icp = (struct icmp *)(mtod(m, caddr_t) + hlen);
848 	icp->icmp_cksum = 0;
849 	m->m_pkthdr.csum_flags = M_ICMP_CSUM_OUT;
850 #ifdef ICMPPRINTFS
851 	if (icmpprintfs) {
852 		char dst[INET_ADDRSTRLEN], src[INET_ADDRSTRLEN];
853 
854 		inet_ntop(AF_INET, &ip->ip_dst, dst, sizeof(dst));
855 		inet_ntop(AF_INET, &ip->ip_src, src, sizeof(src));
856 
857 		printf("icmp_send dst %s src %s\n", dst, src);
858 	}
859 #endif
860 	if (opts != NULL)
861 		m = ip_insertoptions(m, opts, &hlen);
862 
863 	ip_send(m);
864 }
865 
866 u_int32_t
867 iptime(void)
868 {
869 	struct timeval atv;
870 	u_long t;
871 
872 	microtime(&atv);
873 	t = (atv.tv_sec % (24*60*60)) * 1000 + atv.tv_usec / 1000;
874 	return (htonl(t));
875 }
876 
877 int
878 icmp_sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
879     size_t newlen)
880 {
881 	int s, error;
882 
883 	/* All sysctl names at this level are terminal. */
884 	if (namelen != 1)
885 		return (ENOTDIR);
886 
887 	s = splsoftnet();
888 	switch (name[0]) {
889 	case ICMPCTL_REDIRTIMEOUT:
890 
891 		error = sysctl_int(oldp, oldlenp, newp, newlen,
892 		    &icmp_redirtimeout);
893 		if (icmp_redirect_timeout_q != NULL) {
894 			if (icmp_redirtimeout == 0) {
895 				rt_timer_queue_destroy(icmp_redirect_timeout_q);
896 				icmp_redirect_timeout_q = NULL;
897 			} else
898 				rt_timer_queue_change(icmp_redirect_timeout_q,
899 				    icmp_redirtimeout);
900 		} else if (icmp_redirtimeout > 0) {
901 			icmp_redirect_timeout_q =
902 			    rt_timer_queue_create(icmp_redirtimeout);
903 		}
904 		break;
905 
906 	case ICMPCTL_STATS:
907 		if (newp != NULL) {
908 			error = EPERM;
909 			break;
910 		}
911 		error = sysctl_struct(oldp, oldlenp, newp, newlen,
912 		    &icmpstat, sizeof(icmpstat));
913 		break;
914 
915 	default:
916 		if (name[0] < ICMPCTL_MAXID) {
917 			error = sysctl_int_arr(icmpctl_vars, name, namelen,
918 			    oldp, oldlenp, newp, newlen);
919 			break;
920 		}
921 		error = ENOPROTOOPT;
922 		break;
923 	}
924 	splx(s);
925 
926 	return (error);
927 }
928 
929 
930 struct rtentry *
931 icmp_mtudisc_clone(struct in_addr dst, u_int rtableid)
932 {
933 	struct sockaddr_in sin;
934 	struct rtentry *rt;
935 	int error;
936 
937 	memset(&sin, 0, sizeof(sin));
938 	sin.sin_family = AF_INET;
939 	sin.sin_len = sizeof(sin);
940 	sin.sin_addr = dst;
941 
942 	rt = rtalloc(sintosa(&sin), RT_RESOLVE, rtableid);
943 
944 	/* Check if the route is actually usable */
945 	if (!rtisvalid(rt) || (rt->rt_flags & (RTF_REJECT|RTF_BLACKHOLE))) {
946 		rtfree(rt);
947 		return (NULL);
948 	}
949 
950 	/* If we didn't get a host route, allocate one */
951 	if ((rt->rt_flags & RTF_HOST) == 0) {
952 		struct rtentry *nrt;
953 		struct rt_addrinfo info;
954 
955 		memset(&info, 0, sizeof(info));
956 		info.rti_info[RTAX_DST] = sintosa(&sin);
957 		info.rti_info[RTAX_GATEWAY] = rt->rt_gateway;
958 		info.rti_flags = RTF_GATEWAY | RTF_HOST | RTF_DYNAMIC;
959 
960 		error = rtrequest(RTM_ADD, &info, RTP_DEFAULT, &nrt, rtableid);
961 		if (error) {
962 			rtfree(rt);
963 			return (NULL);
964 		}
965 		nrt->rt_rmx = rt->rt_rmx;
966 		rtfree(rt);
967 		rt = nrt;
968 	}
969 	error = rt_timer_add(rt, icmp_mtudisc_timeout, ip_mtudisc_timeout_q,
970 	    rtableid);
971 	if (error) {
972 		rtfree(rt);
973 		return (NULL);
974 	}
975 
976 	return (rt);
977 }
978 
979 /* Table of common MTUs: */
980 static const u_short mtu_table[] = {
981 	65535, 65280, 32000, 17914, 9180, 8166,
982 	4352, 2002, 1492, 1006, 508, 296, 68, 0
983 };
984 
985 void
986 icmp_mtudisc(struct icmp *icp, u_int rtableid)
987 {
988 	struct rtentry *rt;
989 	struct ifnet *ifp;
990 	u_long mtu = ntohs(icp->icmp_nextmtu);  /* Why a long?  IPv6 */
991 
992 	rt = icmp_mtudisc_clone(icp->icmp_ip.ip_dst, rtableid);
993 	if (rt == NULL)
994 		return;
995 
996 	ifp = if_get(rt->rt_ifidx);
997 	if (ifp == NULL) {
998 		rtfree(rt);
999 		return;
1000 	}
1001 
1002 	if (mtu == 0) {
1003 		int i = 0;
1004 
1005 		mtu = ntohs(icp->icmp_ip.ip_len);
1006 		/* Some 4.2BSD-based routers incorrectly adjust the ip_len */
1007 		if (mtu > rt->rt_rmx.rmx_mtu && rt->rt_rmx.rmx_mtu != 0)
1008 			mtu -= (icp->icmp_ip.ip_hl << 2);
1009 
1010 		/* If we still can't guess a value, try the route */
1011 		if (mtu == 0) {
1012 			mtu = rt->rt_rmx.rmx_mtu;
1013 
1014 			/* If no route mtu, default to the interface mtu */
1015 
1016 			if (mtu == 0)
1017 				mtu = ifp->if_mtu;
1018 		}
1019 
1020 		for (i = 0; i < nitems(mtu_table); i++)
1021 			if (mtu > mtu_table[i]) {
1022 				mtu = mtu_table[i];
1023 				break;
1024 			}
1025 	}
1026 
1027 	/*
1028 	 * XXX:   RTV_MTU is overloaded, since the admin can set it
1029 	 *	  to turn off PMTU for a route, and the kernel can
1030 	 *	  set it to indicate a serious problem with PMTU
1031 	 *	  on a route.  We should be using a separate flag
1032 	 *	  for the kernel to indicate this.
1033 	 */
1034 	if ((rt->rt_rmx.rmx_locks & RTV_MTU) == 0) {
1035 		if (mtu < 296 || mtu > ifp->if_mtu)
1036 			rt->rt_rmx.rmx_locks |= RTV_MTU;
1037 		else if (rt->rt_rmx.rmx_mtu > mtu || rt->rt_rmx.rmx_mtu == 0)
1038 			rt->rt_rmx.rmx_mtu = mtu;
1039 	}
1040 
1041 	if_put(ifp);
1042 	rtfree(rt);
1043 }
1044 
1045 void
1046 icmp_mtudisc_timeout(struct rtentry *rt, struct rttimer *r)
1047 {
1048 	struct ifnet *ifp;
1049 	int s;
1050 
1051 	ifp = if_get(rt->rt_ifidx);
1052 	if (ifp == NULL)
1053 		return;
1054 
1055 	if ((rt->rt_flags & (RTF_DYNAMIC|RTF_HOST)) == (RTF_DYNAMIC|RTF_HOST)) {
1056 		void *(*ctlfunc)(int, struct sockaddr *, u_int, void *);
1057 		struct sockaddr_in sin;
1058 
1059 		sin = *satosin(rt_key(rt));
1060 
1061 		s = splsoftnet();
1062 		rtdeletemsg(rt, ifp, r->rtt_tableid);
1063 
1064 		/* Notify TCP layer of increased Path MTU estimate */
1065 		ctlfunc = inetsw[ip_protox[IPPROTO_TCP]].pr_ctlinput;
1066 		if (ctlfunc)
1067 			(*ctlfunc)(PRC_MTUINC, sintosa(&sin),
1068 			    r->rtt_tableid, NULL);
1069 		splx(s);
1070 	} else {
1071 		if ((rt->rt_rmx.rmx_locks & RTV_MTU) == 0)
1072 			rt->rt_rmx.rmx_mtu = 0;
1073 	}
1074 
1075 	if_put(ifp);
1076 }
1077 
1078 /*
1079  * Perform rate limit check.
1080  * Returns 0 if it is okay to send the icmp packet.
1081  * Returns 1 if the router SHOULD NOT send this icmp packet due to rate
1082  * limitation.
1083  *
1084  * XXX per-destination/type check necessary?
1085  */
1086 int
1087 icmp_ratelimit(const struct in_addr *dst, const int type, const int code)
1088 {
1089 	/* PPS limit */
1090 	if (!ppsratecheck(&icmperrppslim_last, &icmperrpps_count,
1091 	    icmperrppslim))
1092 		return 1;	/* The packet is subject to rate limit */
1093 	return 0;	/* okay to send */
1094 }
1095 
1096 void
1097 icmp_redirect_timeout(struct rtentry *rt, struct rttimer *r)
1098 {
1099 	struct ifnet *ifp;
1100 	int s;
1101 
1102 	ifp = if_get(rt->rt_ifidx);
1103 	if (ifp == NULL)
1104 		return;
1105 
1106 	if ((rt->rt_flags & (RTF_DYNAMIC|RTF_HOST)) == (RTF_DYNAMIC|RTF_HOST)) {
1107 		s = splsoftnet();
1108 		rtdeletemsg(rt, ifp, r->rtt_tableid);
1109 		splx(s);
1110 	}
1111 
1112 	if_put(ifp);
1113 }
1114 
1115 int
1116 icmp_do_exthdr(struct mbuf *m, u_int16_t class, u_int8_t ctype, void *buf,
1117     size_t len)
1118 {
1119 	struct ip *ip = mtod(m, struct ip *);
1120 	int hlen, off;
1121 	struct mbuf *n;
1122 	struct icmp *icp;
1123 	struct icmp_ext_hdr *ieh;
1124 	struct {
1125 		struct icmp_ext_hdr	ieh;
1126 		struct icmp_ext_obj_hdr	ieo;
1127 	} hdr;
1128 
1129 	hlen = ip->ip_hl << 2;
1130 	icp = (struct icmp *)(mtod(m, caddr_t) + hlen);
1131 	if (icp->icmp_type != ICMP_TIMXCEED && icp->icmp_type != ICMP_UNREACH &&
1132 	    icp->icmp_type != ICMP_PARAMPROB)
1133 		/* exthdr not supported */
1134 		return (0);
1135 
1136 	if (icp->icmp_length != 0)
1137 		/* exthdr already present, giving up */
1138 		return (0);
1139 
1140 	/* the actual offset starts after the common ICMP header */
1141 	hlen += ICMP_MINLEN;
1142 	/* exthdr must start on a word boundary */
1143 	off = roundup(ntohs(ip->ip_len) - hlen, sizeof(u_int32_t));
1144 	/* ... and at an offset of ICMP_EXT_OFFSET or bigger */
1145 	off = max(off, ICMP_EXT_OFFSET);
1146 	icp->icmp_length = off / sizeof(u_int32_t);
1147 
1148 	memset(&hdr, 0, sizeof(hdr));
1149 	hdr.ieh.ieh_version = ICMP_EXT_HDR_VERSION;
1150 	hdr.ieo.ieo_length = htons(sizeof(struct icmp_ext_obj_hdr) + len);
1151 	hdr.ieo.ieo_cnum = class;
1152 	hdr.ieo.ieo_ctype = ctype;
1153 
1154 	if (m_copyback(m, hlen + off, sizeof(hdr), &hdr, M_NOWAIT) ||
1155 	    m_copyback(m, hlen + off + sizeof(hdr), len, buf, M_NOWAIT)) {
1156 		m_freem(m);
1157 		return (ENOBUFS);
1158 	}
1159 
1160 	/* calculate checksum */
1161 	n = m_getptr(m, hlen + off, &off);
1162 	if (n == NULL)
1163 		panic("icmp_do_exthdr: m_getptr failure");
1164 	ieh = (struct icmp_ext_hdr *)(mtod(n, caddr_t) + off);
1165 	ieh->ieh_cksum = in4_cksum(n, 0, off, sizeof(hdr) + len);
1166 
1167 	ip->ip_len = htons(m->m_pkthdr.len);
1168 
1169 	return (0);
1170 }
1171