xref: /freebsd-13-stable/sys/netinet6/icmp6.c (revision e1dd07ede92382bdcc52b3093e8f2ec5d9c88467)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	$KAME: icmp6.c,v 1.211 2001/04/04 05:56:20 itojun Exp $
32  */
33 
34 /*-
35  * Copyright (c) 1982, 1986, 1988, 1993
36  *	The Regents of the University of California.  All rights reserved.
37  *
38  * Redistribution and use in source and binary forms, with or without
39  * modification, are permitted provided that the following conditions
40  * are met:
41  * 1. Redistributions of source code must retain the above copyright
42  *    notice, this list of conditions and the following disclaimer.
43  * 2. Redistributions in binary form must reproduce the above copyright
44  *    notice, this list of conditions and the following disclaimer in the
45  *    documentation and/or other materials provided with the distribution.
46  * 3. Neither the name of the University nor the names of its contributors
47  *    may be used to endorse or promote products derived from this software
48  *    without specific prior written permission.
49  *
50  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60  * SUCH DAMAGE.
61  *
62  *	@(#)ip_icmp.c	8.2 (Berkeley) 1/4/94
63  */
64 
65 #include <sys/cdefs.h>
66 #define	MBUF_PRIVATE	/* XXXRW: Optimisation tries to avoid M_EXT mbufs */
67 
68 #include "opt_inet.h"
69 #include "opt_inet6.h"
70 
71 #include <sys/param.h>
72 #include <sys/domain.h>
73 #include <sys/jail.h>
74 #include <sys/kernel.h>
75 #include <sys/lock.h>
76 #include <sys/malloc.h>
77 #include <sys/mbuf.h>
78 #include <sys/proc.h>
79 #include <sys/protosw.h>
80 #include <sys/signalvar.h>
81 #include <sys/socket.h>
82 #include <sys/socketvar.h>
83 #include <sys/sx.h>
84 #include <sys/syslog.h>
85 #include <sys/systm.h>
86 #include <sys/time.h>
87 
88 #include <net/if.h>
89 #include <net/if_var.h>
90 #include <net/if_dl.h>
91 #include <net/if_llatbl.h>
92 #include <net/if_types.h>
93 #include <net/route.h>
94 #include <net/route/route_ctl.h>
95 #include <net/route/nhop.h>
96 #include <net/vnet.h>
97 
98 #include <netinet/in.h>
99 #include <netinet/in_pcb.h>
100 #include <netinet/in_var.h>
101 #include <netinet/ip6.h>
102 #include <netinet/icmp6.h>
103 #include <netinet/tcp_var.h>
104 
105 #include <netinet6/in6_fib.h>
106 #include <netinet6/in6_ifattach.h>
107 #include <netinet6/in6_pcb.h>
108 #include <netinet6/ip6protosw.h>
109 #include <netinet6/ip6_var.h>
110 #include <netinet6/scope6_var.h>
111 #include <netinet6/mld6_var.h>
112 #include <netinet6/nd6.h>
113 #include <netinet6/send.h>
114 
115 extern struct domain inet6domain;
116 
117 VNET_PCPUSTAT_DEFINE(struct icmp6stat, icmp6stat);
118 VNET_PCPUSTAT_SYSINIT(icmp6stat);
119 
120 #ifdef VIMAGE
121 VNET_PCPUSTAT_SYSUNINIT(icmp6stat);
122 #endif /* VIMAGE */
123 
124 VNET_DECLARE(struct inpcbinfo, ripcbinfo);
125 VNET_DECLARE(struct inpcbhead, ripcb);
126 VNET_DECLARE(int, icmp6_nodeinfo);
127 
128 #define	V_ripcbinfo			VNET(ripcbinfo)
129 #define	V_ripcb				VNET(ripcb)
130 #define	V_icmp6_nodeinfo		VNET(icmp6_nodeinfo)
131 
132 static void icmp6_errcount(int, int);
133 static int icmp6_rip6_input(struct mbuf **, int);
134 static void icmp6_reflect(struct mbuf *, size_t);
135 static int icmp6_ratelimit(const struct in6_addr *, const int, const int);
136 static const char *icmp6_redirect_diag(struct in6_addr *,
137 	struct in6_addr *, struct in6_addr *);
138 static struct mbuf *ni6_input(struct mbuf *, int, struct prison *);
139 static struct mbuf *ni6_nametodns(const char *, int, int);
140 static int ni6_dnsmatch(const char *, int, const char *, int);
141 static int ni6_addrs(struct icmp6_nodeinfo *, struct mbuf *,
142 			  struct ifnet **, struct in6_addr *);
143 static int ni6_store_addrs(struct icmp6_nodeinfo *, struct icmp6_nodeinfo *,
144 				struct ifnet *, int);
145 static int icmp6_notify_error(struct mbuf **, int, int, int);
146 
147 /*
148  * Kernel module interface for updating icmp6stat.  The argument is an index
149  * into icmp6stat treated as an array of u_quad_t.  While this encodes the
150  * general layout of icmp6stat into the caller, it doesn't encode its
151  * location, so that future changes to add, for example, per-CPU stats
152  * support won't cause binary compatibility problems for kernel modules.
153  */
154 void
kmod_icmp6stat_inc(int statnum)155 kmod_icmp6stat_inc(int statnum)
156 {
157 
158 	counter_u64_add(VNET(icmp6stat)[statnum], 1);
159 }
160 
161 static void
icmp6_errcount(int type,int code)162 icmp6_errcount(int type, int code)
163 {
164 	switch (type) {
165 	case ICMP6_DST_UNREACH:
166 		switch (code) {
167 		case ICMP6_DST_UNREACH_NOROUTE:
168 			ICMP6STAT_INC(icp6s_odst_unreach_noroute);
169 			return;
170 		case ICMP6_DST_UNREACH_ADMIN:
171 			ICMP6STAT_INC(icp6s_odst_unreach_admin);
172 			return;
173 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
174 			ICMP6STAT_INC(icp6s_odst_unreach_beyondscope);
175 			return;
176 		case ICMP6_DST_UNREACH_ADDR:
177 			ICMP6STAT_INC(icp6s_odst_unreach_addr);
178 			return;
179 		case ICMP6_DST_UNREACH_NOPORT:
180 			ICMP6STAT_INC(icp6s_odst_unreach_noport);
181 			return;
182 		}
183 		break;
184 	case ICMP6_PACKET_TOO_BIG:
185 		ICMP6STAT_INC(icp6s_opacket_too_big);
186 		return;
187 	case ICMP6_TIME_EXCEEDED:
188 		switch (code) {
189 		case ICMP6_TIME_EXCEED_TRANSIT:
190 			ICMP6STAT_INC(icp6s_otime_exceed_transit);
191 			return;
192 		case ICMP6_TIME_EXCEED_REASSEMBLY:
193 			ICMP6STAT_INC(icp6s_otime_exceed_reassembly);
194 			return;
195 		}
196 		break;
197 	case ICMP6_PARAM_PROB:
198 		switch (code) {
199 		case ICMP6_PARAMPROB_HEADER:
200 			ICMP6STAT_INC(icp6s_oparamprob_header);
201 			return;
202 		case ICMP6_PARAMPROB_NEXTHEADER:
203 			ICMP6STAT_INC(icp6s_oparamprob_nextheader);
204 			return;
205 		case ICMP6_PARAMPROB_OPTION:
206 			ICMP6STAT_INC(icp6s_oparamprob_option);
207 			return;
208 		}
209 		break;
210 	case ND_REDIRECT:
211 		ICMP6STAT_INC(icp6s_oredirect);
212 		return;
213 	}
214 	ICMP6STAT_INC(icp6s_ounknown);
215 }
216 
217 /*
218  * A wrapper function for icmp6_error() necessary when the erroneous packet
219  * may not contain enough scope zone information.
220  */
221 void
icmp6_error2(struct mbuf * m,int type,int code,int param,struct ifnet * ifp)222 icmp6_error2(struct mbuf *m, int type, int code, int param,
223     struct ifnet *ifp)
224 {
225 	struct ip6_hdr *ip6;
226 
227 	if (ifp == NULL)
228 		return;
229 
230 	if (m->m_len < sizeof(struct ip6_hdr)) {
231 		m = m_pullup(m, sizeof(struct ip6_hdr));
232 		if (m == NULL) {
233 			IP6STAT_INC(ip6s_exthdrtoolong);
234 			return;
235 		}
236 	}
237 	ip6 = mtod(m, struct ip6_hdr *);
238 
239 	if (in6_setscope(&ip6->ip6_src, ifp, NULL) != 0)
240 		return;
241 	if (in6_setscope(&ip6->ip6_dst, ifp, NULL) != 0)
242 		return;
243 
244 	icmp6_error(m, type, code, param);
245 }
246 
247 /*
248  * Generate an error packet of type error in response to bad IP6 packet.
249  */
250 void
icmp6_error(struct mbuf * m,int type,int code,int param)251 icmp6_error(struct mbuf *m, int type, int code, int param)
252 {
253 	struct ip6_hdr *oip6, *nip6;
254 	struct icmp6_hdr *icmp6;
255 	struct epoch_tracker et;
256 	u_int preplen;
257 	int off;
258 	int nxt;
259 
260 	ICMP6STAT_INC(icp6s_error);
261 
262 	/* count per-type-code statistics */
263 	icmp6_errcount(type, code);
264 
265 #ifdef M_DECRYPTED	/*not openbsd*/
266 	if (m->m_flags & M_DECRYPTED) {
267 		ICMP6STAT_INC(icp6s_canterror);
268 		goto freeit;
269 	}
270 #endif
271 
272 	if (m->m_len < sizeof(struct ip6_hdr)) {
273 		m = m_pullup(m, sizeof(struct ip6_hdr));
274 		if (m == NULL) {
275 			IP6STAT_INC(ip6s_exthdrtoolong);
276 			return;
277 		}
278 	}
279 	oip6 = mtod(m, struct ip6_hdr *);
280 
281 	/*
282 	 * If the destination address of the erroneous packet is a multicast
283 	 * address, or the packet was sent using link-layer multicast,
284 	 * we should basically suppress sending an error (RFC 2463, Section
285 	 * 2.4).
286 	 * We have two exceptions (the item e.2 in that section):
287 	 * - the Packet Too Big message can be sent for path MTU discovery.
288 	 * - the Parameter Problem Message that can be allowed an icmp6 error
289 	 *   in the option type field.  This check has been done in
290 	 *   ip6_unknown_opt(), so we can just check the type and code.
291 	 */
292 	if ((m->m_flags & (M_BCAST|M_MCAST) ||
293 	     IN6_IS_ADDR_MULTICAST(&oip6->ip6_dst)) &&
294 	    (type != ICMP6_PACKET_TOO_BIG &&
295 	     (type != ICMP6_PARAM_PROB ||
296 	      code != ICMP6_PARAMPROB_OPTION)))
297 		goto freeit;
298 
299 	/*
300 	 * RFC 2463, 2.4 (e.5): source address check.
301 	 * XXX: the case of anycast source?
302 	 */
303 	if (IN6_IS_ADDR_UNSPECIFIED(&oip6->ip6_src) ||
304 	    IN6_IS_ADDR_MULTICAST(&oip6->ip6_src))
305 		goto freeit;
306 
307 	/*
308 	 * If we are about to send ICMPv6 against ICMPv6 error/redirect,
309 	 * don't do it.
310 	 */
311 	nxt = -1;
312 	off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
313 	if (off >= 0 && nxt == IPPROTO_ICMPV6) {
314 		struct icmp6_hdr *icp;
315 
316 		if (m->m_len < off + sizeof(struct icmp6_hdr)) {
317 			m = m_pullup(m, off + sizeof(struct icmp6_hdr));
318 			if (m == NULL) {
319 				IP6STAT_INC(ip6s_exthdrtoolong);
320 				return;
321 			}
322 		}
323 		oip6 = mtod(m, struct ip6_hdr *);
324 		icp = (struct icmp6_hdr *)(mtod(m, caddr_t) + off);
325 
326 		if (icp->icmp6_type < ICMP6_ECHO_REQUEST ||
327 		    icp->icmp6_type == ND_REDIRECT) {
328 			/*
329 			 * ICMPv6 error
330 			 * Special case: for redirect (which is
331 			 * informational) we must not send icmp6 error.
332 			 */
333 			ICMP6STAT_INC(icp6s_canterror);
334 			goto freeit;
335 		} else {
336 			/* ICMPv6 informational - send the error */
337 		}
338 	} else {
339 		/* non-ICMPv6 - send the error */
340 	}
341 
342 	/* Finally, do rate limitation check. */
343 	if (icmp6_ratelimit(&oip6->ip6_src, type, code))
344 		goto freeit;
345 
346 	/*
347 	 * OK, ICMP6 can be generated.
348 	 */
349 
350 	if (m->m_pkthdr.len >= ICMPV6_PLD_MAXLEN)
351 		m_adj(m, ICMPV6_PLD_MAXLEN - m->m_pkthdr.len);
352 
353 	preplen = sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr);
354 	M_PREPEND(m, preplen, M_NOWAIT);	/* FIB is also copied over. */
355 	if (m == NULL) {
356 		nd6log((LOG_DEBUG, "ENOBUFS in icmp6_error %d\n", __LINE__));
357 		return;
358 	}
359 
360 	nip6 = mtod(m, struct ip6_hdr *);
361 	nip6->ip6_src  = oip6->ip6_src;
362 	nip6->ip6_dst  = oip6->ip6_dst;
363 
364 	in6_clearscope(&oip6->ip6_src);
365 	in6_clearscope(&oip6->ip6_dst);
366 
367 	icmp6 = (struct icmp6_hdr *)(nip6 + 1);
368 	icmp6->icmp6_type = type;
369 	icmp6->icmp6_code = code;
370 	icmp6->icmp6_pptr = htonl((u_int32_t)param);
371 
372 	ICMP6STAT_INC(icp6s_outhist[type]);
373 	NET_EPOCH_ENTER(et);
374 	icmp6_reflect(m, sizeof(struct ip6_hdr)); /* header order: IPv6 - ICMPv6 */
375 	NET_EPOCH_EXIT(et);
376 
377 	return;
378 
379   freeit:
380 	/*
381 	 * If we can't tell whether or not we can generate ICMP6, free it.
382 	 */
383 	m_freem(m);
384 }
385 
386 /*
387  * Process a received ICMP6 message.
388  */
389 int
icmp6_input(struct mbuf ** mp,int * offp,int proto)390 icmp6_input(struct mbuf **mp, int *offp, int proto)
391 {
392 	struct mbuf *m, *n;
393 	struct ifnet *ifp;
394 	struct ip6_hdr *ip6, *nip6;
395 	struct icmp6_hdr *icmp6, *nicmp6;
396 	char ip6bufs[INET6_ADDRSTRLEN], ip6bufd[INET6_ADDRSTRLEN];
397 	int code, error, icmp6len, ip6len, noff, off, sum;
398 
399 	NET_EPOCH_ASSERT();
400 
401 	m = *mp;
402 	off = *offp;
403 
404 	if (m->m_len < off + sizeof(struct icmp6_hdr)) {
405 		m = m_pullup(m, off + sizeof(struct icmp6_hdr));
406 		if (m == NULL) {
407 			IP6STAT_INC(ip6s_exthdrtoolong);
408 			*mp = m;
409 			return (IPPROTO_DONE);
410 		}
411 	}
412 
413 	/*
414 	 * Locate icmp6 structure in mbuf, and check
415 	 * that not corrupted and of at least minimum length
416 	 */
417 
418 	icmp6len = m->m_pkthdr.len - off;
419 	if (icmp6len < sizeof(struct icmp6_hdr)) {
420 		ICMP6STAT_INC(icp6s_tooshort);
421 		goto freeit;
422 	}
423 
424 	ip6 = mtod(m, struct ip6_hdr *);
425 	ifp = m->m_pkthdr.rcvif;
426 	/*
427 	 * Check multicast group membership.
428 	 * Note: SSM filters are not applied for ICMPv6 traffic.
429 	 */
430 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
431 		struct in6_multi	*inm;
432 
433 		inm = in6m_lookup(ifp, &ip6->ip6_dst);
434 		if (inm == NULL) {
435 			IP6STAT_INC(ip6s_notmember);
436 			in6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_discard);
437 			goto freeit;
438 		}
439 	}
440 
441 	/* Calculate the checksum. */
442 	icmp6 = (struct icmp6_hdr *)((caddr_t)ip6 + off);
443 	code = icmp6->icmp6_code;
444 	if ((sum = in6_cksum(m, IPPROTO_ICMPV6, off, icmp6len)) != 0) {
445 		nd6log((LOG_ERR,
446 		    "ICMP6 checksum error(%d|%x) %s\n",
447 		    icmp6->icmp6_type, sum,
448 		    ip6_sprintf(ip6bufs, &ip6->ip6_src)));
449 		ICMP6STAT_INC(icp6s_checksum);
450 		goto freeit;
451 	}
452 
453 	ICMP6STAT_INC(icp6s_inhist[icmp6->icmp6_type]);
454 	icmp6_ifstat_inc(ifp, ifs6_in_msg);
455 	if (icmp6->icmp6_type < ICMP6_INFOMSG_MASK)
456 		icmp6_ifstat_inc(ifp, ifs6_in_error);
457 
458 	ip6len = sizeof(struct ip6_hdr) + ntohs(ip6->ip6_plen);
459 	switch (icmp6->icmp6_type) {
460 	case ICMP6_DST_UNREACH:
461 		icmp6_ifstat_inc(ifp, ifs6_in_dstunreach);
462 		switch (code) {
463 		case ICMP6_DST_UNREACH_NOROUTE:
464 		case ICMP6_DST_UNREACH_ADDR:	/* PRC_HOSTDEAD is a DOS */
465 			code = PRC_UNREACH_NET;
466 			break;
467 		case ICMP6_DST_UNREACH_ADMIN:
468 			icmp6_ifstat_inc(ifp, ifs6_in_adminprohib);
469 			code = PRC_UNREACH_ADMIN_PROHIB;
470 			break;
471 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
472 			/* I mean "source address was incorrect." */
473 			code = PRC_PARAMPROB;
474 			break;
475 		case ICMP6_DST_UNREACH_NOPORT:
476 			code = PRC_UNREACH_PORT;
477 			break;
478 		default:
479 			goto badcode;
480 		}
481 		goto deliver;
482 		break;
483 
484 	case ICMP6_PACKET_TOO_BIG:
485 		icmp6_ifstat_inc(ifp, ifs6_in_pkttoobig);
486 
487 		/* validation is made in icmp6_mtudisc_update */
488 
489 		code = PRC_MSGSIZE;
490 
491 		/*
492 		 * Updating the path MTU will be done after examining
493 		 * intermediate extension headers.
494 		 */
495 		goto deliver;
496 		break;
497 
498 	case ICMP6_TIME_EXCEEDED:
499 		icmp6_ifstat_inc(ifp, ifs6_in_timeexceed);
500 		switch (code) {
501 		case ICMP6_TIME_EXCEED_TRANSIT:
502 			code = PRC_TIMXCEED_INTRANS;
503 			break;
504 		case ICMP6_TIME_EXCEED_REASSEMBLY:
505 			code = PRC_TIMXCEED_REASS;
506 			break;
507 		default:
508 			goto badcode;
509 		}
510 		goto deliver;
511 		break;
512 
513 	case ICMP6_PARAM_PROB:
514 		icmp6_ifstat_inc(ifp, ifs6_in_paramprob);
515 		switch (code) {
516 		case ICMP6_PARAMPROB_NEXTHEADER:
517 			code = PRC_UNREACH_PROTOCOL;
518 			break;
519 		case ICMP6_PARAMPROB_HEADER:
520 		case ICMP6_PARAMPROB_OPTION:
521 			code = PRC_PARAMPROB;
522 			break;
523 		default:
524 			goto badcode;
525 		}
526 		goto deliver;
527 		break;
528 
529 	case ICMP6_ECHO_REQUEST:
530 		icmp6_ifstat_inc(ifp, ifs6_in_echo);
531 		if (code != 0)
532 			goto badcode;
533 		if (icmp6_ratelimit(&ip6->ip6_src, ICMP6_ECHO_REPLY, 0))
534 			break;
535 		if ((n = m_copym(m, 0, M_COPYALL, M_NOWAIT)) == NULL) {
536 			/* Give up remote */
537 			break;
538 		}
539 		if (!M_WRITABLE(n)
540 		 || n->m_len < off + sizeof(struct icmp6_hdr)) {
541 			struct mbuf *n0 = n;
542 			int n0len;
543 
544 			CTASSERT(sizeof(*nip6) + sizeof(*nicmp6) <= MHLEN);
545 			n = m_gethdr(M_NOWAIT, n0->m_type);
546 			if (n == NULL) {
547 				/* Give up remote */
548 				m_freem(n0);
549 				break;
550 			}
551 
552 			m_move_pkthdr(n, n0);	/* FIB copied. */
553 			n0len = n0->m_pkthdr.len;	/* save for use below */
554 			/*
555 			 * Copy IPv6 and ICMPv6 only.
556 			 */
557 			nip6 = mtod(n, struct ip6_hdr *);
558 			bcopy(ip6, nip6, sizeof(struct ip6_hdr));
559 			nicmp6 = (struct icmp6_hdr *)(nip6 + 1);
560 			bcopy(icmp6, nicmp6, sizeof(struct icmp6_hdr));
561 			noff = sizeof(struct ip6_hdr);
562 			/* new mbuf contains only ipv6+icmpv6 headers */
563 			n->m_len = noff + sizeof(struct icmp6_hdr);
564 			/*
565 			 * Adjust mbuf.  ip6_plen will be adjusted in
566 			 * ip6_output().
567 			 */
568 			m_adj(n0, off + sizeof(struct icmp6_hdr));
569 			/* recalculate complete packet size */
570 			n->m_pkthdr.len = n0len + (noff - off);
571 			n->m_next = n0;
572 		} else {
573 			if (n->m_len < off + sizeof(*nicmp6)) {
574 				n = m_pullup(n, off + sizeof(*nicmp6));
575 				if (n == NULL) {
576 					IP6STAT_INC(ip6s_exthdrtoolong);
577 					break;
578 				}
579 			}
580 			nicmp6 = (struct icmp6_hdr *)(mtod(n, caddr_t) + off);
581 			noff = off;
582 		}
583 		if (n) {
584 			nicmp6->icmp6_type = ICMP6_ECHO_REPLY;
585 			nicmp6->icmp6_code = 0;
586 			ICMP6STAT_INC(icp6s_reflect);
587 			ICMP6STAT_INC(icp6s_outhist[ICMP6_ECHO_REPLY]);
588 			icmp6_reflect(n, noff);
589 		}
590 		break;
591 
592 	case ICMP6_ECHO_REPLY:
593 		icmp6_ifstat_inc(ifp, ifs6_in_echoreply);
594 		if (code != 0)
595 			goto badcode;
596 		break;
597 
598 	case MLD_LISTENER_QUERY:
599 	case MLD_LISTENER_REPORT:
600 	case MLD_LISTENER_DONE:
601 	case MLDV2_LISTENER_REPORT:
602 		/*
603 		 * Drop MLD traffic which is not link-local, has a hop limit
604 		 * of greater than 1 hop, or which does not have the
605 		 * IPv6 HBH Router Alert option.
606 		 * As IPv6 HBH options are stripped in ip6_input() we must
607 		 * check an mbuf header flag.
608 		 * XXX Should we also sanity check that these messages
609 		 * were directed to a link-local multicast prefix?
610 		 */
611 		if ((ip6->ip6_hlim != 1) || (m->m_flags & M_RTALERT_MLD) == 0)
612 			goto freeit;
613 		if (mld_input(&m, off, icmp6len) != 0) {
614 			*mp = NULL;
615 			return (IPPROTO_DONE);
616 		}
617 		/* m stays. */
618 		break;
619 
620 	case ICMP6_WRUREQUEST:	/* ICMP6_FQDN_QUERY */
621 	    {
622 		enum { WRU, FQDN } mode;
623 		struct prison *pr;
624 
625 		if (!V_icmp6_nodeinfo)
626 			break;
627 
628 		if (icmp6len == sizeof(struct icmp6_hdr) + 4)
629 			mode = WRU;
630 		else if (icmp6len >= sizeof(struct icmp6_nodeinfo))
631 			mode = FQDN;
632 		else
633 			goto badlen;
634 
635 		pr = NULL;
636 		sx_slock(&allprison_lock);
637 		TAILQ_FOREACH(pr, &allprison, pr_list)
638 			if (pr->pr_vnet == ifp->if_vnet)
639 				break;
640 		sx_sunlock(&allprison_lock);
641 		if (pr == NULL)
642 			pr = curthread->td_ucred->cr_prison;
643 		if (mode == FQDN) {
644 			if (m->m_len < off + sizeof(struct icmp6_nodeinfo)) {
645 				m = m_pullup(m, off +
646 				    sizeof(struct icmp6_nodeinfo));
647 				if (m == NULL) {
648 					IP6STAT_INC(ip6s_exthdrtoolong);
649 					*mp = m;
650 					return (IPPROTO_DONE);
651 				}
652 			}
653 			n = m_copym(m, 0, M_COPYALL, M_NOWAIT);
654 			if (n)
655 				n = ni6_input(n, off, pr);
656 			/* XXX meaningless if n == NULL */
657 			noff = sizeof(struct ip6_hdr);
658 		} else {
659 			u_char *p;
660 			int maxhlen, hlen;
661 
662 			/*
663 			 * XXX: this combination of flags is pointless,
664 			 * but should we keep this for compatibility?
665 			 */
666 			if ((V_icmp6_nodeinfo & (ICMP6_NODEINFO_FQDNOK |
667 			    ICMP6_NODEINFO_TMPADDROK)) !=
668 			    (ICMP6_NODEINFO_FQDNOK | ICMP6_NODEINFO_TMPADDROK))
669 				break;
670 
671 			if (code != 0)
672 				goto badcode;
673 
674 			CTASSERT(sizeof(*nip6) + sizeof(*nicmp6) + 4 <= MHLEN);
675 			n = m_gethdr(M_NOWAIT, m->m_type);
676 			if (n == NULL) {
677 				/* Give up remote */
678 				break;
679 			}
680 			if (!m_dup_pkthdr(n, m, M_NOWAIT)) {
681 				/*
682 				 * Previous code did a blind M_COPY_PKTHDR
683 				 * and said "just for rcvif".  If true, then
684 				 * we could tolerate the dup failing (due to
685 				 * the deep copy of the tag chain).  For now
686 				 * be conservative and just fail.
687 				 */
688 				m_free(n);
689 				n = NULL;
690 				break;
691 			}
692 			/*
693 			 * Copy IPv6 and ICMPv6 only.
694 			 */
695 			nip6 = mtod(n, struct ip6_hdr *);
696 			bcopy(ip6, nip6, sizeof(struct ip6_hdr));
697 			nicmp6 = (struct icmp6_hdr *)(nip6 + 1);
698 			bcopy(icmp6, nicmp6, sizeof(struct icmp6_hdr));
699 			p = (u_char *)(nicmp6 + 1);
700 			bzero(p, 4);
701 
702 			maxhlen = M_TRAILINGSPACE(n) -
703 			    (sizeof(*nip6) + sizeof(*nicmp6) + 4);
704 			mtx_lock(&pr->pr_mtx);
705 			hlen = strlen(pr->pr_hostname);
706 			if (maxhlen > hlen)
707 				maxhlen = hlen;
708 			/* meaningless TTL */
709 			bcopy(pr->pr_hostname, p + 4, maxhlen);
710 			mtx_unlock(&pr->pr_mtx);
711 			noff = sizeof(struct ip6_hdr);
712 			n->m_pkthdr.len = n->m_len = sizeof(struct ip6_hdr) +
713 				sizeof(struct icmp6_hdr) + 4 + maxhlen;
714 			nicmp6->icmp6_type = ICMP6_WRUREPLY;
715 			nicmp6->icmp6_code = 0;
716 		}
717 		if (n) {
718 			ICMP6STAT_INC(icp6s_reflect);
719 			ICMP6STAT_INC(icp6s_outhist[ICMP6_WRUREPLY]);
720 			icmp6_reflect(n, noff);
721 		}
722 		break;
723 	    }
724 
725 	case ICMP6_WRUREPLY:
726 		if (code != 0)
727 			goto badcode;
728 		break;
729 
730 	case ND_ROUTER_SOLICIT:
731 		icmp6_ifstat_inc(ifp, ifs6_in_routersolicit);
732 		if (code != 0)
733 			goto badcode;
734 		if (icmp6len < sizeof(struct nd_router_solicit))
735 			goto badlen;
736 		if (send_sendso_input_hook != NULL) {
737 			if (m->m_len < off + icmp6len) {
738 				m = m_pullup(m, off + icmp6len);
739 				if (m == NULL) {
740 					IP6STAT_INC(ip6s_exthdrtoolong);
741 					*mp = NULL;
742 					return (IPPROTO_DONE);
743 				}
744 			}
745 			error = send_sendso_input_hook(m, ifp, SND_IN, ip6len);
746 			if (error == 0) {
747 				m = NULL;
748 				goto freeit;
749 			}
750 		}
751 		n = m_copym(m, 0, M_COPYALL, M_NOWAIT);
752 		nd6_rs_input(m, off, icmp6len);
753 		m = n;
754 		if (m == NULL)
755 			goto freeit;
756 		break;
757 
758 	case ND_ROUTER_ADVERT:
759 		icmp6_ifstat_inc(ifp, ifs6_in_routeradvert);
760 		if (code != 0)
761 			goto badcode;
762 		if (icmp6len < sizeof(struct nd_router_advert))
763 			goto badlen;
764 		if (send_sendso_input_hook != NULL) {
765 			error = send_sendso_input_hook(m, ifp, SND_IN, ip6len);
766 			if (error == 0) {
767 				m = NULL;
768 				goto freeit;
769 			}
770 		}
771 		n = m_copym(m, 0, M_COPYALL, M_NOWAIT);
772 		nd6_ra_input(m, off, icmp6len);
773 		m = n;
774 		if (m == NULL)
775 			goto freeit;
776 		break;
777 
778 	case ND_NEIGHBOR_SOLICIT:
779 		icmp6_ifstat_inc(ifp, ifs6_in_neighborsolicit);
780 		if (code != 0)
781 			goto badcode;
782 		if (icmp6len < sizeof(struct nd_neighbor_solicit))
783 			goto badlen;
784 		if (send_sendso_input_hook != NULL) {
785 			error = send_sendso_input_hook(m, ifp, SND_IN, ip6len);
786 			if (error == 0) {
787 				m = NULL;
788 				goto freeit;
789 			}
790 		}
791 		n = m_copym(m, 0, M_COPYALL, M_NOWAIT);
792 		nd6_ns_input(m, off, icmp6len);
793 		m = n;
794 		if (m == NULL)
795 			goto freeit;
796 		break;
797 
798 	case ND_NEIGHBOR_ADVERT:
799 		icmp6_ifstat_inc(ifp, ifs6_in_neighboradvert);
800 		if (code != 0)
801 			goto badcode;
802 		if (icmp6len < sizeof(struct nd_neighbor_advert))
803 			goto badlen;
804 		if (send_sendso_input_hook != NULL) {
805 			error = send_sendso_input_hook(m, ifp, SND_IN, ip6len);
806 			if (error == 0) {
807 				m = NULL;
808 				goto freeit;
809 			}
810 		}
811 		n = m_copym(m, 0, M_COPYALL, M_NOWAIT);
812 		nd6_na_input(m, off, icmp6len);
813 		m = n;
814 		if (m == NULL)
815 			goto freeit;
816 		break;
817 
818 	case ND_REDIRECT:
819 		icmp6_ifstat_inc(ifp, ifs6_in_redirect);
820 		if (code != 0)
821 			goto badcode;
822 		if (icmp6len < sizeof(struct nd_redirect))
823 			goto badlen;
824 		if (send_sendso_input_hook != NULL) {
825 			error = send_sendso_input_hook(m, ifp, SND_IN, ip6len);
826 			if (error == 0) {
827 				m = NULL;
828 				goto freeit;
829 			}
830 		}
831 		n = m_copym(m, 0, M_COPYALL, M_NOWAIT);
832 		icmp6_redirect_input(m, off);
833 		m = n;
834 		if (m == NULL)
835 			goto freeit;
836 		break;
837 
838 	case ICMP6_ROUTER_RENUMBERING:
839 		if (code != ICMP6_ROUTER_RENUMBERING_COMMAND &&
840 		    code != ICMP6_ROUTER_RENUMBERING_RESULT)
841 			goto badcode;
842 		if (icmp6len < sizeof(struct icmp6_router_renum))
843 			goto badlen;
844 		break;
845 
846 	default:
847 		nd6log((LOG_DEBUG,
848 		    "icmp6_input: unknown type %d(src=%s, dst=%s, ifid=%d)\n",
849 		    icmp6->icmp6_type, ip6_sprintf(ip6bufs, &ip6->ip6_src),
850 		    ip6_sprintf(ip6bufd, &ip6->ip6_dst),
851 		    ifp ? ifp->if_index : 0));
852 		if (icmp6->icmp6_type < ICMP6_ECHO_REQUEST) {
853 			/* ICMPv6 error: MUST deliver it by spec... */
854 			code = PRC_NCMDS;
855 			/* deliver */
856 		} else {
857 			/* ICMPv6 informational: MUST not deliver */
858 			break;
859 		}
860 	deliver:
861 		if (icmp6_notify_error(&m, off, icmp6len, code) != 0) {
862 			/* In this case, m should've been freed. */
863 			*mp = NULL;
864 			return (IPPROTO_DONE);
865 		}
866 		break;
867 
868 	badcode:
869 		ICMP6STAT_INC(icp6s_badcode);
870 		break;
871 
872 	badlen:
873 		ICMP6STAT_INC(icp6s_badlen);
874 		break;
875 	}
876 
877 	/* deliver the packet to appropriate sockets */
878 	icmp6_rip6_input(&m, *offp);
879 
880 	*mp = m;
881 	return (IPPROTO_DONE);
882 
883  freeit:
884 	m_freem(m);
885 	*mp = NULL;
886 	return (IPPROTO_DONE);
887 }
888 
889 static int
icmp6_notify_error(struct mbuf ** mp,int off,int icmp6len,int code)890 icmp6_notify_error(struct mbuf **mp, int off, int icmp6len, int code)
891 {
892 	struct mbuf *m;
893 	struct icmp6_hdr *icmp6;
894 	struct ip6_hdr *eip6;
895 	u_int32_t notifymtu;
896 	struct sockaddr_in6 icmp6src, icmp6dst;
897 
898 	m = *mp;
899 
900 	if (icmp6len < sizeof(struct icmp6_hdr) + sizeof(struct ip6_hdr)) {
901 		ICMP6STAT_INC(icp6s_tooshort);
902 		goto freeit;
903 	}
904 
905 	if (m->m_len < off + sizeof(*icmp6) + sizeof(struct ip6_hdr)) {
906 		m = m_pullup(m, off + sizeof(*icmp6) + sizeof(struct ip6_hdr));
907 		if (m == NULL) {
908 			IP6STAT_INC(ip6s_exthdrtoolong);
909 			*mp = m;
910 			return (-1);
911 		}
912 	}
913 	icmp6 = (struct icmp6_hdr *)(mtod(m, caddr_t) + off);
914 	eip6 = (struct ip6_hdr *)(icmp6 + 1);
915 	bzero(&icmp6dst, sizeof(icmp6dst));
916 
917 	/* Detect the upper level protocol */
918 	{
919 		void (*ctlfunc)(int, struct sockaddr *, void *);
920 		u_int8_t nxt = eip6->ip6_nxt;
921 		int eoff = off + sizeof(struct icmp6_hdr) +
922 		    sizeof(struct ip6_hdr);
923 		struct ip6ctlparam ip6cp;
924 		int icmp6type = icmp6->icmp6_type;
925 		struct ip6_frag *fh;
926 		struct ip6_rthdr *rth;
927 		struct ip6_rthdr0 *rth0;
928 		int rthlen;
929 
930 		while (1) { /* XXX: should avoid infinite loop explicitly? */
931 			struct ip6_ext *eh;
932 
933 			switch (nxt) {
934 			case IPPROTO_HOPOPTS:
935 			case IPPROTO_DSTOPTS:
936 			case IPPROTO_AH:
937 				if (m->m_len < eoff + sizeof(struct ip6_ext)) {
938 					m = m_pullup(m, eoff +
939 					    sizeof(struct ip6_ext));
940 					if (m == NULL) {
941 						IP6STAT_INC(ip6s_exthdrtoolong);
942 						*mp = m;
943 						return (-1);
944 					}
945 				}
946 				eh = (struct ip6_ext *)
947 				    (mtod(m, caddr_t) + eoff);
948 				if (nxt == IPPROTO_AH)
949 					eoff += (eh->ip6e_len + 2) << 2;
950 				else
951 					eoff += (eh->ip6e_len + 1) << 3;
952 				nxt = eh->ip6e_nxt;
953 				break;
954 			case IPPROTO_ROUTING:
955 				/*
956 				 * When the erroneous packet contains a
957 				 * routing header, we should examine the
958 				 * header to determine the final destination.
959 				 * Otherwise, we can't properly update
960 				 * information that depends on the final
961 				 * destination (e.g. path MTU).
962 				 */
963 				if (m->m_len < eoff + sizeof(*rth)) {
964 					m = m_pullup(m, eoff + sizeof(*rth));
965 					if (m == NULL) {
966 						IP6STAT_INC(ip6s_exthdrtoolong);
967 						*mp = m;
968 						return (-1);
969 					}
970 				}
971 				rth = (struct ip6_rthdr *)
972 				    (mtod(m, caddr_t) + eoff);
973 				rthlen = (rth->ip6r_len + 1) << 3;
974 				/*
975 				 * XXX: currently there is no
976 				 * officially defined type other
977 				 * than type-0.
978 				 * Note that if the segment left field
979 				 * is 0, all intermediate hops must
980 				 * have been passed.
981 				 */
982 				if (rth->ip6r_segleft &&
983 				    rth->ip6r_type == IPV6_RTHDR_TYPE_0) {
984 					int hops;
985 
986 					if (m->m_len < eoff + rthlen) {
987 						m = m_pullup(m, eoff + rthlen);
988 						if (m == NULL) {
989 							IP6STAT_INC(
990 							    ip6s_exthdrtoolong);
991 							*mp = m;
992 							return (-1);
993 						}
994 					}
995 					rth0 = (struct ip6_rthdr0 *)
996 					    (mtod(m, caddr_t) + eoff);
997 
998 					/* just ignore a bogus header */
999 					if ((rth0->ip6r0_len % 2) == 0 &&
1000 					    (hops = rth0->ip6r0_len/2))
1001 						icmp6dst.sin6_addr = *((struct in6_addr *)(rth0 + 1) + (hops - 1));
1002 				}
1003 				eoff += rthlen;
1004 				nxt = rth->ip6r_nxt;
1005 				break;
1006 			case IPPROTO_FRAGMENT:
1007 				if (m->m_len < eoff + sizeof(struct ip6_frag)) {
1008 					m = m_pullup(m, eoff +
1009 					    sizeof(struct ip6_frag));
1010 					if (m == NULL) {
1011 						IP6STAT_INC(ip6s_exthdrtoolong);
1012 						*mp = m;
1013 						return (-1);
1014 					}
1015 				}
1016 				fh = (struct ip6_frag *)(mtod(m, caddr_t) +
1017 				    eoff);
1018 				/*
1019 				 * Data after a fragment header is meaningless
1020 				 * unless it is the first fragment, but
1021 				 * we'll go to the notify label for path MTU
1022 				 * discovery.
1023 				 */
1024 				if (fh->ip6f_offlg & IP6F_OFF_MASK)
1025 					goto notify;
1026 
1027 				eoff += sizeof(struct ip6_frag);
1028 				nxt = fh->ip6f_nxt;
1029 				break;
1030 			default:
1031 				/*
1032 				 * This case includes ESP and the No Next
1033 				 * Header.  In such cases going to the notify
1034 				 * label does not have any meaning
1035 				 * (i.e. ctlfunc will be NULL), but we go
1036 				 * anyway since we might have to update
1037 				 * path MTU information.
1038 				 */
1039 				goto notify;
1040 			}
1041 		}
1042 	  notify:
1043 		icmp6 = (struct icmp6_hdr *)(mtod(m, caddr_t) + off);
1044 
1045 		/*
1046 		 * retrieve parameters from the inner IPv6 header, and convert
1047 		 * them into sockaddr structures.
1048 		 * XXX: there is no guarantee that the source or destination
1049 		 * addresses of the inner packet are in the same scope as
1050 		 * the addresses of the icmp packet.  But there is no other
1051 		 * way to determine the zone.
1052 		 */
1053 		eip6 = (struct ip6_hdr *)(icmp6 + 1);
1054 
1055 		icmp6dst.sin6_len = sizeof(struct sockaddr_in6);
1056 		icmp6dst.sin6_family = AF_INET6;
1057 		if (IN6_IS_ADDR_UNSPECIFIED(&icmp6dst.sin6_addr))
1058 			icmp6dst.sin6_addr = eip6->ip6_dst;
1059 		if (in6_setscope(&icmp6dst.sin6_addr, m->m_pkthdr.rcvif, NULL))
1060 			goto freeit;
1061 		bzero(&icmp6src, sizeof(icmp6src));
1062 		icmp6src.sin6_len = sizeof(struct sockaddr_in6);
1063 		icmp6src.sin6_family = AF_INET6;
1064 		icmp6src.sin6_addr = eip6->ip6_src;
1065 		if (in6_setscope(&icmp6src.sin6_addr, m->m_pkthdr.rcvif, NULL))
1066 			goto freeit;
1067 		icmp6src.sin6_flowinfo =
1068 		    (eip6->ip6_flow & IPV6_FLOWLABEL_MASK);
1069 
1070 		ip6cp.ip6c_m = m;
1071 		ip6cp.ip6c_icmp6 = icmp6;
1072 		ip6cp.ip6c_ip6 = (struct ip6_hdr *)(icmp6 + 1);
1073 		ip6cp.ip6c_off = eoff;
1074 		ip6cp.ip6c_finaldst = &icmp6dst.sin6_addr;
1075 		ip6cp.ip6c_src = &icmp6src;
1076 		ip6cp.ip6c_nxt = nxt;
1077 
1078 		if (icmp6type == ICMP6_PACKET_TOO_BIG) {
1079 			notifymtu = ntohl(icmp6->icmp6_mtu);
1080 			ip6cp.ip6c_cmdarg = (void *)&notifymtu;
1081 			icmp6_mtudisc_update(&ip6cp, 1);	/*XXX*/
1082 		}
1083 
1084 		ctlfunc = (void (*)(int, struct sockaddr *, void *))
1085 		    (inet6sw[ip6_protox[nxt]].pr_ctlinput);
1086 		if (ctlfunc) {
1087 			(void) (*ctlfunc)(code, (struct sockaddr *)&icmp6dst,
1088 			    &ip6cp);
1089 		}
1090 	}
1091 	*mp = m;
1092 	return (0);
1093 
1094   freeit:
1095 	m_freem(m);
1096 	*mp = NULL;
1097 	return (-1);
1098 }
1099 
1100 void
icmp6_mtudisc_update(struct ip6ctlparam * ip6cp,int validated)1101 icmp6_mtudisc_update(struct ip6ctlparam *ip6cp, int validated)
1102 {
1103 	struct in6_addr *dst = ip6cp->ip6c_finaldst;
1104 	struct icmp6_hdr *icmp6 = ip6cp->ip6c_icmp6;
1105 	struct mbuf *m = ip6cp->ip6c_m;	/* will be necessary for scope issue */
1106 	u_int mtu = ntohl(icmp6->icmp6_mtu);
1107 	struct in_conninfo inc;
1108 	uint32_t max_mtu;
1109 
1110 #if 0
1111 	/*
1112 	 * RFC2460 section 5, last paragraph.
1113 	 * even though minimum link MTU for IPv6 is IPV6_MMTU,
1114 	 * we may see ICMPv6 too big with mtu < IPV6_MMTU
1115 	 * due to packet translator in the middle.
1116 	 * see ip6_output() and ip6_getpmtu() "alwaysfrag" case for
1117 	 * special handling.
1118 	 */
1119 	if (mtu < IPV6_MMTU)
1120 		return;
1121 #endif
1122 
1123 	/*
1124 	 * we reject ICMPv6 too big with abnormally small value.
1125 	 * XXX what is the good definition of "abnormally small"?
1126 	 */
1127 	if (mtu < sizeof(struct ip6_hdr) + sizeof(struct ip6_frag) + 8)
1128 		return;
1129 
1130 	if (!validated)
1131 		return;
1132 
1133 	/*
1134 	 * In case the suggested mtu is less than IPV6_MMTU, we
1135 	 * only need to remember that it was for above mentioned
1136 	 * "alwaysfrag" case.
1137 	 * Try to be as close to the spec as possible.
1138 	 */
1139 	if (mtu < IPV6_MMTU)
1140 		mtu = IPV6_MMTU - 8;
1141 
1142 	bzero(&inc, sizeof(inc));
1143 	inc.inc_fibnum = M_GETFIB(m);
1144 	inc.inc_flags |= INC_ISIPV6;
1145 	inc.inc6_faddr = *dst;
1146 	if (in6_setscope(&inc.inc6_faddr, m->m_pkthdr.rcvif, NULL))
1147 		return;
1148 
1149 	max_mtu = tcp_hc_getmtu(&inc);
1150 	if (max_mtu == 0)
1151 		max_mtu = tcp_maxmtu6(&inc, NULL);
1152 
1153 	if (mtu < max_mtu) {
1154 		tcp_hc_updatemtu(&inc, mtu);
1155 		ICMP6STAT_INC(icp6s_pmtuchg);
1156 	}
1157 }
1158 
1159 /*
1160  * Process a Node Information Query packet, based on
1161  * draft-ietf-ipngwg-icmp-name-lookups-07.
1162  *
1163  * Spec incompatibilities:
1164  * - IPv6 Subject address handling
1165  * - IPv4 Subject address handling support missing
1166  * - Proxy reply (answer even if it's not for me)
1167  * - joins NI group address at in6_ifattach() time only, does not cope
1168  *   with hostname changes by sethostname(3)
1169  */
1170 static struct mbuf *
ni6_input(struct mbuf * m,int off,struct prison * pr)1171 ni6_input(struct mbuf *m, int off, struct prison *pr)
1172 {
1173 	struct icmp6_nodeinfo *ni6, *nni6;
1174 	struct mbuf *n = NULL;
1175 	u_int16_t qtype;
1176 	int subjlen;
1177 	int replylen = sizeof(struct ip6_hdr) + sizeof(struct icmp6_nodeinfo);
1178 	struct ni_reply_fqdn *fqdn;
1179 	int addrs;		/* for NI_QTYPE_NODEADDR */
1180 	struct ifnet *ifp = NULL; /* for NI_QTYPE_NODEADDR */
1181 	struct in6_addr in6_subj; /* subject address */
1182 	struct ip6_hdr *ip6;
1183 	int oldfqdn = 0;	/* if 1, return pascal string (03 draft) */
1184 	char *subj = NULL;
1185 	struct in6_ifaddr *ia6 = NULL;
1186 
1187 	ip6 = mtod(m, struct ip6_hdr *);
1188 	ni6 = (struct icmp6_nodeinfo *)(mtod(m, caddr_t) + off);
1189 
1190 	/*
1191 	 * Validate IPv6 source address.
1192 	 * The default configuration MUST be to refuse answering queries from
1193 	 * global-scope addresses according to RFC4602.
1194 	 * Notes:
1195 	 *  - it's not very clear what "refuse" means; this implementation
1196 	 *    simply drops it.
1197 	 *  - it's not very easy to identify global-scope (unicast) addresses
1198 	 *    since there are many prefixes for them.  It should be safer
1199 	 *    and in practice sufficient to check "all" but loopback and
1200 	 *    link-local (note that site-local unicast was deprecated and
1201 	 *    ULA is defined as global scope-wise)
1202 	 */
1203 	if ((V_icmp6_nodeinfo & ICMP6_NODEINFO_GLOBALOK) == 0 &&
1204 	    !IN6_IS_ADDR_LOOPBACK(&ip6->ip6_src) &&
1205 	    !IN6_IS_ADDR_LINKLOCAL(&ip6->ip6_src))
1206 		goto bad;
1207 
1208 	/*
1209 	 * Validate IPv6 destination address.
1210 	 *
1211 	 * The Responder must discard the Query without further processing
1212 	 * unless it is one of the Responder's unicast or anycast addresses, or
1213 	 * a link-local scope multicast address which the Responder has joined.
1214 	 * [RFC4602, Section 5.]
1215 	 */
1216 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
1217 		if (!IN6_IS_ADDR_MC_LINKLOCAL(&ip6->ip6_dst))
1218 			goto bad;
1219 		/* else it's a link-local multicast, fine */
1220 	} else {		/* unicast or anycast */
1221 		ia6 = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */, false);
1222 		if (ia6 == NULL)
1223 			goto bad; /* XXX impossible */
1224 
1225 		if ((ia6->ia6_flags & IN6_IFF_TEMPORARY) &&
1226 		    !(V_icmp6_nodeinfo & ICMP6_NODEINFO_TMPADDROK)) {
1227 			nd6log((LOG_DEBUG, "ni6_input: ignore node info to "
1228 				"a temporary address in %s:%d",
1229 			       __FILE__, __LINE__));
1230 			goto bad;
1231 		}
1232 	}
1233 
1234 	/* validate query Subject field. */
1235 	qtype = ntohs(ni6->ni_qtype);
1236 	subjlen = m->m_pkthdr.len - off - sizeof(struct icmp6_nodeinfo);
1237 	switch (qtype) {
1238 	case NI_QTYPE_NOOP:
1239 	case NI_QTYPE_SUPTYPES:
1240 		/* 07 draft */
1241 		if (ni6->ni_code == ICMP6_NI_SUBJ_FQDN && subjlen == 0)
1242 			break;
1243 		/* FALLTHROUGH */
1244 	case NI_QTYPE_FQDN:
1245 	case NI_QTYPE_NODEADDR:
1246 	case NI_QTYPE_IPV4ADDR:
1247 		switch (ni6->ni_code) {
1248 		case ICMP6_NI_SUBJ_IPV6:
1249 #if ICMP6_NI_SUBJ_IPV6 != 0
1250 		case 0:
1251 #endif
1252 			/*
1253 			 * backward compatibility - try to accept 03 draft
1254 			 * format, where no Subject is present.
1255 			 */
1256 			if (qtype == NI_QTYPE_FQDN && ni6->ni_code == 0 &&
1257 			    subjlen == 0) {
1258 				oldfqdn++;
1259 				break;
1260 			}
1261 #if ICMP6_NI_SUBJ_IPV6 != 0
1262 			if (ni6->ni_code != ICMP6_NI_SUBJ_IPV6)
1263 				goto bad;
1264 #endif
1265 
1266 			if (subjlen != sizeof(struct in6_addr))
1267 				goto bad;
1268 
1269 			/*
1270 			 * Validate Subject address.
1271 			 *
1272 			 * Not sure what exactly "address belongs to the node"
1273 			 * means in the spec, is it just unicast, or what?
1274 			 *
1275 			 * At this moment we consider Subject address as
1276 			 * "belong to the node" if the Subject address equals
1277 			 * to the IPv6 destination address; validation for
1278 			 * IPv6 destination address should have done enough
1279 			 * check for us.
1280 			 *
1281 			 * We do not do proxy at this moment.
1282 			 */
1283 			m_copydata(m, off + sizeof(struct icmp6_nodeinfo),
1284 			    subjlen, (caddr_t)&in6_subj);
1285 			if (in6_setscope(&in6_subj, m->m_pkthdr.rcvif, NULL))
1286 				goto bad;
1287 
1288 			subj = (char *)&in6_subj;
1289 			if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &in6_subj))
1290 				break;
1291 
1292 			/*
1293 			 * XXX if we are to allow other cases, we should really
1294 			 * be careful about scope here.
1295 			 * basically, we should disallow queries toward IPv6
1296 			 * destination X with subject Y,
1297 			 * if scope(X) > scope(Y).
1298 			 * if we allow scope(X) > scope(Y), it will result in
1299 			 * information leakage across scope boundary.
1300 			 */
1301 			goto bad;
1302 
1303 		case ICMP6_NI_SUBJ_FQDN:
1304 			/*
1305 			 * Validate Subject name with gethostname(3).
1306 			 *
1307 			 * The behavior may need some debate, since:
1308 			 * - we are not sure if the node has FQDN as
1309 			 *   hostname (returned by gethostname(3)).
1310 			 * - the code does wildcard match for truncated names.
1311 			 *   however, we are not sure if we want to perform
1312 			 *   wildcard match, if gethostname(3) side has
1313 			 *   truncated hostname.
1314 			 */
1315 			mtx_lock(&pr->pr_mtx);
1316 			n = ni6_nametodns(pr->pr_hostname,
1317 			    strlen(pr->pr_hostname), 0);
1318 			mtx_unlock(&pr->pr_mtx);
1319 			if (!n || n->m_next || n->m_len == 0)
1320 				goto bad;
1321 			if (m->m_len < off + sizeof(struct icmp6_nodeinfo) +
1322 			    subjlen) {
1323 				m = m_pullup(m, off +
1324 				    sizeof(struct icmp6_nodeinfo) + subjlen);
1325 				if (m == NULL) {
1326 					IP6STAT_INC(ip6s_exthdrtoolong);
1327 					goto bad;
1328 				}
1329 			}
1330 			/* ip6 possibly invalid but not used after. */
1331 			ni6 = (struct icmp6_nodeinfo *)(mtod(m, caddr_t) + off);
1332 			subj = (char *)(mtod(m, caddr_t) + off +
1333 			    sizeof(struct icmp6_nodeinfo));
1334 			if (!ni6_dnsmatch(subj, subjlen, mtod(n, const char *),
1335 			    n->m_len)) {
1336 				goto bad;
1337 			}
1338 			m_freem(n);
1339 			n = NULL;
1340 			break;
1341 
1342 		case ICMP6_NI_SUBJ_IPV4:	/* XXX: to be implemented? */
1343 		default:
1344 			goto bad;
1345 		}
1346 		break;
1347 	}
1348 
1349 	/* refuse based on configuration.  XXX ICMP6_NI_REFUSED? */
1350 	switch (qtype) {
1351 	case NI_QTYPE_FQDN:
1352 		if ((V_icmp6_nodeinfo & ICMP6_NODEINFO_FQDNOK) == 0)
1353 			goto bad;
1354 		break;
1355 	case NI_QTYPE_NODEADDR:
1356 	case NI_QTYPE_IPV4ADDR:
1357 		if ((V_icmp6_nodeinfo & ICMP6_NODEINFO_NODEADDROK) == 0)
1358 			goto bad;
1359 		break;
1360 	}
1361 
1362 	/* guess reply length */
1363 	switch (qtype) {
1364 	case NI_QTYPE_NOOP:
1365 		break;		/* no reply data */
1366 	case NI_QTYPE_SUPTYPES:
1367 		replylen += sizeof(u_int32_t);
1368 		break;
1369 	case NI_QTYPE_FQDN:
1370 		/* XXX will append an mbuf */
1371 		replylen += offsetof(struct ni_reply_fqdn, ni_fqdn_namelen);
1372 		break;
1373 	case NI_QTYPE_NODEADDR:
1374 		addrs = ni6_addrs(ni6, m, &ifp, (struct in6_addr *)subj);
1375 		if ((replylen += addrs * (sizeof(struct in6_addr) +
1376 		    sizeof(u_int32_t))) > MCLBYTES)
1377 			replylen = MCLBYTES; /* XXX: will truncate pkt later */
1378 		break;
1379 	case NI_QTYPE_IPV4ADDR:
1380 		/* unsupported - should respond with unknown Qtype? */
1381 		break;
1382 	default:
1383 		/*
1384 		 * XXX: We must return a reply with the ICMP6 code
1385 		 * `unknown Qtype' in this case.  However we regard the case
1386 		 * as an FQDN query for backward compatibility.
1387 		 * Older versions set a random value to this field,
1388 		 * so it rarely varies in the defined qtypes.
1389 		 * But the mechanism is not reliable...
1390 		 * maybe we should obsolete older versions.
1391 		 */
1392 		qtype = NI_QTYPE_FQDN;
1393 		/* XXX will append an mbuf */
1394 		replylen += offsetof(struct ni_reply_fqdn, ni_fqdn_namelen);
1395 		oldfqdn++;
1396 		break;
1397 	}
1398 
1399 	/* Allocate an mbuf to reply. */
1400 	if (replylen > MCLBYTES) {
1401 		/*
1402 		 * XXX: should we try to allocate more? But MCLBYTES
1403 		 * is probably much larger than IPV6_MMTU...
1404 		 */
1405 		goto bad;
1406 	}
1407 	if (replylen > MHLEN)
1408 		n = m_getcl(M_NOWAIT, m->m_type, M_PKTHDR);
1409 	else
1410 		n = m_gethdr(M_NOWAIT, m->m_type);
1411 	if (n == NULL) {
1412 		m_freem(m);
1413 		return (NULL);
1414 	}
1415 	m_move_pkthdr(n, m); /* just for recvif and FIB */
1416 	n->m_pkthdr.len = n->m_len = replylen;
1417 
1418 	/* copy mbuf header and IPv6 + Node Information base headers */
1419 	bcopy(mtod(m, caddr_t), mtod(n, caddr_t), sizeof(struct ip6_hdr));
1420 	nni6 = (struct icmp6_nodeinfo *)(mtod(n, struct ip6_hdr *) + 1);
1421 	bcopy((caddr_t)ni6, (caddr_t)nni6, sizeof(struct icmp6_nodeinfo));
1422 
1423 	/* qtype dependent procedure */
1424 	switch (qtype) {
1425 	case NI_QTYPE_NOOP:
1426 		nni6->ni_code = ICMP6_NI_SUCCESS;
1427 		nni6->ni_flags = 0;
1428 		break;
1429 	case NI_QTYPE_SUPTYPES:
1430 	{
1431 		u_int32_t v;
1432 		nni6->ni_code = ICMP6_NI_SUCCESS;
1433 		nni6->ni_flags = htons(0x0000);	/* raw bitmap */
1434 		/* supports NOOP, SUPTYPES, FQDN, and NODEADDR */
1435 		v = (u_int32_t)htonl(0x0000000f);
1436 		bcopy(&v, nni6 + 1, sizeof(u_int32_t));
1437 		break;
1438 	}
1439 	case NI_QTYPE_FQDN:
1440 		nni6->ni_code = ICMP6_NI_SUCCESS;
1441 		fqdn = (struct ni_reply_fqdn *)(mtod(n, caddr_t) +
1442 		    sizeof(struct ip6_hdr) + sizeof(struct icmp6_nodeinfo));
1443 		nni6->ni_flags = 0; /* XXX: meaningless TTL */
1444 		fqdn->ni_fqdn_ttl = 0;	/* ditto. */
1445 		/*
1446 		 * XXX do we really have FQDN in hostname?
1447 		 */
1448 		mtx_lock(&pr->pr_mtx);
1449 		n->m_next = ni6_nametodns(pr->pr_hostname,
1450 		    strlen(pr->pr_hostname), oldfqdn);
1451 		mtx_unlock(&pr->pr_mtx);
1452 		if (n->m_next == NULL)
1453 			goto bad;
1454 		/* XXX we assume that n->m_next is not a chain */
1455 		if (n->m_next->m_next != NULL)
1456 			goto bad;
1457 		n->m_pkthdr.len += n->m_next->m_len;
1458 		break;
1459 	case NI_QTYPE_NODEADDR:
1460 	{
1461 		int lenlim, copied;
1462 
1463 		nni6->ni_code = ICMP6_NI_SUCCESS;
1464 		n->m_pkthdr.len = n->m_len =
1465 		    sizeof(struct ip6_hdr) + sizeof(struct icmp6_nodeinfo);
1466 		lenlim = M_TRAILINGSPACE(n);
1467 		copied = ni6_store_addrs(ni6, nni6, ifp, lenlim);
1468 		/* XXX: reset mbuf length */
1469 		n->m_pkthdr.len = n->m_len = sizeof(struct ip6_hdr) +
1470 		    sizeof(struct icmp6_nodeinfo) + copied;
1471 		break;
1472 	}
1473 	default:
1474 		break;		/* XXX impossible! */
1475 	}
1476 
1477 	nni6->ni_type = ICMP6_NI_REPLY;
1478 	m_freem(m);
1479 	return (n);
1480 
1481   bad:
1482 	m_freem(m);
1483 	if (n)
1484 		m_freem(n);
1485 	return (NULL);
1486 }
1487 
1488 /*
1489  * make a mbuf with DNS-encoded string.  no compression support.
1490  *
1491  * XXX names with less than 2 dots (like "foo" or "foo.section") will be
1492  * treated as truncated name (two \0 at the end).  this is a wild guess.
1493  *
1494  * old - return pascal string if non-zero
1495  */
1496 static struct mbuf *
ni6_nametodns(const char * name,int namelen,int old)1497 ni6_nametodns(const char *name, int namelen, int old)
1498 {
1499 	struct mbuf *m;
1500 	char *cp, *ep;
1501 	const char *p, *q;
1502 	int i, len, nterm;
1503 
1504 	if (old)
1505 		len = namelen + 1;
1506 	else
1507 		len = MCLBYTES;
1508 
1509 	/* Because MAXHOSTNAMELEN is usually 256, we use cluster mbuf. */
1510 	if (len > MLEN)
1511 		m = m_getcl(M_NOWAIT, MT_DATA, 0);
1512 	else
1513 		m = m_get(M_NOWAIT, MT_DATA);
1514 	if (m == NULL)
1515 		goto fail;
1516 
1517 	if (old) {
1518 		m->m_len = len;
1519 		*mtod(m, char *) = namelen;
1520 		bcopy(name, mtod(m, char *) + 1, namelen);
1521 		return m;
1522 	} else {
1523 		m->m_len = 0;
1524 		cp = mtod(m, char *);
1525 		ep = mtod(m, char *) + M_TRAILINGSPACE(m);
1526 
1527 		/* if not certain about my name, return empty buffer */
1528 		if (namelen == 0)
1529 			return m;
1530 
1531 		/*
1532 		 * guess if it looks like shortened hostname, or FQDN.
1533 		 * shortened hostname needs two trailing "\0".
1534 		 */
1535 		i = 0;
1536 		for (p = name; p < name + namelen; p++) {
1537 			if (*p && *p == '.')
1538 				i++;
1539 		}
1540 		if (i < 2)
1541 			nterm = 2;
1542 		else
1543 			nterm = 1;
1544 
1545 		p = name;
1546 		while (cp < ep && p < name + namelen) {
1547 			i = 0;
1548 			for (q = p; q < name + namelen && *q && *q != '.'; q++)
1549 				i++;
1550 			/* result does not fit into mbuf */
1551 			if (cp + i + 1 >= ep)
1552 				goto fail;
1553 			/*
1554 			 * DNS label length restriction, RFC1035 page 8.
1555 			 * "i == 0" case is included here to avoid returning
1556 			 * 0-length label on "foo..bar".
1557 			 */
1558 			if (i <= 0 || i >= 64)
1559 				goto fail;
1560 			*cp++ = i;
1561 			bcopy(p, cp, i);
1562 			cp += i;
1563 			p = q;
1564 			if (p < name + namelen && *p == '.')
1565 				p++;
1566 		}
1567 		/* termination */
1568 		if (cp + nterm >= ep)
1569 			goto fail;
1570 		while (nterm-- > 0)
1571 			*cp++ = '\0';
1572 		m->m_len = cp - mtod(m, char *);
1573 		return m;
1574 	}
1575 
1576 	panic("should not reach here");
1577 	/* NOTREACHED */
1578 
1579  fail:
1580 	if (m)
1581 		m_freem(m);
1582 	return NULL;
1583 }
1584 
1585 /*
1586  * check if two DNS-encoded string matches.  takes care of truncated
1587  * form (with \0\0 at the end).  no compression support.
1588  * XXX upper/lowercase match (see RFC2065)
1589  */
1590 static int
ni6_dnsmatch(const char * a,int alen,const char * b,int blen)1591 ni6_dnsmatch(const char *a, int alen, const char *b, int blen)
1592 {
1593 	const char *a0, *b0;
1594 	int l;
1595 
1596 	/* simplest case - need validation? */
1597 	if (alen == blen && bcmp(a, b, alen) == 0)
1598 		return 1;
1599 
1600 	a0 = a;
1601 	b0 = b;
1602 
1603 	/* termination is mandatory */
1604 	if (alen < 2 || blen < 2)
1605 		return 0;
1606 	if (a0[alen - 1] != '\0' || b0[blen - 1] != '\0')
1607 		return 0;
1608 	alen--;
1609 	blen--;
1610 
1611 	while (a - a0 < alen && b - b0 < blen) {
1612 		if (a - a0 + 1 > alen || b - b0 + 1 > blen)
1613 			return 0;
1614 
1615 		if ((signed char)a[0] < 0 || (signed char)b[0] < 0)
1616 			return 0;
1617 		/* we don't support compression yet */
1618 		if (a[0] >= 64 || b[0] >= 64)
1619 			return 0;
1620 
1621 		/* truncated case */
1622 		if (a[0] == 0 && a - a0 == alen - 1)
1623 			return 1;
1624 		if (b[0] == 0 && b - b0 == blen - 1)
1625 			return 1;
1626 		if (a[0] == 0 || b[0] == 0)
1627 			return 0;
1628 
1629 		if (a[0] != b[0])
1630 			return 0;
1631 		l = a[0];
1632 		if (a - a0 + 1 + l > alen || b - b0 + 1 + l > blen)
1633 			return 0;
1634 		if (bcmp(a + 1, b + 1, l) != 0)
1635 			return 0;
1636 
1637 		a += 1 + l;
1638 		b += 1 + l;
1639 	}
1640 
1641 	if (a - a0 == alen && b - b0 == blen)
1642 		return 1;
1643 	else
1644 		return 0;
1645 }
1646 
1647 /*
1648  * calculate the number of addresses to be returned in the node info reply.
1649  */
1650 static int
ni6_addrs(struct icmp6_nodeinfo * ni6,struct mbuf * m,struct ifnet ** ifpp,struct in6_addr * subj)1651 ni6_addrs(struct icmp6_nodeinfo *ni6, struct mbuf *m, struct ifnet **ifpp,
1652     struct in6_addr *subj)
1653 {
1654 	struct ifnet *ifp;
1655 	struct in6_ifaddr *ifa6;
1656 	struct ifaddr *ifa;
1657 	int addrs = 0, addrsofif, iffound = 0;
1658 	int niflags = ni6->ni_flags;
1659 
1660 	NET_EPOCH_ASSERT();
1661 
1662 	if ((niflags & NI_NODEADDR_FLAG_ALL) == 0) {
1663 		switch (ni6->ni_code) {
1664 		case ICMP6_NI_SUBJ_IPV6:
1665 			if (subj == NULL) /* must be impossible... */
1666 				return (0);
1667 			break;
1668 		default:
1669 			/*
1670 			 * XXX: we only support IPv6 subject address for
1671 			 * this Qtype.
1672 			 */
1673 			return (0);
1674 		}
1675 	}
1676 
1677 	CK_STAILQ_FOREACH(ifp, &V_ifnet, if_link) {
1678 		addrsofif = 0;
1679 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1680 			if (ifa->ifa_addr->sa_family != AF_INET6)
1681 				continue;
1682 			ifa6 = (struct in6_ifaddr *)ifa;
1683 
1684 			if ((niflags & NI_NODEADDR_FLAG_ALL) == 0 &&
1685 			    IN6_ARE_ADDR_EQUAL(subj, &ifa6->ia_addr.sin6_addr))
1686 				iffound = 1;
1687 
1688 			/*
1689 			 * IPv4-mapped addresses can only be returned by a
1690 			 * Node Information proxy, since they represent
1691 			 * addresses of IPv4-only nodes, which perforce do
1692 			 * not implement this protocol.
1693 			 * [icmp-name-lookups-07, Section 5.4]
1694 			 * So we don't support NI_NODEADDR_FLAG_COMPAT in
1695 			 * this function at this moment.
1696 			 */
1697 
1698 			/* What do we have to do about ::1? */
1699 			switch (in6_addrscope(&ifa6->ia_addr.sin6_addr)) {
1700 			case IPV6_ADDR_SCOPE_LINKLOCAL:
1701 				if ((niflags & NI_NODEADDR_FLAG_LINKLOCAL) == 0)
1702 					continue;
1703 				break;
1704 			case IPV6_ADDR_SCOPE_SITELOCAL:
1705 				if ((niflags & NI_NODEADDR_FLAG_SITELOCAL) == 0)
1706 					continue;
1707 				break;
1708 			case IPV6_ADDR_SCOPE_GLOBAL:
1709 				if ((niflags & NI_NODEADDR_FLAG_GLOBAL) == 0)
1710 					continue;
1711 				break;
1712 			default:
1713 				continue;
1714 			}
1715 
1716 			/*
1717 			 * check if anycast is okay.
1718 			 * XXX: just experimental.  not in the spec.
1719 			 */
1720 			if ((ifa6->ia6_flags & IN6_IFF_ANYCAST) != 0 &&
1721 			    (niflags & NI_NODEADDR_FLAG_ANYCAST) == 0)
1722 				continue; /* we need only unicast addresses */
1723 			if ((ifa6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
1724 			    (V_icmp6_nodeinfo & ICMP6_NODEINFO_TMPADDROK) == 0) {
1725 				continue;
1726 			}
1727 			addrsofif++; /* count the address */
1728 		}
1729 		if (iffound) {
1730 			*ifpp = ifp;
1731 			return (addrsofif);
1732 		}
1733 
1734 		addrs += addrsofif;
1735 	}
1736 
1737 	return (addrs);
1738 }
1739 
1740 static int
ni6_store_addrs(struct icmp6_nodeinfo * ni6,struct icmp6_nodeinfo * nni6,struct ifnet * ifp0,int resid)1741 ni6_store_addrs(struct icmp6_nodeinfo *ni6, struct icmp6_nodeinfo *nni6,
1742     struct ifnet *ifp0, int resid)
1743 {
1744 	struct ifnet *ifp;
1745 	struct in6_ifaddr *ifa6;
1746 	struct ifaddr *ifa;
1747 	struct ifnet *ifp_dep = NULL;
1748 	int copied = 0, allow_deprecated = 0;
1749 	u_char *cp = (u_char *)(nni6 + 1);
1750 	int niflags = ni6->ni_flags;
1751 	u_int32_t ltime;
1752 
1753 	NET_EPOCH_ASSERT();
1754 
1755 	if (ifp0 == NULL && !(niflags & NI_NODEADDR_FLAG_ALL))
1756 		return (0);	/* needless to copy */
1757 
1758 	ifp = ifp0 ? ifp0 : CK_STAILQ_FIRST(&V_ifnet);
1759   again:
1760 
1761 	for (; ifp; ifp = CK_STAILQ_NEXT(ifp, if_link)) {
1762 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1763 			if (ifa->ifa_addr->sa_family != AF_INET6)
1764 				continue;
1765 			ifa6 = (struct in6_ifaddr *)ifa;
1766 
1767 			if ((ifa6->ia6_flags & IN6_IFF_DEPRECATED) != 0 &&
1768 			    allow_deprecated == 0) {
1769 				/*
1770 				 * prefererred address should be put before
1771 				 * deprecated addresses.
1772 				 */
1773 
1774 				/* record the interface for later search */
1775 				if (ifp_dep == NULL)
1776 					ifp_dep = ifp;
1777 
1778 				continue;
1779 			} else if ((ifa6->ia6_flags & IN6_IFF_DEPRECATED) == 0 &&
1780 			    allow_deprecated != 0)
1781 				continue; /* we now collect deprecated addrs */
1782 
1783 			/* What do we have to do about ::1? */
1784 			switch (in6_addrscope(&ifa6->ia_addr.sin6_addr)) {
1785 			case IPV6_ADDR_SCOPE_LINKLOCAL:
1786 				if ((niflags & NI_NODEADDR_FLAG_LINKLOCAL) == 0)
1787 					continue;
1788 				break;
1789 			case IPV6_ADDR_SCOPE_SITELOCAL:
1790 				if ((niflags & NI_NODEADDR_FLAG_SITELOCAL) == 0)
1791 					continue;
1792 				break;
1793 			case IPV6_ADDR_SCOPE_GLOBAL:
1794 				if ((niflags & NI_NODEADDR_FLAG_GLOBAL) == 0)
1795 					continue;
1796 				break;
1797 			default:
1798 				continue;
1799 			}
1800 
1801 			/*
1802 			 * check if anycast is okay.
1803 			 * XXX: just experimental.  not in the spec.
1804 			 */
1805 			if ((ifa6->ia6_flags & IN6_IFF_ANYCAST) != 0 &&
1806 			    (niflags & NI_NODEADDR_FLAG_ANYCAST) == 0)
1807 				continue;
1808 			if ((ifa6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
1809 			    (V_icmp6_nodeinfo & ICMP6_NODEINFO_TMPADDROK) == 0) {
1810 				continue;
1811 			}
1812 
1813 			/* now we can copy the address */
1814 			if (resid < sizeof(struct in6_addr) +
1815 			    sizeof(u_int32_t)) {
1816 				/*
1817 				 * We give up much more copy.
1818 				 * Set the truncate flag and return.
1819 				 */
1820 				nni6->ni_flags |= NI_NODEADDR_FLAG_TRUNCATE;
1821 				return (copied);
1822 			}
1823 
1824 			/*
1825 			 * Set the TTL of the address.
1826 			 * The TTL value should be one of the following
1827 			 * according to the specification:
1828 			 *
1829 			 * 1. The remaining lifetime of a DHCP lease on the
1830 			 *    address, or
1831 			 * 2. The remaining Valid Lifetime of a prefix from
1832 			 *    which the address was derived through Stateless
1833 			 *    Autoconfiguration.
1834 			 *
1835 			 * Note that we currently do not support stateful
1836 			 * address configuration by DHCPv6, so the former
1837 			 * case can't happen.
1838 			 */
1839 			if (ifa6->ia6_lifetime.ia6t_expire == 0)
1840 				ltime = ND6_INFINITE_LIFETIME;
1841 			else {
1842 				if (ifa6->ia6_lifetime.ia6t_expire >
1843 				    time_uptime)
1844 					ltime = htonl(ifa6->ia6_lifetime.ia6t_expire - time_uptime);
1845 				else
1846 					ltime = 0;
1847 			}
1848 
1849 			bcopy(&ltime, cp, sizeof(u_int32_t));
1850 			cp += sizeof(u_int32_t);
1851 
1852 			/* copy the address itself */
1853 			bcopy(&ifa6->ia_addr.sin6_addr, cp,
1854 			    sizeof(struct in6_addr));
1855 			in6_clearscope((struct in6_addr *)cp); /* XXX */
1856 			cp += sizeof(struct in6_addr);
1857 
1858 			resid -= (sizeof(struct in6_addr) + sizeof(u_int32_t));
1859 			copied += (sizeof(struct in6_addr) + sizeof(u_int32_t));
1860 		}
1861 		if (ifp0)	/* we need search only on the specified IF */
1862 			break;
1863 	}
1864 
1865 	if (allow_deprecated == 0 && ifp_dep != NULL) {
1866 		ifp = ifp_dep;
1867 		allow_deprecated = 1;
1868 
1869 		goto again;
1870 	}
1871 
1872 	return (copied);
1873 }
1874 
1875 /*
1876  * XXX almost dup'ed code with rip6_input.
1877  */
1878 static int
icmp6_rip6_input(struct mbuf ** mp,int off)1879 icmp6_rip6_input(struct mbuf **mp, int off)
1880 {
1881 	struct mbuf *m = *mp;
1882 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1883 	struct inpcb *inp;
1884 	struct inpcb *last = NULL;
1885 	struct sockaddr_in6 fromsa;
1886 	struct icmp6_hdr *icmp6;
1887 	struct mbuf *opts = NULL;
1888 
1889 	NET_EPOCH_ASSERT();
1890 
1891 	/* This is assumed to be safe; icmp6_input() does a pullup. */
1892 	icmp6 = (struct icmp6_hdr *)((caddr_t)ip6 + off);
1893 
1894 	/*
1895 	 * XXX: the address may have embedded scope zone ID, which should be
1896 	 * hidden from applications.
1897 	 */
1898 	bzero(&fromsa, sizeof(fromsa));
1899 	fromsa.sin6_family = AF_INET6;
1900 	fromsa.sin6_len = sizeof(struct sockaddr_in6);
1901 	fromsa.sin6_addr = ip6->ip6_src;
1902 	if (sa6_recoverscope(&fromsa)) {
1903 		m_freem(m);
1904 		*mp = NULL;
1905 		return (IPPROTO_DONE);
1906 	}
1907 
1908 	CK_LIST_FOREACH(inp, &V_ripcb, inp_list) {
1909 		if ((inp->inp_vflag & INP_IPV6) == 0)
1910 			continue;
1911 		if (inp->inp_ip_p != IPPROTO_ICMPV6)
1912 			continue;
1913 		if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr) &&
1914 		   !IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr, &ip6->ip6_dst))
1915 			continue;
1916 		if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr) &&
1917 		   !IN6_ARE_ADDR_EQUAL(&inp->in6p_faddr, &ip6->ip6_src))
1918 			continue;
1919 		INP_RLOCK(inp);
1920 		if (__predict_false(inp->inp_flags2 & INP_FREED)) {
1921 			INP_RUNLOCK(inp);
1922 			continue;
1923 		}
1924 		if (ICMP6_FILTER_WILLBLOCK(icmp6->icmp6_type,
1925 		    inp->in6p_icmp6filt)) {
1926 			INP_RUNLOCK(inp);
1927 			continue;
1928 		}
1929 		if (last != NULL) {
1930 			struct	mbuf *n = NULL;
1931 
1932 			/*
1933 			 * Recent network drivers tend to allocate a single
1934 			 * mbuf cluster, rather than to make a couple of
1935 			 * mbufs without clusters.  Also, since the IPv6 code
1936 			 * path tries to avoid m_pullup(), it is highly
1937 			 * probable that we still have an mbuf cluster here
1938 			 * even though the necessary length can be stored in an
1939 			 * mbuf's internal buffer.
1940 			 * Meanwhile, the default size of the receive socket
1941 			 * buffer for raw sockets is not so large.  This means
1942 			 * the possibility of packet loss is relatively higher
1943 			 * than before.  To avoid this scenario, we copy the
1944 			 * received data to a separate mbuf that does not use
1945 			 * a cluster, if possible.
1946 			 * XXX: it is better to copy the data after stripping
1947 			 * intermediate headers.
1948 			 */
1949 			if ((m->m_flags & M_EXT) && m->m_next == NULL &&
1950 			    m->m_len <= MHLEN) {
1951 				n = m_get(M_NOWAIT, m->m_type);
1952 				if (n != NULL) {
1953 					if (m_dup_pkthdr(n, m, M_NOWAIT)) {
1954 						bcopy(m->m_data, n->m_data,
1955 						      m->m_len);
1956 						n->m_len = m->m_len;
1957 					} else {
1958 						m_free(n);
1959 						n = NULL;
1960 					}
1961 				}
1962 			}
1963 			if (n != NULL ||
1964 			    (n = m_copym(m, 0, M_COPYALL, M_NOWAIT)) != NULL) {
1965 				if (last->inp_flags & INP_CONTROLOPTS)
1966 					ip6_savecontrol(last, n, &opts);
1967 				/* strip intermediate headers */
1968 				m_adj(n, off);
1969 				SOCKBUF_LOCK(&last->inp_socket->so_rcv);
1970 				if (sbappendaddr_locked(
1971 				    &last->inp_socket->so_rcv,
1972 				    (struct sockaddr *)&fromsa, n, opts)
1973 				    == 0) {
1974 					soroverflow_locked(last->inp_socket);
1975 					m_freem(n);
1976 					if (opts) {
1977 						m_freem(opts);
1978 					}
1979 				} else
1980 					sorwakeup_locked(last->inp_socket);
1981 				opts = NULL;
1982 			}
1983 			INP_RUNLOCK(last);
1984 		}
1985 		last = inp;
1986 	}
1987 	if (last != NULL) {
1988 		if (last->inp_flags & INP_CONTROLOPTS)
1989 			ip6_savecontrol(last, m, &opts);
1990 		/* strip intermediate headers */
1991 		m_adj(m, off);
1992 
1993 		/* avoid using mbuf clusters if possible (see above) */
1994 		if ((m->m_flags & M_EXT) && m->m_next == NULL &&
1995 		    m->m_len <= MHLEN) {
1996 			struct mbuf *n;
1997 
1998 			n = m_get(M_NOWAIT, m->m_type);
1999 			if (n != NULL) {
2000 				if (m_dup_pkthdr(n, m, M_NOWAIT)) {
2001 					bcopy(m->m_data, n->m_data, m->m_len);
2002 					n->m_len = m->m_len;
2003 
2004 					m_freem(m);
2005 					m = n;
2006 				} else {
2007 					m_freem(n);
2008 					n = NULL;
2009 				}
2010 			}
2011 		}
2012 		SOCKBUF_LOCK(&last->inp_socket->so_rcv);
2013 		if (sbappendaddr_locked(&last->inp_socket->so_rcv,
2014 		    (struct sockaddr *)&fromsa, m, opts) == 0) {
2015 			m_freem(m);
2016 			if (opts)
2017 				m_freem(opts);
2018 			soroverflow_locked(last->inp_socket);
2019 		} else
2020 			sorwakeup_locked(last->inp_socket);
2021 		INP_RUNLOCK(last);
2022 	} else {
2023 		m_freem(m);
2024 		IP6STAT_DEC(ip6s_delivered);
2025 	}
2026 	*mp = NULL;
2027 	return (IPPROTO_DONE);
2028 }
2029 
2030 /*
2031  * Reflect the ip6 packet back to the source.
2032  * OFF points to the icmp6 header, counted from the top of the mbuf.
2033  */
2034 static void
icmp6_reflect(struct mbuf * m,size_t off)2035 icmp6_reflect(struct mbuf *m, size_t off)
2036 {
2037 	struct in6_addr src6, *srcp;
2038 	struct ip6_hdr *ip6;
2039 	struct icmp6_hdr *icmp6;
2040 	struct in6_ifaddr *ia = NULL;
2041 	struct ifnet *outif = NULL;
2042 	int plen;
2043 	int type, code, hlim;
2044 
2045 	/* too short to reflect */
2046 	if (off < sizeof(struct ip6_hdr)) {
2047 		nd6log((LOG_DEBUG,
2048 		    "sanity fail: off=%lx, sizeof(ip6)=%lx in %s:%d\n",
2049 		    (u_long)off, (u_long)sizeof(struct ip6_hdr),
2050 		    __FILE__, __LINE__));
2051 		goto bad;
2052 	}
2053 
2054 	/*
2055 	 * If there are extra headers between IPv6 and ICMPv6, strip
2056 	 * off that header first.
2057 	 */
2058 #ifdef DIAGNOSTIC
2059 	if (sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr) > MHLEN)
2060 		panic("assumption failed in icmp6_reflect");
2061 #endif
2062 	if (off > sizeof(struct ip6_hdr)) {
2063 		size_t l;
2064 		struct ip6_hdr nip6;
2065 
2066 		l = off - sizeof(struct ip6_hdr);
2067 		m_copydata(m, 0, sizeof(nip6), (caddr_t)&nip6);
2068 		m_adj(m, l);
2069 		l = sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr);
2070 		if (m->m_len < l) {
2071 			if ((m = m_pullup(m, l)) == NULL)
2072 				return;
2073 		}
2074 		bcopy((caddr_t)&nip6, mtod(m, caddr_t), sizeof(nip6));
2075 	} else /* off == sizeof(struct ip6_hdr) */ {
2076 		size_t l;
2077 		l = sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr);
2078 		if (m->m_len < l) {
2079 			if ((m = m_pullup(m, l)) == NULL)
2080 				return;
2081 		}
2082 	}
2083 	plen = m->m_pkthdr.len - sizeof(struct ip6_hdr);
2084 	ip6 = mtod(m, struct ip6_hdr *);
2085 	ip6->ip6_nxt = IPPROTO_ICMPV6;
2086 	icmp6 = (struct icmp6_hdr *)(ip6 + 1);
2087 	type = icmp6->icmp6_type; /* keep type for statistics */
2088 	code = icmp6->icmp6_code; /* ditto. */
2089 	hlim = 0;
2090 	srcp = NULL;
2091 
2092 	/*
2093 	 * If the incoming packet was addressed directly to us (i.e. unicast),
2094 	 * use dst as the src for the reply.
2095 	 * The IN6_IFF_NOTREADY case should be VERY rare, but is possible
2096 	 * (for example) when we encounter an error while forwarding procedure
2097 	 * destined to a duplicated address of ours.
2098 	 */
2099 	if (!IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
2100 		ia = in6ifa_ifwithaddr(&ip6->ip6_dst, 0 /* XXX */, false);
2101 		if (ia != NULL && !(ia->ia6_flags &
2102 		    (IN6_IFF_ANYCAST|IN6_IFF_NOTREADY))) {
2103 			src6 = ia->ia_addr.sin6_addr;
2104 			srcp = &src6;
2105 
2106 			if (m->m_pkthdr.rcvif != NULL) {
2107 				/* XXX: This may not be the outgoing interface */
2108 				hlim = ND_IFINFO(m->m_pkthdr.rcvif)->chlim;
2109 			} else
2110 				hlim = V_ip6_defhlim;
2111 		}
2112 	}
2113 
2114 	if (srcp == NULL) {
2115 		int error;
2116 		struct in6_addr dst6;
2117 		uint32_t scopeid;
2118 
2119 		/*
2120 		 * This case matches to multicasts, our anycast, or unicasts
2121 		 * that we do not own.  Select a source address based on the
2122 		 * source address of the erroneous packet.
2123 		 */
2124 		in6_splitscope(&ip6->ip6_src, &dst6, &scopeid);
2125 		error = in6_selectsrc_addr(M_GETFIB(m), &dst6,
2126 		    scopeid, NULL, &src6, &hlim);
2127 
2128 		if (error) {
2129 			char ip6buf[INET6_ADDRSTRLEN];
2130 			nd6log((LOG_DEBUG,
2131 			    "icmp6_reflect: source can't be determined: "
2132 			    "dst=%s, error=%d\n",
2133 			    ip6_sprintf(ip6buf, &ip6->ip6_dst), error));
2134 			goto bad;
2135 		}
2136 		srcp = &src6;
2137 	}
2138 	/*
2139 	 * ip6_input() drops a packet if its src is multicast.
2140 	 * So, the src is never multicast.
2141 	 */
2142 	ip6->ip6_dst = ip6->ip6_src;
2143 	ip6->ip6_src = *srcp;
2144 	ip6->ip6_flow = 0;
2145 	ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
2146 	ip6->ip6_vfc |= IPV6_VERSION;
2147 	ip6->ip6_nxt = IPPROTO_ICMPV6;
2148 	ip6->ip6_hlim = hlim;
2149 
2150 	icmp6->icmp6_cksum = 0;
2151 	icmp6->icmp6_cksum = in6_cksum(m, IPPROTO_ICMPV6,
2152 	    sizeof(struct ip6_hdr), plen);
2153 
2154 	/*
2155 	 * XXX option handling
2156 	 */
2157 
2158 	m->m_flags &= ~(M_BCAST|M_MCAST);
2159 	m->m_pkthdr.rcvif = NULL;
2160 	ip6_output(m, NULL, NULL, 0, NULL, &outif, NULL);
2161 	if (outif)
2162 		icmp6_ifoutstat_inc(outif, type, code);
2163 
2164 	return;
2165 
2166  bad:
2167 	m_freem(m);
2168 	return;
2169 }
2170 
2171 void
icmp6_fasttimo(void)2172 icmp6_fasttimo(void)
2173 {
2174 
2175 	mld_fasttimo();
2176 }
2177 
2178 void
icmp6_slowtimo(void)2179 icmp6_slowtimo(void)
2180 {
2181 
2182 	mld_slowtimo();
2183 }
2184 
2185 static const char *
icmp6_redirect_diag(struct in6_addr * src6,struct in6_addr * dst6,struct in6_addr * tgt6)2186 icmp6_redirect_diag(struct in6_addr *src6, struct in6_addr *dst6,
2187     struct in6_addr *tgt6)
2188 {
2189 	static char buf[1024];
2190 	char ip6bufs[INET6_ADDRSTRLEN];
2191 	char ip6bufd[INET6_ADDRSTRLEN];
2192 	char ip6buft[INET6_ADDRSTRLEN];
2193 	snprintf(buf, sizeof(buf), "(src=%s dst=%s tgt=%s)",
2194 	    ip6_sprintf(ip6bufs, src6), ip6_sprintf(ip6bufd, dst6),
2195 	    ip6_sprintf(ip6buft, tgt6));
2196 	return buf;
2197 }
2198 
2199 void
icmp6_redirect_input(struct mbuf * m,int off)2200 icmp6_redirect_input(struct mbuf *m, int off)
2201 {
2202 	struct ifnet *ifp;
2203 	struct ip6_hdr *ip6;
2204 	struct nd_redirect *nd_rd;
2205 	struct in6_addr src6, redtgt6, reddst6;
2206 	union nd_opts ndopts;
2207 	char ip6buf[INET6_ADDRSTRLEN];
2208 	char *lladdr;
2209 	int icmp6len, is_onlink, is_router, lladdrlen;
2210 
2211 	M_ASSERTPKTHDR(m);
2212 	KASSERT(m->m_pkthdr.rcvif != NULL, ("%s: no rcvif", __func__));
2213 
2214 	/* XXX if we are router, we don't update route by icmp6 redirect */
2215 	if (V_ip6_forwarding)
2216 		goto freeit;
2217 	if (!V_icmp6_rediraccept)
2218 		goto freeit;
2219 
2220 	/* RFC 6980: Nodes MUST silently ignore fragments */
2221 	if(m->m_flags & M_FRAGMENTED)
2222 		goto freeit;
2223 
2224 	ip6 = mtod(m, struct ip6_hdr *);
2225 	icmp6len = ntohs(ip6->ip6_plen);
2226 	if (m->m_len < off + icmp6len) {
2227 		m = m_pullup(m, off + icmp6len);
2228 		if (m == NULL) {
2229 			IP6STAT_INC(ip6s_exthdrtoolong);
2230 			return;
2231 		}
2232 	}
2233 	ip6 = mtod(m, struct ip6_hdr *);
2234 	nd_rd = (struct nd_redirect *)((caddr_t)ip6 + off);
2235 
2236 	ifp = m->m_pkthdr.rcvif;
2237 	redtgt6 = nd_rd->nd_rd_target;
2238 	reddst6 = nd_rd->nd_rd_dst;
2239 
2240 	if (in6_setscope(&redtgt6, ifp, NULL) ||
2241 	    in6_setscope(&reddst6, ifp, NULL)) {
2242 		goto freeit;
2243 	}
2244 
2245 	/* validation */
2246 	src6 = ip6->ip6_src;
2247 	if (!IN6_IS_ADDR_LINKLOCAL(&src6)) {
2248 		nd6log((LOG_ERR,
2249 		    "ICMP6 redirect sent from %s rejected; "
2250 		    "must be from linklocal\n",
2251 		    ip6_sprintf(ip6buf, &src6)));
2252 		goto bad;
2253 	}
2254 	if (__predict_false(ip6->ip6_hlim != 255)) {
2255 		ICMP6STAT_INC(icp6s_invlhlim);
2256 		nd6log((LOG_ERR,
2257 		    "ICMP6 redirect sent from %s rejected; "
2258 		    "hlim=%d (must be 255)\n",
2259 		    ip6_sprintf(ip6buf, &src6), ip6->ip6_hlim));
2260 		goto bad;
2261 	}
2262     {
2263 	/* ip6->ip6_src must be equal to gw for icmp6->icmp6_reddst */
2264 	struct nhop_object *nh;
2265 	struct in6_addr kdst;
2266 	uint32_t scopeid;
2267 
2268 	in6_splitscope(&reddst6, &kdst, &scopeid);
2269 	NET_EPOCH_ASSERT();
2270 	nh = fib6_lookup(ifp->if_fib, &kdst, scopeid, 0, 0);
2271 	if (nh != NULL) {
2272 		struct in6_addr nh_addr;
2273 		nh_addr = ifatoia6(nh->nh_ifa)->ia_addr.sin6_addr;
2274 		if ((nh->nh_flags & NHF_GATEWAY) == 0) {
2275 			nd6log((LOG_ERR,
2276 			    "ICMP6 redirect rejected; no route "
2277 			    "with inet6 gateway found for redirect dst: %s\n",
2278 			    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2279 			goto bad;
2280 		}
2281 
2282 		/*
2283 		 * Embed scope zone id into next hop address.
2284 		 */
2285 		nh_addr = nh->gw6_sa.sin6_addr;
2286 
2287 		if (IN6_ARE_ADDR_EQUAL(&src6, &nh_addr) == 0) {
2288 			nd6log((LOG_ERR,
2289 			    "ICMP6 redirect rejected; "
2290 			    "not equal to gw-for-src=%s (must be same): "
2291 			    "%s\n",
2292 			    ip6_sprintf(ip6buf, &nh_addr),
2293 			    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2294 			goto bad;
2295 		}
2296 	} else {
2297 		nd6log((LOG_ERR,
2298 		    "ICMP6 redirect rejected; "
2299 		    "no route found for redirect dst: %s\n",
2300 		    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2301 		goto bad;
2302 	}
2303     }
2304 	if (IN6_IS_ADDR_MULTICAST(&reddst6)) {
2305 		nd6log((LOG_ERR,
2306 		    "ICMP6 redirect rejected; "
2307 		    "redirect dst must be unicast: %s\n",
2308 		    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2309 		goto bad;
2310 	}
2311 
2312 	is_router = is_onlink = 0;
2313 	if (IN6_IS_ADDR_LINKLOCAL(&redtgt6))
2314 		is_router = 1;	/* router case */
2315 	if (bcmp(&redtgt6, &reddst6, sizeof(redtgt6)) == 0)
2316 		is_onlink = 1;	/* on-link destination case */
2317 	if (!is_router && !is_onlink) {
2318 		nd6log((LOG_ERR,
2319 		    "ICMP6 redirect rejected; "
2320 		    "neither router case nor onlink case: %s\n",
2321 		    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2322 		goto bad;
2323 	}
2324 
2325 	icmp6len -= sizeof(*nd_rd);
2326 	nd6_option_init(nd_rd + 1, icmp6len, &ndopts);
2327 	if (nd6_options(&ndopts) < 0) {
2328 		nd6log((LOG_INFO, "%s: invalid ND option, rejected: %s\n",
2329 		    __func__, icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2330 		/* nd6_options have incremented stats */
2331 		goto freeit;
2332 	}
2333 
2334 	lladdr = NULL;
2335 	lladdrlen = 0;
2336 	if (ndopts.nd_opts_tgt_lladdr) {
2337 		lladdr = (char *)(ndopts.nd_opts_tgt_lladdr + 1);
2338 		lladdrlen = ndopts.nd_opts_tgt_lladdr->nd_opt_len << 3;
2339 	}
2340 
2341 	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
2342 		nd6log((LOG_INFO, "%s: lladdrlen mismatch for %s "
2343 		    "(if %d, icmp6 packet %d): %s\n",
2344 		    __func__, ip6_sprintf(ip6buf, &redtgt6),
2345 		    ifp->if_addrlen, lladdrlen - 2,
2346 		    icmp6_redirect_diag(&src6, &reddst6, &redtgt6)));
2347 		goto bad;
2348 	}
2349 
2350 	/* Validation passed. */
2351 
2352 	/* RFC 2461 8.3 */
2353 	nd6_cache_lladdr(ifp, &redtgt6, lladdr, lladdrlen, ND_REDIRECT,
2354 	    is_onlink ? ND_REDIRECT_ONLINK : ND_REDIRECT_ROUTER);
2355 
2356 	/*
2357 	 * Install a gateway route in the better-router case or an interface
2358 	 * route in the on-link-destination case.
2359 	 */
2360 	{
2361 		struct sockaddr_in6 sdst;
2362 		struct sockaddr_in6 sgw;
2363 		struct sockaddr_in6 ssrc;
2364 		struct sockaddr *gw;
2365 		int rt_flags;
2366 		u_int fibnum;
2367 
2368 		bzero(&sdst, sizeof(sdst));
2369 		bzero(&ssrc, sizeof(ssrc));
2370 		sdst.sin6_family = ssrc.sin6_family = AF_INET6;
2371 		sdst.sin6_len = ssrc.sin6_len = sizeof(struct sockaddr_in6);
2372 		bcopy(&reddst6, &sdst.sin6_addr, sizeof(struct in6_addr));
2373 		bcopy(&src6, &ssrc.sin6_addr, sizeof(struct in6_addr));
2374 		rt_flags = 0;
2375 		if (is_router) {
2376 			bzero(&sgw, sizeof(sgw));
2377 			sgw.sin6_family = AF_INET6;
2378 			sgw.sin6_len = sizeof(struct sockaddr_in6);
2379 			bcopy(&redtgt6, &sgw.sin6_addr,
2380 				sizeof(struct in6_addr));
2381 			gw = (struct sockaddr *)&sgw;
2382 			rt_flags |= RTF_GATEWAY;
2383 		} else
2384 			gw = ifp->if_addr->ifa_addr;
2385 		for (fibnum = 0; fibnum < rt_numfibs; fibnum++)
2386 			rib_add_redirect(fibnum, (struct sockaddr *)&sdst, gw,
2387 			    (struct sockaddr *)&ssrc, ifp, rt_flags,
2388 			    V_icmp6_redirtimeout);
2389 	}
2390 	/* finally update cached route in each socket via pfctlinput */
2391     {
2392 	struct sockaddr_in6 sdst;
2393 
2394 	bzero(&sdst, sizeof(sdst));
2395 	sdst.sin6_family = AF_INET6;
2396 	sdst.sin6_len = sizeof(struct sockaddr_in6);
2397 	bcopy(&reddst6, &sdst.sin6_addr, sizeof(struct in6_addr));
2398 	pfctlinput(PRC_REDIRECT_HOST, (struct sockaddr *)&sdst);
2399     }
2400 
2401  freeit:
2402 	m_freem(m);
2403 	return;
2404 
2405  bad:
2406 	ICMP6STAT_INC(icp6s_badredirect);
2407 	m_freem(m);
2408 }
2409 
2410 void
icmp6_redirect_output(struct mbuf * m0,struct nhop_object * nh)2411 icmp6_redirect_output(struct mbuf *m0, struct nhop_object *nh)
2412 {
2413 	struct ifnet *ifp;	/* my outgoing interface */
2414 	struct in6_addr *ifp_ll6;
2415 	struct in6_addr *router_ll6;
2416 	struct ip6_hdr *sip6;	/* m0 as struct ip6_hdr */
2417 	struct mbuf *m = NULL;	/* newly allocated one */
2418 	struct m_tag *mtag;
2419 	struct ip6_hdr *ip6;	/* m as struct ip6_hdr */
2420 	struct nd_redirect *nd_rd;
2421 	struct llentry *ln = NULL;
2422 	size_t maxlen;
2423 	u_char *p;
2424 	struct ifnet *outif = NULL;
2425 	struct sockaddr_in6 src_sa;
2426 
2427 	icmp6_errcount(ND_REDIRECT, 0);
2428 
2429 	/* if we are not router, we don't send icmp6 redirect */
2430 	if (!V_ip6_forwarding)
2431 		goto fail;
2432 
2433 	/* sanity check */
2434 	if (!m0 || !nh || !(NH_IS_VALID(nh)) || !(ifp = nh->nh_ifp))
2435 		goto fail;
2436 
2437 	/*
2438 	 * Address check:
2439 	 *  the source address must identify a neighbor, and
2440 	 *  the destination address must not be a multicast address
2441 	 *  [RFC 2461, sec 8.2]
2442 	 */
2443 	sip6 = mtod(m0, struct ip6_hdr *);
2444 	bzero(&src_sa, sizeof(src_sa));
2445 	src_sa.sin6_family = AF_INET6;
2446 	src_sa.sin6_len = sizeof(src_sa);
2447 	src_sa.sin6_addr = sip6->ip6_src;
2448 	if (nd6_is_addr_neighbor(&src_sa, ifp) == 0)
2449 		goto fail;
2450 	if (IN6_IS_ADDR_MULTICAST(&sip6->ip6_dst))
2451 		goto fail;	/* what should we do here? */
2452 
2453 	/* rate limit */
2454 	if (icmp6_ratelimit(&sip6->ip6_src, ND_REDIRECT, 0))
2455 		goto fail;
2456 
2457 	/*
2458 	 * Since we are going to append up to 1280 bytes (= IPV6_MMTU),
2459 	 * we almost always ask for an mbuf cluster for simplicity.
2460 	 * (MHLEN < IPV6_MMTU is almost always true)
2461 	 */
2462 #if IPV6_MMTU >= MCLBYTES
2463 # error assumption failed about IPV6_MMTU and MCLBYTES
2464 #endif
2465 	m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
2466 	if (m == NULL)
2467 		goto fail;
2468 	M_SETFIB(m, M_GETFIB(m0));
2469 	maxlen = M_TRAILINGSPACE(m);
2470 	maxlen = min(IPV6_MMTU, maxlen);
2471 	/* just for safety */
2472 	if (maxlen < sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr) +
2473 	    ((sizeof(struct nd_opt_hdr) + ifp->if_addrlen + 7) & ~7)) {
2474 		goto fail;
2475 	}
2476 
2477 	{
2478 		/* get ip6 linklocal address for ifp(my outgoing interface). */
2479 		struct in6_ifaddr *ia;
2480 		if ((ia = in6ifa_ifpforlinklocal(ifp,
2481 						 IN6_IFF_NOTREADY|
2482 						 IN6_IFF_ANYCAST)) == NULL)
2483 			goto fail;
2484 		ifp_ll6 = &ia->ia_addr.sin6_addr;
2485 		/* XXXRW: reference released prematurely. */
2486 		ifa_free(&ia->ia_ifa);
2487 	}
2488 
2489 	/* get ip6 linklocal address for the router. */
2490 	if (nh->nh_flags & NHF_GATEWAY) {
2491 		struct sockaddr_in6 *sin6;
2492 		sin6 = &nh->gw6_sa;
2493 		router_ll6 = &sin6->sin6_addr;
2494 		if (!IN6_IS_ADDR_LINKLOCAL(router_ll6))
2495 			router_ll6 = (struct in6_addr *)NULL;
2496 	} else
2497 		router_ll6 = (struct in6_addr *)NULL;
2498 
2499 	/* ip6 */
2500 	ip6 = mtod(m, struct ip6_hdr *);
2501 	ip6->ip6_flow = 0;
2502 	ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
2503 	ip6->ip6_vfc |= IPV6_VERSION;
2504 	/* ip6->ip6_plen will be set later */
2505 	ip6->ip6_nxt = IPPROTO_ICMPV6;
2506 	ip6->ip6_hlim = 255;
2507 	/* ip6->ip6_src must be linklocal addr for my outgoing if. */
2508 	bcopy(ifp_ll6, &ip6->ip6_src, sizeof(struct in6_addr));
2509 	bcopy(&sip6->ip6_src, &ip6->ip6_dst, sizeof(struct in6_addr));
2510 
2511 	/* ND Redirect */
2512 	nd_rd = (struct nd_redirect *)(ip6 + 1);
2513 	nd_rd->nd_rd_type = ND_REDIRECT;
2514 	nd_rd->nd_rd_code = 0;
2515 	nd_rd->nd_rd_reserved = 0;
2516 	if (nh->nh_flags & NHF_GATEWAY) {
2517 		/*
2518 		 * nd_rd->nd_rd_target must be a link-local address in
2519 		 * better router cases.
2520 		 */
2521 		if (!router_ll6)
2522 			goto fail;
2523 		bcopy(router_ll6, &nd_rd->nd_rd_target,
2524 		    sizeof(nd_rd->nd_rd_target));
2525 		bcopy(&sip6->ip6_dst, &nd_rd->nd_rd_dst,
2526 		    sizeof(nd_rd->nd_rd_dst));
2527 	} else {
2528 		/* make sure redtgt == reddst */
2529 		bcopy(&sip6->ip6_dst, &nd_rd->nd_rd_target,
2530 		    sizeof(nd_rd->nd_rd_target));
2531 		bcopy(&sip6->ip6_dst, &nd_rd->nd_rd_dst,
2532 		    sizeof(nd_rd->nd_rd_dst));
2533 	}
2534 
2535 	p = (u_char *)(nd_rd + 1);
2536 
2537 	if (!router_ll6)
2538 		goto nolladdropt;
2539 
2540 	{
2541 		/* target lladdr option */
2542 		int len;
2543 		struct nd_opt_hdr *nd_opt;
2544 		char *lladdr;
2545 
2546 		ln = nd6_lookup(router_ll6, LLE_SF(AF_INET6,  0), ifp);
2547 		if (ln == NULL)
2548 			goto nolladdropt;
2549 
2550 		len = sizeof(*nd_opt) + ifp->if_addrlen;
2551 		len = (len + 7) & ~7;	/* round by 8 */
2552 		/* safety check */
2553 		if (len + (p - (u_char *)ip6) > maxlen)
2554 			goto nolladdropt;
2555 
2556 		if (ln->la_flags & LLE_VALID) {
2557 			nd_opt = (struct nd_opt_hdr *)p;
2558 			nd_opt->nd_opt_type = ND_OPT_TARGET_LINKADDR;
2559 			nd_opt->nd_opt_len = len >> 3;
2560 			lladdr = (char *)(nd_opt + 1);
2561 			bcopy(ln->ll_addr, lladdr, ifp->if_addrlen);
2562 			p += len;
2563 		}
2564 	}
2565 nolladdropt:
2566 	if (ln != NULL)
2567 		LLE_RUNLOCK(ln);
2568 
2569 	m->m_pkthdr.len = m->m_len = p - (u_char *)ip6;
2570 
2571 	/* just to be safe */
2572 #ifdef M_DECRYPTED	/*not openbsd*/
2573 	if (m0->m_flags & M_DECRYPTED)
2574 		goto noredhdropt;
2575 #endif
2576 	if (p - (u_char *)ip6 > maxlen)
2577 		goto noredhdropt;
2578 
2579 	{
2580 		/* redirected header option */
2581 		int len;
2582 		struct nd_opt_rd_hdr *nd_opt_rh;
2583 
2584 		/*
2585 		 * compute the maximum size for icmp6 redirect header option.
2586 		 * XXX room for auth header?
2587 		 */
2588 		len = maxlen - (p - (u_char *)ip6);
2589 		len &= ~7;
2590 
2591 		/* This is just for simplicity. */
2592 		if (m0->m_pkthdr.len != m0->m_len) {
2593 			if (m0->m_next) {
2594 				m_freem(m0->m_next);
2595 				m0->m_next = NULL;
2596 			}
2597 			m0->m_pkthdr.len = m0->m_len;
2598 		}
2599 
2600 		/*
2601 		 * Redirected header option spec (RFC2461 4.6.3) talks nothing
2602 		 * about padding/truncate rule for the original IP packet.
2603 		 * From the discussion on IPv6imp in Feb 1999,
2604 		 * the consensus was:
2605 		 * - "attach as much as possible" is the goal
2606 		 * - pad if not aligned (original size can be guessed by
2607 		 *   original ip6 header)
2608 		 * Following code adds the padding if it is simple enough,
2609 		 * and truncates if not.
2610 		 */
2611 		if (m0->m_next || m0->m_pkthdr.len != m0->m_len)
2612 			panic("assumption failed in %s:%d", __FILE__,
2613 			    __LINE__);
2614 
2615 		if (len - sizeof(*nd_opt_rh) < m0->m_pkthdr.len) {
2616 			/* not enough room, truncate */
2617 			m0->m_pkthdr.len = m0->m_len = len -
2618 			    sizeof(*nd_opt_rh);
2619 		} else {
2620 			/* enough room, pad or truncate */
2621 			size_t extra;
2622 
2623 			extra = m0->m_pkthdr.len % 8;
2624 			if (extra) {
2625 				/* pad if easy enough, truncate if not */
2626 				if (8 - extra <= M_TRAILINGSPACE(m0)) {
2627 					/* pad */
2628 					m0->m_len += (8 - extra);
2629 					m0->m_pkthdr.len += (8 - extra);
2630 				} else {
2631 					/* truncate */
2632 					m0->m_pkthdr.len -= extra;
2633 					m0->m_len -= extra;
2634 				}
2635 			}
2636 			len = m0->m_pkthdr.len + sizeof(*nd_opt_rh);
2637 			m0->m_pkthdr.len = m0->m_len = len -
2638 			    sizeof(*nd_opt_rh);
2639 		}
2640 
2641 		nd_opt_rh = (struct nd_opt_rd_hdr *)p;
2642 		bzero(nd_opt_rh, sizeof(*nd_opt_rh));
2643 		nd_opt_rh->nd_opt_rh_type = ND_OPT_REDIRECTED_HEADER;
2644 		nd_opt_rh->nd_opt_rh_len = len >> 3;
2645 		p += sizeof(*nd_opt_rh);
2646 		m->m_pkthdr.len = m->m_len = p - (u_char *)ip6;
2647 
2648 		/* connect m0 to m */
2649 		m_tag_delete_chain(m0, NULL);
2650 		m0->m_flags &= ~M_PKTHDR;
2651 		m->m_next = m0;
2652 		m->m_pkthdr.len = m->m_len + m0->m_len;
2653 		m0 = NULL;
2654 	}
2655 noredhdropt:;
2656 	if (m0) {
2657 		m_freem(m0);
2658 		m0 = NULL;
2659 	}
2660 
2661 	/* XXX: clear embedded link IDs in the inner header */
2662 	in6_clearscope(&sip6->ip6_src);
2663 	in6_clearscope(&sip6->ip6_dst);
2664 	in6_clearscope(&nd_rd->nd_rd_target);
2665 	in6_clearscope(&nd_rd->nd_rd_dst);
2666 
2667 	ip6->ip6_plen = htons(m->m_pkthdr.len - sizeof(struct ip6_hdr));
2668 
2669 	nd_rd->nd_rd_cksum = 0;
2670 	nd_rd->nd_rd_cksum = in6_cksum(m, IPPROTO_ICMPV6,
2671 	    sizeof(*ip6), ntohs(ip6->ip6_plen));
2672 
2673         if (send_sendso_input_hook != NULL) {
2674 		mtag = m_tag_get(PACKET_TAG_ND_OUTGOING, sizeof(unsigned short),
2675 			M_NOWAIT);
2676 		if (mtag == NULL)
2677 			goto fail;
2678 		*(unsigned short *)(mtag + 1) = nd_rd->nd_rd_type;
2679 		m_tag_prepend(m, mtag);
2680 	}
2681 
2682 	/* send the packet to outside... */
2683 	ip6_output(m, NULL, NULL, 0, NULL, &outif, NULL);
2684 	if (outif) {
2685 		icmp6_ifstat_inc(outif, ifs6_out_msg);
2686 		icmp6_ifstat_inc(outif, ifs6_out_redirect);
2687 	}
2688 	ICMP6STAT_INC(icp6s_outhist[ND_REDIRECT]);
2689 
2690 	return;
2691 
2692 fail:
2693 	if (m)
2694 		m_freem(m);
2695 	if (m0)
2696 		m_freem(m0);
2697 }
2698 
2699 /*
2700  * ICMPv6 socket option processing.
2701  */
2702 int
icmp6_ctloutput(struct socket * so,struct sockopt * sopt)2703 icmp6_ctloutput(struct socket *so, struct sockopt *sopt)
2704 {
2705 	int error = 0;
2706 	int optlen;
2707 	struct inpcb *inp = sotoinpcb(so);
2708 	int level, op, optname;
2709 
2710 	if (sopt) {
2711 		level = sopt->sopt_level;
2712 		op = sopt->sopt_dir;
2713 		optname = sopt->sopt_name;
2714 		optlen = sopt->sopt_valsize;
2715 	} else
2716 		level = op = optname = optlen = 0;
2717 
2718 	if (level != IPPROTO_ICMPV6) {
2719 		return EINVAL;
2720 	}
2721 
2722 	switch (op) {
2723 	case PRCO_SETOPT:
2724 		switch (optname) {
2725 		case ICMP6_FILTER:
2726 		    {
2727 			struct icmp6_filter ic6f;
2728 
2729 			if (optlen != sizeof(ic6f)) {
2730 				error = EMSGSIZE;
2731 				break;
2732 			}
2733 			error = sooptcopyin(sopt, &ic6f, optlen, optlen);
2734 			if (error == 0) {
2735 				INP_WLOCK(inp);
2736 				*inp->in6p_icmp6filt = ic6f;
2737 				INP_WUNLOCK(inp);
2738 			}
2739 			break;
2740 		    }
2741 
2742 		default:
2743 			error = ENOPROTOOPT;
2744 			break;
2745 		}
2746 		break;
2747 
2748 	case PRCO_GETOPT:
2749 		switch (optname) {
2750 		case ICMP6_FILTER:
2751 		    {
2752 			struct icmp6_filter ic6f;
2753 
2754 			INP_RLOCK(inp);
2755 			ic6f = *inp->in6p_icmp6filt;
2756 			INP_RUNLOCK(inp);
2757 			error = sooptcopyout(sopt, &ic6f, sizeof(ic6f));
2758 			break;
2759 		    }
2760 
2761 		default:
2762 			error = ENOPROTOOPT;
2763 			break;
2764 		}
2765 		break;
2766 	}
2767 
2768 	return (error);
2769 }
2770 
2771 SYSCTL_DECL(_net_inet6_icmp6);
2772 
2773 static int sysctl_icmp6lim_and_jitter(SYSCTL_HANDLER_ARGS);
2774 VNET_DEFINE_STATIC(u_int, icmp6errppslim) = 100;
2775 #define	V_icmp6errppslim	VNET(icmp6errppslim)
2776 SYSCTL_PROC(_net_inet6_icmp6, ICMPV6CTL_ERRPPSLIMIT, errppslimit,
2777     CTLTYPE_UINT | CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(icmp6errppslim), 0,
2778     &sysctl_icmp6lim_and_jitter, "IU",
2779     "Maximum number of ICMPv6 error/reply messages per second");
2780 
2781 typedef enum {
2782 	RATELIM_PARAM_PROB = 0,
2783 	RATELIM_TOO_BIG,
2784 	RATELIM_UNREACH,
2785 	RATELIM_TEXCEED,
2786 	RATELIM_REDIR,
2787 	RATELIM_REPLY,
2788 	RATELIM_OTHER,
2789 	RATELIM_MAX
2790 } ratelim_which;
2791 
2792 static const char *icmp6_rate_descrs[RATELIM_MAX] = {
2793 	[RATELIM_PARAM_PROB] = "bad IPv6 header",
2794 	[RATELIM_TOO_BIG] = "packet too big",
2795 	[RATELIM_UNREACH] = "destination unreachable",
2796 	[RATELIM_TEXCEED] = "time exceeded",
2797 	[RATELIM_REPLY] = "echo reply",
2798 	[RATELIM_REDIR] = "neighbor discovery redirect",
2799 	[RATELIM_OTHER] = "(other)",
2800 };
2801 
2802 VNET_DEFINE_STATIC(int, icmp6lim_curr_jitter[RATELIM_MAX]) = {0};
2803 #define	V_icmp6lim_curr_jitter	VNET(icmp6lim_curr_jitter)
2804 
2805 VNET_DEFINE_STATIC(u_int, icmp6lim_jitter) = 8;
2806 #define	V_icmp6lim_jitter	VNET(icmp6lim_jitter)
2807 SYSCTL_PROC(_net_inet6_icmp6, OID_AUTO, icmp6lim_jitter, CTLTYPE_UINT |
2808     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(icmp6lim_jitter), 0,
2809     &sysctl_icmp6lim_and_jitter, "IU",
2810     "Random errppslimit jitter adjustment limit");
2811 
2812 VNET_DEFINE_STATIC(int, icmp6lim_output) = 1;
2813 #define	V_icmp6lim_output	VNET(icmp6lim_output)
2814 SYSCTL_INT(_net_inet6_icmp6, OID_AUTO, icmp6lim_output,
2815     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(icmp6lim_output), 0,
2816     "Enable logging of ICMPv6 response rate limiting");
2817 
2818 static void
icmp6lim_new_jitter(int which)2819 icmp6lim_new_jitter(int which)
2820 {
2821 	/*
2822 	 * Adjust limit +/- to jitter the measurement to deny a side-channel
2823 	 * port scan as in https://dl.acm.org/doi/10.1145/3372297.3417280
2824 	 */
2825 	KASSERT(which >= 0 && which < RATELIM_MAX,
2826 	    ("%s: which %d", __func__, which));
2827 	if (V_icmp6lim_jitter > 0)
2828 		V_icmp6lim_curr_jitter[which] =
2829 		    arc4random_uniform(V_icmp6lim_jitter * 2 + 1) -
2830 		    V_icmp6lim_jitter;
2831 }
2832 
2833 static int
sysctl_icmp6lim_and_jitter(SYSCTL_HANDLER_ARGS)2834 sysctl_icmp6lim_and_jitter(SYSCTL_HANDLER_ARGS)
2835 {
2836 	uint32_t new;
2837 	int error;
2838 	bool lim;
2839 
2840 	MPASS(oidp->oid_arg1 == &VNET_NAME(icmp6errppslim) ||
2841 	    oidp->oid_arg1 == &VNET_NAME(icmp6lim_jitter));
2842 
2843 	lim = (oidp->oid_arg1 == &VNET_NAME(icmp6errppslim));
2844 	new = lim ? V_icmp6errppslim : V_icmp6lim_jitter;
2845 	error = sysctl_handle_int(oidp, &new, 0, req);
2846 	if (error == 0 && req->newptr) {
2847 		if (lim) {
2848 			if (new != 0 && new <= V_icmp6lim_jitter)
2849 				error = EINVAL;
2850 			else
2851 				V_icmp6errppslim = new;
2852 		} else {
2853 			if (new >= V_icmp6errppslim)
2854 				error = EINVAL;
2855 			else {
2856 				V_icmp6lim_jitter = new;
2857 				for (int i = 0; i < RATELIM_MAX; i++) {
2858 					icmp6lim_new_jitter(i);
2859 				}
2860 			}
2861 		}
2862 	}
2863 	MPASS(V_icmp6errppslim == 0 || V_icmp6errppslim > V_icmp6lim_jitter);
2864 
2865 	return (error);
2866 }
2867 
2868 
2869 VNET_DEFINE_STATIC(struct counter_rate, icmp6_rates[RATELIM_MAX]);
2870 #define	V_icmp6_rates	VNET(icmp6_rates)
2871 
2872 static void
icmp6_ratelimit_init(void)2873 icmp6_ratelimit_init(void)
2874 {
2875 
2876 	for (int i = 0; i < RATELIM_MAX; i++) {
2877 		V_icmp6_rates[i].cr_rate = counter_u64_alloc(M_WAITOK);
2878 		V_icmp6_rates[i].cr_ticks = ticks;
2879 		icmp6lim_new_jitter(i);
2880 	}
2881 }
2882 VNET_SYSINIT(icmp6_ratelimit, SI_SUB_PROTO_DOMAIN, SI_ORDER_ANY,
2883     icmp6_ratelimit_init, NULL);
2884 
2885 #ifdef VIMAGE
2886 static void
icmp6_ratelimit_uninit(void)2887 icmp6_ratelimit_uninit(void)
2888 {
2889 
2890 	for (int i = 0; i < RATELIM_MAX; i++)
2891 		counter_u64_free(V_icmp6_rates[i].cr_rate);
2892 }
2893 VNET_SYSUNINIT(icmp6_ratelimit, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD,
2894     icmp6_ratelimit_uninit, NULL);
2895 #endif
2896 
2897 /*
2898  * Perform rate limit check.
2899  * Returns 0 if it is okay to send the icmp6 packet.
2900  * Returns 1 if the router SHOULD NOT send this icmp6 packet due to rate
2901  * limitation.
2902  *
2903  * XXX per-destination/type check necessary?
2904  *
2905  * dst - not used at this moment
2906  * code - not used at this moment
2907  */
2908 static int
icmp6_ratelimit(const struct in6_addr * dst,const int type,const int code)2909 icmp6_ratelimit(const struct in6_addr *dst, const int type, const int code)
2910 {
2911 	ratelim_which which;
2912 	int64_t pps;
2913 
2914 	if (V_icmp6errppslim == 0)
2915 		return (0);
2916 
2917 	switch (type) {
2918 	case ICMP6_PARAM_PROB:
2919 		which = RATELIM_PARAM_PROB;
2920 		break;
2921 	case ICMP6_PACKET_TOO_BIG:
2922 		which = RATELIM_TOO_BIG;
2923 		break;
2924 	case ICMP6_DST_UNREACH:
2925 		which = RATELIM_UNREACH;
2926 		break;
2927 	case ICMP6_TIME_EXCEEDED:
2928 		which = RATELIM_TEXCEED;
2929 		break;
2930 	case ND_REDIRECT:
2931 		which = RATELIM_REDIR;
2932 		break;
2933 	case ICMP6_ECHO_REPLY:
2934 		which = RATELIM_REPLY;
2935 		break;
2936 	default:
2937 		which = RATELIM_OTHER;
2938 		break;
2939 	};
2940 
2941 	pps = counter_ratecheck(&V_icmp6_rates[which], V_icmp6errppslim +
2942 	    V_icmp6lim_curr_jitter[which]);
2943 	if (pps > 0) {
2944 		if (V_icmp6lim_output)
2945 			log(LOG_NOTICE, "Limiting ICMPv6 %s output from %jd "
2946 			    "to %d packets/sec\n", icmp6_rate_descrs[which],
2947 			    (intmax_t )pps, V_icmp6errppslim +
2948 			    V_icmp6lim_curr_jitter[which]);
2949 		icmp6lim_new_jitter(which);
2950 	}
2951 	if (pps == -1) {
2952 		ICMP6STAT_INC(icp6s_toofreq);
2953 		return (-1);
2954 	}
2955 
2956 	return (0);
2957 }
2958