xref: /xnu-8796.101.5/bsd/netinet6/icmp6.c (revision aca3beaa3dfbd42498b42c5e5ce20a938e6554e5)
1 /*
2  * Copyright (c) 2000-2022 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 
29 /*	$FreeBSD: src/sys/netinet6/icmp6.c,v 1.6.2.6 2001/07/10 09:44:16 ume Exp $	*/
30 /*	$KAME: icmp6.c,v 1.211 2001/04/04 05:56:20 itojun Exp $	*/
31 
32 /*
33  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
34  * All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in the
43  *    documentation and/or other materials provided with the distribution.
44  * 3. Neither the name of the project nor the names of its contributors
45  *    may be used to endorse or promote products derived from this software
46  *    without specific prior written permission.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  */
60 
61 /*
62  * Copyright (c) 1982, 1986, 1988, 1993
63  *	The Regents of the University of California.  All rights reserved.
64  *
65  * Redistribution and use in source and binary forms, with or without
66  * modification, are permitted provided that the following conditions
67  * are met:
68  * 1. Redistributions of source code must retain the above copyright
69  *    notice, this list of conditions and the following disclaimer.
70  * 2. Redistributions in binary form must reproduce the above copyright
71  *    notice, this list of conditions and the following disclaimer in the
72  *    documentation and/or other materials provided with the distribution.
73  * 3. All advertising materials mentioning features or use of this software
74  *    must display the following acknowledgement:
75  *	This product includes software developed by the University of
76  *	California, Berkeley and its contributors.
77  * 4. Neither the name of the University nor the names of its contributors
78  *    may be used to endorse or promote products derived from this software
79  *    without specific prior written permission.
80  *
81  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
82  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
83  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
84  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
85  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
86  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
87  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
88  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
89  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
90  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
91  * SUCH DAMAGE.
92  *
93  *	@(#)ip_icmp.c	8.2 (Berkeley) 1/4/94
94  */
95 
96 
97 #include <sys/param.h>
98 #include <sys/systm.h>
99 #include <sys/lock.h>
100 #include <sys/malloc.h>
101 #include <sys/mcache.h>
102 #include <sys/mbuf.h>
103 #include <sys/protosw.h>
104 #include <sys/socket.h>
105 #include <sys/socketvar.h>
106 #include <sys/time.h>
107 #include <sys/kernel.h>
108 #include <sys/syslog.h>
109 #include <sys/domain.h>
110 #include <sys/kauth.h>
111 
112 #include <net/if.h>
113 #include <net/route.h>
114 #include <net/if_dl.h>
115 #include <net/if_types.h>
116 
117 #include <netinet/in.h>
118 #include <netinet/in_var.h>
119 #include <netinet/ip6.h>
120 #include <netinet6/ip6_var.h>
121 #include <netinet/icmp6.h>
122 #include <netinet6/mld6_var.h>
123 #include <netinet/in_pcb.h>
124 #include <netinet6/in6_pcb.h>
125 #include <netinet6/in6_var.h>
126 #include <netinet6/nd6.h>
127 #include <netinet6/in6_ifattach.h>
128 #include <netinet6/ip6protosw.h>
129 #include <netinet6/scope6_var.h>
130 
131 #if IPSEC
132 #include <netinet6/ipsec.h>
133 #include <netkey/key.h>
134 #endif
135 
136 #include <net/net_osdep.h>
137 
138 #if NECP
139 #include <net/necp.h>
140 #endif
141 
142 extern struct ip6protosw *ip6_protox[];
143 
144 extern uint32_t rip_sendspace;
145 extern uint32_t rip_recvspace;
146 
147 struct icmp6stat icmp6stat;
148 
149 extern struct inpcbhead ripcb;
150 extern int icmp6errppslim;
151 extern int icmp6errppslim_random_incr;
152 extern int icmp6rappslim;
153 static int icmp6errpps_count = 0;
154 static int icmp6rapps_count = 0;
155 static struct timeval icmp6errppslim_last;
156 static struct timeval icmp6rappslim_last;
157 extern int icmp6_nodeinfo;
158 extern struct inpcbinfo ripcbinfo;
159 
160 static void icmp6_errcount(struct icmp6errstat *, int, int);
161 static int icmp6_rip6_input(struct mbuf **, int);
162 static int icmp6_ratelimit(const struct in6_addr *, const int, const int);
163 static const char *icmp6_redirect_diag(struct in6_addr *,
164     struct in6_addr *, struct in6_addr *);
165 static struct mbuf *ni6_input(struct mbuf *, int);
166 static struct mbuf *ni6_nametodns(const char *, uint32_t, int);
167 static int ni6_dnsmatch(const char *, int, const char *, int);
168 static int ni6_addrs(struct icmp6_nodeinfo *,
169     struct ifnet **, char *);
170 static int ni6_store_addrs(struct icmp6_nodeinfo *, struct icmp6_nodeinfo *,
171     struct ifnet *, int);
172 static int icmp6_notify_error(struct mbuf *, int, int, int);
173 
174 
175 
176 void
icmp6_init(struct ip6protosw * pp,struct domain * dp)177 icmp6_init(struct ip6protosw *pp, struct domain *dp)
178 {
179 #pragma unused(dp)
180 	static int icmp6_initialized = 0;
181 
182 	/* Also called from ip6_init() without pp */
183 	VERIFY(pp == NULL ||
184 	    (pp->pr_flags & (PR_INITIALIZED | PR_ATTACHED)) == PR_ATTACHED);
185 
186 	/* This gets called by more than one protocols, so initialize once */
187 	if (!icmp6_initialized) {
188 		icmp6_initialized = 1;
189 		mld_init();
190 		if (icmp6errppslim >= 0 &&
191 		    icmp6errppslim_random_incr > 0 &&
192 		    icmp6errppslim <= INT32_MAX - (icmp6errppslim_random_incr + 1)) {
193 			icmp6errppslim += (random() % icmp6errppslim_random_incr) + 1;
194 		}
195 	}
196 }
197 
198 static void
icmp6_errcount(struct icmp6errstat * stat,int type,int code)199 icmp6_errcount(struct icmp6errstat *stat, int type, int code)
200 {
201 	switch (type) {
202 	case ICMP6_DST_UNREACH:
203 		switch (code) {
204 		case ICMP6_DST_UNREACH_NOROUTE:
205 			stat->icp6errs_dst_unreach_noroute++;
206 			return;
207 		case ICMP6_DST_UNREACH_ADMIN:
208 			stat->icp6errs_dst_unreach_admin++;
209 			return;
210 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
211 			stat->icp6errs_dst_unreach_beyondscope++;
212 			return;
213 		case ICMP6_DST_UNREACH_ADDR:
214 			stat->icp6errs_dst_unreach_addr++;
215 			return;
216 		case ICMP6_DST_UNREACH_NOPORT:
217 			stat->icp6errs_dst_unreach_noport++;
218 			return;
219 		}
220 		break;
221 	case ICMP6_PACKET_TOO_BIG:
222 		stat->icp6errs_packet_too_big++;
223 		return;
224 	case ICMP6_TIME_EXCEEDED:
225 		switch (code) {
226 		case ICMP6_TIME_EXCEED_TRANSIT:
227 			stat->icp6errs_time_exceed_transit++;
228 			return;
229 		case ICMP6_TIME_EXCEED_REASSEMBLY:
230 			stat->icp6errs_time_exceed_reassembly++;
231 			return;
232 		}
233 		break;
234 	case ICMP6_PARAM_PROB:
235 		switch (code) {
236 		case ICMP6_PARAMPROB_HEADER:
237 			stat->icp6errs_paramprob_header++;
238 			return;
239 		case ICMP6_PARAMPROB_NEXTHEADER:
240 			stat->icp6errs_paramprob_nextheader++;
241 			return;
242 		case ICMP6_PARAMPROB_OPTION:
243 			stat->icp6errs_paramprob_option++;
244 			return;
245 		}
246 		break;
247 	case ND_REDIRECT:
248 		stat->icp6errs_redirect++;
249 		return;
250 	}
251 	stat->icp6errs_unknown++;
252 }
253 
254 /*
255  * Generate packet gencount for ICMPv6 for a given error type
256  * and code.
257  */
258 static uint32_t
icmp6_error_packet_gencount(int type,int code)259 icmp6_error_packet_gencount(int type, int code)
260 {
261 	return (PF_INET6 << 24) | (type << 16) | (code << 8);
262 }
263 
264 static int suppress_icmp6_port_unreach = 0;
265 
266 SYSCTL_DECL(_net_inet6_icmp6);
267 SYSCTL_INT(_net_inet6_icmp6, OID_AUTO, suppress_icmp6_port_unreach, CTLFLAG_RW | CTLFLAG_LOCKED,
268     &suppress_icmp6_port_unreach, 0,
269     "Suppress ICMPv6 destination unreachable type with code port unreachable");
270 
271 /*
272  * Generate an error packet of type error in response to bad IP6 packet.
273  */
274 void
icmp6_error(struct mbuf * m,int type,int code,int param)275 icmp6_error(struct mbuf *m, int type, int code, int param)
276 {
277 	icmp6_error_flag(m, type, code, param, ICMP6_ERROR_RST_MRCVIF);
278 }
279 
280 void
icmp6_error_flag(struct mbuf * m,int type,int code,int param,int flags)281 icmp6_error_flag(struct mbuf *m, int type, int code, int param, int flags)
282 {
283 	struct ip6_hdr *oip6, *nip6;
284 	struct icmp6_hdr *icmp6;
285 	u_int preplen;
286 	int off;
287 
288 	icmp6stat.icp6s_error++;
289 
290 	/* count per-type-code statistics */
291 	icmp6_errcount(&icmp6stat.icp6s_outerrhist, type, code);
292 
293 	if (suppress_icmp6_port_unreach && type == ICMP6_DST_UNREACH &&
294 	    code == ICMP6_DST_UNREACH_NOPORT) {
295 		goto freeit;
296 	}
297 
298 #ifdef M_DECRYPTED      /*not openbsd*/
299 	if (m->m_flags & M_DECRYPTED) {
300 		icmp6stat.icp6s_canterror++;
301 		goto freeit;
302 	}
303 #endif
304 
305 #ifndef PULLDOWN_TEST
306 	IP6_EXTHDR_CHECK(m, 0, sizeof(struct ip6_hdr), return );
307 #else
308 	if (m->m_len < sizeof(struct ip6_hdr)) {
309 		m = m_pullup(m, sizeof(struct ip6_hdr));
310 		if (m == NULL) {
311 			return;
312 		}
313 	}
314 #endif
315 	oip6 = mtod(m, struct ip6_hdr *);
316 
317 	/*
318 	 * If the destination address of the erroneous packet is a multicast
319 	 * address, or the packet was sent using link-layer multicast,
320 	 * we should basically suppress sending an error (RFC 2463, Section
321 	 * 2.4).
322 	 * We have two exceptions (the item e.2 in that section):
323 	 * - the Pakcet Too Big message can be sent for path MTU discovery.
324 	 * - the Parameter Problem Message that can be allowed an icmp6 error
325 	 *   in the option type field.  This check has been done in
326 	 *   ip6_unknown_opt(), so we can just check the type and code.
327 	 */
328 	if ((m->m_flags & (M_BCAST | M_MCAST) ||
329 	    IN6_IS_ADDR_MULTICAST(&oip6->ip6_dst)) &&
330 	    (type != ICMP6_PACKET_TOO_BIG &&
331 	    (type != ICMP6_PARAM_PROB ||
332 	    code != ICMP6_PARAMPROB_OPTION))) {
333 		goto freeit;
334 	}
335 
336 	/*
337 	 * RFC 2463, 2.4 (e.5): source address check.
338 	 * XXX: the case of anycast source?
339 	 */
340 	if (IN6_IS_ADDR_UNSPECIFIED(&oip6->ip6_src) ||
341 	    IN6_IS_ADDR_MULTICAST(&oip6->ip6_src)) {
342 		goto freeit;
343 	}
344 
345 	/*
346 	 * If we are about to send ICMPv6 against ICMPv6 error/redirect,
347 	 * don't do it.
348 	 *
349 	 * We want to check for that for all ICMP error types, other than
350 	 * ICMP6_PARAM_PROB when it is being sent in response of first frag
351 	 * with incomplete header.
352 	 * That also includes the case when the first frag has incomplete ICMPv6
353 	 * header. The check below in that case would fail the IP6_EXTHDR_CHECK
354 	 * and would otherwise prevent us from sending the error back.
355 	 */
356 	if (type != ICMP6_PARAM_PROB ||
357 	    code != ICMP6_PARAMPROB_FIRSTFRAG_INCOMP_HDR) {
358 		int nxt = -1;
359 		off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
360 		if (off >= 0 && nxt == IPPROTO_ICMPV6) {
361 			struct icmp6_hdr *icp;
362 
363 #ifndef PULLDOWN_TEST
364 			IP6_EXTHDR_CHECK(m, 0, off + sizeof(struct icmp6_hdr), return );
365 			icp = (struct icmp6_hdr *)(mtod(m, caddr_t) + off);
366 #else
367 			IP6_EXTHDR_GET(icp, struct icmp6_hdr *, m, off,
368 			    sizeof(*icp));
369 			if (icp == NULL) {
370 				icmp6stat.icp6s_tooshort++;
371 				return;
372 			}
373 #endif
374 			if (icp->icmp6_type < ICMP6_ECHO_REQUEST ||
375 			    icp->icmp6_type == ND_REDIRECT) {
376 				/*
377 				 * ICMPv6 error
378 				 * Special case: for redirect (which is
379 				 * informational) we must not send icmp6 error.
380 				 */
381 				icmp6stat.icp6s_canterror++;
382 				goto freeit;
383 			} else {
384 				/* ICMPv6 informational - send the error */
385 			}
386 		} else {
387 			/* non-ICMPv6 - send the error */
388 		}
389 	}
390 
391 	oip6 = mtod(m, struct ip6_hdr *); /* adjust pointer */
392 
393 	/*
394 	 * OK, ICMP6 can be generated.
395 	 */
396 
397 	if (m->m_pkthdr.len >= ICMPV6_PLD_MAXLEN) {
398 		m_adj(m, ICMPV6_PLD_MAXLEN - m->m_pkthdr.len);
399 	}
400 
401 	/*
402 	 * To avoid some flavors of port scanning and other attacks,
403 	 * use packet suppression without using any other sort of
404 	 * rate limiting with static bounds.
405 	 * XXX Not setting PKTF_FLOW_ID here because we were concerned
406 	 * about it triggering regression elsewhere outside of network stack
407 	 * where there might be an assumption around flow ID being non-zero.
408 	 * It should be noted though that previously if PKTF_FLOW_ID was not
409 	 * set, PF would have generated flow hash irrespective of ICMPv4/v6
410 	 * type. That doesn't happen now and PF only computes hash for ICMP
411 	 * types that need state creation (which is not true of error types).
412 	 * It would have been a problem because we really want all the ICMP
413 	 * error type packets to share the same flow ID for global suppression.
414 	 */
415 	m->m_pkthdr.comp_gencnt = icmp6_error_packet_gencount(type, code);
416 
417 	preplen = sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr);
418 	M_PREPEND(m, preplen, M_DONTWAIT, 1);
419 	if (m == NULL) {
420 		nd6log(debug, "ENOBUFS in icmp6_error %d\n", __LINE__);
421 		return;
422 	}
423 
424 	nip6 = mtod(m, struct ip6_hdr *);
425 	nip6->ip6_src  = oip6->ip6_src;
426 	nip6->ip6_dst  = oip6->ip6_dst;
427 
428 	in6_clearscope(&oip6->ip6_src);
429 	in6_clearscope(&oip6->ip6_dst);
430 
431 	icmp6 = (struct icmp6_hdr *)(nip6 + 1);
432 	icmp6->icmp6_type = (uint8_t)type;
433 	icmp6->icmp6_code = (uint8_t)code;
434 	icmp6->icmp6_pptr = htonl((u_int32_t)param);
435 
436 	/*
437 	 * icmp6_reflect() is designed to be in the input path.
438 	 * icmp6_error() can be called from both input and output path,
439 	 * and if we are in output path rcvif could contain bogus value.
440 	 * clear m->m_pkthdr.rcvif for safety, we should have enough scope
441 	 * information in ip header (nip6).
442 	 */
443 	if (flags & ICMP6_ERROR_RST_MRCVIF) {
444 		m->m_pkthdr.rcvif = NULL;
445 	}
446 
447 	icmp6stat.icp6s_outhist[type]++;
448 	icmp6_reflect(m, sizeof(struct ip6_hdr)); /* header order: IPv6 - ICMPv6 */
449 
450 	return;
451 
452 freeit:
453 	/*
454 	 * If we can't tell whether or not we can generate ICMP6, free it.
455 	 */
456 	m_freem(m);
457 }
458 
459 /*
460  * Process a received ICMP6 message.
461  */
462 int
icmp6_input(struct mbuf ** mp,int * offp,int proto)463 icmp6_input(struct mbuf **mp, int *offp, int proto)
464 {
465 #pragma unused(proto)
466 	struct mbuf *m = *mp, *n;
467 	struct ifnet *ifp;
468 	struct ip6_hdr *ip6, *nip6;
469 	struct icmp6_hdr *icmp6, *nicmp6;
470 	int off = *offp;
471 	int icmp6len = m->m_pkthdr.len - *offp;
472 	int code, sum, noff, proxy = 0;
473 
474 	ifp = m->m_pkthdr.rcvif;
475 
476 #ifndef PULLDOWN_TEST
477 	IP6_EXTHDR_CHECK(m, off, sizeof(struct icmp6_hdr), return IPPROTO_DONE);
478 	/* m might change if M_LOOP.  So, call mtod after this */
479 #endif
480 
481 	/* Expect 32-bit aligned data pointer on strict-align platforms */
482 	MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
483 
484 	/*
485 	 * Locate icmp6 structure in mbuf, and check
486 	 * that not corrupted and of at least minimum length
487 	 */
488 	ip6 = mtod(m, struct ip6_hdr *);
489 	if (icmp6len < sizeof(struct icmp6_hdr)) {
490 		icmp6stat.icp6s_tooshort++;
491 		goto freeit;
492 	}
493 
494 #ifndef PULLDOWN_TEST
495 	icmp6 = (struct icmp6_hdr *)((caddr_t)ip6 + off);
496 #else
497 	IP6_EXTHDR_GET(icmp6, struct icmp6_hdr *, m, off, sizeof(*icmp6));
498 	if (icmp6 == NULL) {
499 		icmp6stat.icp6s_tooshort++;
500 		return IPPROTO_DONE;
501 	}
502 #endif
503 	code = icmp6->icmp6_code;
504 
505 	/*
506 	 * Early check for RFC 6980
507 	 * Drop certain NDP packets if they came in fragmented
508 	 */
509 	switch (icmp6->icmp6_type) {
510 	case ND_ROUTER_SOLICIT:
511 	case ND_ROUTER_ADVERT:
512 	case ND_NEIGHBOR_SOLICIT:
513 	case ND_NEIGHBOR_ADVERT:
514 	case ND_REDIRECT:
515 		if (m->m_pkthdr.pkt_flags & PKTF_REASSEMBLED) {
516 			icmp6stat.icp6s_rfc6980_drop++;
517 			goto freeit;
518 		}
519 		break;
520 	default:
521 		break;
522 	}
523 
524 	/* Apply rate limit before checksum validation. */
525 	if (icmp6_ratelimit(&ip6->ip6_dst, icmp6->icmp6_type, code)) {
526 		icmp6stat.icp6s_toofreq++;
527 		goto freeit;
528 	}
529 
530 	/*
531 	 * Check multicast group membership.
532 	 * Note: SSM filters are not applied for ICMPv6 traffic.
533 	 */
534 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
535 		struct in6_multi        *inm;
536 
537 		in6_multihead_lock_shared();
538 		IN6_LOOKUP_MULTI(&ip6->ip6_dst, ifp, inm);
539 		in6_multihead_lock_done();
540 
541 		if (inm == NULL) {
542 			/*
543 			 * Don't discard if this is a Neighbor Solicitation
544 			 * that needs to be proxied (see check down below.)
545 			 */
546 			if (!(m->m_pkthdr.pkt_flags & PKTF_PROXY_DST)) {
547 				ip6stat.ip6s_notmember++;
548 				in6_ifstat_inc(m->m_pkthdr.rcvif,
549 				    ifs6_in_discard);
550 				goto freeit;
551 			}
552 		} else {
553 			IN6M_REMREF(inm);
554 		}
555 	}
556 
557 	/*
558 	 * calculate the checksum
559 	 */
560 	if ((sum = in6_cksum(m, IPPROTO_ICMPV6, off, icmp6len)) != 0) {
561 		nd6log(error,
562 		    "ICMP6 checksum error(%d|%x) %s\n",
563 		    icmp6->icmp6_type, sum, ip6_sprintf(&ip6->ip6_src));
564 		icmp6stat.icp6s_checksum++;
565 		goto freeit;
566 	}
567 
568 	if (m->m_pkthdr.pkt_flags & PKTF_PROXY_DST) {
569 		/*
570 		 * This is the special case of proxying NS (dst is either
571 		 * solicited-node multicast or unicast); process it locally
572 		 * but don't deliver it to sockets.  It practically lets us
573 		 * steer the packet to nd6_prproxy_ns_input, where more
574 		 * specific tests and actions will be taken.
575 		 */
576 		switch (icmp6->icmp6_type) {
577 		case ND_NEIGHBOR_SOLICIT:
578 			proxy = 1;
579 			break;
580 		default:
581 			goto freeit;
582 		}
583 	}
584 
585 	icmp6stat.icp6s_inhist[icmp6->icmp6_type]++;
586 	icmp6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_msg);
587 	if (icmp6->icmp6_type < ICMP6_INFOMSG_MASK) {
588 		icmp6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_error);
589 	}
590 
591 	switch (icmp6->icmp6_type) {
592 	case ICMP6_DST_UNREACH:
593 		icmp6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_dstunreach);
594 		switch (code) {
595 		case ICMP6_DST_UNREACH_NOROUTE:
596 		case ICMP6_DST_UNREACH_ADDR:    /* PRC_HOSTDEAD is a DOS */
597 			code = PRC_UNREACH_NET;
598 			break;
599 		case ICMP6_DST_UNREACH_ADMIN:
600 			icmp6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_adminprohib);
601 			code = PRC_UNREACH_PROTOCOL; /* is this a good code? */
602 			break;
603 		case ICMP6_DST_UNREACH_BEYONDSCOPE:
604 			/* I mean "source address was incorrect." */
605 			code = PRC_PARAMPROB;
606 			break;
607 		case ICMP6_DST_UNREACH_NOPORT:
608 			code = PRC_UNREACH_PORT;
609 			break;
610 		default:
611 			goto badcode;
612 		}
613 		goto deliver;
614 
615 	case ICMP6_PACKET_TOO_BIG:
616 		icmp6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_pkttoobig);
617 		if (ntohl(icmp6->icmp6_mtu) < IPV6_MMTU) {
618 			icmp6stat.icp6s_badpkttoobig++;
619 			goto freeit;
620 		}
621 
622 		code = PRC_MSGSIZE;
623 
624 		/*
625 		 * Updating the path MTU will be done after examining
626 		 * intermediate extension headers.
627 		 */
628 		goto deliver;
629 
630 	case ICMP6_TIME_EXCEEDED:
631 		icmp6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_timeexceed);
632 		switch (code) {
633 		case ICMP6_TIME_EXCEED_TRANSIT:
634 			code = PRC_TIMXCEED_INTRANS;
635 			break;
636 		case ICMP6_TIME_EXCEED_REASSEMBLY:
637 			code = PRC_TIMXCEED_REASS;
638 			break;
639 		default:
640 			goto badcode;
641 		}
642 		goto deliver;
643 
644 	case ICMP6_PARAM_PROB:
645 		icmp6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_paramprob);
646 		switch (code) {
647 		case ICMP6_PARAMPROB_NEXTHEADER:
648 			code = PRC_UNREACH_PROTOCOL;
649 			break;
650 		case ICMP6_PARAMPROB_HEADER:
651 		case ICMP6_PARAMPROB_OPTION:
652 			code = PRC_PARAMPROB;
653 			break;
654 		default:
655 			goto badcode;
656 		}
657 		goto deliver;
658 
659 	case ICMP6_ECHO_REQUEST:
660 		icmp6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_echo);
661 		if (code != 0) {
662 			goto badcode;
663 		}
664 
665 		if ((n = m_copy(m, 0, M_COPYALL)) == NULL) {
666 			/* Give up remote */
667 			goto rate_limit_checked;
668 		}
669 		if ((n->m_flags & M_EXT) != 0
670 		    || n->m_len < off + sizeof(struct icmp6_hdr)) {
671 			struct mbuf *n0 = n;
672 			const int maxlen = sizeof(*nip6) + sizeof(*nicmp6);
673 
674 			/*
675 			 * Prepare an internal mbuf. m_pullup() doesn't
676 			 * always copy the length we specified.
677 			 */
678 			if (maxlen >= MCLBYTES) {
679 				/* Give up remote */
680 				m_freem(n0);
681 				goto rate_limit_checked;
682 			}
683 			MGETHDR(n, M_DONTWAIT, n0->m_type);     /* MAC-OK */
684 			if (n && maxlen >= MHLEN) {
685 				MCLGET(n, M_DONTWAIT);
686 				if ((n->m_flags & M_EXT) == 0) {
687 					m_free(n);
688 					n = NULL;
689 				}
690 			}
691 			if (n == NULL) {
692 				/* Give up remote */
693 				m_freem(n0);
694 				goto rate_limit_checked;
695 			}
696 			M_COPY_PKTHDR(n, n0);
697 			/*
698 			 * Copy IPv6 and ICMPv6 only.
699 			 */
700 			nip6 = mtod(n, struct ip6_hdr *);
701 			bcopy(ip6, nip6, sizeof(struct ip6_hdr));
702 			nicmp6 = (struct icmp6_hdr *)(nip6 + 1);
703 			bcopy(icmp6, nicmp6, sizeof(struct icmp6_hdr));
704 			noff = sizeof(struct ip6_hdr);
705 			n->m_pkthdr.len = n->m_len =
706 			    noff + sizeof(struct icmp6_hdr);
707 			/*
708 			 * Adjust mbuf. ip6_plen will be adjusted in
709 			 * ip6_output().
710 			 */
711 			m_adj(n0, off + sizeof(struct icmp6_hdr));
712 			n->m_pkthdr.len += n0->m_pkthdr.len;
713 			n->m_next = n0;
714 			n0->m_flags &= ~M_PKTHDR;
715 		} else {
716 			nip6 = mtod(n, struct ip6_hdr *);
717 			IP6_EXTHDR_GET(nicmp6, struct icmp6_hdr *, n, off,
718 			    sizeof(*nicmp6));
719 			noff = off;
720 		}
721 		if (nicmp6 == NULL) {
722 			panic("nicmp6 is NULL in %s, which isn't good!", __FUNCTION__);
723 		} else {
724 			nicmp6->icmp6_type = ICMP6_ECHO_REPLY;
725 			nicmp6->icmp6_code = 0;
726 		}
727 		if (n) {
728 			icmp6stat.icp6s_reflect++;
729 			icmp6stat.icp6s_outhist[ICMP6_ECHO_REPLY]++;
730 			icmp6_reflect(n, noff);
731 		}
732 		goto rate_limit_checked;
733 
734 	case ICMP6_ECHO_REPLY:
735 		icmp6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_echoreply);
736 		if (code != 0) {
737 			goto badcode;
738 		}
739 		break;
740 
741 	case MLD_LISTENER_QUERY:
742 	case MLD_LISTENER_REPORT:
743 
744 		if (icmp6len < sizeof(struct mld_hdr)) {
745 			goto badlen;
746 		}
747 		if (icmp6->icmp6_type == MLD_LISTENER_QUERY) { /* XXX: ugly... */
748 			icmp6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_mldquery);
749 		} else {
750 			icmp6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_mldreport);
751 		}
752 
753 		if ((n = m_copym(m, 0, M_COPYALL, M_DONTWAIT)) == NULL) {
754 			/* give up local */
755 			if (mld_input(m, off, icmp6len) == IPPROTO_DONE) {
756 				m = NULL;
757 			}
758 			goto freeit;
759 		}
760 		if (mld_input(n, off, icmp6len) != IPPROTO_DONE) {
761 			m_freem(n);
762 		}
763 		/* m stays. */
764 		goto rate_limit_checked;
765 
766 	case MLD_LISTENER_DONE:
767 		icmp6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_mlddone);
768 		if (icmp6len < sizeof(struct mld_hdr)) { /* necessary? */
769 			goto badlen;
770 		}
771 		break;          /* nothing to be done in kernel */
772 
773 	case MLD_MTRACE_RESP:
774 	case MLD_MTRACE:
775 		/* XXX: these two are experimental.  not officially defined. */
776 		/* XXX: per-interface statistics? */
777 		break;          /* just pass it to applications */
778 
779 	case ICMP6_NI_QUERY:
780 		if (!icmp6_nodeinfo) {
781 			break;
782 		}
783 //### LD 10/20 Check fbsd differences here. Not sure we're more advanced or not.
784 		/* By RFC 4620 refuse to answer queries from global scope addresses */
785 		if ((icmp6_nodeinfo & 8) != 8 && in6_addrscope(&ip6->ip6_src) == IPV6_ADDR_SCOPE_GLOBAL) {
786 			break;
787 		}
788 
789 		if (icmp6len < sizeof(struct icmp6_nodeinfo)) {
790 			goto badlen;
791 		}
792 
793 #ifndef PULLDOWN_TEST
794 		IP6_EXTHDR_CHECK(m, off, sizeof(struct icmp6_nodeinfo),
795 		    return IPPROTO_DONE);
796 #endif
797 
798 		n = m_copy(m, 0, M_COPYALL);
799 		if (n) {
800 			n = ni6_input(n, off);
801 		}
802 		if (n) {
803 			noff = sizeof(struct ip6_hdr);
804 			icmp6stat.icp6s_reflect++;
805 			icmp6stat.icp6s_outhist[ICMP6_WRUREPLY]++;
806 			icmp6_reflect(n, noff);
807 		}
808 		goto rate_limit_checked;
809 
810 	case ICMP6_WRUREPLY:
811 		if (code != 0) {
812 			goto badcode;
813 		}
814 		break;
815 
816 	case ND_ROUTER_SOLICIT:
817 		icmp6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_routersolicit);
818 		if (code != 0) {
819 			goto badcode;
820 		}
821 		if (icmp6len < sizeof(struct nd_router_solicit)) {
822 			goto badlen;
823 		}
824 
825 		if ((n = m_copym(m, 0, M_COPYALL, M_DONTWAIT)) == NULL) {
826 			/* give up local */
827 			nd6_rs_input(m, off, icmp6len);
828 			m = NULL;
829 			goto freeit;
830 		}
831 		nd6_rs_input(n, off, icmp6len);
832 		/* m stays. */
833 		goto rate_limit_checked;
834 
835 	case ND_ROUTER_ADVERT:
836 		icmp6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_routeradvert);
837 		if (code != 0) {
838 			goto badcode;
839 		}
840 		if (icmp6len < sizeof(struct nd_router_advert)) {
841 			goto badlen;
842 		}
843 
844 		if ((n = m_copym(m, 0, M_COPYALL, M_DONTWAIT)) == NULL) {
845 			/* give up local */
846 			nd6_ra_input(m, off, icmp6len);
847 			m = NULL;
848 			goto freeit;
849 		}
850 		nd6_ra_input(n, off, icmp6len);
851 		/* m stays. */
852 		goto rate_limit_checked;
853 
854 	case ND_NEIGHBOR_SOLICIT:
855 		icmp6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_neighborsolicit);
856 		if (code != 0) {
857 			goto badcode;
858 		}
859 		if (icmp6len < sizeof(struct nd_neighbor_solicit)) {
860 			goto badlen;
861 		}
862 
863 		if (proxy ||
864 		    ((n = m_copym(m, 0, M_COPYALL, M_DONTWAIT)) == NULL)) {
865 			/* give up local */
866 			nd6_ns_input(m, off, icmp6len);
867 			m = NULL;
868 			goto freeit;
869 		}
870 		nd6_ns_input(n, off, icmp6len);
871 		/* m stays. */
872 		goto rate_limit_checked;
873 
874 	case ND_NEIGHBOR_ADVERT:
875 		icmp6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_neighboradvert);
876 		if (code != 0) {
877 			goto badcode;
878 		}
879 		if (icmp6len < sizeof(struct nd_neighbor_advert)) {
880 			goto badlen;
881 		}
882 
883 		if ((n = m_copym(m, 0, M_COPYALL, M_DONTWAIT)) == NULL) {
884 			/* give up local */
885 			nd6_na_input(m, off, icmp6len);
886 			m = NULL;
887 			goto freeit;
888 		}
889 		nd6_na_input(n, off, icmp6len);
890 		/* m stays. */
891 		goto rate_limit_checked;
892 
893 	case ND_REDIRECT:
894 		icmp6_ifstat_inc(m->m_pkthdr.rcvif, ifs6_in_redirect);
895 		if (code != 0) {
896 			goto badcode;
897 		}
898 		if (icmp6len < sizeof(struct nd_redirect)) {
899 			goto badlen;
900 		}
901 
902 		if ((n = m_copym(m, 0, M_COPYALL, M_DONTWAIT)) == NULL) {
903 			/* give up local */
904 			icmp6_redirect_input(m, off, icmp6len);
905 			m = NULL;
906 			goto freeit;
907 		}
908 		icmp6_redirect_input(n, off, icmp6len);
909 		/* m stays. */
910 		goto rate_limit_checked;
911 
912 	case ICMP6_ROUTER_RENUMBERING:
913 		if (code != ICMP6_ROUTER_RENUMBERING_COMMAND &&
914 		    code != ICMP6_ROUTER_RENUMBERING_RESULT) {
915 			goto badcode;
916 		}
917 		if (icmp6len < sizeof(struct icmp6_router_renum)) {
918 			goto badlen;
919 		}
920 		break;
921 
922 	default:
923 		nd6log(debug,
924 		    "icmp6_input: unknown type %d(src=%s, dst=%s, ifid=%d)\n",
925 		    icmp6->icmp6_type, ip6_sprintf(&ip6->ip6_src),
926 		    ip6_sprintf(&ip6->ip6_dst),
927 		    m->m_pkthdr.rcvif ? m->m_pkthdr.rcvif->if_index : 0);
928 		if (icmp6->icmp6_type < ICMP6_ECHO_REQUEST) {
929 			/* ICMPv6 error: MUST deliver it by spec... */
930 			code = PRC_NCMDS;
931 			/* deliver */
932 		} else {
933 			/* ICMPv6 informational: MUST not deliver */
934 			goto rate_limit_checked;
935 		}
936 deliver:
937 		if (icmp6_notify_error(m, off, icmp6len, code)) {
938 			/* In this case, m should've been freed. */
939 			return IPPROTO_DONE;
940 		}
941 		break;
942 
943 badcode:
944 		icmp6stat.icp6s_badcode++;
945 		break;
946 
947 badlen:
948 		icmp6stat.icp6s_badlen++;
949 		break;
950 	}
951 
952 rate_limit_checked:
953 	icmp6_rip6_input(&m, *offp);
954 	return IPPROTO_DONE;
955 
956 freeit:
957 	m_freem(m);
958 	return IPPROTO_DONE;
959 }
960 
961 static int
icmp6_notify_error(struct mbuf * m,int off,int icmp6len,int code)962 icmp6_notify_error(struct mbuf *m, int off, int icmp6len, int code)
963 {
964 	struct icmp6_hdr *icmp6;
965 	struct ip6_hdr *eip6;
966 	u_int32_t notifymtu;
967 	struct sockaddr_in6 icmp6src, icmp6dst;
968 
969 	if (icmp6len < sizeof(struct icmp6_hdr) + sizeof(struct ip6_hdr)) {
970 		icmp6stat.icp6s_tooshort++;
971 		goto freeit;
972 	}
973 #ifndef PULLDOWN_TEST
974 	IP6_EXTHDR_CHECK(m, off,
975 	    sizeof(struct icmp6_hdr) + sizeof(struct ip6_hdr),
976 	    return -1);
977 	icmp6 = (struct icmp6_hdr *)(mtod(m, caddr_t) + off);
978 #else
979 	IP6_EXTHDR_GET(icmp6, struct icmp6_hdr *, m, off,
980 	    sizeof(*icmp6) + sizeof(struct ip6_hdr));
981 	if (icmp6 == NULL) {
982 		icmp6stat.icp6s_tooshort++;
983 		return -1;
984 	}
985 #endif
986 	eip6 = (struct ip6_hdr *)(icmp6 + 1);
987 	bzero(&icmp6dst, sizeof(icmp6dst));
988 
989 	/* Detect the upper level protocol */
990 	{
991 		void (*ctlfunc)(int, struct sockaddr *, void *, struct ifnet *);
992 		u_int8_t nxt = eip6->ip6_nxt;
993 		int eoff = off + sizeof(struct icmp6_hdr) +
994 		    sizeof(struct ip6_hdr);
995 		struct ip6ctlparam ip6cp;
996 		int icmp6type = icmp6->icmp6_type;
997 		struct ip6_frag *fh;
998 		struct ip6_rthdr *rth;
999 		struct ip6_rthdr0 *rth0;
1000 		int rthlen;
1001 
1002 		while (1) { /* XXX: should avoid infinite loop explicitly? */
1003 			struct ip6_ext *eh;
1004 
1005 			switch (nxt) {
1006 			case IPPROTO_HOPOPTS:
1007 			case IPPROTO_DSTOPTS:
1008 			case IPPROTO_AH:
1009 #ifndef PULLDOWN_TEST
1010 				IP6_EXTHDR_CHECK(m, 0,
1011 				    eoff + sizeof(struct ip6_ext), return -1);
1012 				eh = (struct ip6_ext *)(mtod(m, caddr_t)
1013 				    + eoff);
1014 #else
1015 				IP6_EXTHDR_GET(eh, struct ip6_ext *, m,
1016 				    eoff, sizeof(*eh));
1017 				if (eh == NULL) {
1018 					icmp6stat.icp6s_tooshort++;
1019 					return -1;
1020 				}
1021 #endif
1022 
1023 				if (nxt == IPPROTO_AH) {
1024 					eoff += (eh->ip6e_len + 2) << 2;
1025 				} else {
1026 					eoff += (eh->ip6e_len + 1) << 3;
1027 				}
1028 				nxt = eh->ip6e_nxt;
1029 				break;
1030 			case IPPROTO_ROUTING:
1031 				/*
1032 				 * When the erroneous packet contains a
1033 				 * routing header, we should examine the
1034 				 * header to determine the final destination.
1035 				 * Otherwise, we can't properly update
1036 				 * information that depends on the final
1037 				 * destination (e.g. path MTU).
1038 				 */
1039 #ifndef PULLDOWN_TEST
1040 				IP6_EXTHDR_CHECK(m, 0, eoff + sizeof(*rth),
1041 				    return -1);
1042 				rth = (struct ip6_rthdr *)
1043 				    (mtod(m, caddr_t) + eoff);
1044 #else
1045 				IP6_EXTHDR_GET(rth, struct ip6_rthdr *, m,
1046 				    eoff, sizeof(*rth));
1047 				if (rth == NULL) {
1048 					icmp6stat.icp6s_tooshort++;
1049 					return -1;
1050 				}
1051 #endif
1052 				rthlen = (rth->ip6r_len + 1) << 3;
1053 				/*
1054 				 * XXX: currently there is no
1055 				 * officially defined type other
1056 				 * than type-0.
1057 				 * Note that if the segment left field
1058 				 * is 0, all intermediate hops must
1059 				 * have been passed.
1060 				 */
1061 				if (rth->ip6r_segleft &&
1062 				    rth->ip6r_type == IPV6_RTHDR_TYPE_0) {
1063 					int hops;
1064 
1065 #ifndef PULLDOWN_TEST
1066 					IP6_EXTHDR_CHECK(m, 0, eoff + rthlen,
1067 					    return -1);
1068 					rth0 = (struct ip6_rthdr0 *)(mtod(m, caddr_t) + eoff);
1069 #else
1070 					IP6_EXTHDR_GET(rth0,
1071 					    struct ip6_rthdr0 *, m,
1072 					    eoff, rthlen);
1073 					if (rth0 == NULL) {
1074 						icmp6stat.icp6s_tooshort++;
1075 						return -1;
1076 					}
1077 #endif
1078 					/* just ignore a bogus header */
1079 					if ((rth0->ip6r0_len % 2) == 0 &&
1080 					    (hops = rth0->ip6r0_len / 2)) {
1081 						icmp6dst.sin6_addr = *((struct in6_addr *)(void *)(rth0 + 1) + (hops - 1));
1082 					}
1083 				}
1084 				eoff += rthlen;
1085 				nxt = rth->ip6r_nxt;
1086 				break;
1087 			case IPPROTO_FRAGMENT:
1088 #ifndef PULLDOWN_TEST
1089 				IP6_EXTHDR_CHECK(m, 0, eoff +
1090 				    sizeof(struct ip6_frag),
1091 				    return -1);
1092 				fh = (struct ip6_frag *)(mtod(m, caddr_t)
1093 				    + eoff);
1094 #else
1095 				IP6_EXTHDR_GET(fh, struct ip6_frag *, m,
1096 				    eoff, sizeof(*fh));
1097 				if (fh == NULL) {
1098 					icmp6stat.icp6s_tooshort++;
1099 					return -1;
1100 				}
1101 #endif
1102 				/*
1103 				 * Data after a fragment header is meaningless
1104 				 * unless it is the first fragment, but
1105 				 * we'll go to the notify label for path MTU
1106 				 * discovery.
1107 				 */
1108 				if (fh->ip6f_offlg & IP6F_OFF_MASK) {
1109 					goto notify;
1110 				}
1111 
1112 				eoff += sizeof(struct ip6_frag);
1113 				nxt = fh->ip6f_nxt;
1114 				break;
1115 			default:
1116 				/*
1117 				 * This case includes ESP and the No Next
1118 				 * Header.  In such cases going to the notify
1119 				 * label does not have any meaning
1120 				 * (i.e. ctlfunc will be NULL), but we go
1121 				 * anyway since we might have to update
1122 				 * path MTU information.
1123 				 */
1124 				goto notify;
1125 			}
1126 		}
1127 notify:
1128 #ifndef PULLDOWN_TEST
1129 		icmp6 = (struct icmp6_hdr *)(mtod(m, caddr_t) + off);
1130 #else
1131 		IP6_EXTHDR_GET(icmp6, struct icmp6_hdr *, m, off,
1132 		    sizeof(*icmp6) + sizeof(struct ip6_hdr));
1133 		if (icmp6 == NULL) {
1134 			icmp6stat.icp6s_tooshort++;
1135 			return -1;
1136 		}
1137 #endif
1138 
1139 		/*
1140 		 * retrieve parameters from the inner IPv6 header, and convert
1141 		 * them into sockaddr structures.
1142 		 * XXX: there is no guarantee that the source or destination
1143 		 * addresses of the inner packet are in the same scope as
1144 		 * the addresses of the icmp packet.  But there is no other
1145 		 * way to determine the zone.
1146 		 */
1147 		eip6 = (struct ip6_hdr *)(icmp6 + 1);
1148 
1149 		icmp6dst.sin6_len = sizeof(struct sockaddr_in6);
1150 		icmp6dst.sin6_family = AF_INET6;
1151 		if (IN6_IS_ADDR_UNSPECIFIED(&icmp6dst.sin6_addr)) {
1152 			icmp6dst.sin6_addr = eip6->ip6_dst;
1153 		}
1154 		if (in6_setscope(&icmp6dst.sin6_addr, m->m_pkthdr.rcvif, IN6_NULL_IF_EMBEDDED_SCOPE(&icmp6dst.sin6_scope_id))) {
1155 			goto freeit;
1156 		}
1157 		bzero(&icmp6src, sizeof(icmp6src));
1158 		icmp6src.sin6_len = sizeof(struct sockaddr_in6);
1159 		icmp6src.sin6_family = AF_INET6;
1160 		icmp6src.sin6_addr = eip6->ip6_src;
1161 		if (in6_setscope(&icmp6src.sin6_addr, m->m_pkthdr.rcvif, IN6_NULL_IF_EMBEDDED_SCOPE(&icmp6dst.sin6_scope_id))) {
1162 			goto freeit;
1163 		}
1164 		icmp6src.sin6_flowinfo =
1165 		    (eip6->ip6_flow & IPV6_FLOWLABEL_MASK);
1166 
1167 		ip6cp.ip6c_m = m;
1168 		ip6cp.ip6c_icmp6 = icmp6;
1169 		ip6cp.ip6c_ip6 = (struct ip6_hdr *)(icmp6 + 1);
1170 		ip6cp.ip6c_off = eoff;
1171 		ip6cp.ip6c_finaldst = &icmp6dst.sin6_addr;
1172 		ip6cp.ip6c_src = &icmp6src;
1173 		ip6cp.ip6c_nxt = nxt;
1174 
1175 		if (icmp6type == ICMP6_PACKET_TOO_BIG) {
1176 			notifymtu = ntohl(icmp6->icmp6_mtu);
1177 			ip6cp.ip6c_cmdarg = (void *)&notifymtu;
1178 			icmp6_mtudisc_update(&ip6cp, 1);        /*XXX*/
1179 		}
1180 
1181 		ctlfunc = ip6_protox[nxt]->pr_ctlinput;
1182 		if (ctlfunc) {
1183 			LCK_MTX_ASSERT(inet6_domain_mutex, LCK_MTX_ASSERT_OWNED);
1184 
1185 			lck_mtx_unlock(inet6_domain_mutex);
1186 
1187 			(void) (*ctlfunc)(code, (struct sockaddr *)&icmp6dst,
1188 			    &ip6cp, m->m_pkthdr.rcvif);
1189 
1190 			lck_mtx_lock(inet6_domain_mutex);
1191 		}
1192 	}
1193 	return 0;
1194 
1195 freeit:
1196 	m_freem(m);
1197 	return -1;
1198 }
1199 
1200 void
icmp6_mtudisc_update(struct ip6ctlparam * ip6cp,int validated)1201 icmp6_mtudisc_update(struct ip6ctlparam *ip6cp, int validated)
1202 {
1203 	struct in6_addr *dst = ip6cp->ip6c_finaldst;
1204 	struct icmp6_hdr *icmp6 = ip6cp->ip6c_icmp6;
1205 	struct mbuf *m = ip6cp->ip6c_m; /* will be necessary for scope issue */
1206 	u_int mtu = ntohl(icmp6->icmp6_mtu);
1207 	struct rtentry *rt = NULL;
1208 	struct sockaddr_in6 sin6;
1209 	/*
1210 	 * we reject ICMPv6 too big with abnormally small value.
1211 	 * XXX what is the good definition of "abnormally small"?
1212 	 */
1213 	if (mtu < sizeof(struct ip6_hdr) + sizeof(struct ip6_frag) + 8) {
1214 		return;
1215 	}
1216 
1217 	if (!validated) {
1218 		return;
1219 	}
1220 
1221 	/* Limit the MTU to the minimum IPv6 MTU */
1222 	if (mtu < IPV6_MMTU) {
1223 		mtu = IPV6_MMTU;
1224 	}
1225 
1226 	bzero(&sin6, sizeof(sin6));
1227 	sin6.sin6_family = PF_INET6;
1228 	sin6.sin6_len = sizeof(struct sockaddr_in6);
1229 	sin6.sin6_addr = *dst;
1230 	/* XXX normally, this won't happen */
1231 	if (in6_embedded_scope && IN6_IS_ADDR_LINKLOCAL(dst)) {
1232 		sin6.sin6_addr.s6_addr16[1] =
1233 		    htons(m->m_pkthdr.rcvif->if_index);
1234 	}
1235 	/* sin6.sin6_scope_id = XXX: should be set if DST is a scoped addr */
1236 	/*
1237 	 * XXX On a side note, for asymmetric data-path
1238 	 * the lookup on receive interace is probably not
1239 	 * what we want to do.
1240 	 * That requires looking at the cached route for the
1241 	 * protocol control block.
1242 	 */
1243 	rt = rtalloc1_scoped((struct sockaddr *)&sin6, 0,
1244 	    RTF_CLONING | RTF_PRCLONING, m->m_pkthdr.rcvif->if_index);
1245 	if (rt != NULL) {
1246 		RT_LOCK(rt);
1247 		if ((rt->rt_flags & RTF_HOST) &&
1248 		    !(rt->rt_rmx.rmx_locks & RTV_MTU) &&
1249 		    mtu < IN6_LINKMTU(rt->rt_ifp) &&
1250 		    rt->rt_rmx.rmx_mtu > mtu) {
1251 			icmp6stat.icp6s_pmtuchg++;
1252 			rt->rt_rmx.rmx_mtu = mtu;
1253 		}
1254 		RT_UNLOCK(rt);
1255 		rtfree(rt);
1256 	}
1257 }
1258 
1259 /*
1260  * Process a Node Information Query packet, based on
1261  * draft-ietf-ipngwg-icmp-name-lookups-07.
1262  *
1263  * Spec incompatibilities:
1264  * - IPv6 Subject address handling
1265  * - IPv4 Subject address handling support missing
1266  * - Proxy reply (answer even if it's not for me)
1267  * - joins NI group address at in6_ifattach() time only, does not cope
1268  *   with hostname changes by sethostname(3)
1269  */
1270 #define hostnamelen     (uint32_t)strlen(hostname)
1271 static struct mbuf *
ni6_input(struct mbuf * m,int off)1272 ni6_input(struct mbuf *m, int off)
1273 {
1274 	struct icmp6_nodeinfo *ni6, *nni6;
1275 	struct mbuf *n = NULL;
1276 	u_int16_t qtype;
1277 	int subjlen;
1278 	int replylen = sizeof(struct ip6_hdr) + sizeof(struct icmp6_nodeinfo);
1279 	struct ni_reply_fqdn *fqdn;
1280 	int addrs;              /* for NI_QTYPE_NODEADDR */
1281 	struct ifnet *ifp = NULL; /* for NI_QTYPE_NODEADDR */
1282 	struct sockaddr_in6 sin6; /* double meaning; ip6_dst and subjectaddr */
1283 	struct sockaddr_in6 sin6_d; /* XXX: we should retrieve this from m_aux */
1284 	struct ip6_hdr *ip6;
1285 	int oldfqdn = 0;        /* if 1, return pascal string (03 draft) */
1286 	char *subj = NULL;
1287 
1288 	ip6 = mtod(m, struct ip6_hdr *);
1289 #ifndef PULLDOWN_TEST
1290 	ni6 = (struct icmp6_nodeinfo *)(mtod(m, caddr_t) + off);
1291 #else
1292 	IP6_EXTHDR_GET(ni6, struct icmp6_nodeinfo *, m, off, sizeof(*ni6));
1293 	if (ni6 == NULL) {
1294 		/* m is already reclaimed */
1295 		return NULL;
1296 	}
1297 #endif
1298 
1299 	/*
1300 	 * Validate IPv6 source address.
1301 	 * The default configuration MUST be to refuse answering queries from
1302 	 * global-scope addresses according to RFC4602.
1303 	 * Notes:
1304 	 *  - it's not very clear what "refuse" means; this implementation
1305 	 *    simply drops it.
1306 	 *  - it's not very easy to identify global-scope (unicast) addresses
1307 	 *    since there are many prefixes for them.  It should be safer
1308 	 *    and in practice sufficient to check "all" but loopback and
1309 	 *    link-local (note that site-local unicast was deprecated and
1310 	 *    ULA is defined as global scope-wise)
1311 	 */
1312 	if ((icmp6_nodeinfo & ICMP6_NODEINFO_GLOBALOK) == 0 &&
1313 	    !IN6_IS_ADDR_LOOPBACK(&ip6->ip6_src) &&
1314 	    !IN6_IS_ADDR_LINKLOCAL(&ip6->ip6_src)) {
1315 		goto bad;
1316 	}
1317 
1318 	/*
1319 	 * Validate IPv6 destination address.
1320 	 *
1321 	 * The Responder must discard the Query without further processing
1322 	 * unless it is one of the Responder's unicast or anycast addresses, or
1323 	 * a link-local scope multicast address which the Responder has joined.
1324 	 * [RFC4602, Section 5.]
1325 	 */
1326 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
1327 		if (!IN6_IS_ADDR_MC_LINKLOCAL(&ip6->ip6_dst) &&
1328 		    !IN6_IS_ADDR_MC_UNICAST_BASED_LINKLOCAL(&ip6->ip6_dst)) {
1329 			goto bad;
1330 		}
1331 		/* else it's a link-local multicast, fine */
1332 	} else {                /* unicast or anycast */
1333 		uint32_t ia6_flags;
1334 
1335 		if (ip6_getdstifaddr_info(m, NULL, &ia6_flags) != 0) {
1336 			goto bad; /* XXX impossible */
1337 		}
1338 		if ((ia6_flags & IN6_IFF_TEMPORARY) &&
1339 		    !(icmp6_nodeinfo & ICMP6_NODEINFO_TMPADDROK)) {
1340 			nd6log(debug, "ni6_input: ignore node info to a temporary address in %s:%d",
1341 			    __func__, __LINE__);
1342 			goto bad;
1343 		}
1344 	}
1345 
1346 	/* validate query Subject field. */
1347 	qtype = ntohs(ni6->ni_qtype);
1348 	subjlen = m->m_pkthdr.len - off - sizeof(struct icmp6_nodeinfo);
1349 	switch (qtype) {
1350 	case NI_QTYPE_NOOP:
1351 	case NI_QTYPE_SUPTYPES:
1352 		/* 07 draft */
1353 		if (ni6->ni_code == ICMP6_NI_SUBJ_FQDN && subjlen == 0) {
1354 			break;
1355 		}
1356 		OS_FALLTHROUGH;
1357 	case NI_QTYPE_FQDN:
1358 	case NI_QTYPE_NODEADDR:
1359 	case NI_QTYPE_IPV4ADDR:
1360 		switch (ni6->ni_code) {
1361 		case ICMP6_NI_SUBJ_IPV6:
1362 #if ICMP6_NI_SUBJ_IPV6 != 0
1363 		case 0:
1364 #endif
1365 			/*
1366 			 * backward compatibility - try to accept 03 draft
1367 			 * format, where no Subject is present.
1368 			 */
1369 			if (qtype == NI_QTYPE_FQDN && ni6->ni_code == 0 &&
1370 			    subjlen == 0) {
1371 				oldfqdn++;
1372 				break;
1373 			}
1374 #if ICMP6_NI_SUBJ_IPV6 != 0
1375 			if (ni6->ni_code != ICMP6_NI_SUBJ_IPV6) {
1376 				goto bad;
1377 			}
1378 #endif
1379 
1380 			if (subjlen != sizeof(struct in6_addr)) {
1381 				goto bad;
1382 			}
1383 
1384 			/*
1385 			 * Validate Subject address.
1386 			 *
1387 			 * Not sure what exactly "address belongs to the node"
1388 			 * means in the spec, is it just unicast, or what?
1389 			 *
1390 			 * At this moment we consider Subject address as
1391 			 * "belong to the node" if the Subject address equals
1392 			 * to the IPv6 destination address; validation for
1393 			 * IPv6 destination address should have done enough
1394 			 * check for us.
1395 			 *
1396 			 * We do not do proxy at this moment.
1397 			 */
1398 			/* m_pulldown instead of copy? */
1399 			m_copydata(m, off + sizeof(struct icmp6_nodeinfo),
1400 			    subjlen, (caddr_t)&sin6.sin6_addr);
1401 			sin6.sin6_scope_id = in6_addr2scopeid(m->m_pkthdr.rcvif,
1402 			    &sin6.sin6_addr);
1403 			in6_embedscope(&sin6.sin6_addr, &sin6, NULL, NULL,
1404 			    NULL, IN6_NULL_IF_EMBEDDED_SCOPE(&sin6.sin6_scope_id));
1405 			bzero(&sin6_d, sizeof(sin6_d));
1406 			sin6_d.sin6_family = AF_INET6; /* not used, actually */
1407 			sin6_d.sin6_len = sizeof(sin6_d); /* ditto */
1408 			sin6_d.sin6_addr = ip6->ip6_dst;
1409 			sin6_d.sin6_scope_id = in6_addr2scopeid(m->m_pkthdr.rcvif,
1410 			    &ip6->ip6_dst);
1411 			in6_embedscope(&sin6_d.sin6_addr, &sin6_d, NULL, NULL,
1412 			    NULL, IN6_NULL_IF_EMBEDDED_SCOPE(&sin6_d.sin6_scope_id));
1413 			subj = (char *)&sin6;
1414 			if (SA6_ARE_ADDR_EQUAL(&sin6, &sin6_d)) {
1415 				break;
1416 			}
1417 
1418 			/*
1419 			 * XXX if we are to allow other cases, we should really
1420 			 * be careful about scope here.
1421 			 * basically, we should disallow queries toward IPv6
1422 			 * destination X with subject Y,
1423 			 * if scope(X) > scope(Y).
1424 			 * if we allow scope(X) > scope(Y), it will result in
1425 			 * information leakage across scope boundary.
1426 			 */
1427 			goto bad;
1428 
1429 		case ICMP6_NI_SUBJ_FQDN:
1430 			/*
1431 			 * Validate Subject name with gethostname(3).
1432 			 *
1433 			 * The behavior may need some debate, since:
1434 			 * - we are not sure if the node has FQDN as
1435 			 *   hostname (returned by gethostname(3)).
1436 			 * - the code does wildcard match for truncated names.
1437 			 *   however, we are not sure if we want to perform
1438 			 *   wildcard match, if gethostname(3) side has
1439 			 *   truncated hostname.
1440 			 */
1441 			lck_mtx_lock(&hostname_lock);
1442 			n = ni6_nametodns(hostname, hostnamelen, 0);
1443 			lck_mtx_unlock(&hostname_lock);
1444 			if (!n || n->m_next || n->m_len == 0) {
1445 				goto bad;
1446 			}
1447 			IP6_EXTHDR_GET(subj, char *, m,
1448 			    off + sizeof(struct icmp6_nodeinfo), subjlen);
1449 			if (subj == NULL) {
1450 				goto bad;
1451 			}
1452 			if (!ni6_dnsmatch(subj, subjlen, mtod(n, const char *),
1453 			    n->m_len)) {
1454 				goto bad;
1455 			}
1456 			m_freem(n);
1457 			n = NULL;
1458 			break;
1459 
1460 		case ICMP6_NI_SUBJ_IPV4:        /* XXX: to be implemented? */
1461 		default:
1462 			goto bad;
1463 		}
1464 		break;
1465 	}
1466 
1467 	/* refuse based on configuration.  XXX ICMP6_NI_REFUSED? */
1468 	switch (qtype) {
1469 	case NI_QTYPE_FQDN:
1470 		if ((icmp6_nodeinfo & ICMP6_NODEINFO_FQDNOK) == 0) {
1471 			goto bad;
1472 		}
1473 		break;
1474 	case NI_QTYPE_NODEADDR:
1475 	case NI_QTYPE_IPV4ADDR:
1476 		if ((icmp6_nodeinfo & ICMP6_NODEINFO_NODEADDROK) == 0) {
1477 			goto bad;
1478 		}
1479 		break;
1480 	}
1481 
1482 	/* guess reply length */
1483 	switch (qtype) {
1484 	case NI_QTYPE_NOOP:
1485 		break;          /* no reply data */
1486 	case NI_QTYPE_SUPTYPES:
1487 		replylen += sizeof(u_int32_t);
1488 		break;
1489 	case NI_QTYPE_FQDN:
1490 		/* XXX will append an mbuf */
1491 		replylen += offsetof(struct ni_reply_fqdn, ni_fqdn_namelen);
1492 		break;
1493 	case NI_QTYPE_NODEADDR:
1494 		addrs = ni6_addrs(ni6, &ifp, subj);
1495 		if ((replylen += addrs * (sizeof(struct in6_addr) +
1496 		    sizeof(u_int32_t))) > MCLBYTES) {
1497 			replylen = MCLBYTES; /* XXX: will truncate pkt later */
1498 		}
1499 		break;
1500 	case NI_QTYPE_IPV4ADDR:
1501 		/* unsupported - should respond with unknown Qtype? */
1502 		break;
1503 	default:
1504 		/*
1505 		 * XXX: We must return a reply with the ICMP6 code
1506 		 * `unknown Qtype' in this case.  However we regard the case
1507 		 * as an FQDN query for backward compatibility.
1508 		 * Older versions set a random value to this field,
1509 		 * so it rarely varies in the defined qtypes.
1510 		 * But the mechanism is not reliable...
1511 		 * maybe we should obsolete older versions.
1512 		 */
1513 		qtype = NI_QTYPE_FQDN;
1514 		/* XXX will append an mbuf */
1515 		replylen += offsetof(struct ni_reply_fqdn, ni_fqdn_namelen);
1516 		oldfqdn++;
1517 		break;
1518 	}
1519 
1520 	/* allocate an mbuf to reply. */
1521 	MGETHDR(n, M_DONTWAIT, m->m_type);      /* MAC-OK */
1522 	if (n == NULL) {
1523 		m_freem(m);
1524 		if (ifp != NULL) {
1525 			ifnet_release(ifp);
1526 		}
1527 		return NULL;
1528 	}
1529 	M_COPY_PKTHDR(n, m); /* just for recvif */
1530 	if (replylen > MHLEN) {
1531 		if (replylen > MCLBYTES) {
1532 			/*
1533 			 * XXX: should we try to allocate more? But MCLBYTES
1534 			 * is probably much larger than IPV6_MMTU...
1535 			 */
1536 			goto bad;
1537 		}
1538 		MCLGET(n, M_DONTWAIT);
1539 		if ((n->m_flags & M_EXT) == 0) {
1540 			goto bad;
1541 		}
1542 	}
1543 	n->m_pkthdr.len = n->m_len = replylen;
1544 
1545 	/* copy mbuf header and IPv6 + Node Information base headers */
1546 	bcopy(mtod(m, caddr_t), mtod(n, caddr_t), sizeof(struct ip6_hdr));
1547 	nni6 = (struct icmp6_nodeinfo *)(mtod(n, struct ip6_hdr *) + 1);
1548 	bcopy((caddr_t)ni6, (caddr_t)nni6, sizeof(struct icmp6_nodeinfo));
1549 
1550 	/* qtype dependent procedure */
1551 	switch (qtype) {
1552 	case NI_QTYPE_NOOP:
1553 		nni6->ni_code = ICMP6_NI_SUCCESS;
1554 		nni6->ni_flags = 0;
1555 		break;
1556 	case NI_QTYPE_SUPTYPES:
1557 	{
1558 		u_int32_t v;
1559 		nni6->ni_code = ICMP6_NI_SUCCESS;
1560 		nni6->ni_flags = htons(0x0000); /* raw bitmap */
1561 		/* supports NOOP, SUPTYPES, FQDN, and NODEADDR */
1562 		v = (u_int32_t)htonl(0x0000000f);
1563 		bcopy(&v, nni6 + 1, sizeof(u_int32_t));
1564 		break;
1565 	}
1566 	case NI_QTYPE_FQDN:
1567 		nni6->ni_code = ICMP6_NI_SUCCESS;
1568 		fqdn = (struct ni_reply_fqdn *)(mtod(n, caddr_t) +
1569 		    sizeof(struct ip6_hdr) +
1570 		    sizeof(struct icmp6_nodeinfo));
1571 		nni6->ni_flags = 0; /* XXX: meaningless TTL */
1572 		fqdn->ni_fqdn_ttl = 0;  /* ditto. */
1573 		/*
1574 		 * XXX do we really have FQDN in variable "hostname"?
1575 		 */
1576 		lck_mtx_lock(&hostname_lock);
1577 		n->m_next = ni6_nametodns(hostname, hostnamelen, oldfqdn);
1578 		lck_mtx_unlock(&hostname_lock);
1579 		if (n->m_next == NULL) {
1580 			goto bad;
1581 		}
1582 		/* XXX we assume that n->m_next is not a chain */
1583 		if (n->m_next->m_next != NULL) {
1584 			goto bad;
1585 		}
1586 		n->m_pkthdr.len += n->m_next->m_len;
1587 		break;
1588 	case NI_QTYPE_NODEADDR:
1589 	{
1590 		int lenlim, copied;
1591 
1592 		nni6->ni_code = ICMP6_NI_SUCCESS;
1593 		n->m_pkthdr.len = n->m_len =
1594 		    sizeof(struct ip6_hdr) + sizeof(struct icmp6_nodeinfo);
1595 		lenlim = (int)M_TRAILINGSPACE(n);
1596 		copied = ni6_store_addrs(ni6, nni6, ifp, lenlim);
1597 		/* XXX: reset mbuf length */
1598 		n->m_pkthdr.len = n->m_len = sizeof(struct ip6_hdr) +
1599 		    sizeof(struct icmp6_nodeinfo) + copied;
1600 		break;
1601 	}
1602 	default:
1603 		break;          /* XXX impossible! */
1604 	}
1605 
1606 	nni6->ni_type = ICMP6_NI_REPLY;
1607 	m_freem(m);
1608 	if (ifp != NULL) {
1609 		ifnet_release(ifp);
1610 	}
1611 	return n;
1612 
1613 bad:
1614 	m_freem(m);
1615 	if (n) {
1616 		m_freem(n);
1617 	}
1618 	if (ifp != NULL) {
1619 		ifnet_release(ifp);
1620 	}
1621 	return NULL;
1622 }
1623 #undef hostnamelen
1624 
1625 /*
1626  * make a mbuf with DNS-encoded string.  no compression support.
1627  *
1628  * XXX names with less than 2 dots (like "foo" or "foo.section") will be
1629  * treated as truncated name (two \0 at the end).  this is a wild guess.
1630  */
1631 static struct mbuf *
ni6_nametodns(const char * name,uint32_t namelen,int old)1632 ni6_nametodns(
1633 	const char *name,
1634 	uint32_t namelen,
1635 	int old)        /* return pascal string if non-zero */
1636 {
1637 	struct mbuf *m;
1638 	char *cp, *ep;
1639 	const char *p, *q;
1640 	int i, nterm;
1641 	uint32_t len;
1642 
1643 	if (old) {
1644 		len = namelen + 1;
1645 	} else {
1646 		len = MCLBYTES;
1647 	}
1648 
1649 	/* because MAXHOSTNAMELEN is usually 256, we use cluster mbuf */
1650 	MGET(m, M_DONTWAIT, MT_DATA);
1651 	if (m && len > MLEN) {
1652 		MCLGET(m, M_DONTWAIT);
1653 		if ((m->m_flags & M_EXT) == 0) {
1654 			goto fail;
1655 		}
1656 	}
1657 	if (!m) {
1658 		goto fail;
1659 	}
1660 	m->m_next = NULL;
1661 
1662 	if (old) {
1663 		m->m_len = len;
1664 		*mtod(m, char *) = (char)namelen;
1665 		bcopy(name, mtod(m, char *) + 1, namelen);
1666 		return m;
1667 	} else {
1668 		m->m_len = 0;
1669 		cp = mtod(m, char *);
1670 		ep = mtod(m, char *) + M_TRAILINGSPACE(m);
1671 
1672 		/* if not certain about my name, return empty buffer */
1673 		if (namelen == 0) {
1674 			return m;
1675 		}
1676 
1677 		/*
1678 		 * guess if it looks like shortened hostname, or FQDN.
1679 		 * shortened hostname needs two trailing "\0".
1680 		 */
1681 		i = 0;
1682 		for (p = name; p < name + namelen; p++) {
1683 			if (*p && *p == '.') {
1684 				i++;
1685 			}
1686 		}
1687 		if (i < 2) {
1688 			nterm = 2;
1689 		} else {
1690 			nterm = 1;
1691 		}
1692 
1693 		p = name;
1694 		while (cp < ep && p < name + namelen) {
1695 			i = 0;
1696 			for (q = p; q < name + namelen && *q && *q != '.'; q++) {
1697 				i++;
1698 			}
1699 			/* result does not fit into mbuf */
1700 			if (cp + i + 1 >= ep) {
1701 				goto fail;
1702 			}
1703 			/*
1704 			 * DNS label length restriction, RFC1035 page 8.
1705 			 * "i == 0" case is included here to avoid returning
1706 			 * 0-length label on "foo..bar".
1707 			 */
1708 			if (i <= 0 || i >= 64) {
1709 				goto fail;
1710 			}
1711 			*cp++ = (char)i;
1712 			bcopy(p, cp, i);
1713 			cp += i;
1714 			p = q;
1715 			if (p < name + namelen && *p == '.') {
1716 				p++;
1717 			}
1718 		}
1719 		/* termination */
1720 		if (cp + nterm >= ep) {
1721 			goto fail;
1722 		}
1723 		while (nterm-- > 0) {
1724 			*cp++ = '\0';
1725 		}
1726 		m->m_len = (int32_t)(cp - mtod(m, char *));
1727 		return m;
1728 	}
1729 
1730 	panic("should not reach here");
1731 	/* NOTREACHED */
1732 
1733 fail:
1734 	if (m) {
1735 		m_freem(m);
1736 	}
1737 	return NULL;
1738 }
1739 
1740 /*
1741  * check if two DNS-encoded string matches.  takes care of truncated
1742  * form (with \0\0 at the end).  no compression support.
1743  * XXX upper/lowercase match (see RFC2065)
1744  */
1745 static int
ni6_dnsmatch(const char * a,int alen,const char * b,int blen)1746 ni6_dnsmatch(const char *a, int alen, const char *b, int blen)
1747 {
1748 	const char *a0, *b0;
1749 	int l;
1750 
1751 	/* simplest case - need validation? */
1752 	if (alen == blen && bcmp(a, b, alen) == 0) {
1753 		return 1;
1754 	}
1755 
1756 	a0 = a;
1757 	b0 = b;
1758 
1759 	/* termination is mandatory */
1760 	if (alen < 2 || blen < 2) {
1761 		return 0;
1762 	}
1763 	if (a0[alen - 1] != '\0' || b0[blen - 1] != '\0') {
1764 		return 0;
1765 	}
1766 	alen--;
1767 	blen--;
1768 
1769 	while (a - a0 < alen && b - b0 < blen) {
1770 		if (a - a0 + 1 > alen || b - b0 + 1 > blen) {
1771 			return 0;
1772 		}
1773 
1774 		if ((signed char)a[0] < 0 || (signed char)b[0] < 0) {
1775 			return 0;
1776 		}
1777 		/* we don't support compression yet */
1778 		if (a[0] >= 64 || b[0] >= 64) {
1779 			return 0;
1780 		}
1781 
1782 		/* truncated case */
1783 		if (a[0] == 0 && a - a0 == alen - 1) {
1784 			return 1;
1785 		}
1786 		if (b[0] == 0 && b - b0 == blen - 1) {
1787 			return 1;
1788 		}
1789 		if (a[0] == 0 || b[0] == 0) {
1790 			return 0;
1791 		}
1792 
1793 		if (a[0] != b[0]) {
1794 			return 0;
1795 		}
1796 		l = a[0];
1797 		if (a - a0 + 1 + l > alen || b - b0 + 1 + l > blen) {
1798 			return 0;
1799 		}
1800 		if (bcmp(a + 1, b + 1, l) != 0) {
1801 			return 0;
1802 		}
1803 
1804 		a += 1 + l;
1805 		b += 1 + l;
1806 	}
1807 
1808 	if (a - a0 == alen && b - b0 == blen) {
1809 		return 1;
1810 	} else {
1811 		return 0;
1812 	}
1813 }
1814 
1815 /*
1816  * calculate the number of addresses to be returned in the node info reply.
1817  */
1818 static int
ni6_addrs(struct icmp6_nodeinfo * ni6,struct ifnet ** ifpp,char * subj)1819 ni6_addrs(struct icmp6_nodeinfo *ni6, struct ifnet **ifpp, char *subj)
1820 {
1821 	struct ifnet *ifp;
1822 	struct in6_ifaddr *ifa6;
1823 	struct ifaddr *ifa;
1824 	struct sockaddr_in6 *subj_ip6 = NULL; /* XXX pedant */
1825 	int addrs = 0, addrsofif, iffound = 0;
1826 	int niflags = ni6->ni_flags;
1827 
1828 	if (ifpp != NULL) {
1829 		*ifpp = NULL;
1830 	}
1831 
1832 	if ((niflags & NI_NODEADDR_FLAG_ALL) == 0) {
1833 		switch (ni6->ni_code) {
1834 		case ICMP6_NI_SUBJ_IPV6:
1835 			if (subj == NULL) { /* must be impossible... */
1836 				return 0;
1837 			}
1838 			subj_ip6 = (struct sockaddr_in6 *)(void *)subj;
1839 			break;
1840 		default:
1841 			/*
1842 			 * XXX: we only support IPv6 subject address for
1843 			 * this Qtype.
1844 			 */
1845 			return 0;
1846 		}
1847 	}
1848 
1849 	ifnet_head_lock_shared();
1850 	TAILQ_FOREACH(ifp, &ifnet_head, if_list) {
1851 		addrsofif = 0;
1852 		ifnet_lock_shared(ifp);
1853 		TAILQ_FOREACH(ifa, &ifp->if_addrlist, ifa_list)
1854 		{
1855 			IFA_LOCK(ifa);
1856 			if (ifa->ifa_addr->sa_family != AF_INET6) {
1857 				IFA_UNLOCK(ifa);
1858 				continue;
1859 			}
1860 			ifa6 = (struct in6_ifaddr *)ifa;
1861 
1862 			if ((niflags & NI_NODEADDR_FLAG_ALL) == 0 &&
1863 			    IN6_ARE_ADDR_EQUAL(&subj_ip6->sin6_addr,
1864 			    &ifa6->ia_addr.sin6_addr)) {
1865 				iffound = 1;
1866 			}
1867 
1868 			/*
1869 			 * IPv4-mapped addresses can only be returned by a
1870 			 * Node Information proxy, since they represent
1871 			 * addresses of IPv4-only nodes, which perforce do
1872 			 * not implement this protocol.
1873 			 * [icmp-name-lookups-07, Section 5.4]
1874 			 * So we don't support NI_NODEADDR_FLAG_COMPAT in
1875 			 * this function at this moment.
1876 			 */
1877 
1878 			/* What do we have to do about ::1? */
1879 			switch (in6_addrscope(&ifa6->ia_addr.sin6_addr)) {
1880 			case IPV6_ADDR_SCOPE_LINKLOCAL:
1881 				if ((niflags & NI_NODEADDR_FLAG_LINKLOCAL) == 0) {
1882 					IFA_UNLOCK(ifa);
1883 					continue;
1884 				}
1885 				break;
1886 			case IPV6_ADDR_SCOPE_SITELOCAL:
1887 				if ((niflags & NI_NODEADDR_FLAG_SITELOCAL) == 0) {
1888 					IFA_UNLOCK(ifa);
1889 					continue;
1890 				}
1891 				break;
1892 			case IPV6_ADDR_SCOPE_GLOBAL:
1893 				if ((niflags & NI_NODEADDR_FLAG_GLOBAL) == 0) {
1894 					IFA_UNLOCK(ifa);
1895 					continue;
1896 				}
1897 				break;
1898 			default:
1899 				IFA_UNLOCK(ifa);
1900 				continue;
1901 			}
1902 
1903 			/*
1904 			 * check if anycast is okay.
1905 			 * XXX: just experimental.  not in the spec.
1906 			 */
1907 			if ((ifa6->ia6_flags & IN6_IFF_ANYCAST) != 0 &&
1908 			    (niflags & NI_NODEADDR_FLAG_ANYCAST) == 0) {
1909 				IFA_UNLOCK(ifa);
1910 				continue; /* we need only unicast addresses */
1911 			}
1912 			if ((ifa6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
1913 			    (icmp6_nodeinfo & ICMP6_NODEINFO_TMPADDROK) == 0) {
1914 				IFA_UNLOCK(ifa);
1915 				continue;
1916 			}
1917 			addrsofif++; /* count the address */
1918 			IFA_UNLOCK(ifa);
1919 		}
1920 		ifnet_lock_done(ifp);
1921 		if (iffound) {
1922 			if (ifpp != NULL) {
1923 				*ifpp = ifp;
1924 				ifnet_reference(ifp);
1925 			}
1926 			ifnet_head_done();
1927 			return addrsofif;
1928 		}
1929 
1930 		addrs += addrsofif;
1931 	}
1932 	ifnet_head_done();
1933 
1934 	return addrs;
1935 }
1936 
1937 static int
ni6_store_addrs(struct icmp6_nodeinfo * ni6,struct icmp6_nodeinfo * nni6,struct ifnet * ifp0,int resid)1938 ni6_store_addrs(struct icmp6_nodeinfo *ni6, struct icmp6_nodeinfo *nni6,
1939     struct ifnet *ifp0, int resid)
1940 {
1941 	struct ifnet *ifp = ifp0;
1942 	struct in6_ifaddr *ifa6;
1943 	struct ifaddr *ifa;
1944 	struct ifnet *ifp_dep = NULL;
1945 	int copied = 0, allow_deprecated = 0;
1946 	u_char *cp = (u_char *)(nni6 + 1);
1947 	int niflags = ni6->ni_flags;
1948 	u_int32_t ltime;
1949 	uint64_t now = net_uptime();
1950 
1951 	if (ifp0 == NULL && !(niflags & NI_NODEADDR_FLAG_ALL)) {
1952 		return 0;     /* needless to copy */
1953 	}
1954 again:
1955 
1956 	ifnet_head_lock_shared();
1957 	if (ifp == NULL) {
1958 		ifp = TAILQ_FIRST(&ifnet_head);
1959 	}
1960 
1961 	for (; ifp; ifp = TAILQ_NEXT(ifp, if_list)) {
1962 		ifnet_lock_shared(ifp);
1963 		for (ifa = ifp->if_addrlist.tqh_first; ifa;
1964 		    ifa = ifa->ifa_list.tqe_next) {
1965 			struct in6_addrlifetime_i *lt;
1966 
1967 			IFA_LOCK(ifa);
1968 			if (ifa->ifa_addr->sa_family != AF_INET6) {
1969 				IFA_UNLOCK(ifa);
1970 				continue;
1971 			}
1972 			ifa6 = (struct in6_ifaddr *)ifa;
1973 
1974 			if ((ifa6->ia6_flags & IN6_IFF_DEPRECATED) != 0 &&
1975 			    allow_deprecated == 0) {
1976 				/*
1977 				 * prefererred address should be put before
1978 				 * deprecated addresses.
1979 				 */
1980 
1981 				/* record the interface for later search */
1982 				if (ifp_dep == NULL) {
1983 					ifp_dep = ifp;
1984 				}
1985 
1986 				IFA_UNLOCK(ifa);
1987 				continue;
1988 			} else if ((ifa6->ia6_flags & IN6_IFF_DEPRECATED) == 0 &&
1989 			    allow_deprecated != 0) {
1990 				IFA_UNLOCK(ifa);
1991 				continue; /* we now collect deprecated addrs */
1992 			}
1993 			/* What do we have to do about ::1? */
1994 			switch (in6_addrscope(&ifa6->ia_addr.sin6_addr)) {
1995 			case IPV6_ADDR_SCOPE_LINKLOCAL:
1996 				if ((niflags & NI_NODEADDR_FLAG_LINKLOCAL) == 0) {
1997 					IFA_UNLOCK(ifa);
1998 					continue;
1999 				}
2000 				break;
2001 			case IPV6_ADDR_SCOPE_SITELOCAL:
2002 				if ((niflags & NI_NODEADDR_FLAG_SITELOCAL) == 0) {
2003 					IFA_UNLOCK(ifa);
2004 					continue;
2005 				}
2006 				break;
2007 			case IPV6_ADDR_SCOPE_GLOBAL:
2008 				if ((niflags & NI_NODEADDR_FLAG_GLOBAL) == 0) {
2009 					IFA_UNLOCK(ifa);
2010 					continue;
2011 				}
2012 				break;
2013 			default:
2014 				IFA_UNLOCK(ifa);
2015 				continue;
2016 			}
2017 
2018 			/*
2019 			 * check if anycast is okay.
2020 			 * XXX: just experimental.  not in the spec.
2021 			 */
2022 			if ((ifa6->ia6_flags & IN6_IFF_ANYCAST) != 0 &&
2023 			    (niflags & NI_NODEADDR_FLAG_ANYCAST) == 0) {
2024 				IFA_UNLOCK(ifa);
2025 				continue;
2026 			}
2027 			if ((ifa6->ia6_flags & IN6_IFF_TEMPORARY) != 0 &&
2028 			    (icmp6_nodeinfo & ICMP6_NODEINFO_TMPADDROK) == 0) {
2029 				IFA_UNLOCK(ifa);
2030 				continue;
2031 			}
2032 
2033 			/* now we can copy the address */
2034 			if (resid < sizeof(struct in6_addr) +
2035 			    sizeof(u_int32_t)) {
2036 				IFA_UNLOCK(ifa);
2037 				/*
2038 				 * We give up much more copy.
2039 				 * Set the truncate flag and return.
2040 				 */
2041 				nni6->ni_flags |=
2042 				    NI_NODEADDR_FLAG_TRUNCATE;
2043 				ifnet_lock_done(ifp);
2044 				ifnet_head_done();
2045 				return copied;
2046 			}
2047 
2048 			/*
2049 			 * Set the TTL of the address.
2050 			 * The TTL value should be one of the following
2051 			 * according to the specification:
2052 			 *
2053 			 * 1. The remaining lifetime of a DHCP lease on the
2054 			 *    address, or
2055 			 * 2. The remaining Valid Lifetime of a prefix from
2056 			 *    which the address was derived through Stateless
2057 			 *    Autoconfiguration.
2058 			 *
2059 			 * Note that we currently do not support stateful
2060 			 * address configuration by DHCPv6, so the former
2061 			 * case can't happen.
2062 			 */
2063 			lt = &ifa6->ia6_lifetime;
2064 			if (lt->ia6ti_expire == 0) {
2065 				ltime = ND6_INFINITE_LIFETIME;
2066 			} else {
2067 				if (lt->ia6ti_expire > now) {
2068 					ltime = htonl((uint32_t)(lt->ia6ti_expire - now));
2069 				} else {
2070 					ltime = 0;
2071 				}
2072 			}
2073 
2074 			bcopy(&ltime, cp, sizeof(u_int32_t));
2075 			cp += sizeof(u_int32_t);
2076 
2077 			/* copy the address itself */
2078 			bcopy(&ifa6->ia_addr.sin6_addr, cp,
2079 			    sizeof(struct in6_addr));
2080 			/* XXX: KAME link-local hack; remove ifindex */
2081 			if (IN6_IS_ADDR_LINKLOCAL(&ifa6->ia_addr.sin6_addr)) {
2082 				((struct in6_addr *)(void *)cp)->s6_addr16[1] = 0;
2083 			}
2084 			cp += sizeof(struct in6_addr);
2085 
2086 			resid -= (sizeof(struct in6_addr) + sizeof(u_int32_t));
2087 			copied += (sizeof(struct in6_addr) +
2088 			    sizeof(u_int32_t));
2089 			IFA_UNLOCK(ifa);
2090 		}
2091 		ifnet_lock_done(ifp);
2092 		if (ifp0) {     /* we need search only on the specified IF */
2093 			break;
2094 		}
2095 	}
2096 	ifnet_head_done();
2097 
2098 	if (allow_deprecated == 0 && ifp_dep != NULL) {
2099 		ifp = ifp_dep;
2100 		allow_deprecated = 1;
2101 
2102 		goto again;
2103 	}
2104 
2105 	return copied;
2106 }
2107 
2108 /*
2109  * XXX almost dup'ed code with rip6_input.
2110  */
2111 static int
icmp6_rip6_input(struct mbuf ** mp,int off)2112 icmp6_rip6_input(struct mbuf **mp, int off)
2113 {
2114 	struct mbuf *m = *mp;
2115 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
2116 	struct in6pcb *in6p;
2117 	struct in6pcb *last = NULL;
2118 	struct sockaddr_in6 rip6src;
2119 	struct icmp6_hdr *icmp6;
2120 	struct mbuf *opts = NULL;
2121 	int ret = 0;
2122 	struct ifnet *ifp = m->m_pkthdr.rcvif;
2123 
2124 #ifndef PULLDOWN_TEST
2125 	/* this is assumed to be safe. */
2126 	icmp6 = (struct icmp6_hdr *)((caddr_t)ip6 + off);
2127 #else
2128 	IP6_EXTHDR_GET(icmp6, struct icmp6_hdr *, m, off, sizeof(*icmp6));
2129 	if (icmp6 == NULL) {
2130 		/* m is already reclaimed */
2131 		return IPPROTO_DONE;
2132 	}
2133 #endif
2134 
2135 	/*
2136 	 * XXX: the address may have embedded scope zone ID, which should be
2137 	 * hidden from applications.
2138 	 */
2139 	bzero(&rip6src, sizeof(rip6src));
2140 	rip6src.sin6_family = AF_INET6;
2141 	rip6src.sin6_len = sizeof(struct sockaddr_in6);
2142 	rip6src.sin6_addr = ip6->ip6_src;
2143 	if (!in6_embedded_scope) {
2144 		rip6src.sin6_scope_id = IN6_IS_SCOPE_EMBED(&rip6src.sin6_addr) ? ip6_input_getsrcifscope(m) : IFSCOPE_NONE;
2145 	}
2146 	if (sa6_recoverscope(&rip6src, TRUE)) {
2147 		return IPPROTO_DONE;
2148 	}
2149 
2150 	lck_rw_lock_shared(&ripcbinfo.ipi_lock);
2151 	LIST_FOREACH(in6p, &ripcb, inp_list)
2152 	{
2153 		if ((in6p->inp_vflag & INP_IPV6) == 0) {
2154 			continue;
2155 		}
2156 		if (in6p->in6p_ip6_nxt != IPPROTO_ICMPV6) {
2157 			continue;
2158 		}
2159 		if (!IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_laddr) &&
2160 		    !in6_are_addr_equal_scoped(&in6p->in6p_laddr, &ip6->ip6_dst, in6p->inp_lifscope, ifp->if_index)) {
2161 			continue;
2162 		}
2163 		if (!IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_faddr) &&
2164 		    !in6_are_addr_equal_scoped(&in6p->in6p_faddr, &ip6->ip6_src, in6p->inp_fifscope, ifp->if_index)) {
2165 			continue;
2166 		}
2167 		if (in6p->in6p_icmp6filt
2168 		    && ICMP6_FILTER_WILLBLOCK(icmp6->icmp6_type,
2169 		    in6p->in6p_icmp6filt)) {
2170 			continue;
2171 		}
2172 
2173 		if (inp_restricted_recv(in6p, ifp)) {
2174 			continue;
2175 		}
2176 
2177 		if (last) {
2178 			struct  mbuf *n;
2179 			if ((n = m_copy(m, 0, (int)M_COPYALL)) != NULL) {
2180 				if ((last->in6p_flags & INP_CONTROLOPTS) != 0 ||
2181 				    SOFLOW_ENABLED(last->in6p_socket) ||
2182 				    SO_RECV_CONTROL_OPTS(last->inp_socket)) {
2183 					ret = ip6_savecontrol(last, n, &opts);
2184 					if (ret != 0) {
2185 						m_freem(n);
2186 						m_freem(opts);
2187 						last = in6p;
2188 						continue;
2189 					}
2190 				}
2191 				/* strip intermediate headers */
2192 				m_adj(n, off);
2193 				so_recv_data_stat(last->in6p_socket, m, 0);
2194 				if (sbappendaddr(&last->in6p_socket->so_rcv,
2195 				    (struct sockaddr *)&rip6src,
2196 				    n, opts, NULL) != 0) {
2197 					sorwakeup(last->in6p_socket);
2198 				}
2199 				opts = NULL;
2200 			}
2201 		}
2202 		last = in6p;
2203 	}
2204 	if (last) {
2205 		if ((last->in6p_flags & INP_CONTROLOPTS) != 0 ||
2206 		    SOFLOW_ENABLED(last->in6p_socket) ||
2207 		    SO_RECV_CONTROL_OPTS(last->inp_socket)) {
2208 			ret = ip6_savecontrol(last, m, &opts);
2209 			if (ret != 0) {
2210 				goto error;
2211 			}
2212 		}
2213 		/* strip intermediate headers */
2214 		m_adj(m, off);
2215 		so_recv_data_stat(last->in6p_socket, m, 0);
2216 		if (sbappendaddr(&last->in6p_socket->so_rcv,
2217 		    (struct sockaddr *)&rip6src, m, opts, NULL) != 0) {
2218 			sorwakeup(last->in6p_socket);
2219 		}
2220 	} else {
2221 		goto error;
2222 	}
2223 	lck_rw_done(&ripcbinfo.ipi_lock);
2224 	return IPPROTO_DONE;
2225 
2226 error:
2227 	lck_rw_done(&ripcbinfo.ipi_lock);
2228 	m_freem(m);
2229 	m_freem(opts);
2230 	ip6stat.ip6s_delivered--;
2231 	return IPPROTO_DONE;
2232 }
2233 
2234 /*
2235  * Reflect the ip6 packet back to the source.
2236  * OFF points to the icmp6 header, counted from the top of the mbuf.
2237  */
2238 void
icmp6_reflect(struct mbuf * m,size_t off)2239 icmp6_reflect(struct mbuf *m, size_t off)
2240 {
2241 	struct mbuf *m_ip6hdr = m;
2242 	struct ip6_hdr *ip6;
2243 	struct icmp6_hdr *icmp6;
2244 	struct in6_ifaddr *ia;
2245 	struct in6_addr t, src_storage, *src = 0;
2246 	int plen;
2247 	int type, code;
2248 	struct ifnet *outif = NULL;
2249 	struct sockaddr_in6 sa6_src, sa6_dst;
2250 	struct nd_ifinfo *ndi = NULL;
2251 	u_int32_t oflow;
2252 	uint32_t sifscope = IFSCOPE_NONE;
2253 	uint32_t fifscope = IFSCOPE_NONE;
2254 	uint32_t tifscope;
2255 	struct ip6_out_args ip6oa;
2256 
2257 	bzero(&ip6oa, sizeof(ip6oa));
2258 	ip6oa.ip6oa_boundif = IFSCOPE_NONE;
2259 	ip6oa.ip6oa_flags = IP6OAF_SELECT_SRCIF | IP6OAF_BOUND_SRCADDR |
2260 	    IP6OAF_INTCOPROC_ALLOWED | IP6OAF_AWDL_UNRESTRICTED;
2261 	ip6oa.ip6oa_sotc = SO_TC_UNSPEC;
2262 	ip6oa.ip6oa_netsvctype = _NET_SERVICE_TYPE_UNSPEC;
2263 
2264 	if (!(m->m_pkthdr.pkt_flags & PKTF_LOOP) && m->m_pkthdr.rcvif != NULL) {
2265 		ip6oa.ip6oa_boundif = m->m_pkthdr.rcvif->if_index;
2266 		ip6oa.ip6oa_flags |= IP6OAF_BOUND_IF;
2267 	}
2268 
2269 	/* too short to reflect */
2270 	if (off < sizeof(struct ip6_hdr)) {
2271 		nd6log(debug,
2272 		    "sanity fail: off=%x, sizeof(ip6)=%x in %s:%d\n",
2273 		    (u_int32_t)off, (u_int32_t)sizeof(struct ip6_hdr),
2274 		    __func__, __LINE__);
2275 		goto bad;
2276 	}
2277 
2278 	/*
2279 	 * If there are extra headers between IPv6 and ICMPv6, strip
2280 	 * off that header first.
2281 	 */
2282 	if (off > sizeof(struct ip6_hdr)) {
2283 		size_t l;
2284 		struct ip6_hdr nip6;
2285 
2286 		l = off - sizeof(struct ip6_hdr);
2287 		m_copydata(m, 0, sizeof(nip6), (caddr_t)&nip6);
2288 		m_adj(m, (int)l);
2289 		l = sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr);
2290 		if (m->m_len < l) {
2291 			if ((m_ip6hdr = m_pulldown(m, 0, (int)l, NULL)) == NULL) {
2292 				return;
2293 			}
2294 		}
2295 		bcopy((caddr_t)&nip6, mtod(m, caddr_t), sizeof(nip6));
2296 	} else { /* off == sizeof(struct ip6_hdr) */
2297 		size_t l;
2298 		l = sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr);
2299 		if (m->m_len < l) {
2300 			if ((m_ip6hdr = m_pulldown(m, 0, (int)l, NULL)) == NULL) {
2301 				return;
2302 			}
2303 		}
2304 	}
2305 	plen = m->m_pkthdr.len - sizeof(struct ip6_hdr);
2306 	ip6 = mtod(m_ip6hdr, struct ip6_hdr *);
2307 	ip6->ip6_nxt = IPPROTO_ICMPV6;
2308 	icmp6 = (struct icmp6_hdr *)(ip6 + 1);
2309 	type = icmp6->icmp6_type; /* keep type for statistics */
2310 	code = icmp6->icmp6_code; /* ditto. */
2311 	if (m->m_pkthdr.rcvif != NULL) {
2312 		fifscope = m->m_pkthdr.rcvif->if_index;
2313 		sifscope = m->m_pkthdr.rcvif->if_index;
2314 	} else if (m->m_pkthdr.pkt_flags & PKTF_IFAINFO) {
2315 		ip6_getsrcifaddr_info(m, &fifscope, NULL);
2316 		ip6_getdstifaddr_info(m, &sifscope, NULL);
2317 	} else if (m->m_pkthdr.pkt_ext_flags & PKTF_EXT_OUTPUT_SCOPE) {
2318 		fifscope = ip6_output_getsrcifscope(m);
2319 		sifscope = ip6_output_getdstifscope(m);
2320 	}
2321 	fifscope = IN6_IS_SCOPE_EMBED(&ip6->ip6_src) ? fifscope : IFSCOPE_NONE;
2322 	sifscope = IN6_IS_SCOPE_EMBED(&ip6->ip6_dst) ? sifscope : IFSCOPE_NONE;
2323 	if (!in6_embedded_scope) {
2324 		m->m_pkthdr.pkt_flags &= ~PKTF_IFAINFO;
2325 	}
2326 
2327 	t = ip6->ip6_dst;
2328 	/*
2329 	 * ip6_input() drops a packet if its src is multicast.
2330 	 * So, the src is never multicast.
2331 	 */
2332 	ip6->ip6_dst = ip6->ip6_src;
2333 	/*
2334 	 * XXX: make sure to embed scope zone information, using
2335 	 * already embedded IDs or the received interface (if any).
2336 	 * Note that rcvif may be NULL.
2337 	 */
2338 	bzero(&sa6_src, sizeof(sa6_src));
2339 	sa6_src.sin6_family = AF_INET6;
2340 	sa6_src.sin6_len = sizeof(sa6_src);
2341 	sa6_src.sin6_addr = ip6->ip6_dst;
2342 	if (!in6_embedded_scope) {
2343 		sa6_src.sin6_scope_id = fifscope;
2344 	}
2345 	in6_recoverscope(&sa6_src, &ip6->ip6_dst, m->m_pkthdr.rcvif);
2346 	in6_embedscope(&ip6->ip6_dst, &sa6_src, NULL, NULL, NULL, IN6_NULL_IF_EMBEDDED_SCOPE(&sa6_src.sin6_scope_id));
2347 	in6_verify_ifscope(&ip6->ip6_dst, sa6_src.sin6_scope_id);
2348 	ip6_output_setdstifscope(m, sa6_src.sin6_scope_id, NULL);
2349 
2350 	if (!in6_embedded_scope &&
2351 	    (ip6oa.ip6oa_flags & IP6OAF_BOUND_IF) == 0 &&
2352 	    IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
2353 		ip6oa.ip6oa_boundif = sa6_src.sin6_scope_id;
2354 		ip6oa.ip6oa_flags |= IP6OAF_BOUND_IF;
2355 	}
2356 
2357 	bzero(&sa6_dst, sizeof(sa6_dst));
2358 	sa6_dst.sin6_family = AF_INET6;
2359 	sa6_dst.sin6_len = sizeof(sa6_dst);
2360 	sa6_dst.sin6_addr = t;
2361 	if (!in6_embedded_scope) {
2362 		sa6_dst.sin6_scope_id = sifscope;
2363 	}
2364 	in6_recoverscope(&sa6_dst, &t, m->m_pkthdr.rcvif);
2365 	in6_embedscope(&t, &sa6_dst, NULL, NULL, NULL, IN6_NULL_IF_EMBEDDED_SCOPE(&sa6_dst.sin6_scope_id));
2366 	tifscope = sa6_dst.sin6_scope_id;
2367 	/*
2368 	 * If the incoming packet was addressed directly to us(i.e. unicast),
2369 	 * use dst as the src for the reply.
2370 	 * The IN6_IFF_NOTREADY case should be VERY rare, but is possible
2371 	 * (for example) when we encounter an error while forwarding procedure
2372 	 * destined to a duplicated address of ours.
2373 	 * Note that ip6_getdstifaddr() may fail if we are in an error handling
2374 	 * procedure of an outgoing packet of our own, in which case we need
2375 	 * to search in the ifaddr list.
2376 	 */
2377 	lck_rw_lock_shared(&in6_ifaddr_rwlock);
2378 	TAILQ_FOREACH(ia, IN6ADDR_HASH(&t), ia6_hash) {
2379 		IFA_LOCK(&ia->ia_ifa);
2380 		if (in6_are_addr_equal_scoped(&t, &ia->ia_addr.sin6_addr, tifscope, ia->ia_addr.sin6_scope_id) &&
2381 		    (ia->ia6_flags & (IN6_IFF_ANYCAST | IN6_IFF_NOTREADY | IN6_IFF_CLAT46)) == 0) {
2382 			IFA_UNLOCK(&ia->ia_ifa);
2383 			src = &t;
2384 			sifscope = tifscope;
2385 			break;
2386 		}
2387 		IFA_UNLOCK(&ia->ia_ifa);
2388 	}
2389 	lck_rw_done(&in6_ifaddr_rwlock);
2390 	if (ia == NULL && IN6_IS_ADDR_LINKLOCAL(&t) &&
2391 	    ((m->m_flags & M_LOOP) || (m->m_pkthdr.pkt_flags & PKTF_LOOP))) {
2392 		/*
2393 		 * This is the case if the dst is our link-local address
2394 		 * and the sender is also ourselves.  Here we test for both
2395 		 * M_LOOP and PKTF_LOOP, since the former may have been set
2396 		 * in ip6_output() and that we get here as part of callling
2397 		 * ip6_process_hopopts().  See comments in <sys/mbuf.h>
2398 		 */
2399 		src = &t;
2400 		sifscope = tifscope;
2401 	}
2402 
2403 	if (src == NULL) {
2404 		int e;
2405 		struct sockaddr_in6 sin6;
2406 		struct route_in6 ro;
2407 
2408 		/*
2409 		 * This case matches to multicasts, our anycast, or unicasts
2410 		 * that we do not own.  Select a source address based on the
2411 		 * source address of the erroneous packet.
2412 		 */
2413 		bzero(&sin6, sizeof(sin6));
2414 		sin6.sin6_family = AF_INET6;
2415 		sin6.sin6_len = sizeof(sin6);
2416 		sin6.sin6_addr = ip6->ip6_dst; /* zone ID should be embedded */
2417 		if (!in6_embedded_scope) {
2418 			sin6.sin6_scope_id = fifscope;
2419 		}
2420 
2421 		bzero(&ro, sizeof(ro));
2422 		/*
2423 		 * in6_selectsrc() might return outif with its reference held
2424 		 * even in the error case, so we always need to release it
2425 		 * if non-NULL.
2426 		 */
2427 		src = in6_selectsrc(&sin6, NULL, NULL, &ro, &outif,
2428 		    &src_storage, ip6oa.ip6oa_boundif, &e);
2429 		ROUTE_RELEASE(&ro);
2430 		if (src == NULL) {
2431 			nd6log(debug,
2432 			    "icmp6_reflect: source can't be determined: "
2433 			    "dst=%s, error=%d\n",
2434 			    ip6_sprintf(&sa6_src.sin6_addr), e);
2435 			goto bad;
2436 		}
2437 		if (outif != NULL) {
2438 			sifscope = outif->if_index;
2439 		}
2440 	}
2441 	oflow = ip6->ip6_flow; /* Save for later */
2442 	ip6->ip6_src = *src;
2443 	ip6->ip6_flow = 0;
2444 	ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
2445 	ip6->ip6_vfc |= IPV6_VERSION;
2446 	ip6_output_setsrcifscope(m, sifscope, NULL);
2447 	in6_verify_ifscope(&ip6->ip6_src, sifscope);
2448 
2449 	if (icmp6->icmp6_type == ICMP6_ECHO_REPLY && icmp6->icmp6_code == 0) {
2450 		ip6->ip6_flow |= (oflow & htonl(0x0ff00000));
2451 	}
2452 	ip6->ip6_nxt = IPPROTO_ICMPV6;
2453 	if (outif != NULL && (ndi = ND_IFINFO(outif)) != NULL &&
2454 	    ndi->initialized) {
2455 		lck_mtx_lock(&ndi->lock);
2456 		ip6->ip6_hlim = ndi->chlim;
2457 		lck_mtx_unlock(&ndi->lock);
2458 	}
2459 	if (m->m_pkthdr.rcvif != NULL &&
2460 	    (ndi = ND_IFINFO(m->m_pkthdr.rcvif)) != NULL &&
2461 	    ndi->initialized) {
2462 		/* XXX: This may not be the outgoing interface */
2463 		lck_mtx_lock(&ndi->lock);
2464 		ip6->ip6_hlim = ndi->chlim;
2465 		lck_mtx_unlock(&ndi->lock);
2466 	} else {
2467 		ip6->ip6_hlim = (uint8_t)ip6_defhlim;
2468 	}
2469 	/* Use the same traffic class as in the request to match IPv4 */
2470 	icmp6->icmp6_cksum = 0;
2471 	icmp6->icmp6_cksum = in6_cksum(m, IPPROTO_ICMPV6,
2472 	    sizeof(struct ip6_hdr), plen);
2473 
2474 	/*
2475 	 * XXX option handling
2476 	 */
2477 	m->m_flags &= ~(M_BCAST | M_MCAST);
2478 
2479 	if (outif != NULL) {
2480 		ifnet_release(outif);
2481 		outif = NULL;
2482 	}
2483 
2484 	m->m_pkthdr.csum_data = 0;
2485 	m->m_pkthdr.csum_flags = 0;
2486 	ip6_output(m, NULL, NULL, IPV6_OUTARGS, NULL, &outif, &ip6oa);
2487 	if (outif != NULL) {
2488 		icmp6_ifoutstat_inc(outif, type, code);
2489 		ifnet_release(outif);
2490 	}
2491 	return;
2492 
2493 bad:
2494 	m_freem(m);
2495 	if (outif != NULL) {
2496 		ifnet_release(outif);
2497 	}
2498 	return;
2499 }
2500 
2501 static const char *
icmp6_redirect_diag(struct in6_addr * src6,struct in6_addr * dst6,struct in6_addr * tgt6)2502 icmp6_redirect_diag(struct in6_addr *src6,
2503     struct in6_addr *dst6,
2504     struct in6_addr *tgt6)
2505 {
2506 	static char buf[1024];
2507 	snprintf(buf, sizeof(buf), "(src=%s dst=%s tgt=%s)",
2508 	    ip6_sprintf(src6), ip6_sprintf(dst6), ip6_sprintf(tgt6));
2509 	return buf;
2510 }
2511 
2512 void
icmp6_redirect_input(struct mbuf * m,int off,int icmp6len)2513 icmp6_redirect_input(struct mbuf *m, int off, int icmp6len)
2514 {
2515 	struct ifnet *ifp = NULL;
2516 	struct ip6_hdr *ip6 = NULL;
2517 	struct nd_redirect *nd_rd = NULL;
2518 	char *lladdr = NULL;
2519 	int lladdrlen = 0;
2520 	u_char *redirhdr = NULL;
2521 	int redirhdrlen = 0;
2522 	struct rtentry *rt = NULL;
2523 	int is_router = 0;
2524 	int is_onlink = 0;
2525 	struct in6_addr src6 = {};
2526 	struct in6_addr redtgt6 = {};
2527 	struct in6_addr reddst6 = {};
2528 	uint32_t src_ifscope = IFSCOPE_NONE, redtgt_ifscope  = IFSCOPE_NONE, reddst_ifscope = IFSCOPE_NONE;
2529 	union nd_opts ndopts = {};
2530 
2531 	if (m == NULL) {
2532 		return;
2533 	}
2534 
2535 	ifp = m->m_pkthdr.rcvif;
2536 	if (ifp == NULL) {
2537 		goto freeit;
2538 	}
2539 
2540 	/*
2541 	 * If we are an advertising router on this interface,
2542 	 * don't update route by icmp6 redirect.
2543 	 */
2544 	if (ifp->if_ipv6_router_mode == IPV6_ROUTER_MODE_EXCLUSIVE) {
2545 		goto freeit;
2546 	}
2547 	if (!icmp6_rediraccept) {
2548 		goto freeit;
2549 	}
2550 
2551 	ip6 = mtod(m, struct ip6_hdr *);
2552 	src6 = ip6->ip6_src;
2553 	src_ifscope = in6_addr2scopeid(ifp, &src6);
2554 #ifndef PULLDOWN_TEST
2555 	IP6_EXTHDR_CHECK(m, off, icmp6len, return );
2556 	nd_rd = (struct nd_redirect *)(mtod(m, caddr_t) + off);
2557 #else
2558 	IP6_EXTHDR_GET(nd_rd, struct nd_redirect *, m, off, icmp6len);
2559 	if (nd_rd == NULL) {
2560 		icmp6stat.icp6s_tooshort++;
2561 		goto freeit;
2562 	}
2563 #endif
2564 	ip6 = mtod(m, struct ip6_hdr *);
2565 
2566 	redtgt6 = nd_rd->nd_rd_target;
2567 	reddst6 = nd_rd->nd_rd_dst;
2568 
2569 	if (in6_setscope(&redtgt6, m->m_pkthdr.rcvif, &redtgt_ifscope) ||
2570 	    in6_setscope(&reddst6, m->m_pkthdr.rcvif, &reddst_ifscope)) {
2571 		goto freeit;
2572 	}
2573 
2574 	/* validation */
2575 	if (!IN6_IS_ADDR_LINKLOCAL(&src6)) {
2576 		nd6log(error,
2577 		    "ICMP6 redirect sent from %s rejected; "
2578 		    "must be from linklocal\n", ip6_sprintf(&src6));
2579 		goto bad;
2580 	}
2581 	if (ip6->ip6_hlim != IPV6_MAXHLIM) {
2582 		nd6log(error,
2583 		    "ICMP6 redirect sent from %s rejected; "
2584 		    "hlim=%d (must be 255)\n",
2585 		    ip6_sprintf(&src6), ip6->ip6_hlim);
2586 		goto bad;
2587 	}
2588 	{
2589 		/* ip6->ip6_src must be equal to gw for icmp6->icmp6_reddst */
2590 		struct sockaddr_in6 sin6;
2591 		struct in6_addr *gw6;
2592 
2593 		bzero(&sin6, sizeof(sin6));
2594 		sin6.sin6_family = AF_INET6;
2595 		sin6.sin6_len = sizeof(struct sockaddr_in6);
2596 		if (!in6_embedded_scope) {
2597 			sin6.sin6_scope_id = reddst_ifscope;
2598 		}
2599 		bcopy(&reddst6, &sin6.sin6_addr, sizeof(reddst6));
2600 		rt = rtalloc1_scoped((struct sockaddr *)&sin6, 0, 0, ifp->if_index);
2601 		if (rt) {
2602 			RT_LOCK(rt);
2603 			if (rt->rt_gateway == NULL ||
2604 			    rt->rt_gateway->sa_family != AF_INET6) {
2605 				nd6log(error,
2606 				    "ICMP6 redirect rejected; no route "
2607 				    "with inet6 gateway found for redirect dst: %s\n",
2608 				    icmp6_redirect_diag(&src6, &reddst6, &redtgt6));
2609 				RT_UNLOCK(rt);
2610 				rtfree(rt);
2611 				goto bad;
2612 			}
2613 
2614 			gw6 = &(((struct sockaddr_in6 *)(void *)
2615 			    rt->rt_gateway)->sin6_addr);
2616 			if (!in6_are_addr_equal_scoped(&src6, gw6, src_ifscope, ((struct sockaddr_in6 *)(void *)
2617 			    rt->rt_gateway)->sin6_scope_id)) {
2618 				nd6log(error,
2619 				    "ICMP6 redirect rejected; "
2620 				    "not equal to gw-for-src=%s (must be same): "
2621 				    "%s\n",
2622 				    ip6_sprintf(gw6),
2623 				    icmp6_redirect_diag(&src6, &reddst6, &redtgt6));
2624 				RT_UNLOCK(rt);
2625 				rtfree(rt);
2626 				goto bad;
2627 			}
2628 		} else {
2629 			nd6log(error,
2630 			    "ICMP6 redirect rejected; "
2631 			    "no route found for redirect dst: %s\n",
2632 			    icmp6_redirect_diag(&src6, &reddst6, &redtgt6));
2633 			goto bad;
2634 		}
2635 		RT_UNLOCK(rt);
2636 		rtfree(rt);
2637 		rt = NULL;
2638 	}
2639 	if (IN6_IS_ADDR_MULTICAST(&reddst6)) {
2640 		nd6log(error,
2641 		    "ICMP6 redirect rejected; "
2642 		    "redirect dst must be unicast: %s\n",
2643 		    icmp6_redirect_diag(&src6, &reddst6, &redtgt6));
2644 		goto bad;
2645 	}
2646 
2647 	is_router = is_onlink = 0;
2648 	if (IN6_IS_ADDR_LINKLOCAL(&redtgt6)) {
2649 		is_router = 1;  /* router case */
2650 	}
2651 	if (bcmp(&redtgt6, &reddst6, sizeof(redtgt6)) == 0) {
2652 		is_onlink = 1;  /* on-link destination case */
2653 	}
2654 	if (!is_router && !is_onlink) {
2655 		nd6log(error,
2656 		    "ICMP6 redirect rejected; "
2657 		    "neither router case nor onlink case: %s\n",
2658 		    icmp6_redirect_diag(&src6, &reddst6, &redtgt6));
2659 		goto bad;
2660 	}
2661 	/* validation passed */
2662 
2663 	icmp6len -= sizeof(*nd_rd);
2664 	nd6_option_init(nd_rd + 1, icmp6len, &ndopts);
2665 	if (nd6_options(&ndopts) < 0) {
2666 		nd6log(info, "icmp6_redirect_input: "
2667 		    "invalid ND option, rejected: %s\n",
2668 		    icmp6_redirect_diag(&src6, &reddst6, &redtgt6));
2669 		/* nd6_options have incremented stats */
2670 		goto freeit;
2671 	}
2672 
2673 	if (ndopts.nd_opts_tgt_lladdr) {
2674 		lladdr = (char *)(ndopts.nd_opts_tgt_lladdr + 1);
2675 		lladdrlen = ndopts.nd_opts_tgt_lladdr->nd_opt_len << 3;
2676 	}
2677 
2678 	if (ndopts.nd_opts_rh) {
2679 		redirhdrlen = ndopts.nd_opts_rh->nd_opt_rh_len;
2680 		redirhdr = (u_char *)(ndopts.nd_opts_rh + 1); /* xxx */
2681 	}
2682 
2683 	if (lladdr && ((ifp->if_addrlen + 2 + 7) & ~7) != lladdrlen) {
2684 		nd6log(info,
2685 		    "icmp6_redirect_input: lladdrlen mismatch for %s "
2686 		    "(if %d, icmp6 packet %d): %s\n",
2687 		    ip6_sprintf(&redtgt6), ifp->if_addrlen, lladdrlen - 2,
2688 		    icmp6_redirect_diag(&src6, &reddst6, &redtgt6));
2689 		goto bad;
2690 	}
2691 
2692 	/* RFC 2461 8.3 */
2693 	nd6_cache_lladdr(ifp, &redtgt6, lladdr, lladdrlen, ND_REDIRECT,
2694 	    is_onlink ? ND_REDIRECT_ONLINK : ND_REDIRECT_ROUTER, NULL);
2695 
2696 	if (!is_onlink) {       /* better router case.  perform rtredirect. */
2697 		/* perform rtredirect */
2698 		struct sockaddr_in6 sdst;
2699 		struct sockaddr_in6 sgw;
2700 		struct sockaddr_in6 ssrc;
2701 
2702 		bzero(&sdst, sizeof(sdst));
2703 		bzero(&sgw, sizeof(sgw));
2704 		bzero(&ssrc, sizeof(ssrc));
2705 		sdst.sin6_family = sgw.sin6_family = ssrc.sin6_family = AF_INET6;
2706 		sdst.sin6_len = sgw.sin6_len = ssrc.sin6_len =
2707 		    sizeof(struct sockaddr_in6);
2708 		if (!in6_embedded_scope) {
2709 			sdst.sin6_scope_id = reddst_ifscope;
2710 			sgw.sin6_scope_id = redtgt_ifscope;
2711 			ssrc.sin6_scope_id = src_ifscope;
2712 		}
2713 		bcopy(&redtgt6, &sgw.sin6_addr, sizeof(struct in6_addr));
2714 		bcopy(&reddst6, &sdst.sin6_addr, sizeof(struct in6_addr));
2715 		bcopy(&src6, &ssrc.sin6_addr, sizeof(struct in6_addr));
2716 
2717 		rtredirect(ifp, (struct sockaddr *)&sdst,
2718 		    (struct sockaddr *)&sgw, NULL, RTF_GATEWAY | RTF_HOST,
2719 		    (struct sockaddr *)&ssrc, NULL);
2720 	}
2721 	/* finally update cached route in each socket via pfctlinput */
2722 	{
2723 		struct sockaddr_in6 sdst;
2724 
2725 		bzero(&sdst, sizeof(sdst));
2726 		sdst.sin6_family = AF_INET6;
2727 		sdst.sin6_len = sizeof(struct sockaddr_in6);
2728 		if (!in6_embedded_scope) {
2729 			sdst.sin6_scope_id = reddst_ifscope;
2730 		}
2731 		bcopy(&reddst6, &sdst.sin6_addr, sizeof(struct in6_addr));
2732 
2733 		pfctlinput(PRC_REDIRECT_HOST, (struct sockaddr *)&sdst);
2734 #if IPSEC
2735 		key_sa_routechange((struct sockaddr *)&sdst);
2736 #endif
2737 	}
2738 
2739 freeit:
2740 	m_freem(m);
2741 	return;
2742 
2743 bad:
2744 	icmp6stat.icp6s_badredirect++;
2745 	m_freem(m);
2746 }
2747 
2748 void
icmp6_redirect_output(struct mbuf * m0,struct rtentry * rt)2749 icmp6_redirect_output(struct mbuf *m0, struct rtentry *rt)
2750 {
2751 	struct ifnet *ifp;      /* my outgoing interface */
2752 	struct in6_addr ifp_ll6;
2753 	struct in6_addr *router_ll6;
2754 	struct ip6_hdr *sip6;   /* m0 as struct ip6_hdr */
2755 	struct mbuf *m = NULL;  /* newly allocated one */
2756 	struct ip6_hdr *ip6;    /* m as struct ip6_hdr */
2757 	struct nd_redirect *nd_rd;
2758 	size_t maxlen;
2759 	u_char *p;
2760 	struct ifnet *outif = NULL;
2761 	struct sockaddr_in6 src_sa;
2762 	struct ip6_out_args ip6oa;
2763 
2764 	bzero(&ip6oa, sizeof(ip6oa));
2765 	ip6oa.ip6oa_boundif = IFSCOPE_NONE;
2766 	ip6oa.ip6oa_flags = IP6OAF_SELECT_SRCIF | IP6OAF_BOUND_SRCADDR;
2767 	ip6oa.ip6oa_sotc = SO_TC_UNSPEC;
2768 	ip6oa.ip6oa_netsvctype = _NET_SERVICE_TYPE_UNSPEC;
2769 
2770 	icmp6_errcount(&icmp6stat.icp6s_outerrhist, ND_REDIRECT, 0);
2771 
2772 	if (rt != NULL) {
2773 		RT_LOCK(rt);
2774 	}
2775 
2776 	/* sanity check */
2777 	if (!m0 || !rt || !(rt->rt_flags & RTF_UP) || !(ifp = rt->rt_ifp)) {
2778 		goto fail;
2779 	}
2780 
2781 	/*
2782 	 * If we are not a router to begin with, or not an advertising
2783 	 * router on this interface, don't send icmp6 redirect.
2784 	 */
2785 	if (!ip6_forwarding || ifp->if_ipv6_router_mode != IPV6_ROUTER_MODE_EXCLUSIVE) {
2786 		goto fail;
2787 	}
2788 
2789 	/*
2790 	 * Address check:
2791 	 *  the source address must identify a neighbor, and
2792 	 *  the destination address must not be a multicast address
2793 	 *  [RFC 2461, sec 8.2]
2794 	 */
2795 	sip6 = mtod(m0, struct ip6_hdr *);
2796 	bzero(&src_sa, sizeof(src_sa));
2797 	src_sa.sin6_family = AF_INET6;
2798 	src_sa.sin6_len = sizeof(src_sa);
2799 	src_sa.sin6_addr = sip6->ip6_src;
2800 	/* we don't currently use sin6_scope_id, but eventually use it */
2801 	src_sa.sin6_scope_id = in6_addr2scopeid(ifp, &sip6->ip6_src);
2802 
2803 	RT_UNLOCK(rt);
2804 	if (nd6_is_addr_neighbor(&src_sa, ifp, 0) == 0) {
2805 		/* already unlocked */
2806 		rt = NULL;
2807 		goto fail;
2808 	}
2809 	RT_LOCK(rt);
2810 	if (IN6_IS_ADDR_MULTICAST(&sip6->ip6_dst)) {
2811 		goto fail;      /* what should we do here? */
2812 	}
2813 	/* rate limit */
2814 	if (icmp6_ratelimit(&sip6->ip6_src, ND_REDIRECT, 0)) {
2815 		goto fail;
2816 	}
2817 
2818 	/*
2819 	 * Since we are going to append up to 1280 bytes (= IPV6_MMTU),
2820 	 * we almost always ask for an mbuf cluster for simplicity.
2821 	 * (MHLEN < IPV6_MMTU is almost always true)
2822 	 */
2823 #if IPV6_MMTU >= MCLBYTES
2824 # error assumption failed about IPV6_MMTU and MCLBYTES
2825 #endif
2826 	MGETHDR(m, M_DONTWAIT, MT_HEADER);      /* MAC-OK */
2827 	if (m && IPV6_MMTU >= MHLEN) {
2828 		MCLGET(m, M_DONTWAIT);
2829 	}
2830 	if (!m) {
2831 		goto fail;
2832 	}
2833 	m->m_pkthdr.rcvif = NULL;
2834 	m->m_len = 0;
2835 	maxlen = M_TRAILINGSPACE(m);
2836 	maxlen = MIN(IPV6_MMTU, maxlen);
2837 	/* just for safety */
2838 	if (maxlen < sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr) +
2839 	    ((sizeof(struct nd_opt_hdr) + ifp->if_addrlen + 7) & ~7)) {
2840 		goto fail;
2841 	}
2842 
2843 	{
2844 		/* get ip6 linklocal address for ifp(my outgoing interface). */
2845 		struct in6_ifaddr *ia;
2846 		if ((ia = in6ifa_ifpforlinklocal(ifp,
2847 		    IN6_IFF_NOTREADY |
2848 		    IN6_IFF_ANYCAST)) == NULL) {
2849 			goto fail;
2850 		}
2851 		IFA_LOCK(&ia->ia_ifa);
2852 		ifp_ll6 = ia->ia_addr.sin6_addr;
2853 		IFA_UNLOCK(&ia->ia_ifa);
2854 		IFA_REMREF(&ia->ia_ifa);
2855 	}
2856 
2857 	/* get ip6 linklocal address for the router. */
2858 	if (rt->rt_gateway && (rt->rt_flags & RTF_GATEWAY)) {
2859 		struct sockaddr_in6 *sin6;
2860 		sin6 = (struct sockaddr_in6 *)(void *)rt->rt_gateway;
2861 		router_ll6 = &sin6->sin6_addr;
2862 		if (!IN6_IS_ADDR_LINKLOCAL(router_ll6)) {
2863 			router_ll6 = (struct in6_addr *)NULL;
2864 		}
2865 	} else {
2866 		router_ll6 = (struct in6_addr *)NULL;
2867 	}
2868 
2869 	/* ip6 */
2870 	ip6 = mtod(m, struct ip6_hdr *);
2871 	ip6->ip6_flow = 0;
2872 	ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
2873 	ip6->ip6_vfc |= IPV6_VERSION;
2874 	/* ip6->ip6_plen will be set later */
2875 	ip6->ip6_nxt = IPPROTO_ICMPV6;
2876 	ip6->ip6_hlim = IPV6_MAXHLIM;
2877 	/* ip6->ip6_src must be linklocal addr for my outgoing if. */
2878 	bcopy(&ifp_ll6, &ip6->ip6_src, sizeof(struct in6_addr));
2879 	bcopy(&sip6->ip6_src, &ip6->ip6_dst, sizeof(struct in6_addr));
2880 
2881 	/* ND Redirect */
2882 	nd_rd = (struct nd_redirect *)(ip6 + 1);
2883 	nd_rd->nd_rd_type = ND_REDIRECT;
2884 	nd_rd->nd_rd_code = 0;
2885 	nd_rd->nd_rd_reserved = 0;
2886 	if (rt->rt_flags & RTF_GATEWAY) {
2887 		/*
2888 		 * nd_rd->nd_rd_target must be a link-local address in
2889 		 * better router cases.
2890 		 */
2891 		if (!router_ll6) {
2892 			goto fail;
2893 		}
2894 		bcopy(router_ll6, &nd_rd->nd_rd_target,
2895 		    sizeof(nd_rd->nd_rd_target));
2896 		bcopy(&sip6->ip6_dst, &nd_rd->nd_rd_dst,
2897 		    sizeof(nd_rd->nd_rd_dst));
2898 	} else {
2899 		/* make sure redtgt == reddst */
2900 		bcopy(&sip6->ip6_dst, &nd_rd->nd_rd_target,
2901 		    sizeof(nd_rd->nd_rd_target));
2902 		bcopy(&sip6->ip6_dst, &nd_rd->nd_rd_dst,
2903 		    sizeof(nd_rd->nd_rd_dst));
2904 	}
2905 	RT_UNLOCK(rt);
2906 	rt = NULL;
2907 
2908 	p = (u_char *)(nd_rd + 1);
2909 
2910 	if (!router_ll6) {
2911 		goto nolladdropt;
2912 	}
2913 
2914 	{
2915 		/* target lladdr option */
2916 		struct rtentry *rt_router = NULL;
2917 		int len;
2918 		struct sockaddr_dl *sdl;
2919 		struct nd_opt_hdr *nd_opt;
2920 		char *lladdr;
2921 
2922 		/* Callee returns a locked route upon success */
2923 		rt_router = nd6_lookup(router_ll6, 0, ifp, 0);
2924 		if (!rt_router) {
2925 			goto nolladdropt;
2926 		}
2927 		RT_LOCK_ASSERT_HELD(rt_router);
2928 		len = sizeof(*nd_opt) + ifp->if_addrlen;
2929 		len = (len + 7) & ~7;   /* round by 8 */
2930 		/* safety check */
2931 		if (len + (p - (u_char *)ip6) > maxlen) {
2932 			RT_REMREF_LOCKED(rt_router);
2933 			RT_UNLOCK(rt_router);
2934 			goto nolladdropt;
2935 		}
2936 
2937 		if (!(rt_router->rt_flags & RTF_GATEWAY) &&
2938 		    (rt_router->rt_flags & RTF_LLINFO) &&
2939 		    (rt_router->rt_gateway->sa_family == AF_LINK) &&
2940 		    (sdl = (struct sockaddr_dl *)(void *)
2941 		    rt_router->rt_gateway) && sdl->sdl_alen) {
2942 			nd_opt = (struct nd_opt_hdr *)p;
2943 			nd_opt->nd_opt_type = ND_OPT_TARGET_LINKADDR;
2944 			nd_opt->nd_opt_len = (uint8_t)(len >> 3);
2945 			lladdr = (char *)(nd_opt + 1);
2946 			bcopy(LLADDR(sdl), lladdr, ifp->if_addrlen);
2947 			p += len;
2948 		}
2949 		RT_REMREF_LOCKED(rt_router);
2950 		RT_UNLOCK(rt_router);
2951 	}
2952 
2953 nolladdropt:;
2954 
2955 	m->m_pkthdr.len = m->m_len = (int32_t)(p - (u_char *)ip6);
2956 
2957 	/* just to be safe */
2958 #ifdef M_DECRYPTED      /*not openbsd*/
2959 	if (m0->m_flags & M_DECRYPTED) {
2960 		goto noredhdropt;
2961 	}
2962 #endif
2963 	if (p - (u_char *)ip6 > maxlen) {
2964 		goto noredhdropt;
2965 	}
2966 
2967 	{
2968 		/* redirected header option */
2969 		int len;
2970 		struct nd_opt_rd_hdr *nd_opt_rh;
2971 
2972 		/*
2973 		 * compute the maximum size for icmp6 redirect header option.
2974 		 * XXX room for auth header?
2975 		 */
2976 		len = (int)(maxlen - (p - (u_char *)ip6));
2977 		len &= ~7;
2978 
2979 		/* This is just for simplicity. */
2980 		if (m0->m_pkthdr.len != m0->m_len) {
2981 			if (m0->m_next) {
2982 				m_freem(m0->m_next);
2983 				m0->m_next = NULL;
2984 			}
2985 			m0->m_pkthdr.len = m0->m_len;
2986 		}
2987 
2988 		/*
2989 		 * Redirected header option spec (RFC2461 4.6.3) talks nothing
2990 		 * about padding/truncate rule for the original IP packet.
2991 		 * From the discussion on IPv6imp in Feb 1999, the consensus was:
2992 		 * - "attach as much as possible" is the goal
2993 		 * - pad if not aligned (original size can be guessed by original
2994 		 *   ip6 header)
2995 		 * Following code adds the padding if it is simple enough,
2996 		 * and truncates if not.
2997 		 */
2998 		if (m0->m_next || m0->m_pkthdr.len != m0->m_len) {
2999 			panic("assumption failed in %s:%d", __func__, __LINE__);
3000 		}
3001 
3002 		if (len - sizeof(*nd_opt_rh) < m0->m_pkthdr.len) {
3003 			/* not enough room, truncate */
3004 			m0->m_pkthdr.len = m0->m_len = len - sizeof(*nd_opt_rh);
3005 		} else {
3006 			/* enough room, pad or truncate */
3007 			size_t extra;
3008 
3009 			extra = m0->m_pkthdr.len % 8;
3010 			if (extra) {
3011 				/* pad if easy enough, truncate if not */
3012 				if (8 - extra <= M_TRAILINGSPACE(m0)) {
3013 					/* pad */
3014 					m0->m_len += (8 - extra);
3015 					m0->m_pkthdr.len += (8 - extra);
3016 				} else {
3017 					/* truncate */
3018 					m0->m_pkthdr.len -= extra;
3019 					m0->m_len -= extra;
3020 				}
3021 			}
3022 			len = m0->m_pkthdr.len + sizeof(*nd_opt_rh);
3023 			m0->m_pkthdr.len = m0->m_len = len - sizeof(*nd_opt_rh);
3024 		}
3025 
3026 		nd_opt_rh = (struct nd_opt_rd_hdr *)p;
3027 		bzero(nd_opt_rh, sizeof(*nd_opt_rh));
3028 		nd_opt_rh->nd_opt_rh_type = ND_OPT_REDIRECTED_HEADER;
3029 		nd_opt_rh->nd_opt_rh_len = (uint8_t)(len >> 3);
3030 		p += sizeof(*nd_opt_rh);
3031 		m->m_pkthdr.len = m->m_len = (int32_t)(p - (u_char *)ip6);
3032 
3033 		/* connect m0 to m */
3034 		m->m_next = m0;
3035 		m->m_pkthdr.len = m->m_len + m0->m_len;
3036 	}
3037 noredhdropt:;
3038 
3039 	/* XXX: clear embedded link IDs in the inner header */
3040 	in6_clearscope(&sip6->ip6_src);
3041 	in6_clearscope(&sip6->ip6_dst);
3042 	in6_clearscope(&nd_rd->nd_rd_target);
3043 	in6_clearscope(&nd_rd->nd_rd_dst);
3044 
3045 	ip6->ip6_plen = htons((uint16_t)(m->m_pkthdr.len - sizeof(struct ip6_hdr)));
3046 
3047 	nd_rd->nd_rd_cksum = 0;
3048 	nd_rd->nd_rd_cksum
3049 	        = in6_cksum(m, IPPROTO_ICMPV6, sizeof(*ip6), ntohs(ip6->ip6_plen));
3050 
3051 	/* send the packet to outside... */
3052 	ip6oa.ip6oa_boundif = ifp->if_index;
3053 	ip6oa.ip6oa_flags |= IP6OAF_BOUND_IF;
3054 	ip6oa.ip6oa_flags |= IP6OAF_DONT_FRAG;
3055 
3056 	ip6_output_setsrcifscope(m, ifp->if_index, NULL);
3057 	ip6_output_setdstifscope(m, ifp->if_index, NULL);
3058 
3059 	ip6_output(m, NULL, NULL, IPV6_OUTARGS, NULL, &outif, &ip6oa);
3060 	if (outif) {
3061 		icmp6_ifstat_inc(outif, ifs6_out_msg);
3062 		icmp6_ifstat_inc(outif, ifs6_out_redirect);
3063 		ifnet_release(outif);
3064 	}
3065 	icmp6stat.icp6s_outhist[ND_REDIRECT]++;
3066 
3067 	return;
3068 
3069 fail:
3070 	if (rt != NULL) {
3071 		RT_UNLOCK(rt);
3072 	}
3073 	if (m) {
3074 		m_freem(m);
3075 	}
3076 	if (m0) {
3077 		m_freem(m0);
3078 	}
3079 }
3080 
3081 /*
3082  * ICMPv6 socket option processing.
3083  */
3084 int
icmp6_ctloutput(struct socket * so,struct sockopt * sopt)3085 icmp6_ctloutput(struct socket *so, struct sockopt *sopt)
3086 {
3087 	int error = 0;
3088 	size_t optlen;
3089 	struct inpcb *inp = sotoinpcb(so);
3090 	int level, op, optname;
3091 
3092 	if (sopt) {
3093 		level = sopt->sopt_level;
3094 		op = sopt->sopt_dir;
3095 		optname = sopt->sopt_name;
3096 		optlen = sopt->sopt_valsize;
3097 	} else {
3098 		level = op = optname = optlen = 0;
3099 	}
3100 
3101 	if (level != IPPROTO_ICMPV6) {
3102 		return EINVAL;
3103 	}
3104 
3105 	switch (op) {
3106 	case PRCO_SETOPT:
3107 		switch (optname) {
3108 		case ICMP6_FILTER:
3109 		{
3110 			struct icmp6_filter *p;
3111 
3112 			if (optlen != 0 && optlen != sizeof(*p)) {
3113 				error = EMSGSIZE;
3114 				break;
3115 			}
3116 			if (inp->in6p_icmp6filt == NULL) {
3117 				error = EINVAL;
3118 				break;
3119 			}
3120 
3121 			if (optlen == 0) {
3122 				/* According to RFC 3542, an installed filter can be
3123 				 * cleared by issuing a setsockopt for ICMP6_FILTER
3124 				 * with a zero length.
3125 				 */
3126 				ICMP6_FILTER_SETPASSALL(inp->in6p_icmp6filt);
3127 			} else {
3128 				error = sooptcopyin(sopt, inp->in6p_icmp6filt, optlen,
3129 				    optlen);
3130 			}
3131 			break;
3132 		}
3133 
3134 		default:
3135 			error = ENOPROTOOPT;
3136 			break;
3137 		}
3138 		break;
3139 
3140 	case PRCO_GETOPT:
3141 		switch (optname) {
3142 		case ICMP6_FILTER:
3143 		{
3144 			if (inp->in6p_icmp6filt == NULL) {
3145 				error = EINVAL;
3146 				break;
3147 			}
3148 			error = sooptcopyout(sopt, inp->in6p_icmp6filt,
3149 			    MIN(sizeof(struct icmp6_filter), optlen));
3150 			break;
3151 		}
3152 
3153 		default:
3154 			error = ENOPROTOOPT;
3155 			break;
3156 		}
3157 		break;
3158 	}
3159 
3160 	return error;
3161 }
3162 
3163 /*
3164  * ICMPv6 socket datagram option processing.
3165  */
3166 int
icmp6_dgram_ctloutput(struct socket * so,struct sockopt * sopt)3167 icmp6_dgram_ctloutput(struct socket *so, struct sockopt *sopt)
3168 {
3169 	/*
3170 	 * For { SOCK_RAW, IPPROTO_ICMPV6 } the pr_ctloutput is
3171 	 * rip6_ctloutput() and not icmp6_ctloutput()
3172 	 */
3173 	if (kauth_cred_issuser(so->so_cred)) {
3174 		return rip6_ctloutput(so, sopt);
3175 	}
3176 
3177 	if (sopt->sopt_level == IPPROTO_ICMPV6) {
3178 		switch (sopt->sopt_name) {
3179 		case ICMP6_FILTER:
3180 			return icmp6_ctloutput(so, sopt);
3181 		default:
3182 			return EPERM;
3183 		}
3184 	}
3185 
3186 	if (sopt->sopt_level != IPPROTO_IPV6) {
3187 		return EINVAL;
3188 	}
3189 
3190 	switch (sopt->sopt_name) {
3191 	case IPV6_UNICAST_HOPS:
3192 	case IPV6_CHECKSUM:
3193 	case IPV6_V6ONLY:
3194 	case IPV6_USE_MIN_MTU:
3195 	case IPV6_RECVRTHDR:
3196 	case IPV6_RECVPKTINFO:
3197 	case IPV6_RECVHOPLIMIT:
3198 	case IPV6_PATHMTU:
3199 	case IPV6_PKTINFO:
3200 	case IPV6_HOPLIMIT:
3201 	case IPV6_HOPOPTS:
3202 	case IPV6_DSTOPTS:
3203 	case IPV6_MULTICAST_IF:
3204 	case IPV6_MULTICAST_HOPS:
3205 	case IPV6_MULTICAST_LOOP:
3206 	case IPV6_JOIN_GROUP:
3207 	case IPV6_LEAVE_GROUP:
3208 	case IPV6_PORTRANGE:
3209 	case IPV6_IPSEC_POLICY:
3210 	case IPV6_RECVTCLASS:
3211 	case IPV6_TCLASS:
3212 	case IPV6_2292PKTOPTIONS:
3213 	case IPV6_2292PKTINFO:
3214 	case IPV6_2292HOPLIMIT:
3215 	case IPV6_2292HOPOPTS:
3216 	case IPV6_2292DSTOPTS:
3217 	case IPV6_2292RTHDR:
3218 	case IPV6_BOUND_IF:
3219 	case IPV6_NO_IFT_CELLULAR:
3220 		return ip6_ctloutput(so, sopt);
3221 
3222 	default:
3223 		return EPERM;
3224 	}
3225 }
3226 
3227 __private_extern__ int
icmp6_dgram_send(struct socket * so,int flags,struct mbuf * m,struct sockaddr * nam,struct mbuf * control,struct proc * p)3228 icmp6_dgram_send(struct socket *so, int flags, struct mbuf *m,
3229     struct sockaddr *nam, struct mbuf *control, struct proc *p)
3230 {
3231 #pragma unused(flags, p)
3232 	int error = 0;
3233 	struct inpcb *inp = sotoinpcb(so);
3234 	struct icmp6_hdr *icmp6;
3235 
3236 	if (inp == NULL
3237 #if NECP
3238 	    || (necp_socket_should_use_flow_divert(inp))
3239 #endif /* NECP */
3240 	    ) {
3241 		error = (inp == NULL ? EINVAL : EPROTOTYPE);
3242 		goto bad;
3243 	}
3244 
3245 	if (kauth_cred_issuser(so->so_cred)) {
3246 		return rip6_output(m, so, SIN6(nam), control, 0);
3247 	}
3248 
3249 	/*
3250 	 * For an ICMPv6 packet, we should know its type and code
3251 	 */
3252 	if (SOCK_PROTO(so) == IPPROTO_ICMPV6) {
3253 		if (m->m_len < sizeof(struct icmp6_hdr) &&
3254 		    (m = m_pullup(m, sizeof(struct icmp6_hdr))) == NULL) {
3255 			error = ENOBUFS;
3256 			goto bad;
3257 		}
3258 		icmp6 = mtod(m, struct icmp6_hdr *);
3259 
3260 		/*
3261 		 * Allow only to send echo request and node information request
3262 		 * See RFC 2463 for Echo Request Message format
3263 		 */
3264 		if ((icmp6->icmp6_type == ICMP6_ECHO_REQUEST &&
3265 		    icmp6->icmp6_code == 0) ||
3266 		    (icmp6->icmp6_type == ICMP6_NI_QUERY &&
3267 		    (icmp6->icmp6_code == ICMP6_NI_SUBJ_IPV6 ||
3268 		    icmp6->icmp6_code == ICMP6_NI_SUBJ_FQDN))) {
3269 			/* Good */
3270 			;
3271 		} else {
3272 			error = EPERM;
3273 			goto bad;
3274 		}
3275 	}
3276 
3277 	return rip6_output(m, so, SIN6(nam), control, 0);
3278 bad:
3279 	VERIFY(error != 0);
3280 
3281 	if (m != NULL) {
3282 		m_freem(m);
3283 	}
3284 	if (control != NULL) {
3285 		m_freem(control);
3286 	}
3287 
3288 	return error;
3289 }
3290 
3291 /* Like rip6_attach but without root privilege enforcement */
3292 __private_extern__ int
icmp6_dgram_attach(struct socket * so,int proto,struct proc * p)3293 icmp6_dgram_attach(struct socket *so, int proto, struct proc *p)
3294 {
3295 	struct inpcb *inp;
3296 	int error;
3297 
3298 	inp = sotoinpcb(so);
3299 	if (inp) {
3300 		panic("icmp6_dgram_attach");
3301 	}
3302 
3303 	if (proto != IPPROTO_ICMPV6) {
3304 		return EINVAL;
3305 	}
3306 
3307 	error = soreserve(so, rip_sendspace, rip_recvspace);
3308 	if (error) {
3309 		return error;
3310 	}
3311 	error = in_pcballoc(so, &ripcbinfo, p);
3312 	if (error) {
3313 		return error;
3314 	}
3315 	inp = (struct inpcb *)so->so_pcb;
3316 	inp->inp_vflag |= INP_IPV6;
3317 	inp->in6p_ip6_nxt = IPPROTO_ICMPV6;
3318 	inp->in6p_hops = -1;    /* use kernel default */
3319 	inp->in6p_cksum = -1;
3320 	inp->in6p_icmp6filt = kalloc_type(struct icmp6_filter,
3321 	    Z_WAITOK | Z_NOFAIL);
3322 	ICMP6_FILTER_SETPASSALL(inp->in6p_icmp6filt);
3323 	return 0;
3324 }
3325 
3326 
3327 /*
3328  * Perform rate limit check.
3329  * Returns 0 if it is okay to send the icmp6 packet.
3330  * Returns 1 if the router SHOULD NOT send this icmp6 packet due to rate
3331  * limitation.
3332  *
3333  * XXX per-destination check necessary?
3334  */
3335 static int
icmp6_ratelimit(__unused const struct in6_addr * dst,const int type,__unused const int code)3336 icmp6_ratelimit(
3337 	__unused const struct in6_addr *dst,    /* not used at this moment */
3338 	const int type,
3339 	__unused const int code)
3340 {
3341 	int ret;
3342 
3343 	ret = 0;        /* okay to send */
3344 
3345 	/* PPS limit */
3346 	if (type == ND_ROUTER_ADVERT) {
3347 		if (!ppsratecheck(&icmp6rappslim_last, &icmp6rapps_count,
3348 		    icmp6rappslim)) {
3349 			ret++;
3350 		}
3351 	} else if (!ppsratecheck(&icmp6errppslim_last, &icmp6errpps_count,
3352 	    icmp6errppslim)) {
3353 		/*
3354 		 * We add some randomness here to still generate ICMPv6 error
3355 		 * post icmp6errppslim limit with a probability that goes down
3356 		 * with increased value of icmp6errpps_count.
3357 		 */
3358 		if (icmp6errpps_count > 0 && icmp6errppslim > 0 &&
3359 		    icmp6errpps_count > icmp6errppslim &&
3360 		    (random() % (icmp6errpps_count - icmp6errppslim)) != 0) {
3361 			/* The packet is subject to rate limit */
3362 			ret++;
3363 		}
3364 	}
3365 
3366 	return ret;
3367 }
3368