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