xref: /xnu-12377.81.4/bsd/netinet6/ip6_input.c (revision 043036a2b3718f7f0be807e2870f8f47d3fa0796)
1 /*
2  * Copyright (c) 2003-2025 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 /*
30  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
31  * All rights reserved.
32  *
33  * Redistribution and use in source and binary forms, with or without
34  * modification, are permitted provided that the following conditions
35  * are met:
36  * 1. Redistributions of source code must retain the above copyright
37  *    notice, this list of conditions and the following disclaimer.
38  * 2. Redistributions in binary form must reproduce the above copyright
39  *    notice, this list of conditions and the following disclaimer in the
40  *    documentation and/or other materials provided with the distribution.
41  * 3. Neither the name of the project nor the names of its contributors
42  *    may be used to endorse or promote products derived from this software
43  *    without specific prior written permission.
44  *
45  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
46  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
49  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55  * SUCH DAMAGE.
56  */
57 
58 /*
59  * Copyright (c) 1982, 1986, 1988, 1993
60  *	The Regents of the University of California.  All rights reserved.
61  *
62  * Redistribution and use in source and binary forms, with or without
63  * modification, are permitted provided that the following conditions
64  * are met:
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  * 2. Redistributions in binary form must reproduce the above copyright
68  *    notice, this list of conditions and the following disclaimer in the
69  *    documentation and/or other materials provided with the distribution.
70  * 3. All advertising materials mentioning features or use of this software
71  *    must display the following acknowledgement:
72  *	This product includes software developed by the University of
73  *	California, Berkeley and its contributors.
74  * 4. Neither the name of the University nor the names of its contributors
75  *    may be used to endorse or promote products derived from this software
76  *    without specific prior written permission.
77  *
78  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
79  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
80  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
81  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
82  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
83  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
84  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
85  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
86  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
87  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
88  * SUCH DAMAGE.
89  *
90  *	@(#)ip_input.c	8.2 (Berkeley) 1/4/94
91  */
92 
93 #include <sys/param.h>
94 #include <sys/systm.h>
95 #include <sys/malloc.h>
96 #include <sys/mbuf.h>
97 #include <sys/domain.h>
98 #include <sys/protosw.h>
99 #include <sys/socket.h>
100 #include <sys/socketvar.h>
101 #include <sys/errno.h>
102 #include <sys/time.h>
103 #include <sys/kernel.h>
104 #include <sys/syslog.h>
105 #include <sys/sysctl.h>
106 #include <sys/proc.h>
107 #include <sys/kauth.h>
108 #include <sys/mcache.h>
109 
110 #include <mach/mach_time.h>
111 #include <mach/sdt.h>
112 #include <pexpert/pexpert.h>
113 #include <dev/random/randomdev.h>
114 
115 #include <net/if.h>
116 #include <net/if_var.h>
117 #include <net/if_types.h>
118 #include <net/if_dl.h>
119 #include <net/route.h>
120 #include <net/kpi_protocol.h>
121 #include <net/ntstat.h>
122 #include <net/init.h>
123 #include <net/net_osdep.h>
124 #include <net/net_perf.h>
125 #include <net/if_ports_used.h>
126 #include <net/droptap.h>
127 
128 #include <netinet/in.h>
129 #include <netinet/in_systm.h>
130 #if INET
131 #include <netinet/ip.h>
132 #include <netinet/ip_icmp.h>
133 #endif /* INET */
134 #include <netinet/kpi_ipfilter_var.h>
135 #include <netinet/ip6.h>
136 #include <netinet/udp.h>
137 #include <netinet6/in6_var.h>
138 #include <netinet6/ip6_var.h>
139 #include <netinet/in_pcb.h>
140 #include <netinet/icmp6.h>
141 #include <netinet6/in6_ifattach.h>
142 #include <netinet6/nd6.h>
143 #include <netinet6/scope6_var.h>
144 #include <netinet6/ip6protosw.h>
145 
146 #if IPSEC
147 #include <netinet6/ipsec.h>
148 #include <netinet6/ipsec6.h>
149 extern int ipsec_bypass;
150 #endif /* IPSEC */
151 
152 #if DUMMYNET
153 #include <netinet/ip_dummynet.h>
154 #endif /* DUMMYNET */
155 
156 /* we need it for NLOOP. */
157 #include "loop.h"
158 
159 #if PF
160 #include <net/pfvar.h>
161 #endif /* PF */
162 
163 #include <os/log.h>
164 
165 struct ip6protosw *ip6_protox[IPPROTO_MAX];
166 
167 static LCK_GRP_DECLARE(in6_ifaddr_rwlock_grp, "in6_ifaddr_rwlock");
168 LCK_RW_DECLARE(in6_ifaddr_rwlock, &in6_ifaddr_rwlock_grp);
169 
170 /* Protected by in6_ifaddr_rwlock */
171 struct in6_ifaddrhead in6_ifaddrhead;
172 uint32_t in6_ifaddrlist_genid = 0;
173 
174 #define IN6ADDR_NHASH    61
175 u_int32_t in6addr_hashp = 0;                  /* next largest prime */
176 u_int32_t in6addr_nhash = 0;                  /* hash table size */
177 struct in6_ifaddrhashhead *__counted_by(in6addr_nhash) in6_ifaddrhashtbl = 0;
178 
179 #define IN6_IFSTAT_REQUIRE_ALIGNED_64(f)        \
180 	static_assert(!(offsetof(struct in6_ifstat, f) % sizeof (uint64_t)))
181 
182 #define ICMP6_IFSTAT_REQUIRE_ALIGNED_64(f)      \
183 	static_assert(!(offsetof(struct icmp6_ifstat, f) % sizeof (uint64_t)))
184 
185 struct ip6stat ip6stat;
186 
187 LCK_ATTR_DECLARE(ip6_mutex_attr, 0, 0);
188 LCK_GRP_DECLARE(ip6_mutex_grp, "ip6");
189 
190 LCK_MTX_DECLARE_ATTR(proxy6_lock, &ip6_mutex_grp, &ip6_mutex_attr);
191 LCK_MTX_DECLARE_ATTR(nd6_mutex_data, &ip6_mutex_grp, &ip6_mutex_attr);
192 
193 extern int loopattach_done;
194 extern void addrsel_policy_init(void);
195 
196 static int sysctl_reset_ip6_input_stats SYSCTL_HANDLER_ARGS;
197 static int sysctl_ip6_input_measure_bins SYSCTL_HANDLER_ARGS;
198 static int sysctl_ip6_input_getperf SYSCTL_HANDLER_ARGS;
199 static void ip6_init_delayed(void);
200 static int ip6_hopopts_input(u_int32_t *, u_int32_t *, struct mbuf **, int *);
201 
202 static void in6_ifaddrhashtbl_init(void);
203 
204 static struct m_tag *m_tag_kalloc_inet6(u_int32_t id, u_int16_t type, uint16_t len, int wait);
205 static void m_tag_kfree_inet6(struct m_tag *tag);
206 
207 #if NSTF
208 extern void stfattach(void);
209 #endif /* NSTF */
210 
211 SYSCTL_DECL(_net_inet6_ip6);
212 
213 static uint32_t ip6_adj_clear_hwcksum = 0;
214 SYSCTL_UINT(_net_inet6_ip6, OID_AUTO, adj_clear_hwcksum,
215     CTLFLAG_RW | CTLFLAG_LOCKED, &ip6_adj_clear_hwcksum, 0,
216     "Invalidate hwcksum info when adjusting length");
217 
218 static uint32_t ip6_adj_partial_sum = 1;
219 SYSCTL_UINT(_net_inet6_ip6, OID_AUTO, adj_partial_sum,
220     CTLFLAG_RW | CTLFLAG_LOCKED, &ip6_adj_partial_sum, 0,
221     "Perform partial sum adjustment of trailing bytes at IP layer");
222 
223 static int ip6_input_measure = 0;
224 SYSCTL_PROC(_net_inet6_ip6, OID_AUTO, input_perf,
225     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
226     &ip6_input_measure, 0, sysctl_reset_ip6_input_stats, "I", "Do time measurement");
227 
228 static uint64_t ip6_input_measure_bins = 0;
229 SYSCTL_PROC(_net_inet6_ip6, OID_AUTO, input_perf_bins,
230     CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED, &ip6_input_measure_bins, 0,
231     sysctl_ip6_input_measure_bins, "I",
232     "bins for chaining performance data histogram");
233 
234 static net_perf_t net_perf;
235 SYSCTL_PROC(_net_inet6_ip6, OID_AUTO, input_perf_data,
236     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED,
237     0, 0, sysctl_ip6_input_getperf, "S,net_perf",
238     "IP6 input performance data (struct net_perf, net/net_perf.h)");
239 
240 /*
241  * ip6_checkinterface controls the receive side of the models for multihoming
242  * that are discussed in RFC 1122.
243  *
244  * sysctl_ip6_checkinterface values are:
245  *  IP6_CHECKINTERFACE_WEAK_ES:
246  *	This corresponds to the Weak End-System model where incoming packets from
247  *	any interface are accepted provided the destination address of the incoming packet
248  *	is assigned to some interface.
249  *
250  *  IP6_CHECKINTERFACE_HYBRID_ES:
251  *	The Hybrid End-System model use the Strong End-System for tunnel interfaces
252  *	(ipsec and utun) and the weak End-System model for other interfaces families.
253  *	This prevents a rogue middle box to probe for signs of TCP connections
254  *	that use the tunnel interface.
255  *
256  *  IP6_CHECKINTERFACE_STRONG_ES:
257  *	The Strong model model requires the packet arrived on an interface that
258  *	is assigned the destination address of the packet.
259  *
260  * Since the routing table and transmit implementation do not implement the Strong ES model,
261  * setting this to a value different from IP6_CHECKINTERFACE_WEAK_ES may lead to unexpected results.
262  *
263  * When forwarding is enabled, the system reverts to the Weak ES model as a router
264  * is expected by design to receive packets from several interfaces to the same address.
265  */
266 #define IP6_CHECKINTERFACE_WEAK_ES       0
267 #define IP6_CHECKINTERFACE_HYBRID_ES     1
268 #define IP6_CHECKINTERFACE_STRONG_ES     2
269 
270 static int ip6_checkinterface = IP6_CHECKINTERFACE_HYBRID_ES;
271 
272 static int sysctl_ip6_checkinterface SYSCTL_HANDLER_ARGS;
273 SYSCTL_PROC(_net_inet6_ip6, OID_AUTO, check_interface,
274     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
275     0, 0, sysctl_ip6_checkinterface, "I", "Verify packet arrives on correct interface");
276 
277 #if (DEBUG || DEVELOPMENT)
278 #define IP6_CHECK_IFDEBUG 1
279 #else
280 #define IP6_CHECK_IFDEBUG 0
281 #endif /* (DEBUG || DEVELOPMENT) */
282 static int ip6_checkinterface_debug = IP6_CHECK_IFDEBUG;
283 SYSCTL_INT(_net_inet6_ip6, OID_AUTO, checkinterface_debug, CTLFLAG_RW | CTLFLAG_LOCKED,
284     &ip6_checkinterface_debug, IP6_CHECK_IFDEBUG, "");
285 
286 typedef enum ip6_check_if_result {
287 	IP6_CHECK_IF_NONE = 0,
288 	IP6_CHECK_IF_OURS = 1,
289 	IP6_CHECK_IF_DROP = 2,
290 	IP6_CHECK_IF_FORWARD = 3
291 } ip6_check_if_result_t;
292 
293 static ip6_check_if_result_t ip6_input_check_interface(struct mbuf *, struct ip6_hdr *, struct ifnet *, struct route_in6 *rin6, struct ifnet **);
294 
295 /*
296  * On platforms which require strict alignment (currently for anything but
297  * i386 or x86_64 or arm64), check if the IP header pointer is 32-bit aligned; if not,
298  * copy the contents of the mbuf chain into a new chain, and free the original
299  * one.  Create some head room in the first mbuf of the new chain, in case
300  * it's needed later on.
301  *
302  * RFC 2460 says that IPv6 headers are 64-bit aligned, but network interfaces
303  * mostly align to 32-bit boundaries.  Care should be taken never to use 64-bit
304  * load/store operations on the fields in IPv6 headers.
305  */
306 #if defined(__i386__) || defined(__x86_64__) || defined(__arm64__)
307 #define IP6_HDR_ALIGNMENT_FIXUP(_m, _ifp, _action) do { } while (0)
308 #else /* !__i386__ && !__x86_64__ && !__arm64__ */
309 #define IP6_HDR_ALIGNMENT_FIXUP(_m, _ifp, _action) do {             \
310 	if (!IP6_HDR_ALIGNED_P(mtod(_m, caddr_t))) {                    \
311 	        mbuf_ref_t _n;                                          \
312 	        ifnet_ref_t __ifp = (_ifp);                             \
313 	        os_atomic_inc(&(__ifp)->if_alignerrs, relaxed);         \
314 	        if (((_m)->m_flags & M_PKTHDR) &&                       \
315 	            (_m)->m_pkthdr.pkt_hdr != NULL)                     \
316 	                (_m)->m_pkthdr.pkt_hdr = NULL;                  \
317 	        _n = m_defrag_offset(_m, max_linkhdr, M_NOWAIT);        \
318 	        if (_n == NULL) {                                       \
319 	                ip6stat.ip6s_toosmall++;                        \
320 	                m_drop(_m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_TOO_SMALL, NULL, 0); \
321 	                (_m) = NULL;                                    \
322 	                _action;                                        \
323 	        } else {                                                \
324 	                VERIFY(_n != (_m));                             \
325 	                (_m) = _n;                                      \
326 	        }                                                       \
327 	}                                                               \
328 } while (0)
329 #endif /* !__i386__ && !__x86_64___ && !__arm64__ */
330 
331 static void
ip6_proto_input(protocol_family_t protocol,mbuf_t packet)332 ip6_proto_input(protocol_family_t protocol, mbuf_t packet)
333 {
334 #pragma unused(protocol)
335 #if INET
336 	struct timeval start_tv;
337 	if (ip6_input_measure) {
338 		net_perf_start_time(&net_perf, &start_tv);
339 	}
340 #endif /* INET */
341 	ip6_input(packet);
342 #if INET
343 	if (ip6_input_measure) {
344 		net_perf_measure_time(&net_perf, &start_tv, 1);
345 		net_perf_histogram(&net_perf, 1);
346 	}
347 #endif /* INET */
348 }
349 
350 /*
351  * IP6 initialization: fill in IP6 protocol switch table.
352  * All protocols not implemented in kernel go to raw IP6 protocol handler.
353  */
354 void
ip6_init(struct protosw * pp,struct domain * dp)355 ip6_init(struct protosw *pp, struct domain *dp)
356 {
357 	static int ip6_initialized = 0;
358 	struct protosw *__single pr;
359 	struct timeval tv;
360 	int i;
361 	domain_unguard_t __single unguard;
362 
363 	domain_proto_mtx_lock_assert_held();
364 	VERIFY((pp->pr_flags & (PR_INITIALIZED | PR_ATTACHED)) == PR_ATTACHED);
365 
366 	static_assert((sizeof(struct ip6_hdr) + sizeof(struct icmp6_hdr)) <= _MHLEN);
367 
368 	static_assert(IP_RECV_LINK_ADDR_TYPE == IPV6_RECV_LINK_ADDR_TYPE);
369 
370 	if (!os_atomic_cmpxchg(&ip6_initialized, 0, 1, relaxed)) {
371 		return;
372 	}
373 
374 	eventhandler_lists_ctxt_init(&in6_evhdlr_ctxt);
375 	(void)EVENTHANDLER_REGISTER(&in6_evhdlr_ctxt, in6_event,
376 	    &in6_eventhdlr_callback, eventhandler_entry_dummy_arg,
377 	    EVENTHANDLER_PRI_ANY);
378 
379 	eventhandler_lists_ctxt_init(&in6_clat46_evhdlr_ctxt);
380 	(void)EVENTHANDLER_REGISTER(&in6_clat46_evhdlr_ctxt, in6_clat46_event,
381 	    &in6_clat46_eventhdlr_callback, eventhandler_entry_dummy_arg,
382 	    EVENTHANDLER_PRI_ANY);
383 
384 	for (i = 0; i < IN6_EVENT_MAX; i++) {
385 		VERIFY(in6_event2kev_array[i].in6_event_code == i);
386 	}
387 
388 	pr = pffindproto_locked(PF_INET6, IPPROTO_RAW, SOCK_RAW);
389 	if (pr == NULL) {
390 		panic("%s: Unable to find [PF_INET6,IPPROTO_RAW,SOCK_RAW]",
391 		    __func__);
392 		/* NOTREACHED */
393 	}
394 
395 	/* Initialize the entire ip6_protox[] array to IPPROTO_RAW. */
396 	for (i = 0; i < IPPROTO_MAX; i++) {
397 		ip6_protox[i] = (struct ip6protosw *)pr;
398 	}
399 	/*
400 	 * Cycle through IP protocols and put them into the appropriate place
401 	 * in ip6_protox[], skipping protocols IPPROTO_{IP,RAW}.
402 	 */
403 	VERIFY(dp == inet6domain && dp->dom_family == PF_INET6);
404 	TAILQ_FOREACH(pr, &dp->dom_protosw, pr_entry) {
405 		VERIFY(pr->pr_domain == dp);
406 		if (pr->pr_protocol != 0 && pr->pr_protocol != IPPROTO_RAW) {
407 			/* Be careful to only index valid IP protocols. */
408 			if (pr->pr_protocol < IPPROTO_MAX) {
409 				ip6_protox[pr->pr_protocol] =
410 				    (struct ip6protosw *)pr;
411 			}
412 		}
413 	}
414 
415 	TAILQ_INIT(&in6_ifaddrhead);
416 	in6_ifaddrhashtbl_init();
417 
418 	IN6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_receive);
419 	IN6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_hdrerr);
420 	IN6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_toobig);
421 	IN6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_noroute);
422 	IN6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_addrerr);
423 	IN6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_protounknown);
424 	IN6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_truncated);
425 	IN6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_discard);
426 	IN6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_deliver);
427 	IN6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_forward);
428 	IN6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_request);
429 	IN6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_discard);
430 	IN6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_fragok);
431 	IN6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_fragfail);
432 	IN6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_fragcreat);
433 	IN6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_reass_reqd);
434 	IN6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_reass_ok);
435 	IN6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_reass_fail);
436 	IN6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_mcast);
437 	IN6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_mcast);
438 
439 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_msg);
440 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_error);
441 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_dstunreach);
442 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_adminprohib);
443 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_timeexceed);
444 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_paramprob);
445 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_pkttoobig);
446 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_echo);
447 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_echoreply);
448 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_routersolicit);
449 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_routeradvert);
450 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_neighborsolicit);
451 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_neighboradvert);
452 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_redirect);
453 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_mldquery);
454 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_mldreport);
455 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_in_mlddone);
456 
457 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_msg);
458 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_error);
459 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_dstunreach);
460 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_adminprohib);
461 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_timeexceed);
462 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_paramprob);
463 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_pkttoobig);
464 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_echo);
465 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_echoreply);
466 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_routersolicit);
467 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_routeradvert);
468 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_neighborsolicit);
469 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_neighboradvert);
470 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_redirect);
471 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_mldquery);
472 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_mldreport);
473 	ICMP6_IFSTAT_REQUIRE_ALIGNED_64(ifs6_out_mlddone);
474 
475 	getmicrotime(&tv);
476 	ip6_desync_factor =
477 	    (RandomULong() ^ tv.tv_usec) % MAX_TEMP_DESYNC_FACTOR;
478 
479 	PE_parse_boot_argn("in6_embedded_scope", &in6_embedded_scope, sizeof(in6_embedded_scope));
480 	PE_parse_boot_argn("ip6_checkinterface", &i, sizeof(i));
481 	switch (i) {
482 	case IP6_CHECKINTERFACE_WEAK_ES:
483 	case IP6_CHECKINTERFACE_HYBRID_ES:
484 	case IP6_CHECKINTERFACE_STRONG_ES:
485 		ip6_checkinterface = i;
486 		break;
487 	default:
488 		break;
489 	}
490 
491 	in6_ifaddr_init();
492 	ip6_moptions_init();
493 	nd6_init();
494 	frag6_init();
495 	icmp6_init(NULL, dp);
496 	addrsel_policy_init();
497 
498 	/*
499 	 * P2P interfaces often route the local address to the loopback
500 	 * interface. At this point, lo0 hasn't been initialized yet, which
501 	 * means that we need to delay the IPv6 configuration of lo0.
502 	 */
503 	net_init_add(ip6_init_delayed);
504 
505 	unguard = domain_unguard_deploy();
506 	i = proto_register_input(PF_INET6, ip6_proto_input, NULL, 0);
507 	if (i != 0) {
508 		panic("%s: failed to register PF_INET6 protocol: %d",
509 		    __func__, i);
510 		/* NOTREACHED */
511 	}
512 	domain_unguard_release(unguard);
513 }
514 
515 static void
ip6_init_delayed(void)516 ip6_init_delayed(void)
517 {
518 	(void) in6_ifattach_prelim(lo_ifp);
519 
520 	/* timer for regeneranation of temporary addresses randomize ID */
521 	timeout(in6_tmpaddrtimer, NULL,
522 	    (ip6_temp_preferred_lifetime - ip6_desync_factor -
523 	    ip6_temp_regen_advance) * hz);
524 
525 #if NSTF
526 	stfattach();
527 #endif /* NSTF */
528 }
529 
530 static void
ip6_input_adjust(struct mbuf * m,struct ip6_hdr * ip6,uint32_t plen,struct ifnet * inifp)531 ip6_input_adjust(struct mbuf *m, struct ip6_hdr *ip6, uint32_t plen,
532     struct ifnet *inifp)
533 {
534 	boolean_t adjust = TRUE;
535 	uint32_t tot_len = sizeof(*ip6) + plen;
536 
537 	ASSERT(m_pktlen(m) > tot_len);
538 
539 	/*
540 	 * Invalidate hardware checksum info if ip6_adj_clear_hwcksum
541 	 * is set; useful to handle buggy drivers.  Note that this
542 	 * should not be enabled by default, as we may get here due
543 	 * to link-layer padding.
544 	 */
545 	if (ip6_adj_clear_hwcksum &&
546 	    (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) &&
547 	    !(inifp->if_flags & IFF_LOOPBACK) &&
548 	    !(m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
549 		m->m_pkthdr.csum_flags &= ~CSUM_DATA_VALID;
550 		m->m_pkthdr.csum_data = 0;
551 		ip6stat.ip6s_adj_hwcsum_clr++;
552 	}
553 
554 	/*
555 	 * If partial checksum information is available, subtract
556 	 * out the partial sum of postpended extraneous bytes, and
557 	 * update the checksum metadata accordingly.  By doing it
558 	 * here, the upper layer transport only needs to adjust any
559 	 * prepended extraneous bytes (else it will do both.)
560 	 */
561 	if (ip6_adj_partial_sum &&
562 	    (m->m_pkthdr.csum_flags & (CSUM_DATA_VALID | CSUM_PARTIAL)) ==
563 	    (CSUM_DATA_VALID | CSUM_PARTIAL)) {
564 		m->m_pkthdr.csum_rx_val = m_adj_sum16(m,
565 		    m->m_pkthdr.csum_rx_start, m->m_pkthdr.csum_rx_start,
566 		    (tot_len - m->m_pkthdr.csum_rx_start),
567 		    m->m_pkthdr.csum_rx_val);
568 	} else if ((m->m_pkthdr.csum_flags &
569 	    (CSUM_DATA_VALID | CSUM_PARTIAL)) ==
570 	    (CSUM_DATA_VALID | CSUM_PARTIAL)) {
571 		/*
572 		 * If packet has partial checksum info and we decided not
573 		 * to subtract the partial sum of postpended extraneous
574 		 * bytes here (not the default case), leave that work to
575 		 * be handled by the other layers.  For now, only TCP, UDP
576 		 * layers are capable of dealing with this.  For all other
577 		 * protocols (including fragments), trim and ditch the
578 		 * partial sum as those layers might not implement partial
579 		 * checksumming (or adjustment) at all.
580 		 */
581 		if (ip6->ip6_nxt == IPPROTO_TCP ||
582 		    ip6->ip6_nxt == IPPROTO_UDP) {
583 			adjust = FALSE;
584 		} else {
585 			m->m_pkthdr.csum_flags &= ~CSUM_DATA_VALID;
586 			m->m_pkthdr.csum_data = 0;
587 			ip6stat.ip6s_adj_hwcsum_clr++;
588 		}
589 	}
590 
591 	if (adjust) {
592 		ip6stat.ip6s_adj++;
593 		if (m->m_len == m->m_pkthdr.len) {
594 			m->m_len = tot_len;
595 			m->m_pkthdr.len = tot_len;
596 		} else {
597 			m_adj(m, tot_len - m->m_pkthdr.len);
598 		}
599 	}
600 }
601 
602 static ip6_check_if_result_t
ip6_input_check_interface(struct mbuf * m,struct ip6_hdr * ip6,struct ifnet * inifp,struct route_in6 * rin6,struct ifnet ** deliverifp)603 ip6_input_check_interface(struct mbuf *m, struct ip6_hdr *ip6, struct ifnet *inifp, struct route_in6 *rin6, struct ifnet **deliverifp)
604 {
605 	struct in6_ifaddr *__single ia6 = NULL;
606 	struct in6_addr tmp_dst = ip6->ip6_dst; /* copy to avoid unaligned access */
607 	struct in6_ifaddr *__single best_ia6 = NULL;
608 	uint32_t dst_ifscope = IFSCOPE_NONE;
609 	ip6_check_if_result_t result = IP6_CHECK_IF_NONE;
610 	enum drop_reason drop_reason = DROP_REASON_IP_RCV_IF_NO_MATCH;
611 
612 	*deliverifp = NULL;
613 
614 	if (m->m_pkthdr.pkt_flags & PKTF_IFAINFO) {
615 		dst_ifscope = m->m_pkthdr.dst_ifindex;
616 	} else {
617 		dst_ifscope = inifp->if_index;
618 	}
619 	/*
620 	 * Check for exact addresses in the hash bucket.
621 	 */
622 	lck_rw_lock_shared(&in6_ifaddr_rwlock);
623 	TAILQ_FOREACH(ia6, IN6ADDR_HASH(&tmp_dst), ia6_hash) {
624 		/*
625 		 * TODO: should we accept loopback
626 		 */
627 		if (in6_are_addr_equal_scoped(&ia6->ia_addr.sin6_addr, &tmp_dst, ia6->ia_ifp->if_index, dst_ifscope)) {
628 			if ((ia6->ia6_flags & IN6_IFF_NOTREADY) != 0) {
629 				continue;
630 			}
631 			best_ia6 = ia6;
632 			if (ia6->ia_ifp == inifp) {
633 				/*
634 				 * TODO: should we also accept locally originated packets
635 				 * or from loopback ???
636 				 */
637 				break;
638 			}
639 			/*
640 			 * Continue the loop in case there's a exact match with another
641 			 * interface
642 			 */
643 		}
644 	}
645 	if (best_ia6 != NULL) {
646 		if (best_ia6->ia_ifp != inifp && ip6_forwarding == 0 &&
647 		    ((ip6_checkinterface == IP6_CHECKINTERFACE_HYBRID_ES &&
648 		    (best_ia6->ia_ifp->if_family == IFNET_FAMILY_IPSEC ||
649 		    best_ia6->ia_ifp->if_family == IFNET_FAMILY_UTUN)) ||
650 		    ip6_checkinterface == IP6_CHECKINTERFACE_STRONG_ES)) {
651 			/*
652 			 * Drop when interface address check is strict and forwarding
653 			 * is disabled
654 			 */
655 			result = IP6_CHECK_IF_DROP;
656 		} else {
657 			if ((m->m_flags & (M_BCAST | M_MCAST)) != 0) {
658 				drop_reason = DROP_REASON_FSW_DEMUX_L2_MULTI_L3_UNI;
659 				result = IP6_CHECK_IF_DROP;
660 			} else {
661 				result = IP6_CHECK_IF_OURS;
662 				*deliverifp = best_ia6->ia_ifp;
663 				ip6_setdstifaddr_info(m, 0, best_ia6);
664 				ip6_setsrcifaddr_info(m, best_ia6->ia_ifp->if_index, NULL);
665 			}
666 		}
667 	}
668 	lck_rw_done(&in6_ifaddr_rwlock);
669 
670 	if (result == IP6_CHECK_IF_NONE) {
671 		/*
672 		 * Slow path: route lookup.
673 		 */
674 		struct sockaddr_in6 *__single dst6;
675 
676 		dst6 = SIN6(&rin6->ro_dst);
677 		dst6->sin6_len = sizeof(struct sockaddr_in6);
678 		dst6->sin6_family = AF_INET6;
679 		dst6->sin6_addr = ip6->ip6_dst;
680 		if (!in6_embedded_scope && IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
681 			dst6->sin6_scope_id = dst_ifscope;
682 		}
683 		rtalloc_scoped_ign((struct route *)rin6,
684 		    RTF_PRCLONING, IFSCOPE_NONE);
685 		if (rin6->ro_rt != NULL) {
686 			RT_LOCK_SPIN(rin6->ro_rt);
687 		}
688 
689 #define rt6_key(r) (SIN6(rn_get_key((r)->rt_nodes)))
690 
691 		/*
692 		 * Accept the packet if the forwarding interface to the destination
693 		 * according to the routing table is the loopback interface,
694 		 * unless the associated route has a gateway.
695 		 * Note that this approach causes to accept a packet if there is a
696 		 * route to the loopback interface for the destination of the packet.
697 		 * But we think it's even useful in some situations, e.g. when using
698 		 * a special daemon which wants to intercept the packet.
699 		 *
700 		 * XXX: some OSes automatically make a cloned route for the destination
701 		 * of an outgoing packet.  If the outgoing interface of the packet
702 		 * is a loopback one, the kernel would consider the packet to be
703 		 * accepted, even if we have no such address assinged on the interface.
704 		 * We check the cloned flag of the route entry to reject such cases,
705 		 * assuming that route entries for our own addresses are not made by
706 		 * cloning (it should be true because in6_addloop explicitly installs
707 		 * the host route).  However, we might have to do an explicit check
708 		 * while it would be less efficient.  Or, should we rather install a
709 		 * reject route for such a case?
710 		 */
711 		if (rin6->ro_rt != NULL &&
712 		    (rin6->ro_rt->rt_flags & (RTF_HOST | RTF_GATEWAY)) == RTF_HOST &&
713 #if RTF_WASCLONED
714 		    !(rin6->ro_rt->rt_flags & RTF_WASCLONED) &&
715 #endif
716 		    rin6->ro_rt->rt_ifp->if_type == IFT_LOOP) {
717 			ia6 = ifatoia6(rin6->ro_rt->rt_ifa);
718 			/*
719 			 * Packets to a tentative, duplicated, or somehow invalid
720 			 * address must not be accepted.
721 			 *
722 			 * For performance, test without acquiring the address lock;
723 			 * a lot of things in the address are set once and never
724 			 * changed (e.g. ia_ifp.)
725 			 */
726 			if (!(ia6->ia6_flags & IN6_IFF_NOTREADY)) {
727 				/* this address is ready */
728 				result = IP6_CHECK_IF_OURS;
729 				*deliverifp = ia6->ia_ifp;       /* correct? */
730 				/*
731 				 * record dst address information into mbuf.
732 				 */
733 				(void) ip6_setdstifaddr_info(m, 0, ia6);
734 				(void) ip6_setsrcifaddr_info(m, ia6->ia_ifp->if_index, NULL);
735 			}
736 		}
737 
738 		if (rin6->ro_rt != NULL) {
739 			RT_UNLOCK(rin6->ro_rt);
740 		}
741 	}
742 
743 	if (result == IP6_CHECK_IF_NONE) {
744 		if (ip6_forwarding == 0) {
745 			result = IP6_CHECK_IF_DROP;
746 		} else {
747 			result = IP6_CHECK_IF_FORWARD;
748 			ip6_setdstifaddr_info(m, inifp->if_index, NULL);
749 			ip6_setsrcifaddr_info(m, inifp->if_index, NULL);
750 		}
751 	}
752 
753 	if (result == IP6_CHECK_IF_OURS && *deliverifp != inifp) {
754 		ASSERT(*deliverifp != NULL);
755 		ip6stat.ip6s_rcv_if_weak_match++;
756 
757 		/*  Logging is too noisy when forwarding is enabled */
758 		if (ip6_checkinterface_debug != IP6_CHECKINTERFACE_WEAK_ES && ip6_forwarding != 0) {
759 			char src_str[MAX_IPv6_STR_LEN];
760 			char dst_str[MAX_IPv6_STR_LEN];
761 
762 			inet_ntop(AF_INET6, &ip6->ip6_src, src_str, sizeof(src_str));
763 			inet_ntop(AF_INET6, &ip6->ip6_dst, dst_str, sizeof(dst_str));
764 			os_log_info(OS_LOG_DEFAULT,
765 			    "%s: weak ES interface match to %s for packet from %s to %s proto %u received via %s",
766 			    __func__, (*deliverifp)->if_xname, src_str, dst_str, ip6->ip6_nxt, inifp->if_xname);
767 		}
768 	} else if (result == IP6_CHECK_IF_DROP) {
769 		ip6stat.ip6s_rcv_if_no_match++;
770 		if (ip6_checkinterface_debug > 0) {
771 			char src_str[MAX_IPv6_STR_LEN];
772 			char dst_str[MAX_IPv6_STR_LEN];
773 
774 			inet_ntop(AF_INET6, &ip6->ip6_src, src_str, sizeof(src_str));
775 			inet_ntop(AF_INET6, &ip6->ip6_dst, dst_str, sizeof(dst_str));
776 			if (drop_reason == DROP_REASON_IP_RCV_IF_NO_MATCH) {
777 				os_log(OS_LOG_DEFAULT,
778 				    "%s: no interface match for packet from %s to %s proto %u received via %s",
779 				    __func__, src_str, dst_str, ip6->ip6_nxt, inifp->if_xname);
780 			} else if (drop_reason == DROP_REASON_FSW_DEMUX_L2_MULTI_L3_UNI) {
781 				os_log(OS_LOG_DEFAULT,
782 				    "%s: Layer 3 unicast dst sent to layer 2 non unicast dst: from %s to %s proto %u received via %s",
783 				    __func__, src_str, dst_str, ip6->ip6_nxt, inifp->if_xname);
784 			}
785 		}
786 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, drop_reason, NULL, 0);
787 	}
788 
789 	return result;
790 }
791 
792 static void
ip6_input_process_wake_packet(struct mbuf * m)793 ip6_input_process_wake_packet(struct mbuf *m)
794 {
795 	struct ifnet *ifp = m->m_pkthdr.rcvif;
796 
797 	if (if_is_lpw_enabled(ifp)) {
798 		if_exit_lpw(ifp, "IP6 packet");
799 	}
800 }
801 
802 void
ip6_input(struct mbuf * m)803 ip6_input(struct mbuf *m)
804 {
805 	struct ip6_hdr *ip6;
806 	int off = sizeof(struct ip6_hdr), nest;
807 	u_int32_t plen;
808 	u_int32_t rtalert = ~0;
809 	int nxt = 0, ours = 0;
810 	ifnet_ref_t inifp, deliverifp = NULL;
811 	ipfilter_t __single inject_ipfref = NULL;
812 	int seen = 1;
813 #if DUMMYNET
814 	struct m_tag *__single tag;
815 	struct ip_fw_args args = {};
816 #endif /* DUMMYNET */
817 	struct route_in6 rin6 = {};
818 
819 	/*
820 	 * Check if the packet we received is valid after interface filter
821 	 * processing
822 	 */
823 	MBUF_INPUT_CHECK(m, m->m_pkthdr.rcvif);
824 	inifp = m->m_pkthdr.rcvif;
825 	VERIFY(inifp != NULL);
826 
827 	/* Perform IP header alignment fixup, if needed */
828 	IP6_HDR_ALIGNMENT_FIXUP(m, inifp, return );
829 
830 	m->m_pkthdr.pkt_flags &= ~PKTF_FORWARDED;
831 #if IPSEC
832 	/*
833 	 * should the inner packet be considered authentic?
834 	 * see comment in ah4_input().
835 	 */
836 	m->m_flags &= ~M_AUTHIPHDR;
837 	m->m_flags &= ~M_AUTHIPDGM;
838 #endif /* IPSEC */
839 
840 	/*
841 	 * make sure we don't have onion peering information into m_aux.
842 	 */
843 	ip6_delaux(m);
844 
845 #if DUMMYNET
846 	if ((tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID,
847 	    KERNEL_TAG_TYPE_DUMMYNET)) != NULL) {
848 		struct dn_pkt_tag *__single dn_tag;
849 
850 		dn_tag = (struct dn_pkt_tag *)(tag->m_tag_data);
851 
852 		args.fwa_pf_rule = dn_tag->dn_pf_rule;
853 
854 		m_tag_delete(m, tag);
855 	}
856 
857 	if (args.fwa_pf_rule) {
858 		ip6 = mtod(m, struct ip6_hdr *); /* In case PF got disabled */
859 
860 		goto check_with_pf;
861 	}
862 #endif /* DUMMYNET */
863 
864 	/*
865 	 * No need to process packet twice if we've already seen it.
866 	 */
867 	inject_ipfref = ipf_get_inject_filter(m);
868 	if (inject_ipfref != NULL) {
869 		ip6 = mtod(m, struct ip6_hdr *);
870 		nxt = ip6->ip6_nxt;
871 		seen = 0;
872 		goto injectit;
873 	} else {
874 		seen = 1;
875 	}
876 
877 	if (__improbable(m->m_pkthdr.pkt_flags & PKTF_WAKE_PKT)) {
878 		if_ports_used_match_mbuf(inifp, PF_INET6, m);
879 	}
880 
881 	/*
882 	 * mbuf statistics
883 	 */
884 	if (m->m_flags & M_EXT) {
885 		if (m->m_next != NULL) {
886 			ip6stat.ip6s_mext2m++;
887 		} else {
888 			ip6stat.ip6s_mext1++;
889 		}
890 	} else {
891 #define M2MMAX  (sizeof (ip6stat.ip6s_m2m) / sizeof (ip6stat.ip6s_m2m[0]))
892 		if (m->m_next != NULL) {
893 			if (m->m_pkthdr.pkt_flags & PKTF_LOOP) {
894 				/* XXX */
895 				ip6stat.ip6s_m2m[ifnet_index(lo_ifp)]++;
896 			} else if (inifp->if_index < M2MMAX) {
897 				ip6stat.ip6s_m2m[inifp->if_index]++;
898 			} else {
899 				ip6stat.ip6s_m2m[0]++;
900 			}
901 		} else {
902 			ip6stat.ip6s_m1++;
903 		}
904 #undef M2MMAX
905 	}
906 
907 	/*
908 	 * Drop the packet if IPv6 operation is disabled on the interface.
909 	 */
910 	if (inifp->if_eflags & IFEF_IPV6_DISABLED) {
911 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_IF_IPV6_DISABLED, NULL, 0);
912 		goto bad;
913 	}
914 
915 	in6_ifstat_inc_na(inifp, ifs6_in_receive);
916 	ip6stat.ip6s_total++;
917 
918 	/*
919 	 * L2 bridge code and some other code can return mbuf chain
920 	 * that does not conform to KAME requirement.  too bad.
921 	 * XXX: fails to join if interface MTU > MCLBYTES.  jumbogram?
922 	 */
923 	if (m->m_next != NULL && m->m_pkthdr.len < MCLBYTES) {
924 		mbuf_ref_t n;
925 
926 		MGETHDR(n, M_DONTWAIT, MT_HEADER);      /* MAC-OK */
927 		if (n) {
928 			M_COPY_PKTHDR(n, m);
929 		}
930 		if (n && m->m_pkthdr.len > MHLEN) {
931 			MCLGET(n, M_DONTWAIT);
932 			if ((n->m_flags & M_EXT) == 0) {
933 				m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_TOO_SMALL, NULL, 0);
934 				n = NULL;
935 			}
936 		}
937 		if (n == NULL) {
938 			goto bad;
939 		}
940 
941 		m_copydata(m, 0, m->m_pkthdr.len, mtod(n, caddr_t));
942 		n->m_len = m->m_pkthdr.len;
943 		m_freem(m);
944 		m = n;
945 	}
946 	IP6_EXTHDR_CHECK(m, 0, sizeof(struct ip6_hdr), { goto done; });
947 
948 	if (m->m_len < sizeof(struct ip6_hdr)) {
949 		if ((m = m_pullup(m, sizeof(struct ip6_hdr))) == 0) {
950 			ip6stat.ip6s_toosmall++;
951 			in6_ifstat_inc(inifp, ifs6_in_hdrerr);
952 			goto done;
953 		}
954 	}
955 
956 	ip6 = mtod(m, struct ip6_hdr *);
957 
958 	if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
959 		ip6stat.ip6s_badvers++;
960 		in6_ifstat_inc(inifp, ifs6_in_hdrerr);
961 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_BAD_VERSION, NULL, 0);
962 		goto bad;
963 	}
964 
965 	ip6stat.ip6s_nxthist[ip6->ip6_nxt]++;
966 
967 	/*
968 	 * Check against address spoofing/corruption.
969 	 */
970 	if (!(m->m_pkthdr.pkt_flags & PKTF_LOOP) &&
971 	    IN6_IS_ADDR_LOOPBACK(&ip6->ip6_src)) {
972 		ip6stat.ip6s_badscope++;
973 		in6_ifstat_inc(inifp, ifs6_in_addrerr);
974 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_SCOPE, NULL, 0);
975 		goto bad;
976 	}
977 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_src) ||
978 	    IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_dst)) {
979 		/*
980 		 * XXX: "badscope" is not very suitable for a multicast source.
981 		 */
982 		ip6stat.ip6s_badscope++;
983 		in6_ifstat_inc(inifp, ifs6_in_addrerr);
984 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_SCOPE, NULL, 0);
985 		goto bad;
986 	}
987 	if (IN6_IS_ADDR_MC_INTFACELOCAL(&ip6->ip6_dst) &&
988 	    !(m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
989 		/*
990 		 * In this case, the packet should come from the loopback
991 		 * interface.  However, we cannot just check the if_flags,
992 		 * because ip6_mloopback() passes the "actual" interface
993 		 * as the outgoing/incoming interface.
994 		 */
995 		ip6stat.ip6s_badscope++;
996 		in6_ifstat_inc(inifp, ifs6_in_addrerr);
997 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_SCOPE, NULL, 0);
998 		goto bad;
999 	}
1000 
1001 	/*
1002 	 * The following check is not documented in specs.  A malicious
1003 	 * party may be able to use IPv4 mapped addr to confuse tcp/udp stack
1004 	 * and bypass security checks (act as if it was from 127.0.0.1 by using
1005 	 * IPv6 src ::ffff:127.0.0.1).  Be cautious.
1006 	 *
1007 	 * This check chokes if we are in an SIIT cloud.  As none of BSDs
1008 	 * support IPv4-less kernel compilation, we cannot support SIIT
1009 	 * environment at all.  So, it makes more sense for us to reject any
1010 	 * malicious packets for non-SIIT environment, than try to do a
1011 	 * partial support for SIIT environment.
1012 	 */
1013 	if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
1014 	    IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
1015 		ip6stat.ip6s_badscope++;
1016 		in6_ifstat_inc(inifp, ifs6_in_addrerr);
1017 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_SCOPE, NULL, 0);
1018 		goto bad;
1019 	}
1020 
1021 	if (((ntohl(ip6->ip6_flow & IPV6_FLOW_ECN_MASK) >> 20) & IPTOS_ECN_ECT1) == IPTOS_ECN_ECT1) {
1022 		m->m_pkthdr.pkt_ext_flags |= PKTF_EXT_L4S;
1023 	}
1024 
1025 #if 0
1026 	/*
1027 	 * Reject packets with IPv4 compatible addresses (auto tunnel).
1028 	 *
1029 	 * The code forbids auto tunnel relay case in RFC1933 (the check is
1030 	 * stronger than RFC1933).  We may want to re-enable it if mech-xx
1031 	 * is revised to forbid relaying case.
1032 	 */
1033 	if (IN6_IS_ADDR_V4COMPAT(&ip6->ip6_src) ||
1034 	    IN6_IS_ADDR_V4COMPAT(&ip6->ip6_dst)) {
1035 		ip6stat.ip6s_badscope++;
1036 		in6_ifstat_inc(inifp, ifs6_in_addrerr);
1037 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_SCOPE, NULL, 0);
1038 		goto bad;
1039 	}
1040 #endif
1041 
1042 	/*
1043 	 * Naively assume we can attribute inbound data to the route we would
1044 	 * use to send to this destination. Asymetric routing breaks this
1045 	 * assumption, but it still allows us to account for traffic from
1046 	 * a remote node in the routing table.
1047 	 * this has a very significant performance impact so we bypass
1048 	 * if nstat_collect is disabled. We may also bypass if the
1049 	 * protocol is tcp in the future because tcp will have a route that
1050 	 * we can use to attribute the data to. That does mean we would not
1051 	 * account for forwarded tcp traffic.
1052 	 */
1053 	if (nstat_collect) {
1054 		rtentry_ref_t rte =
1055 		    ifnet_cached_rtlookup_inet6(inifp, &ip6->ip6_src);
1056 		if (rte != NULL) {
1057 			nstat_route_rx(rte, 1, m->m_pkthdr.len, 0);
1058 			rtfree(rte);
1059 		}
1060 	}
1061 
1062 #if DUMMYNET
1063 check_with_pf:
1064 #endif /* DUMMYNET */
1065 #if PF
1066 	/* Invoke inbound packet filter */
1067 	if (PF_IS_ENABLED) {
1068 		int error;
1069 #if DUMMYNET
1070 		error = pf_af_hook(inifp, NULL, &m, AF_INET6, TRUE, &args);
1071 #else /* !DUMMYNET */
1072 		error = pf_af_hook(inifp, NULL, &m, AF_INET6, TRUE, NULL);
1073 #endif /* !DUMMYNET */
1074 		if (error != 0 || m == NULL) {
1075 			if (m != NULL) {
1076 				panic("%s: unexpected packet %p",
1077 				    __func__, m);
1078 				/* NOTREACHED */
1079 			}
1080 			/* Already freed by callee */
1081 			goto done;
1082 		}
1083 		ip6 = mtod(m, struct ip6_hdr *);
1084 	}
1085 #endif /* PF */
1086 
1087 	/* drop packets if interface ID portion is already filled */
1088 	if (!(inifp->if_flags & IFF_LOOPBACK) &&
1089 	    !(m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
1090 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src) &&
1091 		    ip6->ip6_src.s6_addr16[1]) {
1092 			ip6stat.ip6s_badscope++;
1093 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_SCOPE, NULL, 0);
1094 			goto bad;
1095 		}
1096 		if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst) &&
1097 		    ip6->ip6_dst.s6_addr16[1]) {
1098 			ip6stat.ip6s_badscope++;
1099 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_SCOPE, NULL, 0);
1100 			goto bad;
1101 		}
1102 	}
1103 
1104 	if ((m->m_pkthdr.pkt_flags & PKTF_IFAINFO) != 0 && in6_embedded_scope) {
1105 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
1106 			ip6->ip6_src.s6_addr16[1] =
1107 			    htons(m->m_pkthdr.src_ifindex);
1108 		}
1109 		if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
1110 			ip6->ip6_dst.s6_addr16[1] =
1111 			    htons(m->m_pkthdr.dst_ifindex);
1112 		}
1113 	} else if (in6_embedded_scope) {
1114 		if (IN6_IS_SCOPE_LINKLOCAL(&ip6->ip6_src)) {
1115 			ip6->ip6_src.s6_addr16[1] = htons(inifp->if_index);
1116 		}
1117 		if (IN6_IS_SCOPE_EMBED(&ip6->ip6_dst)) {
1118 			ip6->ip6_dst.s6_addr16[1] = htons(inifp->if_index);
1119 		}
1120 	}
1121 
1122 	/*
1123 	 * Multicast check
1124 	 */
1125 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
1126 		struct in6_multi *__single in6m = NULL;
1127 
1128 		in6_ifstat_inc_na(inifp, ifs6_in_mcast);
1129 		/*
1130 		 * See if we belong to the destination multicast group on the
1131 		 * arrival interface.
1132 		 */
1133 		in6_multihead_lock_shared();
1134 		IN6_LOOKUP_MULTI(&ip6->ip6_dst, inifp, in6m);
1135 		in6_multihead_lock_done();
1136 		if (in6m != NULL) {
1137 			IN6M_REMREF(in6m);
1138 			ours = 1;
1139 		} else if (!nd6_prproxy) {
1140 			ip6stat.ip6s_notmember++;
1141 			ip6stat.ip6s_cantforward++;
1142 			in6_ifstat_inc(inifp, ifs6_in_discard);
1143 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_UNKNOWN_MULTICAST_GROUP, NULL, 0);
1144 			goto bad;
1145 		}
1146 		deliverifp = inifp;
1147 		/*
1148 		 * record dst address information into mbuf, if we don't have one yet.
1149 		 * note that we are unable to record it, if the address is not listed
1150 		 * as our interface address (e.g. multicast addresses, etc.)
1151 		 */
1152 		if (deliverifp != NULL) {
1153 			struct in6_ifaddr *__single ia6 = NULL;
1154 
1155 			ia6 = in6_ifawithifp(deliverifp, &ip6->ip6_dst);
1156 			if (ia6 != NULL) {
1157 				(void) ip6_setdstifaddr_info(m, 0, ia6);
1158 				(void) ip6_setsrcifaddr_info(m, ia6->ia_ifp->if_index, NULL);
1159 				ifa_remref(&ia6->ia_ifa);
1160 			} else {
1161 				(void) ip6_setdstifaddr_info(m, inifp->if_index, NULL);
1162 				(void) ip6_setsrcifaddr_info(m, inifp->if_index, NULL);
1163 			}
1164 		}
1165 		goto hbhcheck;
1166 	} else {
1167 		/*
1168 		 * Unicast check
1169 		 */
1170 		ip6_check_if_result_t check_if_result = IP6_CHECK_IF_NONE;
1171 		check_if_result = ip6_input_check_interface(m, ip6, inifp, &rin6, &deliverifp);
1172 		ASSERT(check_if_result != IP6_CHECK_IF_NONE);
1173 		if (check_if_result == IP6_CHECK_IF_OURS) {
1174 			ours = 1;
1175 			goto hbhcheck;
1176 		} else if (check_if_result == IP6_CHECK_IF_DROP) {
1177 			goto bad;
1178 		}
1179 	}
1180 
1181 	/*
1182 	 * Now there is no reason to process the packet if it's not our own
1183 	 * and we're not a router.
1184 	 */
1185 	if (!ip6_forwarding) {
1186 		ip6stat.ip6s_cantforward++;
1187 		in6_ifstat_inc(inifp, ifs6_in_discard);
1188 		/*
1189 		 * Raise a kernel event if the packet received on cellular
1190 		 * interface is not intended for local host.
1191 		 * For now limit it to ICMPv6 packets.
1192 		 */
1193 		if (inifp->if_type == IFT_CELLULAR &&
1194 		    ip6->ip6_nxt == IPPROTO_ICMPV6) {
1195 			in6_ifstat_inc(inifp, ifs6_cantfoward_icmp6);
1196 		}
1197 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_CANNOT_FORWARD, NULL, 0);
1198 		goto bad;
1199 	}
1200 
1201 hbhcheck:
1202 	/*
1203 	 * Process Hop-by-Hop options header if it's contained.
1204 	 * m may be modified in ip6_hopopts_input().
1205 	 * If a JumboPayload option is included, plen will also be modified.
1206 	 */
1207 	plen = (u_int32_t)ntohs(ip6->ip6_plen);
1208 	if (ip6->ip6_nxt == IPPROTO_HOPOPTS) {
1209 		struct ip6_hbh *__single hbh;
1210 
1211 		/*
1212 		 * Mark the packet to imply that HBH option has been checked.
1213 		 * This can only be true is the packet came in unfragmented
1214 		 * or if the option is in the first fragment
1215 		 */
1216 		m->m_pkthdr.pkt_flags |= PKTF_HBH_CHKED;
1217 		if (ip6_hopopts_input(&plen, &rtalert, &m, &off)) {
1218 #if 0   /* touches NULL pointer */
1219 			in6_ifstat_inc(inifp, ifs6_in_discard);
1220 #endif
1221 			goto done;      /* m have already been freed */
1222 		}
1223 
1224 		/* adjust pointer */
1225 		ip6 = mtod(m, struct ip6_hdr *);
1226 
1227 		/*
1228 		 * if the payload length field is 0 and the next header field
1229 		 * indicates Hop-by-Hop Options header, then a Jumbo Payload
1230 		 * option MUST be included.
1231 		 */
1232 		if (ip6->ip6_plen == 0 && plen == 0) {
1233 			/*
1234 			 * Note that if a valid jumbo payload option is
1235 			 * contained, ip6_hopopts_input() must set a valid
1236 			 * (non-zero) payload length to the variable plen.
1237 			 */
1238 			ip6stat.ip6s_badoptions++;
1239 			in6_ifstat_inc(inifp, ifs6_in_discard);
1240 			in6_ifstat_inc(inifp, ifs6_in_hdrerr);
1241 			icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_HEADER,
1242 			    (int)((caddr_t)&ip6->ip6_plen - (caddr_t)ip6));
1243 			goto done;
1244 		}
1245 		/* ip6_hopopts_input() ensures that mbuf is contiguous */
1246 		hbh = (struct ip6_hbh *)(ip6 + 1);
1247 		nxt = hbh->ip6h_nxt;
1248 
1249 		/*
1250 		 * If we are acting as a router and the packet contains a
1251 		 * router alert option, see if we know the option value.
1252 		 * Currently, we only support the option value for MLD, in which
1253 		 * case we should pass the packet to the multicast routing
1254 		 * daemon.
1255 		 */
1256 		if (rtalert != ~0 && ip6_forwarding) {
1257 			switch (rtalert) {
1258 			case IP6OPT_RTALERT_MLD:
1259 				ours = 1;
1260 				break;
1261 			default:
1262 				/*
1263 				 * RFC2711 requires unrecognized values must be
1264 				 * silently ignored.
1265 				 */
1266 				break;
1267 			}
1268 		}
1269 	} else {
1270 		nxt = ip6->ip6_nxt;
1271 	}
1272 
1273 	/*
1274 	 * Check that the amount of data in the buffers
1275 	 * is as at least much as the IPv6 header would have us expect.
1276 	 * Trim mbufs if longer than we expect.
1277 	 * Drop packet if shorter than we expect.
1278 	 */
1279 	if (m->m_pkthdr.len - sizeof(struct ip6_hdr) < plen) {
1280 		ip6stat.ip6s_tooshort++;
1281 		in6_ifstat_inc(inifp, ifs6_in_truncated);
1282 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_TOO_SHORT, NULL, 0);
1283 		goto bad;
1284 	}
1285 
1286 	if (m->m_pkthdr.len > sizeof(struct ip6_hdr) + plen) {
1287 		ip6_input_adjust(m, ip6, plen, inifp);
1288 	}
1289 
1290 	/*
1291 	 * Forward if desirable.
1292 	 */
1293 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
1294 		if (!ours && nd6_prproxy) {
1295 			/*
1296 			 * If this isn't for us, this might be a Neighbor
1297 			 * Solicitation (dst is solicited-node multicast)
1298 			 * against an address in one of the proxied prefixes;
1299 			 * if so, claim the packet and let icmp6_input()
1300 			 * handle the rest.
1301 			 */
1302 			ours = nd6_prproxy_isours(m, ip6, NULL, IFSCOPE_NONE);
1303 			VERIFY(!ours ||
1304 			    (m->m_pkthdr.pkt_flags & PKTF_PROXY_DST));
1305 		}
1306 		if (!ours) {
1307 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_UNPROXIED_NS, NULL, 0);
1308 			goto bad;
1309 		}
1310 	} else if (!ours) {
1311 		/*
1312 		 * The unicast forwarding function might return the packet
1313 		 * if we are proxying prefix(es), and if the packet is an
1314 		 * ICMPv6 packet that has failed the zone checks, but is
1315 		 * targetted towards a proxied address (this is optimized by
1316 		 * way of RTF_PROXY test.)  If so, claim the packet as ours
1317 		 * and let icmp6_input() handle the rest.  The packet's hop
1318 		 * limit value is kept intact (it's not decremented).  This
1319 		 * is for supporting Neighbor Unreachability Detection between
1320 		 * proxied nodes on different links (src is link-local, dst
1321 		 * is target address.)
1322 		 */
1323 		if ((m = ip6_forward(m, &rin6, 0)) == NULL) {
1324 			goto done;
1325 		}
1326 		VERIFY(rin6.ro_rt != NULL);
1327 		VERIFY(m->m_pkthdr.pkt_flags & PKTF_PROXY_DST);
1328 		deliverifp = rin6.ro_rt->rt_ifp;
1329 		ours = 1;
1330 	}
1331 
1332 	ip6 = mtod(m, struct ip6_hdr *);
1333 
1334 	/*
1335 	 * Malicious party may be able to use IPv4 mapped addr to confuse
1336 	 * tcp/udp stack and bypass security checks (act as if it was from
1337 	 * 127.0.0.1 by using IPv6 src ::ffff:127.0.0.1).  Be cautious.
1338 	 *
1339 	 * For SIIT end node behavior, you may want to disable the check.
1340 	 * However, you will  become vulnerable to attacks using IPv4 mapped
1341 	 * source.
1342 	 */
1343 	if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
1344 	    IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
1345 		ip6stat.ip6s_badscope++;
1346 		in6_ifstat_inc(inifp, ifs6_in_addrerr);
1347 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_SCOPE, NULL, 0);
1348 		goto bad;
1349 	}
1350 
1351 	/*
1352 	 * Tell launch routine the next header
1353 	 */
1354 	ip6stat.ip6s_delivered++;
1355 	in6_ifstat_inc_na(deliverifp, ifs6_in_deliver);
1356 
1357 injectit:
1358 	nest = 0;
1359 
1360 	/*
1361 	 * Perform IP header alignment fixup again, if needed.  Note that
1362 	 * we do it once for the outermost protocol, and we assume each
1363 	 * protocol handler wouldn't mess with the alignment afterwards.
1364 	 */
1365 	IP6_HDR_ALIGNMENT_FIXUP(m, inifp, return );
1366 
1367 	while (nxt != IPPROTO_DONE) {
1368 		struct ipfilter *__single filter;
1369 		int (*pr_input)(struct mbuf **, int *, int);
1370 
1371 		/*
1372 		 * This would imply either IPPROTO_HOPOPTS was not the first
1373 		 * option or it did not come in the first fragment.
1374 		 */
1375 		if (nxt == IPPROTO_HOPOPTS &&
1376 		    (m->m_pkthdr.pkt_flags & PKTF_HBH_CHKED) == 0) {
1377 			/*
1378 			 * This implies that HBH option was not contained
1379 			 * in the first fragment
1380 			 */
1381 			ip6stat.ip6s_badoptions++;
1382 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_OPTION, NULL, 0);
1383 			goto bad;
1384 		}
1385 
1386 		if (ip6_hdrnestlimit && (++nest > ip6_hdrnestlimit)) {
1387 			ip6stat.ip6s_toomanyhdr++;
1388 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_TOO_MANY_OPTIONS, NULL, 0);
1389 			goto bad;
1390 		}
1391 
1392 		/*
1393 		 * protection against faulty packet - there should be
1394 		 * more sanity checks in header chain processing.
1395 		 */
1396 		if (m->m_pkthdr.len < off) {
1397 			ip6stat.ip6s_tooshort++;
1398 			in6_ifstat_inc(inifp, ifs6_in_truncated);
1399 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_TOO_SHORT, NULL, 0);
1400 			goto bad;
1401 		}
1402 
1403 #if IPSEC
1404 		/*
1405 		 * enforce IPsec policy checking if we are seeing last header.
1406 		 * note that we do not visit this with protocols with pcb layer
1407 		 * code - like udp/tcp/raw ip.
1408 		 */
1409 		if ((ipsec_bypass == 0) &&
1410 		    (ip6_protox[nxt]->pr_flags & PR_LASTHDR) != 0) {
1411 			if (ipsec6_in_reject(m, NULL)) {
1412 				IPSEC_STAT_INCREMENT(ipsec6stat.in_polvio);
1413 				m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IPSEC_REJECT, NULL, 0);
1414 				goto bad;
1415 			}
1416 		}
1417 #endif /* IPSEC */
1418 
1419 		/*
1420 		 * Call IP filter
1421 		 */
1422 		if (!TAILQ_EMPTY(&ipv6_filters) && !IFNET_IS_INTCOPROC(inifp)) {
1423 			ipf_ref();
1424 			TAILQ_FOREACH(filter, &ipv6_filters, ipf_link) {
1425 				if (seen == 0) {
1426 					if ((struct ipfilter *)inject_ipfref ==
1427 					    filter) {
1428 						seen = 1;
1429 					}
1430 				} else if (filter->ipf_filter.ipf_input) {
1431 					errno_t result;
1432 
1433 					result = filter->ipf_filter.ipf_input(
1434 						filter->ipf_filter.cookie,
1435 						(mbuf_t *)&m, off, (uint8_t)nxt);
1436 					if (result == EJUSTRETURN) {
1437 						ipf_unref();
1438 						goto done;
1439 					}
1440 					if (result != 0) {
1441 						ipf_unref();
1442 						m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_FILTER_DROP, NULL, 0);
1443 						goto bad;
1444 					}
1445 				}
1446 			}
1447 			ipf_unref();
1448 		}
1449 
1450 		DTRACE_IP6(receive, struct mbuf *, m, struct inpcb *, NULL,
1451 		    struct ip6_hdr *, ip6, struct ifnet *, inifp,
1452 		    struct ip *, NULL, struct ip6_hdr *, ip6);
1453 
1454 		/*
1455 		 * Check if need to switch to full wake mode -- TCP knows about idle connections
1456 		 */
1457 		if (__improbable(nxt != IPPROTO_TCP && (m->m_pkthdr.pkt_flags & PKTF_WAKE_PKT) != 0)) {
1458 			ip6_input_process_wake_packet(m);
1459 		}
1460 
1461 		if ((pr_input = ip6_protox[nxt]->pr_input) == NULL) {
1462 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_NO_PROTO, NULL, 0);
1463 			m = NULL;
1464 			nxt = IPPROTO_DONE;
1465 		} else if (!(ip6_protox[nxt]->pr_flags & PR_PROTOLOCK)) {
1466 			lck_mtx_lock(inet6_domain_mutex);
1467 			nxt = pr_input(&m, &off, nxt);
1468 			lck_mtx_unlock(inet6_domain_mutex);
1469 		} else {
1470 			nxt = pr_input(&m, &off, nxt);
1471 		}
1472 	}
1473 done:
1474 	ROUTE_RELEASE(&rin6);
1475 	return;
1476 bad:
1477 	goto done;
1478 }
1479 
1480 void
ip6_setsrcifaddr_info(struct mbuf * m,uint32_t src_idx,struct in6_ifaddr * ia6)1481 ip6_setsrcifaddr_info(struct mbuf *m, uint32_t src_idx, struct in6_ifaddr *ia6)
1482 {
1483 	VERIFY(m->m_flags & M_PKTHDR);
1484 	m->m_pkthdr.pkt_ext_flags &= ~PKTF_EXT_OUTPUT_SCOPE;
1485 	/*
1486 	 * If the source ifaddr is specified, pick up the information
1487 	 * from there; otherwise just grab the passed-in ifindex as the
1488 	 * caller may not have the ifaddr available.
1489 	 */
1490 	if (ia6 != NULL) {
1491 		m->m_pkthdr.pkt_flags |= PKTF_IFAINFO;
1492 		m->m_pkthdr.src_ifindex = ia6->ia_ifp->if_index;
1493 
1494 		/* See IN6_IFF comments in in6_var.h */
1495 		m->m_pkthdr.src_iff = (ia6->ia6_flags & 0xffff);
1496 	} else {
1497 		m->m_pkthdr.src_iff = 0;
1498 		m->m_pkthdr.src_ifindex = (uint16_t)src_idx;
1499 		if (src_idx != 0) {
1500 			m->m_pkthdr.pkt_flags |= PKTF_IFAINFO;
1501 		}
1502 	}
1503 }
1504 
1505 void
ip6_setdstifaddr_info(struct mbuf * m,uint32_t dst_idx,struct in6_ifaddr * ia6)1506 ip6_setdstifaddr_info(struct mbuf *m, uint32_t dst_idx, struct in6_ifaddr *ia6)
1507 {
1508 	VERIFY(m->m_flags & M_PKTHDR);
1509 	m->m_pkthdr.pkt_ext_flags &= ~PKTF_EXT_OUTPUT_SCOPE;
1510 
1511 	/*
1512 	 * If the destination ifaddr is specified, pick up the information
1513 	 * from there; otherwise just grab the passed-in ifindex as the
1514 	 * caller may not have the ifaddr available.
1515 	 */
1516 	if (ia6 != NULL) {
1517 		m->m_pkthdr.pkt_flags |= PKTF_IFAINFO;
1518 		m->m_pkthdr.dst_ifindex = ia6->ia_ifp->if_index;
1519 
1520 		/* See IN6_IFF comments in in6_var.h */
1521 		m->m_pkthdr.dst_iff = (ia6->ia6_flags & 0xffff);
1522 	} else {
1523 		m->m_pkthdr.dst_iff = 0;
1524 		m->m_pkthdr.dst_ifindex = (uint16_t)dst_idx;
1525 		if (dst_idx != 0) {
1526 			m->m_pkthdr.pkt_flags |= PKTF_IFAINFO;
1527 		}
1528 	}
1529 }
1530 
1531 int
ip6_getsrcifaddr_info(struct mbuf * m,uint32_t * src_idx,uint32_t * ia6f)1532 ip6_getsrcifaddr_info(struct mbuf *m, uint32_t *src_idx, uint32_t *ia6f)
1533 {
1534 	VERIFY(m->m_flags & M_PKTHDR);
1535 
1536 	if (!(m->m_pkthdr.pkt_flags & PKTF_IFAINFO)) {
1537 		return -1;
1538 	}
1539 
1540 	if (src_idx != NULL) {
1541 		*src_idx = m->m_pkthdr.src_ifindex;
1542 	}
1543 
1544 	if (ia6f != NULL) {
1545 		*ia6f = m->m_pkthdr.src_iff;
1546 	}
1547 
1548 	return 0;
1549 }
1550 
1551 int
ip6_getdstifaddr_info(struct mbuf * m,uint32_t * dst_idx,uint32_t * ia6f)1552 ip6_getdstifaddr_info(struct mbuf *m, uint32_t *dst_idx, uint32_t *ia6f)
1553 {
1554 	VERIFY(m->m_flags & M_PKTHDR);
1555 
1556 	if (!(m->m_pkthdr.pkt_flags & PKTF_IFAINFO)) {
1557 		return -1;
1558 	}
1559 
1560 	if (dst_idx != NULL) {
1561 		*dst_idx = m->m_pkthdr.dst_ifindex;
1562 	}
1563 
1564 	if (ia6f != NULL) {
1565 		*ia6f = m->m_pkthdr.dst_iff;
1566 	}
1567 
1568 	return 0;
1569 }
1570 
1571 uint32_t
ip6_input_getsrcifscope(struct mbuf * m)1572 ip6_input_getsrcifscope(struct mbuf *m)
1573 {
1574 	VERIFY(m->m_flags & M_PKTHDR);
1575 
1576 	if (m->m_pkthdr.rcvif != NULL) {
1577 		return m->m_pkthdr.rcvif->if_index;
1578 	}
1579 
1580 	uint32_t src_ifscope = IFSCOPE_NONE;
1581 	ip6_getsrcifaddr_info(m, &src_ifscope, NULL);
1582 	return src_ifscope;
1583 }
1584 
1585 uint32_t
ip6_input_getdstifscope(struct mbuf * m)1586 ip6_input_getdstifscope(struct mbuf *m)
1587 {
1588 	VERIFY(m->m_flags & M_PKTHDR);
1589 
1590 	if (m->m_pkthdr.rcvif != NULL) {
1591 		return m->m_pkthdr.rcvif->if_index;
1592 	}
1593 
1594 	uint32_t dst_ifscope = IFSCOPE_NONE;
1595 	ip6_getdstifaddr_info(m, &dst_ifscope, NULL);
1596 	return dst_ifscope;
1597 }
1598 
1599 /*
1600  * Hop-by-Hop options header processing. If a valid jumbo payload option is
1601  * included, the real payload length will be stored in plenp.
1602  */
1603 static int
ip6_hopopts_input(uint32_t * plenp,uint32_t * rtalertp,struct mbuf ** mp,int * offp)1604 ip6_hopopts_input(uint32_t *plenp, uint32_t *rtalertp, struct mbuf **mp,
1605     int *offp)
1606 {
1607 	mbuf_ref_t m = *mp;
1608 	int off = *offp, hbhlen;
1609 	struct ip6_hbh *hbh;
1610 	u_int8_t *opt;
1611 
1612 	/* validation of the length of the header */
1613 	IP6_EXTHDR_CHECK(m, off, sizeof(*hbh), return (-1));
1614 	hbh = (struct ip6_hbh *)(mtod(m, caddr_t) + off);
1615 	hbhlen = (hbh->ip6h_len + 1) << 3;
1616 
1617 	IP6_EXTHDR_CHECK(m, off, hbhlen, return (-1));
1618 	hbh = (struct ip6_hbh *)(mtod(m, caddr_t) + off);
1619 	off += hbhlen;
1620 	hbhlen -= sizeof(struct ip6_hbh);
1621 	opt = (u_int8_t *)hbh + sizeof(struct ip6_hbh);
1622 
1623 	if (ip6_process_hopopts(m, (u_int8_t *)hbh + sizeof(struct ip6_hbh),
1624 	    hbhlen, rtalertp, plenp) < 0) {
1625 		return -1;
1626 	}
1627 
1628 	*offp = off;
1629 	*mp = m;
1630 	return 0;
1631 }
1632 
1633 /*
1634  * Search header for all Hop-by-hop options and process each option.
1635  * This function is separate from ip6_hopopts_input() in order to
1636  * handle a case where the sending node itself process its hop-by-hop
1637  * options header. In such a case, the function is called from ip6_output().
1638  *
1639  * The function assumes that hbh header is located right after the IPv6 header
1640  * (RFC2460 p7), opthead is pointer into data content in m, and opthead to
1641  * opthead + hbhlen is located in continuous memory region.
1642  */
1643 int
ip6_process_hopopts(struct mbuf * m,u_int8_t * __sized_by (inhbhlen)opthead,int inhbhlen,u_int32_t * rtalertp,u_int32_t * plenp)1644 ip6_process_hopopts(struct mbuf *m, u_int8_t *__sized_by(inhbhlen)opthead, int inhbhlen,
1645     u_int32_t *rtalertp, u_int32_t *plenp)
1646 {
1647 	struct ip6_hdr *__single ip6;
1648 	int optlen = 0;
1649 	int hbhlen = inhbhlen;
1650 	u_int8_t *opt = opthead;
1651 	u_int16_t rtalert_val;
1652 	u_int32_t jumboplen;
1653 	const int erroff = sizeof(struct ip6_hdr) + sizeof(struct ip6_hbh);
1654 
1655 	for (; hbhlen > 0; hbhlen -= optlen, opt += optlen) {
1656 		switch (*opt) {
1657 		case IP6OPT_PAD1:
1658 			optlen = 1;
1659 			break;
1660 		case IP6OPT_PADN:
1661 			if (hbhlen < IP6OPT_MINLEN) {
1662 				ip6stat.ip6s_toosmall++;
1663 				m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_TOO_SMALL, NULL, 0);
1664 				goto bad;
1665 			}
1666 			optlen = *(opt + 1) + 2;
1667 			break;
1668 		case IP6OPT_ROUTER_ALERT:
1669 			/* XXX may need check for alignment */
1670 			if (hbhlen < IP6OPT_RTALERT_LEN) {
1671 				ip6stat.ip6s_toosmall++;
1672 				goto bad;
1673 			}
1674 			if (*(opt + 1) != IP6OPT_RTALERT_LEN - 2) {
1675 				/* XXX stat */
1676 				icmp6_error(m, ICMP6_PARAM_PROB,
1677 				    ICMP6_PARAMPROB_HEADER,
1678 				    (int)(erroff + opt + 1 - opthead));
1679 				return -1;
1680 			}
1681 			optlen = IP6OPT_RTALERT_LEN;
1682 			bcopy((caddr_t)(opt + 2), (caddr_t)&rtalert_val, 2);
1683 			*rtalertp = ntohs(rtalert_val);
1684 			break;
1685 		case IP6OPT_JUMBO:
1686 			/* XXX may need check for alignment */
1687 			if (hbhlen < IP6OPT_JUMBO_LEN) {
1688 				ip6stat.ip6s_toosmall++;
1689 				m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_TOO_SMALL, NULL, 0);
1690 				goto bad;
1691 			}
1692 			if (*(opt + 1) != IP6OPT_JUMBO_LEN - 2) {
1693 				/* XXX stat */
1694 				icmp6_error(m, ICMP6_PARAM_PROB,
1695 				    ICMP6_PARAMPROB_HEADER,
1696 				    (int)(erroff + opt + 1 - opthead));
1697 				return -1;
1698 			}
1699 			optlen = IP6OPT_JUMBO_LEN;
1700 
1701 			/*
1702 			 * IPv6 packets that have non 0 payload length
1703 			 * must not contain a jumbo payload option.
1704 			 */
1705 			ip6 = mtod(m, struct ip6_hdr *);
1706 			if (ip6->ip6_plen) {
1707 				ip6stat.ip6s_badoptions++;
1708 				icmp6_error(m, ICMP6_PARAM_PROB,
1709 				    ICMP6_PARAMPROB_HEADER,
1710 				    (int)(erroff + opt - opthead));
1711 				return -1;
1712 			}
1713 
1714 			/*
1715 			 * We may see jumbolen in unaligned location, so
1716 			 * we'd need to perform bcopy().
1717 			 */
1718 			bcopy(opt + 2, &jumboplen, sizeof(jumboplen));
1719 			jumboplen = (u_int32_t)htonl(jumboplen);
1720 
1721 #if 1
1722 			/*
1723 			 * if there are multiple jumbo payload options,
1724 			 * *plenp will be non-zero and the packet will be
1725 			 * rejected.
1726 			 * the behavior may need some debate in ipngwg -
1727 			 * multiple options does not make sense, however,
1728 			 * there's no explicit mention in specification.
1729 			 */
1730 			if (*plenp != 0) {
1731 				ip6stat.ip6s_badoptions++;
1732 				icmp6_error(m, ICMP6_PARAM_PROB,
1733 				    ICMP6_PARAMPROB_HEADER,
1734 				    (int)(erroff + opt + 2 - opthead));
1735 				return -1;
1736 			}
1737 #endif
1738 
1739 			/*
1740 			 * jumbo payload length must be larger than 65535.
1741 			 */
1742 			if (jumboplen <= IPV6_MAXPACKET) {
1743 				ip6stat.ip6s_badoptions++;
1744 				icmp6_error(m, ICMP6_PARAM_PROB,
1745 				    ICMP6_PARAMPROB_HEADER,
1746 				    (int)(erroff + opt + 2 - opthead));
1747 				return -1;
1748 			}
1749 			*plenp = jumboplen;
1750 
1751 			break;
1752 		default:                /* unknown option */
1753 			if (hbhlen < IP6OPT_MINLEN) {
1754 				ip6stat.ip6s_toosmall++;
1755 				m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP_TOO_SMALL, NULL, 0);
1756 				goto bad;
1757 			}
1758 			optlen = ip6_unknown_opt(opt, hbhlen, m,
1759 			    erroff + opt - opthead);
1760 			if (optlen == -1) {
1761 				return -1;
1762 			}
1763 			optlen += 2;
1764 			break;
1765 		}
1766 	}
1767 
1768 	return 0;
1769 
1770 bad:
1771 	return -1;
1772 }
1773 
1774 /*
1775  * Unknown option processing.
1776  * The fourth argument `off' is the offset from the IPv6 header to the option,
1777  * which is necessary if the IPv6 header the and option header and IPv6 header
1778  * is not continuous in order to return an ICMPv6 error.
1779  */
1780 int
ip6_unknown_opt(uint8_t * __counted_by (optplen)optp,size_t optplen,struct mbuf * m,size_t off)1781 ip6_unknown_opt(uint8_t *__counted_by(optplen) optp, size_t optplen, struct mbuf *m, size_t off)
1782 {
1783 #pragma unused(optplen)
1784 
1785 	struct ip6_hdr *__single ip6;
1786 
1787 	switch (IP6OPT_TYPE(*optp)) {
1788 	case IP6OPT_TYPE_SKIP: /* ignore the option */
1789 		return (int)*(optp + 1);
1790 
1791 	case IP6OPT_TYPE_DISCARD:       /* silently discard */
1792 		m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_OPT_DISCARD, NULL, 0);
1793 		return -1;
1794 
1795 	case IP6OPT_TYPE_FORCEICMP: /* send ICMP even if multicasted */
1796 		ip6stat.ip6s_badoptions++;
1797 		icmp6_error(m, ICMP6_PARAM_PROB, ICMP6_PARAMPROB_OPTION, (int)off);
1798 		return -1;
1799 
1800 	case IP6OPT_TYPE_ICMP: /* send ICMP if not multicasted */
1801 		ip6stat.ip6s_badoptions++;
1802 		ip6 = mtod(m, struct ip6_hdr *);
1803 		if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1804 		    (m->m_flags & (M_BCAST | M_MCAST))) {
1805 			m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_IP6_BAD_OPTION, NULL, 0);
1806 		} else {
1807 			icmp6_error(m, ICMP6_PARAM_PROB,
1808 			    ICMP6_PARAMPROB_OPTION, (int)off);
1809 		}
1810 		return -1;
1811 	}
1812 
1813 	m_drop(m, DROPTAP_FLAG_DIR_IN | DROPTAP_FLAG_L2_MISSING, DROP_REASON_UNSPECIFIED, NULL, 0); /* XXX: NOTREACHED */
1814 	return -1;
1815 }
1816 
1817 /*
1818  * Create the "control" list for this pcb.
1819  * These functions will not modify mbuf chain at all.
1820  *
1821  * With KAME mbuf chain restriction:
1822  * The routine will be called from upper layer handlers like tcp6_input().
1823  * Thus the routine assumes that the caller (tcp6_input) have already
1824  * called IP6_EXTHDR_CHECK() and all the extension headers are located in the
1825  * very first mbuf on the mbuf chain.
1826  *
1827  * ip6_savecontrol_v4 will handle those options that are possible to be
1828  * set on a v4-mapped socket.
1829  * ip6_savecontrol will directly call ip6_savecontrol_v4 to handle those
1830  * options and handle the v6-only ones itself.
1831  */
1832 struct mbuf **
ip6_savecontrol_v4(struct inpcb * inp,struct mbuf * m,struct mbuf ** mp,int * v4only)1833 ip6_savecontrol_v4(struct inpcb *inp, struct mbuf *m, struct mbuf **mp,
1834     int *v4only)
1835 {
1836 	struct ip6_hdr *__single ip6 = mtod(m, struct ip6_hdr *);
1837 
1838 	if ((inp->inp_socket->so_options & SO_TIMESTAMP) != 0) {
1839 		struct timeval tv;
1840 
1841 		getmicrotime(&tv);
1842 		mp = sbcreatecontrol_mbuf((caddr_t)&tv, sizeof(tv),
1843 		    SCM_TIMESTAMP, SOL_SOCKET, mp);
1844 		if (*mp == NULL) {
1845 			return NULL;
1846 		}
1847 	}
1848 	if ((inp->inp_socket->so_options & SO_TIMESTAMP_MONOTONIC) != 0) {
1849 		uint64_t time;
1850 
1851 		time = mach_absolute_time();
1852 		mp = sbcreatecontrol_mbuf((caddr_t)&time, sizeof(time),
1853 		    SCM_TIMESTAMP_MONOTONIC, SOL_SOCKET, mp);
1854 		if (*mp == NULL) {
1855 			return NULL;
1856 		}
1857 	}
1858 	if ((inp->inp_socket->so_options & SO_TIMESTAMP_CONTINUOUS) != 0) {
1859 		uint64_t time;
1860 
1861 		time = mach_continuous_time();
1862 		mp = sbcreatecontrol_mbuf((caddr_t)&time, sizeof(time),
1863 		    SCM_TIMESTAMP_CONTINUOUS, SOL_SOCKET, mp);
1864 		if (*mp == NULL) {
1865 			return NULL;
1866 		}
1867 	}
1868 	if ((inp->inp_socket->so_flags & SOF_RECV_TRAFFIC_CLASS) != 0) {
1869 		int tc = m_get_traffic_class(m);
1870 
1871 		mp = sbcreatecontrol_mbuf((caddr_t)&tc, sizeof(tc),
1872 		    SO_TRAFFIC_CLASS, SOL_SOCKET, mp);
1873 		if (*mp == NULL) {
1874 			return NULL;
1875 		}
1876 	}
1877 
1878 	if ((inp->inp_socket->so_flags & SOF_RECV_WAKE_PKT) &&
1879 	    (m->m_pkthdr.pkt_flags & PKTF_WAKE_PKT)) {
1880 		int flag = 1;
1881 
1882 		mp = sbcreatecontrol_mbuf((caddr_t)&flag, sizeof(flag),
1883 		    SO_RECV_WAKE_PKT, SOL_SOCKET, mp);
1884 		if (*mp == NULL) {
1885 			return NULL;
1886 		}
1887 	}
1888 
1889 #define IS2292(inp, x, y)       (((inp)->inp_flags & IN6P_RFC2292) ? (x) : (y))
1890 	if ((ip6->ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
1891 		if (v4only != NULL) {
1892 			*v4only = 1;
1893 		}
1894 
1895 		// Send ECN flags for v4-mapped addresses
1896 		if ((inp->inp_flags & IN6P_TCLASS) != 0) {
1897 			struct ip *__single ip_header = mtod(m, struct ip *);
1898 
1899 			int tclass = (int)(ip_header->ip_tos);
1900 			mp = sbcreatecontrol_mbuf((caddr_t)&tclass, sizeof(tclass),
1901 			    IPV6_TCLASS, IPPROTO_IPV6, mp);
1902 			if (*mp == NULL) {
1903 				return NULL;
1904 			}
1905 		}
1906 
1907 		// Send IN6P_PKTINFO for v4-mapped address
1908 		if ((inp->inp_flags & IN6P_PKTINFO) != 0 || SOFLOW_ENABLED(inp->inp_socket)) {
1909 			struct in6_pktinfo pi6 = {
1910 				.ipi6_addr = IN6ADDR_V4MAPPED_INIT,
1911 				.ipi6_ifindex = (m && m->m_pkthdr.rcvif) ? m->m_pkthdr.rcvif->if_index : 0,
1912 			};
1913 
1914 			struct ip *__single ip_header = mtod(m, struct ip *);
1915 			bcopy(&ip_header->ip_dst, &pi6.ipi6_addr.s6_addr32[3], sizeof(struct in_addr));
1916 
1917 			mp = sbcreatecontrol_mbuf((caddr_t)&pi6,
1918 			    sizeof(struct in6_pktinfo),
1919 			    IS2292(inp, IPV6_2292PKTINFO, IPV6_PKTINFO),
1920 			    IPPROTO_IPV6, mp);
1921 			if (*mp == NULL) {
1922 				return NULL;
1923 			}
1924 		}
1925 		return mp;
1926 	}
1927 
1928 	/* RFC 2292 sec. 5 */
1929 	if ((inp->inp_flags & IN6P_PKTINFO) != 0 || SOFLOW_ENABLED(inp->inp_socket)) {
1930 		struct in6_pktinfo pi6;
1931 
1932 		bcopy(&ip6->ip6_dst, &pi6.ipi6_addr, sizeof(struct in6_addr));
1933 		in6_clearscope(&pi6.ipi6_addr); /* XXX */
1934 		pi6.ipi6_ifindex =
1935 		    (m && m->m_pkthdr.rcvif) ? m->m_pkthdr.rcvif->if_index : 0;
1936 
1937 		mp = sbcreatecontrol_mbuf((caddr_t)&pi6,
1938 		    sizeof(struct in6_pktinfo),
1939 		    IS2292(inp, IPV6_2292PKTINFO, IPV6_PKTINFO),
1940 		    IPPROTO_IPV6, mp);
1941 		if (*mp == NULL) {
1942 			return NULL;
1943 		}
1944 	}
1945 
1946 	if ((inp->inp_flags & IN6P_HOPLIMIT) != 0) {
1947 		int hlim = ip6->ip6_hlim & 0xff;
1948 
1949 		mp = sbcreatecontrol_mbuf((caddr_t)&hlim, sizeof(int),
1950 		    IS2292(inp, IPV6_2292HOPLIMIT, IPV6_HOPLIMIT),
1951 		    IPPROTO_IPV6, mp);
1952 		if (*mp == NULL) {
1953 			return NULL;
1954 		}
1955 	}
1956 
1957 	if (inp->inp_flags2 & INP2_RECV_LINK_ADDR_TYPE) {
1958 		int mode = IP_RECV_LINK_ADDR_UNICAST;
1959 
1960 		/* There is no broadcast for IPv6 */
1961 		if (m->m_flags & M_MCAST) {
1962 			mode = IP_RECV_LINK_ADDR_MULTICAST;
1963 		}
1964 
1965 		mp = sbcreatecontrol_mbuf((caddr_t)&mode,
1966 		    sizeof(int), IPV6_RECV_LINK_ADDR_TYPE, IPPROTO_IPV6, mp);
1967 		if (*mp == NULL) {
1968 			return NULL;
1969 		}
1970 	}
1971 
1972 	if (v4only != NULL) {
1973 		*v4only = 0;
1974 	}
1975 	return mp;
1976 }
1977 
1978 int
ip6_savecontrol(struct inpcb * in6p,struct mbuf * m,struct mbuf ** mp)1979 ip6_savecontrol(struct inpcb *in6p, struct mbuf *m, struct mbuf **mp)
1980 {
1981 	struct mbuf **np;
1982 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
1983 	int v4only = 0;
1984 
1985 	*mp = NULL;
1986 	np = ip6_savecontrol_v4(in6p, m, mp, &v4only);
1987 	if (np == NULL) {
1988 		goto no_mbufs;
1989 	}
1990 
1991 	mp = np;
1992 	if (v4only) {
1993 		return 0;
1994 	}
1995 
1996 	if ((in6p->inp_flags & IN6P_TCLASS) != 0) {
1997 		u_int32_t flowinfo;
1998 		int tclass;
1999 
2000 		flowinfo = (u_int32_t)ntohl(ip6->ip6_flow & IPV6_FLOWINFO_MASK);
2001 		flowinfo >>= 20;
2002 
2003 		tclass = flowinfo & 0xff;
2004 		mp = sbcreatecontrol_mbuf((caddr_t)&tclass, sizeof(tclass),
2005 		    IPV6_TCLASS, IPPROTO_IPV6, mp);
2006 		if (*mp == NULL) {
2007 			goto no_mbufs;
2008 		}
2009 	}
2010 
2011 	/*
2012 	 * IPV6_HOPOPTS socket option.  Recall that we required super-user
2013 	 * privilege for the option (see ip6_ctloutput), but it might be too
2014 	 * strict, since there might be some hop-by-hop options which can be
2015 	 * returned to normal user.
2016 	 * See also RFC 2292 section 6 (or RFC 3542 section 8).
2017 	 */
2018 	if ((in6p->inp_flags & IN6P_HOPOPTS) != 0) {
2019 		/*
2020 		 * Check if a hop-by-hop options header is contatined in the
2021 		 * received packet, and if so, store the options as ancillary
2022 		 * data. Note that a hop-by-hop options header must be
2023 		 * just after the IPv6 header, which is assured through the
2024 		 * IPv6 input processing.
2025 		 */
2026 		ip6 = mtod(m, struct ip6_hdr *);
2027 		if (ip6->ip6_nxt == IPPROTO_HOPOPTS) {
2028 			struct ip6_hbh *hbh;
2029 			int hbhlen = 0;
2030 			hbh = (struct ip6_hbh *)(ip6 + 1);
2031 			hbhlen = (hbh->ip6h_len + 1) << 3;
2032 
2033 			/*
2034 			 * XXX: We copy the whole header even if a
2035 			 * jumbo payload option is included, the option which
2036 			 * is to be removed before returning according to
2037 			 * RFC2292.
2038 			 * Note: this constraint is removed in RFC3542
2039 			 */
2040 			mp = sbcreatecontrol_mbuf((caddr_t)hbh, hbhlen,
2041 			    IS2292(in6p, IPV6_2292HOPOPTS, IPV6_HOPOPTS),
2042 			    IPPROTO_IPV6, mp);
2043 
2044 			if (*mp == NULL) {
2045 				goto no_mbufs;
2046 			}
2047 		}
2048 	}
2049 
2050 	if ((in6p->inp_flags & (IN6P_RTHDR | IN6P_DSTOPTS)) != 0) {
2051 		int nxt = ip6->ip6_nxt, off = sizeof(struct ip6_hdr);
2052 
2053 		/*
2054 		 * Search for destination options headers or routing
2055 		 * header(s) through the header chain, and stores each
2056 		 * header as ancillary data.
2057 		 * Note that the order of the headers remains in
2058 		 * the chain of ancillary data.
2059 		 */
2060 		while (1) {     /* is explicit loop prevention necessary? */
2061 			struct ip6_ext *ip6e = NULL;
2062 			int elen;
2063 
2064 			/*
2065 			 * if it is not an extension header, don't try to
2066 			 * pull it from the chain.
2067 			 */
2068 			switch (nxt) {
2069 			case IPPROTO_DSTOPTS:
2070 			case IPPROTO_ROUTING:
2071 			case IPPROTO_HOPOPTS:
2072 			case IPPROTO_AH: /* is it possible? */
2073 				break;
2074 			default:
2075 				goto loopend;
2076 			}
2077 
2078 			if (off + sizeof(*ip6e) > m->m_len) {
2079 				goto loopend;
2080 			}
2081 			ip6e = (struct ip6_ext *)(mtod(m, caddr_t) + off);
2082 			if (nxt == IPPROTO_AH) {
2083 				elen = (ip6e->ip6e_len + 2) << 2;
2084 			} else {
2085 				elen = (ip6e->ip6e_len + 1) << 3;
2086 			}
2087 			if (off + elen > m->m_len) {
2088 				goto loopend;
2089 			}
2090 
2091 			switch (nxt) {
2092 			case IPPROTO_DSTOPTS:
2093 				if (!(in6p->inp_flags & IN6P_DSTOPTS)) {
2094 					break;
2095 				}
2096 
2097 				mp = sbcreatecontrol_mbuf((caddr_t)ip6e, elen,
2098 				    IS2292(in6p, IPV6_2292DSTOPTS,
2099 				    IPV6_DSTOPTS), IPPROTO_IPV6, mp);
2100 				if (*mp == NULL) {
2101 					goto no_mbufs;
2102 				}
2103 				break;
2104 			case IPPROTO_ROUTING:
2105 				if (!(in6p->inp_flags & IN6P_RTHDR)) {
2106 					break;
2107 				}
2108 
2109 				mp = sbcreatecontrol_mbuf((caddr_t)ip6e, elen,
2110 				    IS2292(in6p, IPV6_2292RTHDR, IPV6_RTHDR),
2111 				    IPPROTO_IPV6, mp);
2112 				if (*mp == NULL) {
2113 					goto no_mbufs;
2114 				}
2115 				break;
2116 			case IPPROTO_HOPOPTS:
2117 			case IPPROTO_AH: /* is it possible? */
2118 				break;
2119 
2120 			default:
2121 				/*
2122 				 * other cases have been filtered in the above.
2123 				 * none will visit this case.  here we supply
2124 				 * the code just in case (nxt overwritten or
2125 				 * other cases).
2126 				 */
2127 				goto loopend;
2128 			}
2129 
2130 			/* proceed with the next header. */
2131 			off += elen;
2132 			nxt = ip6e->ip6e_nxt;
2133 			ip6e = NULL;
2134 		}
2135 loopend:
2136 		;
2137 	}
2138 	return 0;
2139 no_mbufs:
2140 	ip6stat.ip6s_pktdropcntrl++;
2141 	/* XXX increment a stat to show the failure */
2142 	return ENOBUFS;
2143 }
2144 #undef IS2292
2145 
2146 void
ip6_notify_pmtu(struct inpcb * in6p,struct sockaddr_in6 * dst,u_int32_t * mtu)2147 ip6_notify_pmtu(struct inpcb *in6p, struct sockaddr_in6 *dst, u_int32_t *mtu)
2148 {
2149 	struct socket *__single so;
2150 	mbuf_ref_t m_mtu;
2151 	struct ip6_mtuinfo mtuctl;
2152 
2153 	so =  in6p->inp_socket;
2154 
2155 	if ((in6p->inp_flags & IN6P_MTU) == 0) {
2156 		return;
2157 	}
2158 
2159 	if (mtu == NULL) {
2160 		return;
2161 	}
2162 
2163 	if (IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_faddr) && SOCK_CHECK_PROTO(so, IPPROTO_TCP)) {
2164 		return;
2165 	}
2166 
2167 	if (!IN6_IS_ADDR_UNSPECIFIED(&in6p->in6p_faddr) &&
2168 	    !in6_are_addr_equal_scoped(&in6p->in6p_faddr, &dst->sin6_addr, in6p->inp_fifscope, dst->sin6_scope_id)) {
2169 		return;
2170 	}
2171 
2172 	bzero(&mtuctl, sizeof(mtuctl));         /* zero-clear for safety */
2173 	mtuctl.ip6m_mtu = *mtu;
2174 	mtuctl.ip6m_addr = *dst;
2175 	if (!in6_embedded_scope) {
2176 		mtuctl.ip6m_addr.sin6_scope_id = dst->sin6_scope_id;
2177 	}
2178 	if (sa6_recoverscope(&mtuctl.ip6m_addr, TRUE)) {
2179 		return;
2180 	}
2181 
2182 	if ((m_mtu = sbcreatecontrol((caddr_t)&mtuctl, sizeof(mtuctl),
2183 	    IPV6_PATHMTU, IPPROTO_IPV6)) == NULL) {
2184 		return;
2185 	}
2186 
2187 	if (sbappendaddr(&so->so_rcv, SA(dst), NULL, m_mtu, NULL) == 0) {
2188 		return;
2189 	}
2190 	sorwakeup(so);
2191 }
2192 
2193 /*
2194  * Get pointer to the previous header followed by the header
2195  * currently processed.
2196  * XXX: This function supposes that
2197  *	M includes all headers,
2198  *	the next header field and the header length field of each header
2199  *	are valid, and
2200  *	the sum of each header length equals to OFF.
2201  * Because of these assumptions, this function must be called very
2202  * carefully. Moreover, it will not be used in the near future when
2203  * we develop `neater' mechanism to process extension headers.
2204  */
2205 char *
ip6_get_prevhdr(struct mbuf * m,int off)2206 ip6_get_prevhdr(struct mbuf *m, int off)
2207 {
2208 	struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
2209 
2210 	if (off == sizeof(struct ip6_hdr)) {
2211 		return (char *)&ip6->ip6_nxt;
2212 	} else {
2213 		int len, nxt;
2214 		struct ip6_ext *ip6e = NULL;
2215 
2216 		nxt = ip6->ip6_nxt;
2217 		len = sizeof(struct ip6_hdr);
2218 		while (len < off) {
2219 			ip6e = (struct ip6_ext *)(mtod(m, caddr_t) + len);
2220 
2221 			switch (nxt) {
2222 			case IPPROTO_FRAGMENT:
2223 				len += sizeof(struct ip6_frag);
2224 				break;
2225 			case IPPROTO_AH:
2226 				len += (ip6e->ip6e_len + 2) << 2;
2227 				break;
2228 			default:
2229 				len += (ip6e->ip6e_len + 1) << 3;
2230 				break;
2231 			}
2232 			nxt = ip6e->ip6e_nxt;
2233 		}
2234 		if (ip6e) {
2235 			return (char *)&ip6e->ip6e_nxt;
2236 		} else {
2237 			return NULL;
2238 		}
2239 	}
2240 }
2241 
2242 /*
2243  * get next header offset.  m will be retained.
2244  */
2245 int
ip6_nexthdr(struct mbuf * m,int off,int proto,int * nxtp)2246 ip6_nexthdr(struct mbuf *m, int off, int proto, int *nxtp)
2247 {
2248 	struct ip6_hdr ip6;
2249 	struct ip6_ext ip6e;
2250 	struct ip6_frag fh;
2251 
2252 	/* just in case */
2253 	VERIFY(m != NULL);
2254 	if ((m->m_flags & M_PKTHDR) == 0 || m->m_pkthdr.len < off) {
2255 		return -1;
2256 	}
2257 
2258 	switch (proto) {
2259 	case IPPROTO_IPV6:
2260 		if (m->m_pkthdr.len < off + sizeof(ip6)) {
2261 			return -1;
2262 		}
2263 		m_copydata(m, off, sizeof(ip6), (caddr_t)&ip6);
2264 		if (nxtp) {
2265 			*nxtp = ip6.ip6_nxt;
2266 		}
2267 		off += sizeof(ip6);
2268 		return off;
2269 
2270 	case IPPROTO_FRAGMENT:
2271 		/*
2272 		 * terminate parsing if it is not the first fragment,
2273 		 * it does not make sense to parse through it.
2274 		 */
2275 		if (m->m_pkthdr.len < off + sizeof(fh)) {
2276 			return -1;
2277 		}
2278 		m_copydata(m, off, sizeof(fh), (caddr_t)&fh);
2279 		/* IP6F_OFF_MASK = 0xfff8(BigEndian), 0xf8ff(LittleEndian) */
2280 		if (fh.ip6f_offlg & IP6F_OFF_MASK) {
2281 			return -1;
2282 		}
2283 		if (nxtp) {
2284 			*nxtp = fh.ip6f_nxt;
2285 		}
2286 		off += sizeof(struct ip6_frag);
2287 		return off;
2288 
2289 	case IPPROTO_AH:
2290 		if (m->m_pkthdr.len < off + sizeof(ip6e)) {
2291 			return -1;
2292 		}
2293 		m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
2294 		if (nxtp) {
2295 			*nxtp = ip6e.ip6e_nxt;
2296 		}
2297 		off += (ip6e.ip6e_len + 2) << 2;
2298 		return off;
2299 
2300 	case IPPROTO_HOPOPTS:
2301 	case IPPROTO_ROUTING:
2302 	case IPPROTO_DSTOPTS:
2303 		if (m->m_pkthdr.len < off + sizeof(ip6e)) {
2304 			return -1;
2305 		}
2306 		m_copydata(m, off, sizeof(ip6e), (caddr_t)&ip6e);
2307 		if (nxtp) {
2308 			*nxtp = ip6e.ip6e_nxt;
2309 		}
2310 		off += (ip6e.ip6e_len + 1) << 3;
2311 		return off;
2312 
2313 	case IPPROTO_NONE:
2314 	case IPPROTO_ESP:
2315 	case IPPROTO_IPCOMP:
2316 		/* give up */
2317 		return -1;
2318 
2319 	default:
2320 		return -1;
2321 	}
2322 }
2323 
2324 /*
2325  * get offset for the last header in the chain.  m will be kept untainted.
2326  */
2327 int
ip6_lasthdr(struct mbuf * m,int off,int proto,int * nxtp)2328 ip6_lasthdr(struct mbuf *m, int off, int proto, int *nxtp)
2329 {
2330 	int newoff;
2331 	int nxt;
2332 
2333 	if (!nxtp) {
2334 		nxt = -1;
2335 		nxtp = &nxt;
2336 	}
2337 	while (1) {
2338 		newoff = ip6_nexthdr(m, off, proto, nxtp);
2339 		if (newoff < 0) {
2340 			return off;
2341 		} else if (newoff < off) {
2342 			return -1;    /* invalid */
2343 		} else if (newoff == off) {
2344 			return newoff;
2345 		}
2346 
2347 		off = newoff;
2348 		proto = *nxtp;
2349 	}
2350 }
2351 
2352 boolean_t
ip6_pkt_has_ulp(struct mbuf * m)2353 ip6_pkt_has_ulp(struct mbuf *m)
2354 {
2355 	int off = 0, nxt = IPPROTO_NONE;
2356 
2357 	off = ip6_lasthdr(m, 0, IPPROTO_IPV6, &nxt);
2358 	if (off < 0 || m->m_pkthdr.len < off) {
2359 		return FALSE;
2360 	}
2361 
2362 	switch (nxt) {
2363 	case IPPROTO_TCP:
2364 		if (off + sizeof(struct tcphdr) > m->m_pkthdr.len) {
2365 			return FALSE;
2366 		}
2367 		break;
2368 	case IPPROTO_UDP:
2369 		if (off + sizeof(struct udphdr) > m->m_pkthdr.len) {
2370 			return FALSE;
2371 		}
2372 		break;
2373 	case IPPROTO_ICMPV6:
2374 		if (off + sizeof(uint32_t) > m->m_pkthdr.len) {
2375 			return FALSE;
2376 		}
2377 		break;
2378 	case IPPROTO_NONE:
2379 		return TRUE;
2380 	case IPPROTO_ESP:
2381 		return TRUE;
2382 	case IPPROTO_IPCOMP:
2383 		return TRUE;
2384 	default:
2385 		return FALSE;
2386 	}
2387 	return TRUE;
2388 }
2389 
2390 struct ip6aux *
ip6_addaux(struct mbuf * m)2391 ip6_addaux(struct mbuf *m)
2392 {
2393 	struct m_tag *__single tag;
2394 
2395 	/* Check if one is already allocated */
2396 	tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID,
2397 	    KERNEL_TAG_TYPE_INET6);
2398 	if (tag == NULL) {
2399 		/* Allocate a tag */
2400 		tag = m_tag_create(KERNEL_MODULE_TAG_ID, KERNEL_TAG_TYPE_INET6,
2401 		    sizeof(struct ip6aux), M_DONTWAIT, m);
2402 
2403 		/* Attach it to the mbuf */
2404 		if (tag) {
2405 			m_tag_prepend(m, tag);
2406 		}
2407 	}
2408 
2409 	return tag ? (struct ip6aux *)(tag->m_tag_data) : NULL;
2410 }
2411 
2412 struct ip6aux *
ip6_findaux(struct mbuf * m)2413 ip6_findaux(struct mbuf *m)
2414 {
2415 	struct m_tag *__single tag;
2416 
2417 	tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID,
2418 	    KERNEL_TAG_TYPE_INET6);
2419 
2420 	return tag != NULL ? (struct ip6aux *)(tag->m_tag_data) : NULL;
2421 }
2422 
2423 void
ip6_delaux(struct mbuf * m)2424 ip6_delaux(struct mbuf *m)
2425 {
2426 	struct m_tag *__single tag;
2427 
2428 	tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID,
2429 	    KERNEL_TAG_TYPE_INET6);
2430 	if (tag != NULL) {
2431 		m_tag_delete(m, tag);
2432 	}
2433 }
2434 
2435 struct inet6_tag_container {
2436 	struct m_tag    inet6_m_tag;
2437 	struct ip6aux   inet6_ip6a;
2438 };
2439 
2440 struct m_tag *
m_tag_kalloc_inet6(u_int32_t id,u_int16_t type,uint16_t len,int wait)2441 m_tag_kalloc_inet6(u_int32_t id, u_int16_t type, uint16_t len, int wait)
2442 {
2443 	struct inet6_tag_container *tag_container;
2444 	struct m_tag *tag = NULL;
2445 
2446 	assert3u(id, ==, KERNEL_MODULE_TAG_ID);
2447 	assert3u(type, ==, KERNEL_TAG_TYPE_INET6);
2448 	assert3u(len, ==, sizeof(struct ip6aux));
2449 
2450 	if (len != sizeof(struct ip6aux)) {
2451 		return NULL;
2452 	}
2453 
2454 	tag_container = kalloc_type(struct inet6_tag_container, wait | M_ZERO);
2455 	if (tag_container != NULL) {
2456 		tag =  &tag_container->inet6_m_tag;
2457 
2458 		assert3p(tag, ==, tag_container);
2459 
2460 		M_TAG_INIT(tag, id, type, len, &tag_container->inet6_ip6a, NULL);
2461 	}
2462 
2463 	return tag;
2464 }
2465 
2466 void
m_tag_kfree_inet6(struct m_tag * tag)2467 m_tag_kfree_inet6(struct m_tag *tag)
2468 {
2469 	struct inet6_tag_container *__single tag_container = (struct inet6_tag_container *)tag;
2470 
2471 	assert3u(tag->m_tag_len, ==, sizeof(struct ip6aux));
2472 
2473 	kfree_type(struct inet6_tag_container, tag_container);
2474 }
2475 
2476 void
ip6_register_m_tag(void)2477 ip6_register_m_tag(void)
2478 {
2479 	int error;
2480 
2481 	error = m_register_internal_tag_type(KERNEL_TAG_TYPE_INET6, sizeof(struct ip6aux),
2482 	    m_tag_kalloc_inet6, m_tag_kfree_inet6);
2483 
2484 	assert3u(error, ==, 0);
2485 }
2486 
2487 /*
2488  * Drain callback
2489  */
2490 void
ip6_drain(void)2491 ip6_drain(void)
2492 {
2493 	frag6_drain();          /* fragments */
2494 	in6_rtqdrain();         /* protocol cloned routes */
2495 	nd6_drain(NULL);        /* cloned routes: ND6 */
2496 }
2497 
2498 /*
2499  * System control for IP6
2500  */
2501 
2502 u_char  inet6ctlerrmap[PRC_NCMDS] = {
2503 	0, 0, 0, 0,
2504 	0, EMSGSIZE, EHOSTDOWN, EHOSTUNREACH,
2505 	EHOSTUNREACH, EHOSTUNREACH, ECONNREFUSED, ECONNREFUSED,
2506 	EMSGSIZE, EHOSTUNREACH, 0, 0,
2507 	0, 0, 0, 0,
2508 	ENOPROTOOPT, ECONNREFUSED
2509 };
2510 
2511 static int
2512 sysctl_reset_ip6_input_stats SYSCTL_HANDLER_ARGS
2513 {
2514 #pragma unused(arg1, arg2)
2515 	int error, i;
2516 
2517 	i = ip6_input_measure;
2518 	error = sysctl_handle_int(oidp, &i, 0, req);
2519 	if (error || req->newptr == USER_ADDR_NULL) {
2520 		goto done;
2521 	}
2522 	/* impose bounds */
2523 	if (i < 0 || i > 1) {
2524 		error = EINVAL;
2525 		goto done;
2526 	}
2527 	if (ip6_input_measure != i && i == 1) {
2528 		net_perf_initialize(&net_perf, ip6_input_measure_bins);
2529 	}
2530 	ip6_input_measure = i;
2531 done:
2532 	return error;
2533 }
2534 
2535 static int
2536 sysctl_ip6_input_measure_bins SYSCTL_HANDLER_ARGS
2537 {
2538 #pragma unused(arg1, arg2)
2539 	int error;
2540 	uint64_t i;
2541 
2542 	i = ip6_input_measure_bins;
2543 	error = sysctl_handle_quad(oidp, &i, 0, req);
2544 	if (error || req->newptr == USER_ADDR_NULL) {
2545 		goto done;
2546 	}
2547 	/* validate data */
2548 	if (!net_perf_validate_bins(i)) {
2549 		error = EINVAL;
2550 		goto done;
2551 	}
2552 	ip6_input_measure_bins = i;
2553 done:
2554 	return error;
2555 }
2556 
2557 static int
2558 sysctl_ip6_input_getperf SYSCTL_HANDLER_ARGS
2559 {
2560 #pragma unused(oidp, arg1, arg2)
2561 	if (req->oldptr == USER_ADDR_NULL) {
2562 		req->oldlen = (size_t)sizeof(struct net_perf);
2563 	}
2564 
2565 	return SYSCTL_OUT(req, &net_perf, MIN(sizeof(net_perf), req->oldlen));
2566 }
2567 
2568 
2569 /*
2570  * Initialize IPv6 source address hash table.
2571  */
2572 static void
in6_ifaddrhashtbl_init(void)2573 in6_ifaddrhashtbl_init(void)
2574 {
2575 	int i, k, p;
2576 	uint32_t nhash = 0;
2577 	uint32_t hash_size;
2578 
2579 	if (in6_ifaddrhashtbl != NULL) {
2580 		return;
2581 	}
2582 
2583 	PE_parse_boot_argn("ina6ddr_nhash", &nhash,
2584 	    sizeof(in6addr_nhash));
2585 	if (nhash == 0) {
2586 		nhash = IN6ADDR_NHASH;
2587 	}
2588 
2589 	hash_size = nhash * sizeof(*in6_ifaddrhashtbl);
2590 
2591 	in6_ifaddrhashtbl = zalloc_permanent(
2592 		hash_size,
2593 		ZALIGN_PTR);
2594 	in6addr_nhash = nhash;
2595 
2596 	/*
2597 	 * Generate the next largest prime greater than in6addr_nhash.
2598 	 */
2599 	k = (in6addr_nhash % 2 == 0) ? in6addr_nhash + 1 : in6addr_nhash + 2;
2600 	for (;;) {
2601 		p = 1;
2602 		for (i = 3; i * i <= k; i += 2) {
2603 			if (k % i == 0) {
2604 				p = 0;
2605 			}
2606 		}
2607 		if (p == 1) {
2608 			break;
2609 		}
2610 		k += 2;
2611 	}
2612 	in6addr_hashp = k;
2613 }
2614 
2615 static int
2616 sysctl_ip6_checkinterface SYSCTL_HANDLER_ARGS
2617 {
2618 #pragma unused(arg1, arg2)
2619 	int error, i;
2620 
2621 	i = ip6_checkinterface;
2622 	error = sysctl_handle_int(oidp, &i, 0, req);
2623 	if (error || req->newptr == USER_ADDR_NULL) {
2624 		return error;
2625 	}
2626 
2627 	switch (i) {
2628 	case IP6_CHECKINTERFACE_WEAK_ES:
2629 	case IP6_CHECKINTERFACE_HYBRID_ES:
2630 	case IP6_CHECKINTERFACE_STRONG_ES:
2631 		if (ip6_checkinterface != i) {
2632 			ip6_checkinterface = i;
2633 			os_log(OS_LOG_DEFAULT, "%s: ip6_checkinterface is now %d\n",
2634 			    __func__, ip6_checkinterface);
2635 		}
2636 		break;
2637 	default:
2638 		error = EINVAL;
2639 		break;
2640 	}
2641 	return error;
2642 }
2643